前面讲的都是规则驱动的机器人------预设关键词、预设回复。但这种机器人局限性很明显:只能回答固定问题,无法理解自然语言。这一节讲如何接入AI大模型------让机器人能理解人话、能对话、有记忆,变成真正的智能助手。
1. 为什么需要AI大模型
| 对比 | 关键词匹配 | AI大模型 |
|---|---|---|
| 理解能力 | 只能识别固定关键词 | 理解自然语言 |
| 回复灵活性 | 预设回复 | 动态生成 |
| 上下文 | 无 | 有记忆、能对话 |
| 扩展性 | 需手动添加规则 | 自动学习 |
| 维护成本 | 高 | 低 |
接入AI后,用户可以问:
- "我还有哪些作业没做?" → 理解意图,返回作业列表
- "帮我看看视频看到哪了" → 理解意图,返回进度
- "有没有市场营销学的复习资料" → 理解意图,搜索并返回
2. 接入方案选择
2.1 云端API
| 服务商 | 模型 | 特点 | 价格 |
|---|---|---|---|
| OpenAI | GPT-4/3.5 | 效果好 | 按量付费 |
| 阿里云 | 通义千问 | 中文好 | 较便宜 |
| 百度 | 文心一言 | 中文好 | 较便宜 |
| 智谱 | GLM-4 | 性价比高 | 较便宜 |
| MiniMax | MoE | 便宜 | 适合国内 |
2.2 本地部署
| 方案 | 模型 | 特点 |
|---|---|---|
| Ollama | Llama/Mistral | 简单易用 |
| LM Studio | 各种模型 | 图形界面 |
| vLLM | 高性能 | 需要GPU |
这一节用MiniMax作为示例(便宜效果好),但代码结构通用,换API只需改配置。
3. 快速接入:5分钟集成
Step 1:安装依赖
bash
pip install requests
Step 2:调用API
python
import requests
import json
# MiniMax 配置
API_KEY = "your_api_key" # 格式: sk-xxxx
BASE_URL = "https://api.minimax.chat/v1"
def chat(prompt, model="abab6.5s-chat"):
"""调用AI对话"""
url = f"{BASE_URL}/text/chatcompletion_v2"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": model,
"messages": [
{"role": "user", "content": prompt}
]
}
resp = requests.post(url, headers=headers, json=data)
result = resp.json()
if "choices" in result and len(result["choices"]) > 0:
return result["choices"][0]["message"]["content"]
return f"Error: {result}"
# 测试
response = chat("你好,请介绍一下你自己")
print(response)
Step 3:接入企业微信
python
"""
企业微信AI问答机器人
用户发消息 → AI处理 → 返回回复
"""
import requests
import json
# ===== 配置 =====
# 企业微信
WEBHOOK_KEY = "your_webhook_key"
WEBHOOK_URL = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={WEBHOOK_KEY}"
# AI 配置
API_KEY = "your_minimax_api_key"
def chat_to_ai(prompt):
"""调用AI"""
url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "abab6.5s-chat",
"messages": [
{"role": "user", "content": prompt}
]
}
resp = requests.post(url, headers=headers, json=data)
result = resp.json()
if "choices" in result:
return result["choices"][0]["message"]["content"]
return "抱歉,我现在有点累,稍后再试"
def send_message(content):
"""发送消息到群"""
data = {
"msgtype": "text",
"text": {"content": content}
}
requests.post(WEBHOOK_URL, json=data)
def process_and_reply(user_message):
"""处理消息并回复"""
# 构建提示词(让AI扮演国开学习助手)
system_prompt = """你是一位热心的高校教务助手,名字叫"小开"。
你的任务是帮助学生解决国开学习网(menhu.pt.ouchn.cn)相关问题。
回答要点:
1. 回答要简洁友好
2. 如果不确定的问题,建议用户联系班主任或查看官网
3. 适当使用emoji让回复更生动
常见问题参考:
- 登录问题:学号登录,密码为身份证后6位
- 作业:在"在线作业"栏目完成
- 视频:需要看完60%以上才能考试
- 成绩:在"我的成绩"查看
- 毕业论文:需要选题、撰写、查重、答辩
"""
full_prompt = f"{system_prompt}\n\n用户问题:{user_message}"
# 调用AI
reply = chat_to_ai(full_prompt)
# 发回群
send_message(reply)
# ===== 使用 =====
if __name__ == "__main__":
# 测试
test_messages = [
"你好",
"我的密码忘了怎么办",
"作业什么时候截止",
"视频要全部看完吗"
]
for msg in test_messages:
print(f"用户: {msg}")
process_and_reply(msg)
print("已回复\n")
4. 进阶:多轮对话与上下文
上面的方案每次都是独立对话,没有记忆。要实现真正的对话,需要维护对话历史:
python
"""
带记忆的AI对话机器人
"""
import requests
from datetime import datetime
class AIBot:
def __init__(self, api_key):
self.api_key = api_key
# 对话历史:{user_id: [messages]}
self.conversations = {}
# 最大历史条数
self.max_history = 10
# 系统提示词
self.system_prompt = """你是一位高校教务助手,名字叫"小开"。
特点:
- 回答简洁明了
- 适当使用emoji
- 不确定的问题建议用户联系班主任
身份说明:
- 学校:国家开放大学
- 平台:menhu.pt.ouchn.cn
- 主要服务:成人学历教育
"""
def chat(self, user_id, message):
"""对话"""
# 初始化历史
if user_id not in self.conversations:
self.conversations[user_id] = []
# 添加用户消息
self.conversations[user_id].append({
"role": "user",
"content": message
})
# 裁剪历史
history = self.conversations[user_id][-self.max_history:]
# 构建消息列表
messages = [{"role": "system", "content": self.system_prompt}] + history
# 调用API
url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
data = {
"model": "abab6.5s-chat",
"messages": messages
}
resp = requests.post(url, headers=headers, json=data)
result = resp.json()
# 提取回复
if "choices" in result and len(result["choices"]) > 0:
reply = result["choices"][0]["message"]["content"]
# 记录回复
self.conversations[user_id].append({
"role": "assistant",
"content": reply
})
return reply
return "抱歉,我现在有点累..."
def clear_history(self, user_id):
"""清除对话历史"""
if user_id in self.conversations:
del self.conversations[user_id]
def get_history(self, user_id):
"""获取对话历史"""
return self.conversations.get(user_id, [])
# ===== 使用示例 =====
bot = AIBot("your_api_key")
# 模拟对话
dialogue = [
("user1", "你好"),
("user1", "我是新生,请问怎么登录?"),
("user1", "密码忘了呢?"),
("user1", "好的,谢谢"),
]
for user_id, msg in dialogue:
print(f"👤 用户: {msg}")
reply = bot.chat(user_id, msg)
print(f"🤖 助手: {reply}")
print()
5. 进阶:流式输出
大段文字等待时间长,可以用流式输出让字一个个出来:
python
"""
流式输出的AI对话
"""
import requests
import json
def chat_stream(prompt):
"""流式对话"""
url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "abab6.5s-chat",
"messages": [{"role": "user", "content": prompt}],
"stream": True # 开启流式
}
response = requests.post(url, headers=headers, json=data, stream=True)
print("🤖 ", end="", flush=True)
full_content = ""
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data_str = line[6:]
if data_str.strip() == '[DONE]':
break
try:
chunk = json.loads(data_str)
if 'choices' in chunk and len(chunk['choices']) > 0:
content = chunk['choices'][0].get('delta', {}).get('content', '')
if content:
print(content, end="", flush=True)
full_content += content
except:
pass
print() # 换行
return full_content
# 使用
reply = chat_stream("介绍一下国开学习网")
6. 实战:智能国开问答助手
python
"""
企业微信 + AI 大模型
国开学习网智能问答助手
"""
import requests
import json
# 配置
WEBHOOK_KEY = "your_webhook_key"
WEBHOOK_URL = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={WEBHOOK_KEY}"
API_KEY = "your_minimax_key"
# ===== AI 对话类 =====
class OUCHNAIBot:
def __init__(self, api_key):
self.api_key = api_key
self.conversations = {} # user_id -> history
self.max_history = 6
self.system_prompt = """你是国家开放大学(国开/OUCHN)的智能助教"小开"。
学校信息:
- 全称:国家开放大学
- 简称:国开、OUCHN
- 官网:menhu.pt.ouchn.cn
- 学历:开放教育(成人学历)
常见问题:
1. 登录:学号+身份证后6位
2. 作业:在"在线作业"完成,截止日期前可多次提交
3. 视频:需观看60%以上才能约考
4. 成绩:综合成绩=平时40%+期末60%
5. 毕业:需所有课程及格+论文通过
回复要求:
- 简洁友好,不超过200字
- 适当用emoji
- 不确定的建议联系班主任
- 如果是技术问题,引导联系技术支持0558-xxxxxxx
"""
def chat(self, user_id, message):
"""对话"""
if user_id not in self.conversations:
self.conversations[user_id] = []
# 添加用户消息
self.conversations[user_id].append({"role": "user", "content": message})
# 构建消息
messages = [{"role": "system", "content": self.system_prompt}]
messages += self.conversations[user_id][-self.max_history:]
# 调用API
url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
data = {
"model": "abab6.5s-chat",
"messages": messages,
"temperature": 0.7 # 创意程度
}
resp = requests.post(url, headers=headers, json=data)
result = resp.json()
if "choices" in result and result["choices"]:
reply = result["choices"][0]["message"]["content"]
self.conversations[user_id].append({"role": "assistant", "content": reply})
return reply
return "抱歉,请稍后再试"
def clear(self, user_id):
"""清除记忆"""
if user_id in self.conversations:
del self.conversations[user_id]
# ===== 消息发送 =====
def send_text(content):
"""发送文本"""
data = {"msgtype": "text", "text": {"content": content}}
requests.post(WEBHOOK_URL, json=data)
def send_markdown(content):
"""发送Markdown"""
data = {"msgtype": "markdown", "markdown": {"content": content}}
requests.post(WEBHOOK_URL, json=data)
# ===== 主程序 =====
def handle_message(user_id, message):
"""处理消息"""
bot = OUCHNAIBot(API_KEY)
# 特殊命令
if message.strip() in ["清除记忆", " forget", "clear"]:
bot.clear(user_id)
send_text("✅ 已清除对话历史")
return
# AI对话
reply = bot.chat(user_id, message)
# 发送回复
send_markdown(reply)
# ===== 测试 =====
if __name__ == "__main__":
# 测试对话
bot = OUCHNAIBot(API_KEY)
test_messages = [
"你好",
"我是新生,怎么登录?",
"密码忘了怎么办",
"作业在哪做",
"视频要全部看完吗",
]
for msg in test_messages:
print(f"👤 {msg}")
reply = bot.chat("test_user", msg)
print(f"🤖 {reply}\n")
7. 成本优化技巧
7.1 缓存常见问题
python
# 常见问题缓存
COMMON_QA = {
"登录": "登录账号为学号,初始密码为身份证后6位。首次登录需修改密码。",
"密码": "忘记密码可点击"忘记密码"用手机验证码找回,或联系班主任重置。",
"成绩": "成绩在"我的成绩"栏目查看,综合成绩=平时40%+期末60%。",
"作业": "作业在"在线作业"栏目完成,截止日期前可多次提交。",
"视频": "视频需观看60%以上才能预约期末考试。",
}
def quick_answer(question):
"""快速回答常见问题"""
for key, answer in COMMON_QA.items():
if key in question:
return answer
return None # 需要AI回答
7.2 分层处理
python
def smart_answer(question):
"""智能回答:先缓存 → 再AI"""
# 1. 先尝试缓存命中
cached = quick_answer(question)
if cached:
return cached
# 2. 缓存未命中,调用AI
return chat_to_ai(question)
小结
| 学会的 | 要点 |
|---|---|
| API调用 | requests POST JSON即可调用 |
| 多轮对话 | 维护历史消息列表 |
| 流式输出 | stream=True,逐字显示 |
| 成本优化 | 常见问题缓存,分层处理 |
| 结合企业微信 | 消息接收 → AI处理 → 发回群里 |
下节预告
第4节:实战------国开学习网课程问答助手,从0搭建完整问答系统
📺 系列文章: 企业微信机器人:从被动回复到智能助手
- 第1节:企业微信机器人入门(已发布)
- 第2节:被动回复与关键词匹配(已发布)
- 第3节:接入AI大模型(本文)
- 第4节:实战:国开学习网课程问答助手(待发布)
- 第5节:打通OA系统:通知自动推送(待发布)