如何为CONVERSATIONAL_REACT_DESCRIPTION Agent集成对话历史?报错求助
解决方案
问题根源
CONVERSATIONAL_REACT_DESCRIPTION类型的Agent默认要求输入包含两个参数:input(当前用户提问)和chat_history(对话历史)。你的错误来自两方面:
- 调用
agent.run()时传入了单个字符串,而非符合要求的字典格式 - 配置的
ConversationBufferMemory使用了自定义的memory_key="memory",但该Agent默认期望对话历史的key是chat_history
修正代码
1. 统一对话历史的参数名
把MessagesPlaceholder的variable_name、ConversationBufferMemory的memory_key都改为chat_history,匹配Agent的默认要求:
agent_kwargs = { 'prefix': '''Answer the questions to provide relevant information to a etc etc Begin! ''', "extra_prompt_messages": [MessagesPlaceholder(variable_name="chat_history")] } memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
2. 按正确格式调用Agent
调用agent.run()时传入包含input键的字典,LangChain会自动通过Memory填充chat_history参数:
agent.run({"input": user_question})
完整修正后代码示例
agent_kwargs = { 'prefix': '''Answer the questions to provide relevant information to a etc etc Begin! ''', "extra_prompt_messages": [MessagesPlaceholder(variable_name="chat_history")] } memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) # initialize the LLM agent agent = initialize_agent( tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, agent_kwargs=agent_kwargs, memory=memory, ) agent.run({"input": user_question})
补充说明
- 不需要手动传递
chat_history参数,配置好Memory后,LangChain会自动从Memory中提取对话历史注入到Agent的输入中 - 必须保证
MessagesPlaceholder、ConversationBufferMemory使用的参数名和Agent默认的chat_history完全一致
内容的提问来源于stack exchange,提问作者Teestaa Saha
相关产品推荐
相关产品推荐

