0Pricing
AI Agents · บทเรียน

การจัดการบริบทและประวัติลูกค้า

ตอบกลับแบบเฉพาะบุคคลโดยใช้ประวัติการซื้อ ทิกเก็ต และการตั้งค่าที่ผ่านมา

การจัดการบริบทและประวัติลูกค้า เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

เหตุใดบริบทจึงทำให้เอเจนต์ดูเหมือนมนุษย์

ความแตกต่างระหว่างเจ้าหน้าที่บริการลูกค้าระดับพอใช้กับระดับยอดเยี่ยมคือบริบท เมื่อเอเจนต์พูดว่า 'ฉันเห็นว่าการสมัครสมาชิกของคุณจะต่ออายุในสัปดาห์หน้า — คุณต้องการหยุดการต่ออายุไว้ก่อนไหม' ลูกค้าจะรู้สึกว่าได้รับการเข้าใจ ไม่ใช่แค่ถูกดำเนินการตามขั้นตอน

บทนี้ครอบคลุมการสร้างชั้นบริบทลูกค้าที่มีข้อมูลครบถ้วนสำหรับเอเจนต์ของคุณ

โครงสร้างข้อมูลโปรไฟล์ลูกค้า

กำหนดโปรไฟล์ลูกค้ามาตรฐานที่รวบรวมข้อมูลจากหลายแหล่ง เอเจนต์จะได้รับข้อมูลชนิดพจนานุกรมนี้เมื่อเริ่มต้นทุกบทสนทนา

from dataclasses import dataclass, field
from datetime import date

@dataclass
class CustomerProfile:
    customer_id: str
    name: str
    email: str
    join_date: date
    subscription_tier: str          # 'free', 'pro', 'enterprise'
    account_age_days: int
    lifetime_value_usd: float
    previous_tickets: list[dict] = field(default_factory=list)
    recent_purchases: list[dict]  = field(default_factory=list)
    preferences: dict             = field(default_factory=dict)

    @property
    def is_long_term_customer(self) -> bool:
        return self.account_age_days > 365

if __name__ == '__main__':
    from datetime import date
    profile = CustomerProfile(
        customer_id='cust_1', name='Jane Doe', email='jane@example.com',
        join_date=date(2023, 1, 15), subscription_tier='pro',
        account_age_days=400, lifetime_value_usd=1250.50,
    )
    print(f'{profile.name} ({profile.subscription_tier}) - long-term customer: {profile.is_long_term_customer}')

การดึงประวัติการสั่งซื้อ

ดึงคำสั่งซื้อ N รายการล่าสุดจากระบบแบ็กเอนด์ของร้านค้าออนไลน์ของคุณ โดยรวมวันที่สั่งซื้อ รายการสินค้า ยอดรวม และสถานะไว้ด้วย ข้อมูลนี้ช่วยให้เอเจนต์ทราบว่าลูกค้าเคยซื้ออะไรบ้าง และมีคำสั่งซื้อช่วงล่าสุดรายการใดที่อาจมีปัญหาหรือไม่

import requests

SHOP_API = 'https://api.yourshop.com'
SHOP_KEY  = 'YOUR_SHOP_API_KEY'

def get_purchase_history(customer_id: str, limit: int = 10) -> list[dict]:
    resp = requests.get(
        f'{SHOP_API}/customers/{customer_id}/orders',
        headers={'Authorization': f'Bearer {SHOP_KEY}'},
        params={'limit': limit, 'sort': '-created_at'}
    )
    resp.raise_for_status()
    orders = resp.json()['orders']
    return [
        {
            'order_id':   o['id'],
            'date':       o['created_at'][:10],
            'total_usd':  o['total'],
            'status':     o['status'],
            'items':      [i['name'] for i in o['line_items']]
        }
        for o in orders
    ]

การดึงคำร้องฝ่ายสนับสนุนก่อนหน้า

ดึงคำร้องฝ่ายสนับสนุน N รายการล่าสุดเพื่อทำความเข้าใจปัญหาที่เกิดซ้ำ หากลูกค้าเคยแจ้งปัญหาเดิมและได้รับการแก้ไขแล้วสามครั้ง นั่นถือเป็นปัญหาของผลิตภัณฑ์ ให้ส่งต่อเรื่องและติดแฟล็กตามความเหมาะสม

def get_support_history(customer_id: str, limit: int = 5) -> list[dict]:
    resp = requests.get(
        f'{SHOP_API}/customers/{customer_id}/tickets',
        headers={'Authorization': f'Bearer {SHOP_KEY}'},
        params={'limit': limit, 'sort': '-created_at'}
    )
    resp.raise_for_status()
    tickets = resp.json()['tickets']
    return [
        {
            'ticket_id': t['id'],
            'subject':   t['subject'],
            'status':    t['status'],
            'resolved':  t.get('resolved_at', ''),
            'category':  t.get('category', 'general')
        }
        for t in tickets
    ]

