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

如何为Langchain的create_pandas_dataframe_agent添加记忆实现模型后处理?

给LangChain Pandas DataFrame Agent添加对话记忆

直接添加ConversationBufferMemory无效,是因为默认的Pandas DataFrame Agent类型不支持对话记忆,需要指定适配的agent类型并正确配置记忆参数。

完整实现代码

from langchain.llms import OpenAI
import pandas as pd
from langchain.memory import ConversationBufferMemory
from langchain.agents import AgentType

# 加载数据集
df = pd.read_csv('titanic.csv')

# 初始化对话记忆,指定记忆键为"chat_history"
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# 创建带记忆的Pandas DataFrame Agent
agent = create_pandas_dataframe_agent(
    OpenAI(temperature=0),
    [df],
    verbose=True,
    memory=memory,
    agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION  # 指定支持对话记忆的agent类型
)

关键注意点

  • 必须指定agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,该类型的agent模板包含chat_history变量,能读取并使用对话记忆
  • 记忆对象需设置return_messages=True,确保对话历史以消息格式传递给agent
  • 记忆的memory_key要与agent模板中的变量名保持一致(默认是"chat_history")

验证记忆功能

可以通过连续提问测试上下文关联效果:

# 第一个问题
agent.run("泰坦尼克号数据里有多少男性乘客?")

# 第二个问题,依赖上一个问题的上下文
agent.run("其中有多少人幸存了?")

此时agent会记住第一个问题的内容,基于上下文正确回答第二个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:05:02