首页 > 基础资料 博客日记
AI开发-python-langchain框架(3-17-ReactAngent的增加会话记录)
2026-04-01 11:30:04基础资料围观1次
LangChain ReAct Agent 实现会话记录功能:让智能体拥有“记忆”
一、核心痛点:为什么需要给ReAct Agent添加会话记录?
二、关键实现思路:会话记录功能的核心逻辑
1. 预留会话记录占位符
2. 实时记录对话历史
3. 多轮调用时传递会话历史
三、实践亮点:轻量实现,无需额外依赖
四、效果验证:会话记录功能的实际价值
五、总结与延伸
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
# 1. 初始化 LLM
DEEPSEEK_API_KEY = "123" # 替换为实际的 API Key
llm = ChatOpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="http://192.168.0.100: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}
""")
# 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)
# 这里我们为 chat_history 传递一个空的消息列表,因为它是聊天中的第一条消息
chat1 = agent_executor.invoke({"input": "你好,我叫小老虎", "chat_history": []})
print(chat1)
history = [] + [HumanMessage(content=chat1['input']), AIMessage(content=chat1['output'])]
chat2 = agent_executor.invoke({"chat_history": history, "input": "我叫是什么?", })
print('---------------')
print(chat2['output'])
print('#################')
print(chat2)
输出:
Agent 创建成功
============================================================
测试 Agent 工具调用
============================================================
> Entering new AgentExecutor chain...
n.
</think>
Thought: 用户是在打招呼并自我介绍,这不是一个需要查询华为商城信息的问题,我应该友好地回应这个问候。
Final Answer: 你好,小老虎!很高兴认识你。我是你的智能助手,有什么我可以帮助你的吗?比如查询华为商城的产品信息、活动优惠、购买政策等,都可以告诉我哦!
> Finished chain.
{'input': '你好,我叫小老虎', 'chat_history': [], 'output': '你好,小老虎!很高兴认识你。我是你的智能助手,有什么我可以帮助你的吗?比如查询华为商城的产品信息、活动优惠、购买政策等,都可以告诉我哦!', 'intermediate_steps': []}
> Entering new AgentExecutor chain...
y.
</think>
Thought: 这个问题是关于用户自己的名字,从之前的对话历史中我可以看到用户已经自我介绍过叫"小老虎",所以我不需要使用工具来查询,可以直接从对话历史中回答。
Final Answer: 你叫小老虎!这是你在我们第一次对话时告诉我的名字。
> Finished chain.
---------------
你叫小老虎!这是你在我们第一次对话时告诉我的名字。
#################
{'chat_history': [HumanMessage(content='你好,我叫小老虎'), AIMessage(content='你好,小老虎!很高兴认识你。我是你的智能助手,有什么我可以帮助你的吗?比如查询华为商城的产品信息、活动优惠、购买政策等,都可以告诉我哦!')], 'input': '我叫是什么?', 'output': '你叫小老虎!这是你在我们第一次对话时告诉我的名字。', 'intermediate_steps': []}
Process finished with exit code 0
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- 关于列式存储(Column-base Storage)的几个要点解读
- 同样都是九年义务教育,他知道的AI算力科普好像比我多耶
- Slickflow 与 OpenClaw 结合实践:技术原理、集成方式与 Skill 说明
- 如何使用 UEFI Shell 执行 Hello World 程序
- Agent构建:声明式优于硬编码
- AI 可以取代运维了吗?
- 测试人必备的4个AI Skills(附下载地址和详细用法)
- 记一次Webshell流量分析2 | 添柴不加火
- 直击政企AI落地“深水区”,华为混合云推出OpenClaw本地部署方案
- FastAPI里玩转Redis和数据库的正确姿势,别让异步任务把你坑哭了!

