AI Agents · 课时

客户上下文与历史记录管理

利用过往购买记录、工单和偏好生成个性化回复

第 4 / 4 课13 个步骤

客户上下文与历史记录管理 是 CoddyKit 上的免费 AI Agents 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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

缓存客户上下文

每条消息都从多个 API 获取资料数据,既缓慢又昂贵。请在会话开始时缓存资料,只更新可能发生变化的字段(订单状态、工单状态)。

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 导师学习 AI Agents — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
60
课程
239

常见问题解答

「客户上下文与历史记录管理」课时是免费的吗?

是的 — 「客户上下文与历史记录管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。

「客户上下文与历史记录管理」这节课中我会学到什么?

利用过往购买记录、工单和偏好生成个性化回复 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Agents 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「客户上下文与历史记录管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Agents 课中编写并运行代码吗?

能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 工单路由与升级逻辑
  2. CRM 集成:Salesforce 与 HubSpot
  3. 人工接管协议
  4. 客户上下文与历史记录管理
← 返回 AI Agents