制作AI微信客服机器人
·
AI微信客服的本质,是在消息网关和发送接口之间插一个LLM推理层。用户消息进来 → 网关做去重和路由 → LLM生成回复 → 发送接口回出去。WTAPI负责收发,大模型负责理解和生成,各管一段。
api文档 WTAPI框架文档weiti.apifox.cn 。
一、整体架构
用户消息 → Webhook → 消息队列 → 会话管理 → LLM推理 → 发送接口 → 用户
关键点:消息收发和LLM推理解耦,中间靠会话管理层串联上下文。
二、LLM接入层
WTAPI官方文档提到支持接入ChatGPT、文心一言、自研NLP等大模型。这里用一个统一的LLM客户端封装,方便后续切换模型:
class LLMClient:
def __init__(self, provider="chatgpt"):
self.provider = provider
def chat(self, messages):
if self.provider == "chatgpt":
return self._chatgpt(messages)
elif self.provider == "ernie":
return self._ernie(messages)
# 其他自研NLP...
def _chatgpt(self, messages):
# 调用大模型接口,返回回复文本
# 具体实现按所选模型的SDK文档
pass
三、会话上下文管理
多轮对话需要维护上下文。按 instanceId:fromWxid 存最近N轮消息:
import json
MAX_HISTORY = 10 # 保留最近10轮
def get_history(instance_id, from_wxid):
raw = redis.get(f"history:{instance_id}:{from_wxid}")
return json.loads(raw) if raw else []
def append_history(instance_id, from_wxid, role, content):
history = get_history(instance_id, from_wxid)
history.append({"role": role, "content": content})
# 只保留最近N轮
history = history[-MAX_HISTORY:]
redis.setex(
f"history:{instance_id}:{from_wxid}",
3600, # 1小时过期
json.dumps(history, ensure_ascii=False),
)
四、完整处理流程
def handle_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. 调用LLM
llm = 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": "<appId>",
"instanceId": instance_id,
"toWxid": from_wxid,
"content": reply,
},
timeout=10,
)
五、生产环境的防护
AI客服直接面向用户,必须加防护:
- 超时控制:LLM调用设超时,超时回兜底话术,不让用户干等
- 内容审核:LLM输出过一遍敏感词过滤,防止生成不当内容
- 人工兜底:用户连续3次说"人工"或LLM置信度低时,转人工客服
- 上下文清理:会话超过1小时自动清空,避免上下文污染
六、工具调用(进阶)
如果要让AI能查订单、查物流,需要给LLM加工具调用能力。但微信侧只负责消息收发,工具实现对接业务后端——这部分不在WTAPI能力范围内,按所选大模型的function calling机制实现即可。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)