feat: 增强 Agent 系统和完善项目结构

主要改进:
- Agent 增强: 订单查询、售后支持、客服路由等功能优化
- 新增语言检测和 Token 管理模块
- 改进 Chatwoot webhook 处理和用户标识
- MCP 服务器增强: 订单 MCP 和 Strapi MCP 功能扩展
- 新增商城客户端、知识库、缓存和同步模块
- 添加多语言提示词系统 (YAML)
- 完善项目结构: 整理文档、脚本和测试文件
- 新增调试和测试工具脚本

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
wangliang
2026-01-16 16:28:47 +08:00
parent 0e59f3067e
commit e093995368
48 changed files with 5263 additions and 395 deletions

View File

@@ -6,109 +6,20 @@ 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 prompts import get_prompt
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
"""
@@ -117,34 +28,70 @@ async def aftersale_agent(state: AgentState) -> AgentState:
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)
# Get detected language
locale = state.get("detected_language", "en")
# Auto-query FAQ for return-related questions
message_lower = state["current_message"].lower()
faq_keywords = ["return", "refund", "defective", "exchange", "complaint", "damaged", "wrong", "missing"]
# 如果消息包含退货相关关键词,且没有工具调用记录,自动查询 FAQ
if any(keyword in message_lower for keyword in faq_keywords):
# 检查是否已经查询过 FAQ
tool_calls = state.get("tool_calls", [])
has_faq_query = any(tc.get("tool_name") in ["query_faq", "search_knowledge_base"] for tc in tool_calls)
if not has_faq_query:
logger.info(
"Auto-querying FAQ for return-related question",
conversation_id=state["conversation_id"]
)
# 自动添加 FAQ 工具调用
state = add_tool_call(
state,
tool_name="query_faq",
arguments={
"category": "return",
"locale": locale,
"limit": 5
},
server="strapi"
)
state["state"] = ConversationState.TOOL_CALLING.value
return state
# Build messages for LLM
# Load prompt in detected language
system_prompt = get_prompt("aftersale", locale)
messages = [
Message(role="system", content=AFTERSALE_AGENT_PROMPT),
Message(role="system", content=system_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"
context_info = f"User ID: {state['user_id']}\nAccount ID: {state['account_id']}\n"
if state["entities"]:
context_info += f"已提取的信息: {json.dumps(state['entities'], ensure_ascii=False)}\n"
context_info += f"Extracted entities: {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']}"
context_info += f"Conversation context: {json.dumps(state['context'], ensure_ascii=False)}\n"
user_content = f"{context_info}\nUser message: {state['current_message']}"
messages.append(Message(role="user", content=user_content))
try:
@@ -206,46 +153,46 @@ async def aftersale_agent(state: AgentState) -> AgentState:
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)}")
tool_context.append(f"Tool {result['tool_name']} returned:\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"""基于以下售后系统返回的信息,生成对用户的回复。
tool_context.append(f"Tool {result['tool_name']} failed: {result['error']}")
用户问题: {state["current_message"]}
prompt = f"""Based on the following aftersale system information, generate a response to the user.
系统返回信息:
User question: {state["current_message"]}
System returned information:
{chr(10).join(tool_context)}
请生成一个体贴、专业的回复:
- 如果是申请提交成功,告知用户售后单号和后续流程
- 如果是状态查询,清晰说明当前进度
- 如果申请失败,说明原因并提供解决方案
- 对用户的问题表示理解
Please generate a compassionate and professional response:
- If application submitted successfully, inform user of aftersale ID and next steps
- If status query, clearly explain current progress
- If application failed, explain reason and provide solution
- Show understanding for user's issue
Return only the response content, do not return JSON."""
只返回回复内容,不要返回 JSON。"""
messages = [
Message(role="system", content="你是一个专业的售后客服助手,请根据系统返回的信息回答用户的售后问题。"),
Message(role="system", content="You are a professional aftersale service assistant, please answer user's aftersale questions based on system returned information."),
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, "抱歉,处理售后请求时遇到问题。请稍后重试或联系人工客服。")
state = set_response(state, "Sorry, there was a problem processing your aftersale request. Please try again later or contact customer support.")
return state