LangChain OpenAIFunctions类型Agent无法调用对话记忆问题求助
LangChain OpenAIFunctions Agent记忆功能失效修复方案
问题根源分析
你的代码存在以下关键问题导致记忆功能无法正常工作:
- 使用错误的模板类型:OpenAIFunctions Agent依赖聊天模型,需用
ChatPromptTemplate构建提示,而非普通的PromptTemplate。 - 对话历史处理方式错误:直接通过
{chat_history}插入文本无法被聊天模型正确识别,必须使用MessagesPlaceholder来管理对话消息序列。 - 记忆配置缺失关键参数:
ConversationBufferMemory未设置return_messages=True,导致返回的是纯文本而非聊天模型所需的消息对象。 - 自定义prompt结构不符合Agent规范:
agent_scratchpad的位置和格式错误,影响Agent对工具调用历史的处理。
修复后的完整代码
from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.agents import tool, initialize_agent, AgentType from langchain.memory import ConversationBufferMemory llm = ChatOpenAI(model="gpt-4-1106-preview", temperature=0) @tool def getSquareOfNumber(number: str) -> str: """Method used to return the square of the provided input.""" print("Inside method getSquareOfNumber") x = int(number) * int(number) return f"The square of {number} is {x}" tools = [getSquareOfNumber] # 使用ChatPromptTemplate构建符合要求的提示 prompt = ChatPromptTemplate.from_messages([ ("system", "You are a very powerful assistant with access to chat history and can use tools when required. You don't know how to calculate the square of a number, so you'll use the getSquareOfNumber tool."), MessagesPlaceholder(variable_name="chat_history"), # 用MessagesPlaceholder管理对话历史 ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad") # 正确放置agent_scratchpad ]) # 配置记忆,设置return_messages=True返回消息对象 memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) agent = initialize_agent( tools=tools, agent=AgentType.OPENAI_FUNCTIONS, llm=llm, prompt=prompt, memory=memory, verbose=True, ) user_input = "" while user_input != 'exit': user_input = input('Ask > ') if user_input != 'exit': response = agent.invoke({"input": user_input}) print(response['output'])
关键修改说明
- 替换
PromptTemplate为ChatPromptTemplate,通过from_messages方法构建由不同类型消息组成的提示。 - 用
MessagesPlaceholder替代字符串占位符{chat_history}和{agent_scratchpad},确保对话历史和工具调用记录以消息对象形式传递给模型。 - 给
ConversationBufferMemory添加return_messages=True参数,让记忆返回聊天模型能识别的消息对象列表。 - 调整提示结构,将系统消息、对话历史、用户输入、工具调用scratchpad按正确顺序排列。
内容的提问来源于stack exchange,提问作者San_nad
相关产品推荐
相关产品推荐

