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

如何为LangChain中的create_csv_agent添加ConversationBufferMemory

解决LangChain create_csv_agent添加ConversationBufferMemory无效的问题

直接给create_csv_agent传入ConversationBufferMemory不生效的核心原因是:该方法默认创建的是ZeroShotAgent,它的prompt模板没有预留对话历史的插入位置,因此即使传入记忆组件也不会被使用。

修正后的代码

from langchain.memory import ConversationBufferMemory
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI
from langchain.agents.agent_types import AgentType

# 配置记忆,指定memory_key为ConversationalChatAgent默认使用的"chat_history"
csv_memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# 使用支持对话记忆的Agent类型
agent = create_csv_agent(
    OpenAI(temperature=0),
    file_path,
    verbose=True,
    memory=csv_memory,
    agent_type=AgentType.CONVERSATIONAL_CHAT_AGENT
)

关键说明

  1. 指定Agent类型:AgentType.CONVERSATIONAL_CHAT_AGENT是专门为对话场景设计的agent,其内置prompt包含chat_history变量,能自动读取并使用传入的记忆内容。
  2. 匹配Memory的key:必须将ConversationBufferMemory的memory_key设为"chat_history",和ConversationalChatAgent的prompt变量名对应,否则记忆无法被正确加载。
  3. return_messages=True:让记忆存储结构化的消息对象,而非纯文本,更适配对话agent的处理逻辑。

调试验证步骤

  • 确保你的LangChain版本≥0.1.0,旧版本不支持在create_csv_agent中指定agent_type参数。
  • 连续提问上下文相关的问题(比如先问"CSV里有多少条记录?",再问"其中性别为男的有多少?"),观察agent是否能利用之前的对话信息。
  • 开启verbose=True后,查看控制台日志,确认chat_history是否被正确注入到prompt中。

内容的提问来源于stack exchange,提问作者nb123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:52:35