Customer Support Agent — Chatbot hỗ trợ production-grade
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Để áp dụng kiến trúc hệ thống hiệu quả, bạn cần nắm rõ: Customer Message | v Intent Detection -- Hoi ve don hang? FAQ? Khieu nai? | +--FAQ --> Knowledge Base Search --> Tra loi truc tiep | +--Order --> Order Lookup Tool --> Tra loi voi du lieu thuc | +- — đây là bước quan trọng giúp tối ưu quy trình làm việc với AI trong thực tế.
- 2 Góc nhìn thực tế về dữ liệu mẫu — mock database: timedelta client anthropic.Anthropic # Mock database don hang ORDERS_DB "ORD-001": "id": "ORD-001", "customer": "Nguyen Van An", "email": "an@example.com", "items": "name": "Claude API Credits 100K tokens", "qty": 1, "price": 150000 , "total": 150000, "status": "delivered", "created_at": "2026-03-20", "delivered_at": "2026- — hiệu quả phụ thuộc nhiều vào cách triển khai và ngữ cảnh sử dụng cụ thể.
- 3 Dữ liệu từ tool implementations cho thấy: # Tool 1: Tim kiem knowledge base str -> str: query_lower query.lower results for article in KNOWLEDGE_BASE: score 0 for word in query_lower.split: if word in article"question".lower: score + 2 if word in article"answer" — những con số này phản ánh mức độ cải thiện thực tế mà người dùng có thể kỳ vọng.
- 4 Bước thực hành then chốt trong support agent với multi-turn memory: SUPPORT_SYSTEM """Ban la nhan vien ho tro khach hang cua Claude.vn, chuyen nghiep, than thien, va luon tim cach giai quyet van de. Quy tac: 1. Chao hoi lich su, xac nhan van de truoc khi xu ly 2 — nắm vững điều này giúp bạn triển khai nhanh hơn và giảm thiểu lỗi thường gặp.
- 5 Về demo conversation, thực tế cho thấy agent CustomerSupportAgent # Kich ban 1: Tra cuu don hang printagent.chat"Xin chao, toi muon biet don hang ORD-001 di den dau roi?" # Agent: tra cuu ORDERS_DB — đây là con dao hai lưỡi nếu không hiểu rõ giới hạn và điều kiện áp dụng của nó.
Một chatbot hỗ trợ khách hàng thực sự hữu ích không chỉ trả lời câu hỏi — nó phải tra cứu được đơn hàng thực, tạo ticket, và biết khi nào cần chuyển đến nhân viên. Bài viết này xây dựng một customer support agent production-grade với đầy đủ tính năng đó.
Architecture dựa trên reference implementation chính thức của Anthropic, được mở rộng với các pattern thực tế từ production deployments.
Kiến trúc hệ thống
Customer Message
|
v
[Intent Detection] -- Hoi ve don hang? FAQ? Khieu nai?
|
+--[FAQ] --> Knowledge Base Search --> Tra loi truc tiep
|
+--[Order] --> Order Lookup Tool --> Tra loi voi du lieu thuc
|
+--[Complaint] --> Ticket Creation Tool --> Tao ticket + thong bao
|
+--[Complex] --> Escalation Tool --> Chuyen nhan vien con nguoi
Dữ liệu mẫu — Mock Database
import anthropic
import json
from datetime import datetime, timedelta
client = anthropic.Anthropic()
# Mock database don hang
ORDERS_DB = {
"ORD-001": {
"id": "ORD-001",
"customer": "Nguyen Van An",
"email": "an@example.com",
"items": [
{"name": "Claude API Credits 100K tokens", "qty": 1, "price": 150000}
],
"total": 150000,
"status": "delivered",
"created_at": "2026-03-20",
"delivered_at": "2026-03-23",
"tracking": "VN123456789"
},
"ORD-002": {
"id": "ORD-002",
"customer": "Tran Thi Binh",
"email": "binh@example.com",
"items": [
{"name": "Claude Pro Monthly", "qty": 1, "price": 500000}
],
"total": 500000,
"status": "processing",
"created_at": "2026-03-25",
"delivered_at": None,
"tracking": None
}
}
# Mock tickets
TICKETS_DB = {}
ticket_counter = 1000
# Knowledge base (FAQ)
KNOWLEDGE_BASE = [
{
"id": "faq-001",
"category": "billing",
"question": "Lam the nao de xem hoa don?",
"answer": "Dang nhap vao dashboard.claude.ai, chon 'Billing' trong menu Settings. "
"Tat ca hoa don se hien thi tai day, co the tai xuong dang PDF."
},
{
"id": "faq-002",
"category": "api",
"question": "Rate limit cua Claude API la bao nhieu?",
"answer": "Rate limit phu thuoc vao plan:
"
"- Free: 5 req/min, 10K tokens/day
"
"- Pro: 50 req/min, 1M tokens/day
"
"- Team: Custom, lien he sales"
},
{
"id": "faq-003",
"category": "refund",
"question": "Chinh sach hoan tien nhu the nao?",
"answer": "Anthropic ho tro hoan tien trong vong 7 ngay ke tu ngay mua "
"neu san pham loi ky thuat. Gui ticket de duoc ho tro."
},
{
"id": "faq-004",
"category": "account",
"question": "Quen mat khau phai lam gi?",
"answer": "Vao trang login.claude.ai, click 'Quen mat khau', "
"nhap email va check hop thu de lay link reset."
}
]
Tool Implementations
# Tool 1: Tim kiem knowledge base
def search_knowledge_base(query: str) -> str:
query_lower = query.lower()
results = []
for article in KNOWLEDGE_BASE:
score = 0
for word in query_lower.split():
if word in article["question"].lower():
score += 2
if word in article["answer"].lower():
score += 1
if word in article["category"].lower():
score += 1
if score > 0:
results.append((score, article))
results.sort(key=lambda x: x[0], reverse=True)
if not results:
return json.dumps({
"found": False,
"message": "Khong tim thay thong tin lien quan trong knowledge base"
})
top = results[0][1]
return json.dumps({
"found": True,
"category": top["category"],
"answer": top["answer"],
"article_id": top["id"]
}, ensure_ascii=False)
# Tool 2: Tra cuu don hang
def get_order_status(order_id: str = None, email: str = None) -> str:
if order_id:
order_id = order_id.upper()
order = ORDERS_DB.get(order_id)
if not order:
return json.dumps({
"found": False,
"message": f"Khong tim thay don hang {order_id}"
})
return json.dumps(order, ensure_ascii=False)
if email:
orders = [o for o in ORDERS_DB.values() if o["email"] == email]
if not orders:
return json.dumps({
"found": False,
"message": f"Khong tim thay don hang nao voi email {email}"
})
return json.dumps({
"found": True,
"orders": orders,
"count": len(orders)
}, ensure_ascii=False)
return json.dumps({"error": "Vui long cung cap order_id hoac email"})
# Tool 3: Tao ticket ho tro
def create_ticket(
customer_name: str,
email: str,
category: str,
description: str,
priority: str = "medium"
) -> str:
global ticket_counter
ticket_counter += 1
ticket_id = f"TKT-{ticket_counter}"
ticket = {
"id": ticket_id,
"customer_name": customer_name,
"email": email,
"category": category,
"description": description,
"priority": priority,
"status": "open",
"created_at": datetime.now().isoformat(),
"estimated_response": "1-2 ngay lam viec"
}
TICKETS_DB[ticket_id] = ticket
return json.dumps({
"success": True,
"ticket_id": ticket_id,
"message": (
f"Da tao ticket {ticket_id} thanh cong. "
f"Doi ngu ho tro se lien he qua {email} trong {ticket['estimated_response']}."
)
}, ensure_ascii=False)
# Tool 4: Leo thang den nhan vien
def escalate_to_human(
reason: str,
customer_email: str,
conversation_summary: str
) -> str:
# Trong thuc te: gui Slack notification, tao Zendesk ticket, etc.
escalation_id = f"ESC-{datetime.now().strftime('%Y%m%d%H%M%S')}"
return json.dumps({
"success": True,
"escalation_id": escalation_id,
"message": (
"Da chuyen cuoc tro chuyen den chuyen vien ho tro. "
"Ho se lien he voi ban trong vong 30 phut (gio lam viec)."
),
"next_steps": [
"Chuyen vien se review lich su chat nay",
f"Email xac nhan duoc gui den {customer_email}",
"Neu khan cap, goi hotline: 1900-xxxx"
]
}, ensure_ascii=False)
Tool Schemas
support_tools = [
{
"name": "search_knowledge_base",
"description": "Tim kiem trong FAQ va knowledge base de tra loi cau hoi pho bien",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Cau hoi hoac tu khoa can tim kiem"
}
},
"required": ["query"]
}
},
{
"name": "get_order_status",
"description": "Tra cuu trang thai don hang theo ma don hang hoac email",
"input_schema": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "Ma don hang, vi du: ORD-001"
},
"email": {
"type": "string",
"description": "Email khach hang"
}
}
}
},
{
"name": "create_ticket",
"description": "Tao ticket ho tro khi can giai quyet van de phuc tap",
"input_schema": {
"type": "object",
"properties": {
"customer_name": {"type": "string"},
"email": {"type": "string"},
"category": {
"type": "string",
"enum": ["billing", "technical", "shipping", "refund", "other"]
},
"description": {"type": "string", "description": "Mo ta van de chi tiet"},
"priority": {
"type": "string",
"enum": ["low", "medium", "high", "urgent"],
"description": "Mac dinh: medium"
}
},
"required": ["customer_name", "email", "category", "description"]
}
},
{
"name": "escalate_to_human",
"description": "Leo thang den nhan vien con nguoi khi van de vuot qua kha nang xu ly tu dong",
"input_schema": {
"type": "object",
"properties": {
"reason": {"type": "string", "description": "Ly do can leo thang"},
"customer_email": {"type": "string"},
"conversation_summary": {"type": "string", "description": "Tom tat van de"}
},
"required": ["reason", "customer_email", "conversation_summary"]
}
}
]
tool_map = {
"search_knowledge_base": search_knowledge_base,
"get_order_status": get_order_status,
"create_ticket": create_ticket,
"escalate_to_human": escalate_to_human
}
Support Agent với Multi-turn Memory
SUPPORT_SYSTEM = """Ban la nhan vien ho tro khach hang cua Claude.vn,
chuyen nghiep, than thien, va luon tim cach giai quyet van de.
Quy tac:
1. Chao hoi lich su, xac nhan van de truoc khi xu ly
2. Tim kiem knowledge base truoc khi hoi them thong tin
3. Neu lien quan den don hang, yeu cau ma don hoac email de tra cuu
4. Neu giai quyet duoc: tra loi day du, ro rang, co buoc thuc hien cu the
5. Neu phuc tap hoac cam xuc cao: tao ticket hoac leo thang den nhan vien
6. Luon ket thuc bang hoi: 'Ban con can ho tro gi khong?'
Ngon ngu: Tieng Viet, lich su nhung khong cung nhac."""
class CustomerSupportAgent:
def __init__(self):
self.conversation_history = []
def chat(self, user_message: str) -> str:
self.conversation_history.append({
"role": "user",
"content": user_message
})
while True:
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=2048,
system=SUPPORT_SYSTEM,
tools=support_tools,
messages=self.conversation_history
)
self.conversation_history.append({
"role": "assistant",
"content": response.content
})
if response.stop_reason == "end_turn":
return next(
(b.text for b in response.content if hasattr(b, "text")), ""
)
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = self._execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
self.conversation_history.append({
"role": "user",
"content": tool_results
})
def _execute_tool(self, name: str, inputs: dict) -> str:
if name not in tool_map:
return json.dumps({"error": f"Unknown tool: {name}"})
try:
return tool_map[name](**inputs)
except Exception as e:
return json.dumps({"error": str(e)})
def reset(self):
self.conversation_history = []
Demo conversation
agent = CustomerSupportAgent()
# Kich ban 1: Tra cuu don hang
print(agent.chat("Xin chao, toi muon biet don hang ORD-001 di den dau roi?"))
# Agent: tra cuu ORDERS_DB, tra loi voi thong tin cu the
# Kich ban 2: Hoan tien
print(agent.chat("Toi muon hoan tien don hang ORD-002"))
# Agent: tra cuu don hang, tao ticket category=refund
# Kich ban 3: Cau hoi ky thuat
print(agent.chat("Rate limit cua API la bao nhieu?"))
# Agent: tim trong knowledge base, tra loi truc tiep
# Kich ban 4: Khieu nai phuc tap
print(agent.chat("Toi bi tinh phi sai, bi mat 500k roi ma khong ai giai quyet!"))
# Agent: escalate_to_human vi cam xuc cao va van de tai chinh
Production Checklist
Trước khi deploy, cần đảm bảo:
- Rate limiting — Giới hạn số request/user/giờ để tránh abuse
- PII handling — Không lưu thông tin nhạy cảm trong conversation logs
- Fallback — Khi API lỗi, hiển thị message thân thiện thay vì crash
- Analytics — Track: resolution rate, escalation rate, CSAT score
- A/B testing — So sánh different system prompts để tối ưu satisfaction
- Human review — Sampling 5% conversations để QA định kỳ
Tổng kết
| Tính năng | Tool | Use case |
|---|---|---|
| FAQ Lookup | search_knowledge_base | Câu hỏi thường gặp |
| Order Tracking | get_order_status | Tra cứu đơn hàng thực |
| Ticket Creation | create_ticket | Vấn đề cần xử lý manual |
| Human Escalation | escalate_to_human | Tình huống phức tạp/nhạy cảm |
Customer Support Agent là pattern phổ biến nhất khi deploy Claude vào doanh nghiệp. Muốn đi xa hơn? Xem Financial Data Analyst để thấy cách dùng Claude phân tích dữ liệu và tạo báo cáo tự động, hoặc quay lại LLM Agent từ đầu để nắm vững kiến trúc foundation.
Bài viết liên quan
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.




