首页 > 基础资料 博客日记
AI开发-python-langchain框架(3-19-智能问答-保留会话历史)
2026-04-03 11:30:03基础资料围观2次
基于RunnableWithMessageHistory实现多会话隔离与持久化记忆
一、核心需求:为什么需要会话隔离与持久化记忆?
二、实践核心:用RunnableWithMessageHistory实现多会话隔离
三、扩展升级:对话历史持久化(数据库落地方案)
(一)主流持久化方案选型
(二)持久化通用实现步骤
(三)持久化核心设计要点
四、生产级落地建议
五、总结
from langchain_openai import ChatOpenAI
from langchain_core.tools import Tool
from langchain.agents import create_react_agent # 改用 ReAct 智能体
from langchain.agents import AgentExecutor
from langchain_core.prompts import PromptTemplate # ReAct 用 PromptTemplate 而非 ChatPromptTemplate
from langchain_core.messages import AIMessage, HumanMessage
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
# 1. 初始化 LLM(保持不变)
DEEPSEEK_API_KEY = "123" # 替换为实际的 API Key
llm = ChatOpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="http://172.25.133.51:8085/v1",
model="qwen3.5-27b-awq",
temperature=0.3,
max_tokens=1024,
)
# 2. 工具函数
def huawei_mall_search(query: str) -> str:
"""华为商城搜索工具"""
print(f"[DEBUG] 工具被调用!搜索关键词:{query}")
search_results = {
"众测活动": "华为商城众测活动是让用户体验新品并反馈意见的活动。目前有Mate 60系列众测,参与可赢取礼品。",
"手机": "华为商城最新手机:Mate 60系列、P60系列、nova系列等。",
"笔记本": "华为MateBook X Pro、MateBook D系列笔记本电脑。",
"手表": "华为Watch 4、Watch GT系列智能手表。",
"默认": "请在华为商城官网查看详细信息或联系客服。"
}
for keyword in search_results:
if keyword in query:
return f"华为商城搜索结果:{search_results[keyword]}"
return search_results["默认"]
# 3. 创建工具
huawei_tool = Tool(
name="huawei_mall_search",
description="查询华为商城相关信息,包括产品、活动、政策等",
func=huawei_mall_search,
)
tools = [huawei_tool]
# 4. 定义 ReAct 提示词模板(关键修改!)
react_prompt = PromptTemplate.from_template("""
Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Previous conversation history:
{chat_history}
Question: {input}
Thought: {agent_scratchpad}
""")
#上面提示词中{chat_history}是记录历史会话记录的不能少
# 5. 创建 ReAct 智能体(关键修改!)
try:
agent = create_react_agent(llm=llm, tools=tools, prompt=react_prompt)
print("Agent 创建成功")
except Exception as e:
print(f"创建 Agent 失败: {e}")
exit()
# 6. 创建执行器(保持不变)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
max_iterations=3,
handle_parsing_errors=True,
return_intermediate_steps=True
)
# 7. 测试(保持不变)
print("\n" + "=" * 60)
print("测试 Agent 工具调用")
print("=" * 60)
# 1. 用字典存储每个 session_id 的独立历史
session_histories = {}
# 2. 会话存储函数:为每个 session_id 创建/返回独立的历史
def get_session_history(session_id: str) -> ChatMessageHistory:
if session_id not in session_histories:
session_histories[session_id] = ChatMessageHistory()
return session_histories[session_id]
# 3. 创建带历史的智能体
agent_with_chat_history = RunnableWithMessageHistory(
agent_executor,
get_session_history, # 使用新的会话存储函数
input_messages_key="input",
history_messages_key="chat_history",
)
# 4. 测试不同 session_id
chat1 = agent_with_chat_history.invoke(
{"input": "你好,我是小老虎"},
config={"configurable": {"session_id": "tiger"}},
)
chat2 = agent_with_chat_history.invoke(
{"input": "你好,我是小兔子"},
config={"configurable": {"session_id": "rabbit"}},
)
# 5. 查看特定 session_id 的会话记录
print("tiger 的会话记录:")
for msg in session_histories["tiger"].messages:
print(f"{msg.type}: {msg.content}")
print("\nrabbit 的会话记录:")
for msg in session_histories["rabbit"].messages:
print(f"{msg.type}: {msg.content}")
输出结果:
Agent 创建成功
============================================================
测试 Agent 工具调用
============================================================
Parent run 5a054763-47a5-4360-b529-78012bbde271 not found for run 7b1f1b02-d9ac-4da8-b935-034ee28d0b7c. Treating as a root run.
> Entering new AgentExecutor chain...
l.
</think>
Thought: 用户只是在打招呼自我介绍,这是一个简单的问候,不需要使用华为商城搜索工具来查询信息。我应该友好地回应用户的问候。
Final Answer: 你好,小老虎!很高兴认识你。我是你的智能助手,有什么我可以帮助你的吗?比如查询华为商城的产品信息、优惠活动或者相关政策等,都可以告诉我哦!
> Finished chain.
Parent run b6d86ca8-bcb5-4e4e-8182-080f8381338e not found for run a05acc86-23a1-4fcc-9d89-ea8209b9a02e. Treating as a root run.
> Entering new AgentExecutor chain...
r.
</think>
Thought: 用户只是在打招呼并自我介绍,这是一个简单的问候,不需要使用华为商城搜索工具来查询任何信息。我应该友好地回应用户的问候。
Final Answer: 你好,小兔子!很高兴认识你~有什么我可以帮助你的吗?😊
> Finished chain.
tiger 的会话记录:
human: 你好,我是小老虎
ai: 你好,小老虎!很高兴认识你。我是你的智能助手,有什么我可以帮助你的吗?比如查询华为商城的产品信息、优惠活动或者相关政策等,都可以告诉我哦!
rabbit 的会话记录:
human: 你好,我是小兔子
ai: 你好,小兔子!很高兴认识你~有什么我可以帮助你的吗?😊
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:

