LangGraph--聊天机器人构建(2)
·

1. 核心设计理念
构建多轮对话聊天机器人需要解决三大关键问题:
1.1 对话上下文记忆
聊天机器人必须能够“记住”用户历史对话,从而生成上下文相关的回答。
实现方式:
- 在
State中维护history列表,记录多轮消息; - 每轮调用时,将历史消息拼接到 prompt 中;
- 回答生成后,将新对话追加到历史中,形成连续上下文。
1.2 用户区分与会话管理(session_id)
在多用户场景下,必须确保每个用户的会话独立,互不干扰。
实现方式:
- 使用
session_id区分不同用户; - 可结合 Redis 或数据库持久化存储历史,实现跨设备访问。
1.3 调用硅基流动 LLM API
机器人通过 HTTP 调用硅基流动 LLM(如 Qwen、Llama)生成回答。
特点:
- 与 OpenAI API 调用方式类似;
- 支持多种参数配置,如
temperature、top_p等; - 可灵活选择模型类型和响应格式。
2. State 定义
为了实现多轮记忆,我们需要一个统一的数据结构 State:
from typing import TypedDict, List
class State(TypedDict):
question: str # 当前用户问题
answer: str # 机器人回答
session_id: str # 会话ID
history: List[str] # 完整对话历史(字符串列表)
示例 history:
用户: 你好
助手: 您好,我能帮你什么?
3. 调用硅基流动 LLM 函数
以下函数封装了对 LLM 的调用:
import requests
API_KEY = "<你的API_KEY>"
URL = "https://api.siliconflow.cn/v1/chat/completions"
def call_siliconflow_llm(prompt: str) -> str:
"""
调用硅基流动 LLM,返回模型生成文本
"""
payload = {
"model": "Qwen/Qwen3-VL-30B-A3B-Instruct",
"messages": [{"role": "user", "content": prompt}],
"stream": False,
"max_tokens": 2048,
"temperature": 0.7,
"top_p": 0.7,
"frequency_penalty": 0.5,
"response_format": {"type": "text"},
}
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
response = requests.post(URL, json=payload, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
4. 多轮对话管理
为了保证对话的自然性和系统性能,我们对历史管理进行了优化:
4.1 轮数限制
MAX_TURNS = 10 # 最多保留最近10轮对话
def trim_history(history, max_turns=MAX_TURNS):
"""
只保留最近 max_turns 轮对话(用户+助手共 2 条为一轮)
"""
max_len = max_turns * 2
if len(history) > max_len:
history = history[-max_len:]
return history
4.2 历史内容摘要
当历史过长时,使用 LLM 自动生成摘要,减少 prompt 长度:
def summarize_history(history: list) -> str:
"""
用 LLM 将长对话总结为一段短摘要,用于减少 prompt 长度。
"""
text = "\n".join(history)
prompt = f"请总结以下对话,不超过200字:\n\n{text}\n\n总结:"
summary = call_siliconflow_llm(prompt)
return summary
4.3 核心回答节点
def answer(state: State):
"""
核心节点:生成回答并维护对话历史
- 限制轮数
- 自动摘要长历史
"""
history = state.get("history", [])
# 限制轮数
history = trim_history(history, MAX_TURNS)
# 自动摘要
if len(history) > 30:
summary = summarize_history(history)
history = ["对话摘要: " + summary]
# 构造 prompt
prompt = "你是一个专业且友好的助手,请基于以下对话历史回答用户问题:\n\n"
if history:
prompt += "\n".join(history) + "\n"
prompt += f"用户当前问题: {state['question']}\n请直接回答:"
# 调用 LLM
ans = call_siliconflow_llm(prompt)
# 更新历史
history.append(f"用户: {state['question']}")
history.append(f"助手: {ans}")
# 更新 state
state["history"] = history
state["answer"] = ans
return {"answer": ans, "history": history}
5. LangGraph 构建
利用 LangGraph 将对话逻辑节点化:
from langgraph.graph import StateGraph
graph = StateGraph(State)
graph.add_node("answer", answer)
graph.set_entry_point("answer")
app = graph.compile()
6. 多轮对话示例
session_id = "user123"
state = {
"question": "你好,你是谁?",
"answer": "",
"session_id": session_id,
"history": []
}
# 第一轮
result = app.invoke(state)
print("助手:", result["answer"])
# 第二轮
state["question"] = "你记得我刚才问了什么吗?"
result = app.invoke(state)
print("助手:", result["answer"])
# 第三轮
state["question"] = "请总结一下我们的对话"
result = app.invoke(state)
print("助手:", result["answer"])
特点:
- 历史记忆自然流畅;
- 上下文关联回答准确;
- 自动摘要与截断机制保证性能稳定。
7. 可扩展方向
- RAG(检索增强生成):在回答前引入文档检索节点,提高问答准确性。
- 持久化多用户会话:利用 Redis 或 MySQL 保存
session_id → history,支持跨设备多轮对话。 - 流式输出:实时返回生成内容,提升交互体验。
- 历史优化策略:摘要 + 截断 + 历史优先级,节省 Token,提高响应速度。
- 多模态能力:结合 Qwen-VL 等支持图像的模型,实现图文交互。
8. 总结
通过以上设计,聊天机器人不仅能记住多轮对话,还能在多用户环境中保持上下文独立,同时通过 LLM API 生成高质量回答。进一步结合检索增强和历史优化策略,机器人将具备更强的理解和生成能力,成为真正智能的多轮对话助手。
更多推荐

所有评论(0)