1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
| class IntelligentCustomerServiceSystem:
"""智能客服系统 - 基于AutoGen的企业级实现"""
def __init__(self):
self.runtime = SingleThreadedAgentRuntime()
self.agents = {}
self.conversation_manager = ConversationManager()
self.knowledge_base = KnowledgeBaseAgent()
async def setup_agents(self):
"""设置客服系统的各类代理"""
# 1. 路由代理 - 负责客户请求分类和路由
router_agent = CustomerServiceRouter(
name="router",
model_client=self._create_model_client(),
classification_rules=self._load_classification_rules()
)
# 2. 知识库代理 - 负责FAQ和知识检索
knowledge_agent = KnowledgeBaseAgent(
name="knowledge",
vector_store=self._create_vector_store(),
search_engine=self._create_search_engine()
)
# 3. 人工客服代理 - 处理复杂问题
human_agent = HumanEscalationAgent(
name="human_support",
escalation_queue=self._create_escalation_queue()
)
# 4. 质量监控代理 - 监控对话质量
quality_agent = QualityMonitorAgent(
name="quality_monitor",
sentiment_analyzer=self._create_sentiment_analyzer()
)
# 注册所有代理
agents = [router_agent, knowledge_agent, human_agent, quality_agent]
for agent in agents:
await agent.register(self.runtime, agent.name, lambda a=agent: a)
self.agents[agent.name] = agent
async def handle_customer_inquiry(self, customer_id: str, inquiry: str) -> CustomerServiceResponse:
"""处理客户咨询的完整流程"""
conversation_id = f"conv_{customer_id}_{int(time.time())}"
# 1. 路由分类
routing_result = await self.agents['router'].classify_inquiry(inquiry)
# 2. 根据分类结果选择处理策略
if routing_result.category == "faq":
# 知识库查询
knowledge_result = await self.agents['knowledge'].search_knowledge(inquiry)
if knowledge_result.confidence > 0.8:
response = CustomerServiceResponse(
conversation_id=conversation_id,
response_type="knowledge_base",
content=knowledge_result.answer,
confidence=knowledge_result.confidence
)
else:
# 转人工
response = await self._escalate_to_human(customer_id, inquiry, conversation_id)
elif routing_result.category == "technical":
# 技术支持流程
response = await self._handle_technical_support(customer_id, inquiry, conversation_id)
elif routing_result.category == "complaint":
# 投诉处理流程
response = await self._handle_complaint(customer_id, inquiry, conversation_id)
else:
# 默认处理
response = await self._handle_general_inquiry(customer_id, inquiry, conversation_id)
# 3. 质量监控和反馈
await self.agents['quality_monitor'].analyze_interaction(conversation_id, inquiry, response)
return response
class CustomerServiceRouter(RoutedAgent):
"""客服路由代理 - 智能分类客户请求"""
def __init__(self, name: str, model_client, classification_rules: Dict[str, Any]):
super().__init__("客服请求路由和分类专家")
self.model_client = model_client
self.classification_rules = classification_rules
self.classification_cache = TTLCache(maxsize=10000, ttl=3600) # 1小时缓存
async def classify_inquiry(self, inquiry: str) -> ClassificationResult:
"""
智能分类客户咨询
使用机器学习模型和规则引擎相结合的方式,
准确识别客户咨询的类型和紧急程度
"""
# 检查缓存
cache_key = hashlib.md5(inquiry.encode()).hexdigest()
if cache_key in self.classification_cache:
return self.classification_cache[cache_key]
# 预处理查询
processed_inquiry = await self._preprocess_inquiry(inquiry)
# 规则引擎快速分类
rule_result = await self._apply_classification_rules(processed_inquiry)
if rule_result.confidence > 0.9:
self.classification_cache[cache_key] = rule_result
return rule_result
# 使用LLM进行智能分类
llm_result = await self._llm_classify(processed_inquiry)
# 结合规则和LLM结果
final_result = await self._combine_classification_results(rule_result, llm_result)
# 缓存结果
self.classification_cache[cache_key] = final_result
return final_result
async def _preprocess_inquiry(self, inquiry: str) -> str:
"""预处理客户咨询"""
# 1. 文本清理
cleaned = re.sub(r'[^\w\s]', ' ', inquiry)
cleaned = ' '.join(cleaned.split())
# 2. 敏感信息脱敏
cleaned = self._mask_sensitive_info(cleaned)
# 3. 标准化处理
cleaned = cleaned.lower().strip()
return cleaned
async def _apply_classification_rules(self, inquiry: str) -> ClassificationResult:
"""应用分类规则引擎"""
# 关键词匹配规则
for category, rules in self.classification_rules.items():
for rule in rules['keywords']:
if rule['pattern'] in inquiry:
return ClassificationResult(
category=category,
confidence=rule['confidence'],
matched_rule=rule['pattern'],
urgency=rules.get('default_urgency', 'normal')
)
# 默认分类
return ClassificationResult(
category='general',
confidence=0.3,
matched_rule='default',
urgency='normal'
)
async def _llm_classify(self, inquiry: str) -> ClassificationResult:
"""使用LLM进行智能分类"""
classification_prompt = f"""
请分析以下客户咨询,并分类到合适的类别:
咨询内容: {inquiry}
可选类别:
- faq: 常见问题
- technical: 技术支持
- billing: 账单问题
- complaint: 投诉建议
- sales: 销售咨询
- general: 一般咨询
请以JSON格式返回分类结果,包含:
- category: 分类类别
- confidence: 置信度 (0-1)
- reasoning: 分类理由
- urgency: 紧急程度 (low/normal/high/critical)
"""
response = await self.model_client.create([
SystemMessage("你是专业的客服分类专家,能够准确识别客户需求类型"),
UserMessage(classification_prompt)
])
# 解析LLM响应
try:
result_data = json.loads(response.content)
return ClassificationResult(
category=result_data['category'],
confidence=result_data['confidence'],
reasoning=result_data['reasoning'],
urgency=result_data['urgency']
)
except Exception as e:
logger.warning(f"LLM分类结果解析失败: {e}")
return ClassificationResult(category='general', confidence=0.5)
|