You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:28:15