feat: 初始化 B2B AI Shopping Assistant 项目
- 配置 Docker Compose 多服务编排 - 实现 Chatwoot + Agent 集成 - 配置 Strapi MCP 知识库 - 支持 7 种语言的 FAQ 系统 - 实现 LangGraph AI 工作流 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
15
agent/agents/__init__.py
Normal file
15
agent/agents/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""Agents package"""
|
||||
from .router import classify_intent, route_by_intent
|
||||
from .customer_service import customer_service_agent
|
||||
from .order import order_agent
|
||||
from .aftersale import aftersale_agent
|
||||
from .product import product_agent
|
||||
|
||||
__all__ = [
|
||||
"classify_intent",
|
||||
"route_by_intent",
|
||||
"customer_service_agent",
|
||||
"order_agent",
|
||||
"aftersale_agent",
|
||||
"product_agent",
|
||||
]
|
||||
251
agent/agents/aftersale.py
Normal file
251
agent/agents/aftersale.py
Normal file
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
Aftersale Agent - Handles returns, exchanges, and complaints
|
||||
"""
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from core.state import AgentState, ConversationState, add_tool_call, set_response, update_context
|
||||
from core.llm import get_llm_client, Message
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
AFTERSALE_AGENT_PROMPT = """你是一个专业的 B2B 售后服务助手。
|
||||
你的职责是帮助用户处理售后问题,包括:
|
||||
- 退货申请
|
||||
- 换货申请
|
||||
- 投诉处理
|
||||
- 工单创建
|
||||
- 售后进度查询
|
||||
|
||||
## 可用工具
|
||||
|
||||
1. **apply_return** - 退货申请
|
||||
- order_id: 订单号
|
||||
- items: 退货商品列表 [{item_id, quantity, reason}]
|
||||
- description: 问题描述
|
||||
- images: 图片URL列表(可选)
|
||||
|
||||
2. **apply_exchange** - 换货申请
|
||||
- order_id: 订单号
|
||||
- items: 换货商品列表 [{item_id, reason}]
|
||||
- description: 问题描述
|
||||
|
||||
3. **create_complaint** - 创建投诉
|
||||
- type: 投诉类型(product_quality/service/logistics/other)
|
||||
- title: 投诉标题
|
||||
- description: 详细描述
|
||||
- related_order_id: 关联订单号(可选)
|
||||
- attachments: 附件URL列表(可选)
|
||||
|
||||
4. **create_ticket** - 创建工单
|
||||
- category: 工单类别
|
||||
- priority: 优先级(low/medium/high/urgent)
|
||||
- title: 工单标题
|
||||
- description: 详细描述
|
||||
|
||||
5. **query_aftersale_status** - 查询售后状态
|
||||
- aftersale_id: 售后单号(可选,不填查询全部)
|
||||
|
||||
## 工具调用格式
|
||||
|
||||
当需要使用工具时,请返回 JSON 格式:
|
||||
```json
|
||||
{
|
||||
"action": "call_tool",
|
||||
"tool_name": "工具名称",
|
||||
"arguments": {
|
||||
"参数名": "参数值"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当需要向用户询问更多信息时:
|
||||
```json
|
||||
{
|
||||
"action": "ask_info",
|
||||
"question": "需要询问的问题",
|
||||
"required_fields": ["需要收集的字段列表"]
|
||||
}
|
||||
```
|
||||
|
||||
当可以直接回答时:
|
||||
```json
|
||||
{
|
||||
"action": "respond",
|
||||
"response": "回复内容"
|
||||
}
|
||||
```
|
||||
|
||||
## 售后流程引导
|
||||
|
||||
退货流程:
|
||||
1. 确认订单号和退货商品
|
||||
2. 了解退货原因
|
||||
3. 收集问题描述和图片(质量问题时)
|
||||
4. 提交退货申请
|
||||
5. 告知用户后续流程
|
||||
|
||||
换货流程:
|
||||
1. 确认订单号和换货商品
|
||||
2. 了解换货原因
|
||||
3. 确认是否有库存
|
||||
4. 提交换货申请
|
||||
|
||||
## 注意事项
|
||||
- 售后申请需要完整信息才能提交
|
||||
- 对用户的问题要表示理解和歉意
|
||||
- 复杂投诉建议转人工处理
|
||||
- 金额较大的退款需要特别确认
|
||||
"""
|
||||
|
||||
|
||||
async def aftersale_agent(state: AgentState) -> AgentState:
|
||||
"""Aftersale agent node
|
||||
|
||||
Handles returns, exchanges, complaints and aftersale queries.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Updated state with tool calls or response
|
||||
"""
|
||||
logger.info(
|
||||
"Aftersale agent processing",
|
||||
conversation_id=state["conversation_id"],
|
||||
sub_intent=state.get("sub_intent")
|
||||
)
|
||||
|
||||
state["current_agent"] = "aftersale"
|
||||
state["agent_history"].append("aftersale")
|
||||
state["state"] = ConversationState.PROCESSING.value
|
||||
|
||||
# Check if we have tool results to process
|
||||
if state["tool_results"]:
|
||||
return await _generate_aftersale_response(state)
|
||||
|
||||
# Build messages for LLM
|
||||
messages = [
|
||||
Message(role="system", content=AFTERSALE_AGENT_PROMPT),
|
||||
]
|
||||
|
||||
# Add conversation history
|
||||
for msg in state["messages"][-8:]: # More history for aftersale context
|
||||
messages.append(Message(role=msg["role"], content=msg["content"]))
|
||||
|
||||
# Build context info
|
||||
context_info = f"用户ID: {state['user_id']}\n账户ID: {state['account_id']}\n"
|
||||
|
||||
if state["entities"]:
|
||||
context_info += f"已提取的信息: {json.dumps(state['entities'], ensure_ascii=False)}\n"
|
||||
|
||||
if state["context"]:
|
||||
context_info += f"会话上下文: {json.dumps(state['context'], ensure_ascii=False)}\n"
|
||||
|
||||
user_content = f"{context_info}\n用户消息: {state['current_message']}"
|
||||
messages.append(Message(role="user", content=user_content))
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.5)
|
||||
|
||||
# Parse response
|
||||
content = response.content.strip()
|
||||
if content.startswith("```"):
|
||||
content = content.split("```")[1]
|
||||
if content.startswith("json"):
|
||||
content = content[4:]
|
||||
|
||||
result = json.loads(content)
|
||||
action = result.get("action")
|
||||
|
||||
if action == "call_tool":
|
||||
arguments = result.get("arguments", {})
|
||||
arguments["user_id"] = state["user_id"]
|
||||
|
||||
# Use entity if available
|
||||
if "order_id" not in arguments and state["entities"].get("order_id"):
|
||||
arguments["order_id"] = state["entities"]["order_id"]
|
||||
|
||||
state = add_tool_call(
|
||||
state,
|
||||
tool_name=result["tool_name"],
|
||||
arguments=arguments,
|
||||
server="aftersale"
|
||||
)
|
||||
state["state"] = ConversationState.TOOL_CALLING.value
|
||||
|
||||
elif action == "ask_info":
|
||||
state = set_response(state, result["question"])
|
||||
state["state"] = ConversationState.AWAITING_INFO.value
|
||||
# Store required fields in context for next iteration
|
||||
if result.get("required_fields"):
|
||||
state = update_context(state, {"required_fields": result["required_fields"]})
|
||||
|
||||
elif action == "respond":
|
||||
state = set_response(state, result["response"])
|
||||
state["state"] = ConversationState.GENERATING.value
|
||||
|
||||
elif action == "handoff":
|
||||
state["requires_human"] = True
|
||||
state["handoff_reason"] = result.get("reason", "Complex aftersale issue")
|
||||
|
||||
return state
|
||||
|
||||
except json.JSONDecodeError:
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Aftersale agent failed", error=str(e))
|
||||
state["error"] = str(e)
|
||||
return state
|
||||
|
||||
|
||||
async def _generate_aftersale_response(state: AgentState) -> AgentState:
|
||||
"""Generate response based on aftersale tool results"""
|
||||
|
||||
tool_context = []
|
||||
for result in state["tool_results"]:
|
||||
if result["success"]:
|
||||
data = result["data"]
|
||||
tool_context.append(f"工具 {result['tool_name']} 返回:\n{json.dumps(data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
# Extract aftersale_id for context
|
||||
if isinstance(data, dict) and data.get("aftersale_id"):
|
||||
state = update_context(state, {"aftersale_id": data["aftersale_id"]})
|
||||
else:
|
||||
tool_context.append(f"工具 {result['tool_name']} 执行失败: {result['error']}")
|
||||
|
||||
prompt = f"""基于以下售后系统返回的信息,生成对用户的回复。
|
||||
|
||||
用户问题: {state["current_message"]}
|
||||
|
||||
系统返回信息:
|
||||
{chr(10).join(tool_context)}
|
||||
|
||||
请生成一个体贴、专业的回复:
|
||||
- 如果是申请提交成功,告知用户售后单号和后续流程
|
||||
- 如果是状态查询,清晰说明当前进度
|
||||
- 如果申请失败,说明原因并提供解决方案
|
||||
- 对用户的问题表示理解
|
||||
|
||||
只返回回复内容,不要返回 JSON。"""
|
||||
|
||||
messages = [
|
||||
Message(role="system", content="你是一个专业的售后客服助手,请根据系统返回的信息回答用户的售后问题。"),
|
||||
Message(role="user", content=prompt)
|
||||
]
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Aftersale response generation failed", error=str(e))
|
||||
state = set_response(state, "抱歉,处理售后请求时遇到问题。请稍后重试或联系人工客服。")
|
||||
return state
|
||||
187
agent/agents/customer_service.py
Normal file
187
agent/agents/customer_service.py
Normal file
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Customer Service Agent - Handles FAQ and general inquiries
|
||||
"""
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from core.state import AgentState, ConversationState, add_tool_call, set_response
|
||||
from core.llm import get_llm_client, Message
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
CUSTOMER_SERVICE_PROMPT = """你是一个专业的 B2B 购物网站客服助手。
|
||||
你的职责是回答用户的一般性问题,包括:
|
||||
- 常见问题解答 (FAQ)
|
||||
- 公司信息查询
|
||||
- 政策咨询(退换货政策、隐私政策等)
|
||||
- 产品使用指南
|
||||
- 其他一般性咨询
|
||||
|
||||
## 可用工具
|
||||
|
||||
你可以使用以下工具获取信息:
|
||||
1. **query_faq** - 搜索 FAQ 常见问题
|
||||
- query: 搜索关键词
|
||||
- category: 分类(可选)
|
||||
|
||||
2. **get_company_info** - 获取公司信息
|
||||
- section: 信息类别(about_us, contact, etc.)
|
||||
|
||||
3. **get_policy** - 获取政策文档
|
||||
- policy_type: 政策类型(return_policy, privacy_policy, etc.)
|
||||
|
||||
## 工具调用格式
|
||||
|
||||
当需要使用工具时,请返回 JSON 格式:
|
||||
```json
|
||||
{
|
||||
"action": "call_tool",
|
||||
"tool_name": "工具名称",
|
||||
"arguments": {
|
||||
"参数名": "参数值"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当可以直接回答时,请返回:
|
||||
```json
|
||||
{
|
||||
"action": "respond",
|
||||
"response": "回复内容"
|
||||
}
|
||||
```
|
||||
|
||||
当需要转人工时,请返回:
|
||||
```json
|
||||
{
|
||||
"action": "handoff",
|
||||
"reason": "转人工原因"
|
||||
}
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
- 保持专业、友好的语气
|
||||
- 如果不确定答案,建议用户联系人工客服
|
||||
- 不要编造信息,只使用工具返回的数据
|
||||
"""
|
||||
|
||||
|
||||
async def customer_service_agent(state: AgentState) -> AgentState:
|
||||
"""Customer service agent node
|
||||
|
||||
Handles FAQ, company info, and general inquiries using Strapi MCP tools.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Updated state with tool calls or response
|
||||
"""
|
||||
logger.info(
|
||||
"Customer service agent processing",
|
||||
conversation_id=state["conversation_id"]
|
||||
)
|
||||
|
||||
state["current_agent"] = "customer_service"
|
||||
state["agent_history"].append("customer_service")
|
||||
state["state"] = ConversationState.PROCESSING.value
|
||||
|
||||
# Check if we have tool results to process
|
||||
if state["tool_results"]:
|
||||
return await _generate_response_from_results(state)
|
||||
|
||||
# Build messages for LLM
|
||||
messages = [
|
||||
Message(role="system", content=CUSTOMER_SERVICE_PROMPT),
|
||||
]
|
||||
|
||||
# Add conversation history
|
||||
for msg in state["messages"][-6:]:
|
||||
messages.append(Message(role=msg["role"], content=msg["content"]))
|
||||
|
||||
# Add current message
|
||||
messages.append(Message(role="user", content=state["current_message"]))
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
|
||||
# Parse response
|
||||
content = response.content.strip()
|
||||
if content.startswith("```"):
|
||||
content = content.split("```")[1]
|
||||
if content.startswith("json"):
|
||||
content = content[4:]
|
||||
|
||||
result = json.loads(content)
|
||||
action = result.get("action")
|
||||
|
||||
if action == "call_tool":
|
||||
# Add tool call to state
|
||||
state = add_tool_call(
|
||||
state,
|
||||
tool_name=result["tool_name"],
|
||||
arguments=result.get("arguments", {}),
|
||||
server="strapi"
|
||||
)
|
||||
state["state"] = ConversationState.TOOL_CALLING.value
|
||||
|
||||
elif action == "respond":
|
||||
state = set_response(state, result["response"])
|
||||
state["state"] = ConversationState.GENERATING.value
|
||||
|
||||
elif action == "handoff":
|
||||
state["requires_human"] = True
|
||||
state["handoff_reason"] = result.get("reason", "User request")
|
||||
|
||||
return state
|
||||
|
||||
except json.JSONDecodeError:
|
||||
# LLM returned plain text, use as response
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Customer service agent failed", error=str(e))
|
||||
state["error"] = str(e)
|
||||
return state
|
||||
|
||||
|
||||
async def _generate_response_from_results(state: AgentState) -> AgentState:
|
||||
"""Generate response based on tool results"""
|
||||
|
||||
# Build context from tool results
|
||||
tool_context = []
|
||||
for result in state["tool_results"]:
|
||||
if result["success"]:
|
||||
tool_context.append(f"工具 {result['tool_name']} 返回:\n{json.dumps(result['data'], ensure_ascii=False, indent=2)}")
|
||||
else:
|
||||
tool_context.append(f"工具 {result['tool_name']} 执行失败: {result['error']}")
|
||||
|
||||
prompt = f"""基于以下工具返回的信息,生成对用户的回复。
|
||||
|
||||
用户问题: {state["current_message"]}
|
||||
|
||||
工具返回信息:
|
||||
{chr(10).join(tool_context)}
|
||||
|
||||
请生成一个友好、专业的回复。如果工具没有返回有用信息,请诚实告知用户并建议其他方式获取帮助。
|
||||
只返回回复内容,不要返回 JSON。"""
|
||||
|
||||
messages = [
|
||||
Message(role="system", content="你是一个专业的 B2B 客服助手,请根据工具返回的信息回答用户问题。"),
|
||||
Message(role="user", content=prompt)
|
||||
]
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Response generation failed", error=str(e))
|
||||
state = set_response(state, "抱歉,处理您的请求时遇到问题。请稍后重试或联系人工客服。")
|
||||
return state
|
||||
231
agent/agents/order.py
Normal file
231
agent/agents/order.py
Normal file
@@ -0,0 +1,231 @@
|
||||
"""
|
||||
Order Agent - Handles order-related queries and operations
|
||||
"""
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from core.state import AgentState, ConversationState, add_tool_call, set_response, update_context
|
||||
from core.llm import get_llm_client, Message
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
ORDER_AGENT_PROMPT = """你是一个专业的 B2B 订单服务助手。
|
||||
你的职责是帮助用户处理订单相关的问题,包括:
|
||||
- 订单查询
|
||||
- 物流跟踪
|
||||
- 订单修改
|
||||
- 订单取消
|
||||
- 发票获取
|
||||
|
||||
## 可用工具
|
||||
|
||||
1. **query_order** - 查询订单
|
||||
- order_id: 订单号(可选,不填则查询最近订单)
|
||||
- date_start: 开始日期(可选)
|
||||
- date_end: 结束日期(可选)
|
||||
- status: 订单状态(可选)
|
||||
|
||||
2. **track_logistics** - 物流跟踪
|
||||
- order_id: 订单号
|
||||
- tracking_number: 物流单号(可选)
|
||||
|
||||
3. **modify_order** - 修改订单
|
||||
- order_id: 订单号
|
||||
- modifications: 修改内容(address/items/quantity 等)
|
||||
|
||||
4. **cancel_order** - 取消订单
|
||||
- order_id: 订单号
|
||||
- reason: 取消原因
|
||||
|
||||
5. **get_invoice** - 获取发票
|
||||
- order_id: 订单号
|
||||
- invoice_type: 发票类型(normal/vat)
|
||||
|
||||
## 工具调用格式
|
||||
|
||||
当需要使用工具时,请返回 JSON 格式:
|
||||
```json
|
||||
{
|
||||
"action": "call_tool",
|
||||
"tool_name": "工具名称",
|
||||
"arguments": {
|
||||
"参数名": "参数值"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当需要向用户询问更多信息时:
|
||||
```json
|
||||
{
|
||||
"action": "ask_info",
|
||||
"question": "需要询问的问题"
|
||||
}
|
||||
```
|
||||
|
||||
当可以直接回答时:
|
||||
```json
|
||||
{
|
||||
"action": "respond",
|
||||
"response": "回复内容"
|
||||
}
|
||||
```
|
||||
|
||||
## 重要提示
|
||||
- 订单修改和取消是敏感操作,需要确认订单号
|
||||
- 如果用户没有提供订单号,先查询他的最近订单
|
||||
- 物流查询需要订单号或物流单号
|
||||
- 对于批量操作或大金额订单,建议转人工处理
|
||||
"""
|
||||
|
||||
|
||||
async def order_agent(state: AgentState) -> AgentState:
|
||||
"""Order agent node
|
||||
|
||||
Handles order queries, tracking, modifications, and cancellations.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Updated state with tool calls or response
|
||||
"""
|
||||
logger.info(
|
||||
"Order agent processing",
|
||||
conversation_id=state["conversation_id"],
|
||||
sub_intent=state.get("sub_intent")
|
||||
)
|
||||
|
||||
state["current_agent"] = "order"
|
||||
state["agent_history"].append("order")
|
||||
state["state"] = ConversationState.PROCESSING.value
|
||||
|
||||
# Check if we have tool results to process
|
||||
if state["tool_results"]:
|
||||
return await _generate_order_response(state)
|
||||
|
||||
# Build messages for LLM
|
||||
messages = [
|
||||
Message(role="system", content=ORDER_AGENT_PROMPT),
|
||||
]
|
||||
|
||||
# Add conversation history
|
||||
for msg in state["messages"][-6:]:
|
||||
messages.append(Message(role=msg["role"], content=msg["content"]))
|
||||
|
||||
# Build context info
|
||||
context_info = f"用户ID: {state['user_id']}\n账户ID: {state['account_id']}\n"
|
||||
|
||||
# Add entities if available
|
||||
if state["entities"]:
|
||||
context_info += f"已提取的信息: {json.dumps(state['entities'], ensure_ascii=False)}\n"
|
||||
|
||||
# Add existing context
|
||||
if state["context"].get("order_id"):
|
||||
context_info += f"当前讨论的订单号: {state['context']['order_id']}\n"
|
||||
|
||||
user_content = f"{context_info}\n用户消息: {state['current_message']}"
|
||||
messages.append(Message(role="user", content=user_content))
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.5)
|
||||
|
||||
# Parse response
|
||||
content = response.content.strip()
|
||||
if content.startswith("```"):
|
||||
content = content.split("```")[1]
|
||||
if content.startswith("json"):
|
||||
content = content[4:]
|
||||
|
||||
result = json.loads(content)
|
||||
action = result.get("action")
|
||||
|
||||
if action == "call_tool":
|
||||
# Inject user context into arguments
|
||||
arguments = result.get("arguments", {})
|
||||
arguments["user_id"] = state["user_id"]
|
||||
arguments["account_id"] = state["account_id"]
|
||||
|
||||
# Use entity if available
|
||||
if "order_id" not in arguments and state["entities"].get("order_id"):
|
||||
arguments["order_id"] = state["entities"]["order_id"]
|
||||
|
||||
state = add_tool_call(
|
||||
state,
|
||||
tool_name=result["tool_name"],
|
||||
arguments=arguments,
|
||||
server="order"
|
||||
)
|
||||
state["state"] = ConversationState.TOOL_CALLING.value
|
||||
|
||||
elif action == "ask_info":
|
||||
state = set_response(state, result["question"])
|
||||
state["state"] = ConversationState.AWAITING_INFO.value
|
||||
|
||||
elif action == "respond":
|
||||
state = set_response(state, result["response"])
|
||||
state["state"] = ConversationState.GENERATING.value
|
||||
|
||||
elif action == "handoff":
|
||||
state["requires_human"] = True
|
||||
state["handoff_reason"] = result.get("reason", "Complex order operation")
|
||||
|
||||
return state
|
||||
|
||||
except json.JSONDecodeError:
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Order agent failed", error=str(e))
|
||||
state["error"] = str(e)
|
||||
return state
|
||||
|
||||
|
||||
async def _generate_order_response(state: AgentState) -> AgentState:
|
||||
"""Generate response based on order tool results"""
|
||||
|
||||
# Build context from tool results
|
||||
tool_context = []
|
||||
for result in state["tool_results"]:
|
||||
if result["success"]:
|
||||
data = result["data"]
|
||||
tool_context.append(f"工具 {result['tool_name']} 返回:\n{json.dumps(data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
# Extract order_id for context
|
||||
if isinstance(data, dict):
|
||||
if data.get("order_id"):
|
||||
state = update_context(state, {"order_id": data["order_id"]})
|
||||
elif data.get("orders") and len(data["orders"]) > 0:
|
||||
state = update_context(state, {"order_id": data["orders"][0].get("order_id")})
|
||||
else:
|
||||
tool_context.append(f"工具 {result['tool_name']} 执行失败: {result['error']}")
|
||||
|
||||
prompt = f"""基于以下订单系统返回的信息,生成对用户的回复。
|
||||
|
||||
用户问题: {state["current_message"]}
|
||||
|
||||
系统返回信息:
|
||||
{chr(10).join(tool_context)}
|
||||
|
||||
请生成一个清晰、友好的回复,包含订单的关键信息(订单号、状态、金额、物流等)。
|
||||
如果是物流信息,请按时间线整理展示。
|
||||
只返回回复内容,不要返回 JSON。"""
|
||||
|
||||
messages = [
|
||||
Message(role="system", content="你是一个专业的订单客服助手,请根据系统返回的信息回答用户的订单问题。"),
|
||||
Message(role="user", content=prompt)
|
||||
]
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Order response generation failed", error=str(e))
|
||||
state = set_response(state, "抱歉,处理订单信息时遇到问题。请稍后重试或联系人工客服。")
|
||||
return state
|
||||
256
agent/agents/product.py
Normal file
256
agent/agents/product.py
Normal file
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
Product Agent - Handles product search, recommendations, and quotes
|
||||
"""
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from core.state import AgentState, ConversationState, add_tool_call, set_response, update_context
|
||||
from core.llm import get_llm_client, Message
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
PRODUCT_AGENT_PROMPT = """你是一个专业的 B2B 商品顾问助手。
|
||||
你的职责是帮助用户找到合适的商品,包括:
|
||||
- 商品搜索
|
||||
- 智能推荐
|
||||
- B2B 询价
|
||||
- 库存查询
|
||||
- 商品详情
|
||||
|
||||
## 可用工具
|
||||
|
||||
1. **search_products** - 搜索商品
|
||||
- query: 搜索关键词
|
||||
- filters: 过滤条件(category, price_range, brand 等)
|
||||
- sort: 排序方式(price_asc/price_desc/sales/latest)
|
||||
- page: 页码
|
||||
- page_size: 每页数量
|
||||
|
||||
2. **get_product_detail** - 获取商品详情
|
||||
- product_id: 商品ID
|
||||
|
||||
3. **recommend_products** - 智能推荐
|
||||
- context: 推荐上下文(可包含当前查询、浏览历史等)
|
||||
- limit: 推荐数量
|
||||
|
||||
4. **get_quote** - B2B 询价
|
||||
- product_id: 商品ID
|
||||
- quantity: 采购数量
|
||||
- delivery_address: 收货地址(可选,用于计算运费)
|
||||
|
||||
5. **check_inventory** - 库存查询
|
||||
- product_ids: 商品ID列表
|
||||
- warehouse: 仓库(可选)
|
||||
|
||||
## 工具调用格式
|
||||
|
||||
当需要使用工具时,请返回 JSON 格式:
|
||||
```json
|
||||
{
|
||||
"action": "call_tool",
|
||||
"tool_name": "工具名称",
|
||||
"arguments": {
|
||||
"参数名": "参数值"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当需要向用户询问更多信息时:
|
||||
```json
|
||||
{
|
||||
"action": "ask_info",
|
||||
"question": "需要询问的问题"
|
||||
}
|
||||
```
|
||||
|
||||
当可以直接回答时:
|
||||
```json
|
||||
{
|
||||
"action": "respond",
|
||||
"response": "回复内容"
|
||||
}
|
||||
```
|
||||
|
||||
## B2B 询价特点
|
||||
- 大批量采购通常有阶梯价格
|
||||
- 可能需要考虑运费
|
||||
- 企业客户可能有专属折扣
|
||||
- 报价通常有有效期
|
||||
|
||||
## 商品推荐策略
|
||||
- 根据用户采购历史推荐
|
||||
- 根据当前查询语义推荐
|
||||
- 根据企业行业特点推荐
|
||||
- 根据季节性和热门商品推荐
|
||||
|
||||
## 注意事项
|
||||
- 帮助用户准确描述需求
|
||||
- 如果搜索结果太多,建议用户缩小范围
|
||||
- 询价时确认数量,因为会影响价格
|
||||
- 库存紧张时及时告知用户
|
||||
"""
|
||||
|
||||
|
||||
async def product_agent(state: AgentState) -> AgentState:
|
||||
"""Product agent node
|
||||
|
||||
Handles product search, recommendations, quotes and inventory queries.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Updated state with tool calls or response
|
||||
"""
|
||||
logger.info(
|
||||
"Product agent processing",
|
||||
conversation_id=state["conversation_id"],
|
||||
sub_intent=state.get("sub_intent")
|
||||
)
|
||||
|
||||
state["current_agent"] = "product"
|
||||
state["agent_history"].append("product")
|
||||
state["state"] = ConversationState.PROCESSING.value
|
||||
|
||||
# Check if we have tool results to process
|
||||
if state["tool_results"]:
|
||||
return await _generate_product_response(state)
|
||||
|
||||
# Build messages for LLM
|
||||
messages = [
|
||||
Message(role="system", content=PRODUCT_AGENT_PROMPT),
|
||||
]
|
||||
|
||||
# Add conversation history
|
||||
for msg in state["messages"][-6:]:
|
||||
messages.append(Message(role=msg["role"], content=msg["content"]))
|
||||
|
||||
# Build context info
|
||||
context_info = f"用户ID: {state['user_id']}\n账户ID: {state['account_id']}\n"
|
||||
|
||||
if state["entities"]:
|
||||
context_info += f"已提取的信息: {json.dumps(state['entities'], ensure_ascii=False)}\n"
|
||||
|
||||
if state["context"].get("product_id"):
|
||||
context_info += f"当前讨论的商品ID: {state['context']['product_id']}\n"
|
||||
|
||||
if state["context"].get("recent_searches"):
|
||||
context_info += f"最近搜索: {state['context']['recent_searches']}\n"
|
||||
|
||||
user_content = f"{context_info}\n用户消息: {state['current_message']}"
|
||||
messages.append(Message(role="user", content=user_content))
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
|
||||
# Parse response
|
||||
content = response.content.strip()
|
||||
if content.startswith("```"):
|
||||
content = content.split("```")[1]
|
||||
if content.startswith("json"):
|
||||
content = content[4:]
|
||||
|
||||
result = json.loads(content)
|
||||
action = result.get("action")
|
||||
|
||||
if action == "call_tool":
|
||||
arguments = result.get("arguments", {})
|
||||
|
||||
# Inject context for recommendation
|
||||
if result["tool_name"] == "recommend_products":
|
||||
arguments["user_id"] = state["user_id"]
|
||||
arguments["account_id"] = state["account_id"]
|
||||
|
||||
# Inject context for quote
|
||||
if result["tool_name"] == "get_quote":
|
||||
arguments["account_id"] = state["account_id"]
|
||||
|
||||
# Use entity if available
|
||||
if "product_id" not in arguments and state["entities"].get("product_id"):
|
||||
arguments["product_id"] = state["entities"]["product_id"]
|
||||
|
||||
if "quantity" not in arguments and state["entities"].get("quantity"):
|
||||
arguments["quantity"] = state["entities"]["quantity"]
|
||||
|
||||
state = add_tool_call(
|
||||
state,
|
||||
tool_name=result["tool_name"],
|
||||
arguments=arguments,
|
||||
server="product"
|
||||
)
|
||||
state["state"] = ConversationState.TOOL_CALLING.value
|
||||
|
||||
elif action == "ask_info":
|
||||
state = set_response(state, result["question"])
|
||||
state["state"] = ConversationState.AWAITING_INFO.value
|
||||
|
||||
elif action == "respond":
|
||||
state = set_response(state, result["response"])
|
||||
state["state"] = ConversationState.GENERATING.value
|
||||
|
||||
return state
|
||||
|
||||
except json.JSONDecodeError:
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Product agent failed", error=str(e))
|
||||
state["error"] = str(e)
|
||||
return state
|
||||
|
||||
|
||||
async def _generate_product_response(state: AgentState) -> AgentState:
|
||||
"""Generate response based on product tool results"""
|
||||
|
||||
tool_context = []
|
||||
for result in state["tool_results"]:
|
||||
if result["success"]:
|
||||
data = result["data"]
|
||||
tool_context.append(f"工具 {result['tool_name']} 返回:\n{json.dumps(data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
# Extract product context
|
||||
if isinstance(data, dict):
|
||||
if data.get("product_id"):
|
||||
state = update_context(state, {"product_id": data["product_id"]})
|
||||
if data.get("products"):
|
||||
# Store recent search results
|
||||
product_ids = [p.get("product_id") for p in data["products"][:5]]
|
||||
state = update_context(state, {"recent_product_ids": product_ids})
|
||||
else:
|
||||
tool_context.append(f"工具 {result['tool_name']} 执行失败: {result['error']}")
|
||||
|
||||
prompt = f"""基于以下商品系统返回的信息,生成对用户的回复。
|
||||
|
||||
用户问题: {state["current_message"]}
|
||||
|
||||
系统返回信息:
|
||||
{chr(10).join(tool_context)}
|
||||
|
||||
请生成一个清晰、有帮助的回复:
|
||||
- 如果是搜索结果,展示商品名称、价格、规格等关键信息
|
||||
- 如果是询价结果,清晰说明单价、总价、折扣、有效期等
|
||||
- 如果是推荐商品,简要说明推荐理由
|
||||
- 如果是库存查询,告知可用数量和发货时间
|
||||
- 结果较多时可以总结关键信息
|
||||
|
||||
只返回回复内容,不要返回 JSON。"""
|
||||
|
||||
messages = [
|
||||
Message(role="system", content="你是一个专业的商品顾问,请根据系统返回的信息回答用户的商品问题。"),
|
||||
Message(role="user", content=prompt)
|
||||
]
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.7)
|
||||
state = set_response(state, response.content)
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Product response generation failed", error=str(e))
|
||||
state = set_response(state, "抱歉,处理商品信息时遇到问题。请稍后重试或联系人工客服。")
|
||||
return state
|
||||
220
agent/agents/router.py
Normal file
220
agent/agents/router.py
Normal file
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
Router Agent - Intent recognition and routing
|
||||
"""
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from core.state import AgentState, Intent, ConversationState, set_intent, add_entity
|
||||
from core.llm import get_llm_client, Message
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# Intent classification prompt
|
||||
CLASSIFICATION_PROMPT = """你是一个 B2B 购物网站的智能助手路由器。
|
||||
你的任务是分析用户消息,识别用户意图并提取关键实体。
|
||||
|
||||
## 可用意图分类
|
||||
|
||||
1. **customer_service** - 通用咨询
|
||||
- FAQ 问答
|
||||
- 产品使用问题
|
||||
- 公司信息查询
|
||||
- 政策咨询(退换货政策、隐私政策等)
|
||||
|
||||
2. **order** - 订单相关
|
||||
- 订单查询("我的订单在哪"、"查一下订单")
|
||||
- 物流跟踪("快递到哪了"、"什么时候到货")
|
||||
- 订单修改("改一下收货地址"、"修改订单数量")
|
||||
- 订单取消("取消订单"、"不想要了")
|
||||
- 发票查询("开发票"、"要发票")
|
||||
|
||||
3. **aftersale** - 售后服务
|
||||
- 退货申请("退货"、"不满意想退")
|
||||
- 换货申请("换货"、"换一个")
|
||||
- 投诉("投诉"、"服务态度差")
|
||||
- 工单/问题反馈
|
||||
|
||||
4. **product** - 商品相关
|
||||
- 商品搜索("有没有xx"、"找一下xx")
|
||||
- 商品推荐("推荐"、"有什么好的")
|
||||
- 询价("多少钱"、"批发价"、"大量购买价格")
|
||||
- 库存查询("有货吗"、"还有多少")
|
||||
|
||||
5. **human_handoff** - 需要转人工
|
||||
- 用户明确要求转人工
|
||||
- 复杂问题 AI 无法处理
|
||||
- 敏感问题需要人工处理
|
||||
|
||||
## 实体提取
|
||||
|
||||
请从消息中提取以下实体(如果存在):
|
||||
- order_id: 订单号(如 ORD123456)
|
||||
- product_id: 商品ID
|
||||
- product_name: 商品名称
|
||||
- quantity: 数量
|
||||
- date_reference: 时间引用(今天、昨天、上周、具体日期等)
|
||||
- tracking_number: 物流单号
|
||||
- phone: 电话号码
|
||||
- address: 地址信息
|
||||
|
||||
## 输出格式
|
||||
|
||||
请以 JSON 格式返回,包含以下字段:
|
||||
```json
|
||||
{
|
||||
"intent": "意图分类",
|
||||
"confidence": 0.95,
|
||||
"sub_intent": "子意图(可选)",
|
||||
"entities": {
|
||||
"entity_type": "entity_value"
|
||||
},
|
||||
"reasoning": "简短的推理说明"
|
||||
}
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
- 如果意图不明确,置信度应该较低
|
||||
- 如果无法确定意图,返回 "unknown"
|
||||
- 实体提取要准确,没有的字段不要填写
|
||||
"""
|
||||
|
||||
|
||||
async def classify_intent(state: AgentState) -> AgentState:
|
||||
"""Classify user intent and extract entities
|
||||
|
||||
This is the first node in the workflow that analyzes the user's message
|
||||
and determines which agent should handle it.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Updated state with intent and entities
|
||||
"""
|
||||
logger.info(
|
||||
"Classifying intent",
|
||||
conversation_id=state["conversation_id"],
|
||||
message=state["current_message"][:100]
|
||||
)
|
||||
|
||||
state["state"] = ConversationState.CLASSIFYING.value
|
||||
state["step_count"] += 1
|
||||
|
||||
# Build context from conversation history
|
||||
context_summary = ""
|
||||
if state["context"]:
|
||||
context_parts = []
|
||||
if state["context"].get("order_id"):
|
||||
context_parts.append(f"当前讨论的订单: {state['context']['order_id']}")
|
||||
if state["context"].get("product_id"):
|
||||
context_parts.append(f"当前讨论的商品: {state['context']['product_id']}")
|
||||
if context_parts:
|
||||
context_summary = "\n".join(context_parts)
|
||||
|
||||
# Build messages for LLM
|
||||
messages = [
|
||||
Message(role="system", content=CLASSIFICATION_PROMPT),
|
||||
]
|
||||
|
||||
# Add recent conversation history for context
|
||||
for msg in state["messages"][-6:]: # Last 3 turns
|
||||
messages.append(Message(role=msg["role"], content=msg["content"]))
|
||||
|
||||
# Add current message with context
|
||||
user_content = f"用户消息: {state['current_message']}"
|
||||
if context_summary:
|
||||
user_content += f"\n\n当前上下文:\n{context_summary}"
|
||||
|
||||
messages.append(Message(role="user", content=user_content))
|
||||
|
||||
try:
|
||||
llm = get_llm_client()
|
||||
response = await llm.chat(messages, temperature=0.3)
|
||||
|
||||
# Parse JSON response
|
||||
content = response.content.strip()
|
||||
# Handle markdown code blocks
|
||||
if content.startswith("```"):
|
||||
content = content.split("```")[1]
|
||||
if content.startswith("json"):
|
||||
content = content[4:]
|
||||
|
||||
result = json.loads(content)
|
||||
|
||||
# Extract intent
|
||||
intent_str = result.get("intent", "unknown")
|
||||
try:
|
||||
intent = Intent(intent_str)
|
||||
except ValueError:
|
||||
intent = Intent.UNKNOWN
|
||||
|
||||
confidence = float(result.get("confidence", 0.5))
|
||||
sub_intent = result.get("sub_intent")
|
||||
|
||||
# Set intent in state
|
||||
state = set_intent(state, intent, confidence, sub_intent)
|
||||
|
||||
# Extract entities
|
||||
entities = result.get("entities", {})
|
||||
for entity_type, entity_value in entities.items():
|
||||
if entity_value:
|
||||
state = add_entity(state, entity_type, entity_value)
|
||||
|
||||
logger.info(
|
||||
"Intent classified",
|
||||
intent=intent.value,
|
||||
confidence=confidence,
|
||||
entities=list(entities.keys())
|
||||
)
|
||||
|
||||
# Check if human handoff is needed
|
||||
if intent == Intent.HUMAN_HANDOFF or confidence < 0.5:
|
||||
state["requires_human"] = True
|
||||
state["handoff_reason"] = result.get("reasoning", "Intent unclear")
|
||||
|
||||
return state
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error("Failed to parse intent response", error=str(e))
|
||||
state["intent"] = Intent.UNKNOWN.value
|
||||
state["intent_confidence"] = 0.0
|
||||
return state
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Intent classification failed", error=str(e))
|
||||
state["error"] = str(e)
|
||||
state["intent"] = Intent.UNKNOWN.value
|
||||
return state
|
||||
|
||||
|
||||
def route_by_intent(state: AgentState) -> str:
|
||||
"""Route to appropriate agent based on intent
|
||||
|
||||
This is the routing function used by conditional edges in the graph.
|
||||
|
||||
Args:
|
||||
state: Current agent state
|
||||
|
||||
Returns:
|
||||
Name of the next node to execute
|
||||
"""
|
||||
intent = state.get("intent")
|
||||
requires_human = state.get("requires_human", False)
|
||||
|
||||
# Human handoff takes priority
|
||||
if requires_human:
|
||||
return "human_handoff"
|
||||
|
||||
# Route based on intent
|
||||
routing_map = {
|
||||
Intent.CUSTOMER_SERVICE.value: "customer_service_agent",
|
||||
Intent.ORDER.value: "order_agent",
|
||||
Intent.AFTERSALE.value: "aftersale_agent",
|
||||
Intent.PRODUCT.value: "product_agent",
|
||||
Intent.HUMAN_HANDOFF.value: "human_handoff",
|
||||
Intent.UNKNOWN.value: "customer_service_agent" # Default to customer service
|
||||
}
|
||||
|
||||
return routing_map.get(intent, "customer_service_agent")
|
||||
Reference in New Issue
Block a user