고객 맥락 및 이력 관리
과거 구매 내역, 티켓, 환경설정을 활용해 개인화된 답변을 제공합니다.
고객 맥락 및 이력 관리은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
컨텍스트가 Agent를 인간적으로 느끼게 하는 이유
평범한 고객 서비스 agent와 뛰어난 고객 서비스 agent의 차이는 컨텍스트입니다. agent가 '고객님의 구독이 다음 주에 갱신되는데, 그 전에 일시 중지하시겠어요?'라고 말하면 고객은 단순히 처리되는 것이 아니라 자신을 이해받고 있다고 느낍니다.
이 레슨에서는 agent를 위한 풍부한 고객 컨텍스트 계층을 구축하는 방법을 다룹니다.
고객 프로필 스키마
여러 출처의 데이터를 통합하는 표준 고객 프로필을 정의합니다. agent는 모든 대화가 시작될 때 이 dict를 받습니다.
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 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“고객 맥락 및 이력 관리”에서 뭘 배우나요?
과거 구매 내역, 티켓, 환경설정을 활용해 개인화된 답변을 제공합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“고객 맥락 및 이력 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.