AI微信客服的本质,是在消息网关和发送接口之间插一个LLM推理层。用户消息进来→网关做去重和路由→LLM生成回复→发送接口回出去。WTAPI负责收发,大模型负责理解和生成,各管一段。这篇给出可直接落地的完整代码。
一、整体架构
用户消息 → Webhook → 消息队列 → 会话管理 → LLM推理 → 发送接口 → 用户关键点:消息收发和LLM推理解耦,中间靠会话管理层串联上下文。
二、LLM接入层
WTAPI官方文档提到支持接入ChatGPT、文心一言、自研NLP等大模型。用统一客户端封装,方便后续切换:
classLLMClient:def__init__(self,provider="chatgpt"):self.provider=providerdefchat(self,messages):ifself.provider=="chatgpt":returnself._chatgpt(messages)elifself.provider=="ernie":returnself._ernie(messages)# 其他自研NLP...def_chatgpt(self,messages):# 调用大模型接口,返回回复文本# 具体实现按所选模型的SDK文档pass三、会话上下文管理
多轮对话需要维护上下文,按instanceId:fromWxid存最近N轮消息:
importjson MAX_HISTORY=10# 保留最近10轮defget_history(instance_id,from_wxid):raw=redis.get(f"history:{instance_id}:{from_wxid}")returnjson.loads(raw)ifrawelse[]defappend_history(instance_id,from_wxid,role,content):history=get_history(instance_id,from_wxid)history.append({"role":role,"content":content})history=history[-MAX_HISTORY:]redis.setex(f"history:{instance_id}:{from_wxid}",3600,json.dumps(history,ensure_ascii=False),)四、完整处理流程
defhandle_ai_reply(instance_id,from_wxid,content):# 1. 加入用户消息到上下文append_history(instance_id,from_wxid,"user",content)# 2. 构造prompt(含系统人设)system_prompt="你是一个专业的客服,回答要简洁友好"messages=[{"role":"system","content":system_prompt}]messages+=get_history(instance_id,from_wxid)# 3. 调用LLMllm=LLMClient(provider="chatgpt")reply=llm.chat(messages)# 4. 加入助手回复到上下文append_history(instance_id,from_wxid,"assistant",reply)# 5. 发送回复requests.post(f"{BASE}/finder/v2/api/postText",headers=HEADERS,json={"appId":APP_ID,"instanceId":instance_id,"toWxid":from_wxid,"content":reply,},timeout=10,)五、生产环境的防护
AI客服直接面向用户,必须加防护:LLM调用设超时,超时回兜底话术,不让用户干等;LLM输出过一遍敏感词过滤,防止生成不当内容;用户连续3次说"人工"或LLM置信度低时转人工客服;会话超过1小时自动清空,避免上下文污染。
六、工具调用(进阶)
如果要让AI能查订单、查物流,需要给LLM加工具调用能力。但微信侧只负责消息收发,工具实现对接业务后端——这部分不在WTAPI能力范围内,按所选大模型的function calling机制实现即可。
参考资料WTAPI框架
微信机器人接口二次开发平台
感兴趣的朋友可以测试开发,有试用
接口字段见api文档weiti.apifox.cn 。