def has_recurring_issue(tickets: list[dict], category: str) -> bool:
    return sum(1 for t in tickets if t['category'] == category) >= 3

การอ่านระดับและสถานะการสมัครสมาชิก

ระดับการสมัครสมาชิกเป็นตัวกำหนดว่าลูกค้ามีสิทธิ์ได้รับอะไรบ้าง ลูกค้าระดับมืออาชีพที่สอบถามเกี่ยวกับฟีเจอร์ซึ่งไม่มีในแผนของตน ย่อมต้องได้รับคำตอบแตกต่างจากลูกค้าระดับองค์กรที่ถามคำถามเดียวกัน

def get_subscription_info(customer_id: str) -> dict:
    resp = requests.get(
        f'{SHOP_API}/customers/{customer_id}/subscription',
        headers={'Authorization': f'Bearer {SHOP_KEY}'}
    )
    if resp.status_code == 404:
        return {'tier': 'free', 'status': 'active', 'renewal_date': None}
    resp.raise_for_status()
    sub = resp.json()
    return {
        'tier':         sub['plan'],
        'status':       sub['status'],        # active / past_due / canceled
        'renewal_date': sub.get('current_period_end', '')[:10],
        'cancel_at':    sub.get('cancel_at_period_end', False)
    }

การคำนวณอายุบัญชี

อายุบัญชีเป็นสัญญาณบ่งบอกความภักดีของลูกค้า ลูกค้าที่ใช้บริการกับคุณมาตั้งแต่ปี 2021 ควรได้รับการดูแลแตกต่างจากผู้ที่เพิ่งสมัครเมื่อวานนี้ เมื่อเหมาะสม ให้กล่าวถึงระยะเวลาที่ลูกค้าใช้บริการเพื่อสร้างความสัมพันธ์ที่ดี

from datetime import datetime, timezone

def calculate_account_age(join_date_str: str) -> dict:
    join = datetime.fromisoformat(join_date_str.replace('Z', '+00:00'))
    now  = datetime.now(timezone.utc)
    delta = now - join
    years  = delta.days // 365
    months = (delta.days % 365) // 30
    return {
        'days':   delta.days,
        'years':  years,
        'months': months,
        'label':  f'{years} year(s) and {months} month(s)' if years else f'{months} month(s)'
    }

age = calculate_account_age('2021-03-15T00:00:00Z')
print(age['label'])  # e.g. '5 year(s) and 2 month(s)'

การสร้างสตริงบริบทสำหรับ LLM

แปลงโปรไฟล์ลูกค้าให้เป็นบล็อกบริบทที่กระชับ แล้วแทรกลงในพรอมป์ระบบ เก็บไว้เฉพาะข้อเท็จจริงที่เกี่ยวข้องโดยตรงกับเซสชันปัจจุบัน และควรทำให้สั้น

def build_context_block(profile: CustomerProfile) -> str:
    recent_order = profile.recent_purchases[0] if profile.recent_purchases else None
    last_ticket  = profile.previous_tickets[0]  if profile.previous_tickets  else None
    parts = [
        f'Customer: {profile.name} ({profile.email})',
        f'Account age: {profile.account_age_days} days | Tier: {profile.subscription_tier}',
        f'Lifetime value: USD {profile.lifetime_value_usd:.0f}',
    ]
    if recent_order:
        parts.append(
            f'Last order: {recent_order["date"]} — '
            f'{', '.join(recent_order["items"][:2])} ({recent_order["status"]})'
        )
    if last_ticket:
        parts.append(f'Last ticket: "{last_ticket["subject"]}" ({last_ticket["status"]})')
    return '\n'.join(parts)

การปรับแต่งคำตอบด้วยบริบท

แทรกบล็อกบริบทลงในพรอมป์ระบบ เพื่อให้ LLM อ้างอิงข้อมูลดังกล่าวในคำตอบได้อย่างเป็นธรรมชาติ โดยไม่ต้องกำชับอย่างชัดเจน

import openai

client = openai.OpenAI(api_key='YOUR_OPENAI_KEY')

def respond_with_context(user_message: str, profile: CustomerProfile) -> str:
    context = build_context_block(profile)
    system_prompt = (
        f'You are a helpful customer service agent for ShopCo.\n'
        f'Customer context:\n{context}\n\n'
        f'Be warm and personal. Reference their history when relevant. '
        f'Address the customer by first name.'
    )
    resp = client.chat.completions.create(
        model='gpt-4o',
        messages=[
            {'role': 'system', 'content': system_prompt},
            {'role': 'user',   'content': user_message}
        ]
    )
    return resp.choices[0].message.content

การแคชบริบทของลูกค้า

การดึงข้อมูลโปรไฟล์จากส่วนเชื่อมต่อหลายแห่งทุกครั้งที่มีข้อความเข้ามานั้นช้าและมีค่าใช้จ่ายสูง ให้แคชโปรไฟล์เมื่อเริ่มการสนทนา และอัปเดตเฉพาะฟิลด์ที่อาจเปลี่ยนแปลง เช่น สถานะคำสั่งซื้อและสถานะคำร้อง

