إدارة سياق العميل وسجله
تقديم ردود مخصصة باستخدام المشتريات السابقة والتذاكر والتفضيلات.
إدارة سياق العميل وسجله درس مجاني في AI Agents على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 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قراءة مستوى الاشتراك وحالته
يحدد مستوى الاشتراك ما يحق للعميل الحصول عليه. فالعميل المشترك في Pro والذي يسأل عن ميزة غير متاحة في خطته يحتاج إلى رد مختلف عن عميل Enterprise الذي يطرح السؤال نفسه.
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"؟
يتطلب تخصيص الردود الإشارة إلى نقاط بيانات محددة من ملف العميل. ويُعد تحديد الحقل الذي يتيح هذه العبارة سؤالًا عمليًا لاسترجاع المعلومات.
مراجعة سياق العميل
يبني وكيل خدمة العملاء المتميز ملفًا غنيًا بالاعتماد على سجل المشتريات وتذاكر الدعم ومستوى الاشتراك وعمر الحساب. احقن كتلة سياق موجزة في مطالبة النظام، وخزّنها مؤقتًا طوال الجلسة، واستخدم علامات المخاطر لاكتشاف المواقف الحساسة قبل تصعيدها.
الأسئلة الشائعة
هل درس «إدارة سياق العميل وسجله» مجاني؟
نعم — نص درس «إدارة سياق العميل وسجله» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Agents، انتقل إلى CoddyKit PRO. تتضمن دورة AI Agents 4 دروس في المجموع.
ماذا ستتعلم في «إدارة سياق العميل وسجله»؟
تقديم ردود مخصصة باستخدام المشتريات السابقة والتذاكر والتفضيلات. تتمرن على AI Agents مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ AI Agents؟
لا تُشترط خبرة سابقة. AI Agents على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «إدارة سياق العميل وسجله»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس AI Agents هذا؟
نعم. كل درس في AI Agents يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- منطق توجيه التذاكر وتصعيدها
- تكامل CRM: Salesforce وHubSpot
- بروتوكولات التسليم إلى العنصر البشري
- إدارة سياق العميل وسجله