This commit is contained in:
2026-03-06 14:39:42 +08:00
parent f06bfb1fa0
commit 3020ae4691
4 changed files with 197 additions and 11 deletions

View File

@@ -6,7 +6,7 @@ from pydantic import BaseModel, Field
from pydantic_ai import RunContext
from core.schema import StandardResponse
from services.dispatch_service import dispatch_service
from db.chat_log_db import get_conversation
from db.chat_log_db import get_conversation, get_customer_orders
logger = logging.getLogger("cs_agent")
@@ -35,9 +35,53 @@ async def transfer_to_human_tool(ctx: RunContext[Any], reason: str = Field(descr
return "ERROR_DESIGNER_BUSY设计师暂时不在位你告诉客户稍等马上帮忙联系设计师。不要说下班。"
async def check_order_status_tool(ctx: RunContext[Any], customer_id: str = Field(description="客户ID")) -> str:
"""查询订单状态。"""
return "我在帮你加急处理中,稍等哈。"
async def lookup_customer_orders_tool(
ctx: RunContext[Any],
customer_id: str = Field(description="客户ID从当前对话上下文中获取"),
) -> str:
"""
【订单查询工具】查询该客户的订单记录(订单号、状态、金额等)。
使用场景:
- 客户问"我的订单怎么样了""付款了""发货了吗"
- 客户提到订单号
- 需要确认客户是否已付款
返回该客户的所有订单及其状态。
"""
logger.info(f"[Tool] 查询客户订单: customer_id={customer_id}")
try:
rows = await asyncio.to_thread(get_customer_orders, customer_id, limit=10)
if not rows:
return f"该客户({customer_id})暂无订单记录。"
lines = []
for r in rows:
oid = r.get("order_id", "")
status = r.get("order_status", "")
amount = r.get("amount", 0)
qty = r.get("quantity", 0)
title = r.get("product_title", "")
note = r.get("buyer_note", "")
updated = str(r.get("updated_at", ""))
line = f"订单号:{oid} 状态:{status} 金额:{amount}元 数量:{qty} 商品:{title}"
if note:
line += f" 备注:{note}"
line += f" 更新时间:{updated}"
lines.append(line)
has_paid = any("已付款" in r.get("order_status", "") for r in rows)
has_shipped = any("已发货" in r.get("order_status", "") for r in rows)
summary_parts = [f"{len(rows)}条订单记录。"]
if has_paid:
summary_parts.append("客户已付款!")
if has_shipped:
summary_parts.append("已发货。")
summary = " ".join(summary_parts)
return f"【订单摘要】{summary}\n\n【订单详情】\n" + "\n".join(lines)
except Exception as e:
logger.error(f"[Tool] 查询订单失败: {e}")
return f"查询订单失败: {e}"
async def lookup_chat_history_tool(
@@ -92,6 +136,6 @@ async def lookup_chat_history_tool(
def register_agent_tools(agent: Any):
"""注册工具"""
agent.tool(transfer_to_human_tool)
agent.tool(check_order_status_tool)
agent.tool(lookup_chat_history_tool)
logger.info("[Agent] 工具箱已更新:含转人工、订单查询、历史记录查询。")
agent.tool(lookup_customer_orders_tool)
logger.info("[Agent] 工具箱已更新:含转人工、历史记录查询、订单查询。")

View File

@@ -123,13 +123,44 @@ class SystemOrchestrator:
async def _handle_order_packet(self, platform: str, msg: StandardMessage):
try:
price_match = re.search(r"订单金额:金额:\s*([\d\.]+)元", msg.content)
if price_match: await repo.update_task_price(platform, msg.user_id, float(price_match.group(1)))
# 判定成交结果(扩大范围:已付款 或 已发货 都视为成功,用于后期 AI 话术微调)
if any(k in msg.content for k in ["买家已付款", "卖家已发货"]):
from core.order_helpers import parse_order_info
from db.chat_log_db import upsert_order
content = msg.content or ""
info = parse_order_info(content)
price_match = re.search(r"金额[:]\s*([\d\.]+)\s*元", content)
if price_match:
await repo.update_task_price(platform, msg.user_id, float(price_match.group(1)))
if any(k in content for k in ["买家已付款", "卖家已发货"]):
await repo.update_task_outcome(platform, msg.user_id, "deal_success")
elif any(k in msg.content for k in ["退款", "已关闭", "已取消"]):
elif any(k in content for k in ["退款", "已关闭", "已取消"]):
await repo.update_task_outcome(platform, msg.user_id, "refunded")
# 结构化写入 customer_orders 表
order_id = info.get("order_id", "")
if order_id and msg.user_id and msg.user_id != "unknown":
title_match = re.search(r"商品标题[:]\s*([^\s]+(?:\s+[^\s订]+)*)", content)
product_title = title_match.group(1).strip() if title_match else ""
amount = float(info.get("amount", 0))
quantity = int(info.get("quantity", 0))
order_status = info.get("order_status", "")
buyer_note = info.get("buyer_note", "")
await asyncio.to_thread(
upsert_order,
customer_id=msg.user_id,
order_id=order_id,
order_status=order_status,
acc_id=msg.acc_id,
product_title=product_title,
amount=amount,
quantity=quantity,
buyer_note=buyer_note,
)
logger.info(f"[订单入库] user={msg.user_id} order={order_id} status={order_status} amount={amount}")
except Exception as e:
logger.warning(f"[Orchestrator] 订单消息处理异常: {e}")

View File

@@ -72,6 +72,14 @@ class CustomerServiceBrain:
"4. 【近期对话回顾】中显示客户之前已发过图或说过需求\n"
"查到历史后,根据历史内容回复,绝对不要再重复问客户已经回答过的问题!\n\n"
"【订单查询工具】\n"
"你有一个 lookup_customer_orders_tool 工具,可以查询客户的订单记录。\n"
"以下情况你【必须】调用此工具:\n"
"1. 客户问'我付款了''订单怎么样了''发货了吗'\n"
"2. 客户提到订单号\n"
"3. 你需要确认客户是否已付款再决定如何回复\n"
"查到订单后,根据订单状态回复(已付款→'收到,马上安排';已发货→'已经发了哈')。\n\n"
"【核心逻辑】\n"
"1. 业务:只聊高清修复和找原图。核心链路:引导发图 -> 问需求 -> 找设计师。\n"
"2. **主动引导**:只有当客户【从未发过图】且没有历史图片记录时,才引导发图。\n"