import time

profile_cache: dict[str, dict] = {}  # customer_id -> {profile, fetched_at}
CACHE_TTL = 300  # 5 minutes

def get_cached_profile(customer_id: str) -> CustomerProfile | None:
    entry = profile_cache.get(customer_id)
    if entry and time.time() - entry['fetched_at'] < CACHE_TTL:
        return entry['profile']
    return None

def set_cached_profile(customer_id: str, profile: CustomerProfile):
    profile_cache[customer_id] = {
        'profile': profile,
        'fetched_at': time.time()
    }

การตรวจจับสถานการณ์ละเอียดอ่อนจากประวัติ

ประวัติอาจเผยให้เห็นรูปแบบที่ต้องจัดการเป็นพิเศษ เช่น ลูกค้าที่คำสั่งซื้อสามรายการล่าสุดมีสินค้าชำรุด คนที่ขู่ว่าจะยกเลิกเมื่อเดือนที่แล้ว หรือผู้ใช้ที่ใช้บริการกับคุณมานาน 7 ปี

def assess_risk_flags(profile: CustomerProfile) -> list[str]:
    flags = []

    # Check for cancellation risk
    cancel_keywords = ['cancel', 'unsubscribe', 'quit', 'competitor']
    for ticket in profile.previous_tickets:
        if any(kw in ticket.get('subject', '').lower() for kw in cancel_keywords):
            flags.append('cancellation_risk')
            break

    # Defective product pattern
    defective = sum(1 for o in profile.recent_purchases if o.get('status') == 'refunded')
    if defective >= 2:
        flags.append('product_quality_issue')

    # High-value customer
    if profile.lifetime_value_usd > 5000:
        flags.append('high_value_customer')

    return flags

ลำดับขั้นการประกอบบริบทแบบสมบูรณ์

รวมแหล่งข้อมูลทั้งหมดไว้ในฟังก์ชัน assemble_context() เดียว ซึ่งเรียกใช้ครั้งเดียวเมื่อเริ่มการสนทนา

from datetime import date

def assemble_context(email: str) -> CustomerProfile:
    # Try cache first
    # In production: look up customer_id from email in your user DB
    customer_id = 'CUST_123'

    cached = get_cached_profile(customer_id)
    if cached:
        return cached

    # Fetch from all sources
    sub    = get_subscription_info(customer_id)
    orders = get_purchase_history(customer_id)
    tickets = get_support_history(customer_id)

    profile = CustomerProfile(
        customer_id=customer_id,
        name='Alice Smith',
        email=email,
        join_date=date(2021, 3, 15),
        subscription_tier=sub['tier'],
        account_age_days=calculate_account_age('2021-03-15T00:00:00Z')['days'],
        lifetime_value_usd=1240.00,
        previous_tickets=tickets,
        recent_purchases=orders
    )
    set_cached_profile(customer_id, profile)
    return profile

ข้อมูลบริบทของลูกค้าส่วนใดช่วยให้เอเจนต์พูดว่า 'เห็นว่าคุณใช้บริการกับเรามาตั้งแต่ปี 2021' ได้โดยตรงที่สุด

การปรับแต่งคำตอบให้เหมาะกับลูกค้าต้องอ้างอิงข้อมูลเฉพาะจากโปรไฟล์ลูกค้า การระบุว่าฟิลด์ใดช่วยให้สร้างข้อความนี้ได้ ถือเป็นคำถามทบทวนความเข้าใจเชิงปฏิบัติ

สรุปบริบทของลูกค้า

เอเจนต์บริการลูกค้าที่ดีจะสร้าง โปรไฟล์ที่มีข้อมูลครบถ้วน จากประวัติการสั่งซื้อ คำร้องฝ่ายสนับสนุน ระดับการสมัครสมาชิก และอายุบัญชี ให้แทรกบล็อกบริบทที่กระชับลงในพรอมป์ระบบ แคชบล็อกนี้ ไว้ตลอดเซสชัน และใช้ แฟล็กความเสี่ยง เพื่อตรวจจับสถานการณ์ละเอียดอ่อนก่อนที่ปัญหาจะบานปลาย

คำถามที่พบบ่อย

บทเรียน “การจัดการบริบทและประวัติลูกค้า” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดการบริบทและประวัติลูกค้า” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดการบริบทและประวัติลูกค้า”

ตอบกลับแบบเฉพาะบุคคลโดยใช้ประวัติการซื้อ ทิกเก็ต และการตั้งค่าที่ผ่านมา คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การจัดการบริบทและประวัติลูกค้า” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ตรรกะการจัดเส้นทางและยกระดับทิกเก็ต
  2. การผสาน CRM: Salesforce และ HubSpot
  3. โพรโทคอลการส่งต่องานให้มนุษย์
  4. การจัดการบริบทและประวัติลูกค้า
← กลับไปที่ AI Agents