一句话答案:ChatGPT 接入微信的做法是:订阅消息回调,把用户消息和上下文交给大模型生成回复,再调用发送接口发回微信。整个链路通常在 1–3 秒内完成。
架构
- 托管账号收到消息,推送
message.received到你的回调地址。 - 你的服务校验签名,判断是否需要回复(私聊,或群里 @ 了机器人)。
- 读取该用户最近几轮对话和知识库内容,调用 ChatGPT 等大模型 API 生成回复。
- 调用
send_text发回原会话;需要人工时转给客服并打标签。
示例代码(Python)
import hmac, hashlib, requests
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = b"YOUR_CALLBACK_SECRET"
HEADERS = {"Authorization": "Bearer YOUR_API_KEY"}
def ask_llm(user_text, history):
# 换成你使用的大模型 API,传入系统提示词、知识库片段和历史对话
return "这是 AI 的回复"
@app.post("/callback")
def callback():
sig = hmac.new(SECRET, request.data, hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, request.headers.get("X-Signature", "")):
abort(401)
evt = request.get_json()
d = evt.get("data", {})
if evt["event"] == "message.received" and d.get("type") == "text":
if d.get("room_id") and not d.get("at_me"):
return {"ok": True} # 群里没 @ 机器人就不回复
reply = ask_llm(d["content"], history=[])
requests.post("https://api.wechatapilabs.com/v1/message/send_text", headers=HEADERS, json={
"account_id": evt["account_id"],
"to": d.get("room_id") or d["from"],
"content": reply,
}, timeout=10)
return {"ok": True}
上线建议
- 回调要在 5 秒内返回,大模型调用放到异步队列里处理。
- 微信机器人回复前加 1–3 秒随机延迟,更像真人,也能降低风控概率。
- 设置转人工关键词,例如“人工”“投诉”,命中后停止自动回复。
- 为每个会话保存最近若干轮对话作为上下文,并设置过期时间。
相关阅读: 微信 API 有哪些?公众号、小程序、支付、开放平台与企业微信全景指南 · 企业微信机器人 Webhook 发送消息教程 · 个人微信能调用 API 吗?官方边界与可选方案