如何为搭载双工具的Agent传入已创建的Combined Memory
问题解决:LangChain Agent集成CombinedMemory失败的处理方案
核心原因
你遇到的问题根源是默认Agent的Prompt模板没有包含CombinedMemory中定义的多个记忆变量。默认模板只会引用单一的chat_history变量,而你的CombinedMemory包含chat_history_buffer、chat_history_summary、chat_history_KG三个独立记忆键,这些变量没有被注入到Agent的Prompt中,导致记忆功能不生效。
解决步骤:修改Prompt模板
必须自定义Agent的Prompt,将所有记忆变量明确加入模板内容,同时保留Agent运行所需的核心变量(如input、agent_scratchpad)。
完整实现代码
from langchain.chat_models import ChatOpenAI from langchain.memory import ( ConversationBufferWindowMemory, ConversationSummaryMemory, ConversationKGMemory, CombinedMemory ) from langchain.agents import initialize_agent, AgentType from langchain.tools import Tool from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder # 初始化LLM实例 llm_code = ChatOpenAI(temperature=0, model_name="gpt-4-0613") llm_context = ChatOpenAI(temperature=0.5, model_name="gpt-4") # 定义工具(替换为你的python_reply_tool和search_documents) python_reply_tool = Tool( name="Python代码执行", func=lambda x: "执行Python代码的结果:" + x, description="用于执行Python代码并返回结果" ) search_documents = Tool( name="文档搜索", func=lambda x: "搜索到的文档内容:" + x, description="用于搜索指定文档的相关信息" ) tools = [python_reply_tool, search_documents] # 创建组合记忆实例 chat_history_buffer = ConversationBufferWindowMemory( k=5, memory_key="chat_history_buffer", input_key="input", return_messages=True # 适配ChatPromptTemplate的消息格式 ) chat_history_summary = ConversationSummaryMemory( llm=llm_context, memory_key="chat_history_summary", input_key="input", return_messages=True ) chat_history_KG = ConversationKGMemory( llm=llm_context, memory_key="chat_history_KG", input_key="input", return_messages=True ) memory = CombinedMemory(memories=[chat_history_buffer, chat_history_summary, chat_history_KG]) # 自定义Prompt模板:加入所有记忆变量 prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个具备多记忆能力的助手,结合以下信息回答用户问题:\n1. 近期对话记录:{chat_history_buffer}\n2. 对话总结:{chat_history_summary}\n3. 对话知识图谱:{chat_history_KG}"), ("user", "{input}"), ("assistant", "{agent_scratchpad}") ]) # 初始化Agent,传入自定义Prompt和组合记忆 agent = initialize_agent( tools, llm_code, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, memory=memory, prompt=prompt, verbose=True ) # 测试Agent agent.run(input="帮我搜索关于LangChain组合记忆的文档")
关键注意点
- 确保每个记忆实例的
memory_key与Prompt模板中的变量名完全一致 - 开启
return_messages=True(针对Chat模型),让记忆返回消息格式的内容,适配ChatPromptTemplate - 自定义Prompt时必须保留
agent_scratchpad变量,这是Agent思考过程的占位符 - 选择适配的Agent类型(如
CHAT_CONVERSATIONAL_REACT_DESCRIPTION),与Chat模型和记忆类型匹配
内容的提问来源于stack exchange,提问作者Jakub Szlaur
相关产品推荐
相关产品推荐

