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

LangChain带记忆的CSV Agent返回错误结果求助

问题根源

你的问题出在外层Agent虽然能通过记忆识别出“his”指Medjedovic,但传给csv_extractor工具的prompt还是模糊的“what is his birth date?”,而内部的csv agent没有对话上下文,根本不知道“his”是谁,所以只会返回数据集里的第一条出生日期。

解决方法

方法1:让外层Agent生成明确查询后再调用工具

修改外层Agent的prompt,明确要求它把对话中的指代(比如“他”“这个人”)替换成具体实体名称,再调用工具。

调整prompt的prefix部分:

prefix = """和用户对话必须结合历史信息,若问题里有指代(如“他”),先替换成历史提到的具体实体(比如Medjedovic),再用工具查询。你可用以下工具:"""

这样外层Agent在生成Action Input时,会把模糊的{"prompt":"what is his birth date?","path":"file.csv"}转换成明确的{"prompt":"what is Medjedovic's birth date?","path":"file.csv"},内部csv agent就能直接查询正确数据。

方法2:让csv_extractor工具结合对话历史补全查询

修改工具函数,让它接收对话历史,在构造内部查询时补全模糊指代。

# 修改csv_extractor函数,新增对话历史参数
def csv_extractor(json_request: str, chat_history: str):
    arguments_dictionary = json.loads(json_request)
    question = arguments_dictionary["prompt"]
    file_name = arguments_dictionary["path"]
    
    # 结合历史补全问题
    full_question = f"参考对话历史:{chat_history},回答问题:{question}"
    
    csv_agent = create_csv_agent(llm=OpenAI(), path=file_name, verbose=True)
    return csv_agent(full_question)

# 修改Tool定义,传入记忆中的对话历史
csv_extractor_tool = Tool(
    name="csv_extractor",
    func=lambda x: csv_extractor(x, memory.load_memory_variables({})['chat_history']),
    description=description,
    verbose=True,
)

内部csv agent拿到完整对话上下文后,就能理解“his”的指代对象,返回正确结果。

方法3:换用ConversationalAgent替代ZeroShotAgent

ZeroShotAgent是无记忆设计,ConversationalAgent专门针对对话场景优化,能自动处理指代关系。

修改Agent创建代码:

from langchain.agents import ConversationalAgent

# 构造ConversationalAgent专属prompt
prompt = ConversationalAgent.create_prompt(
    tools=tools,
    prefix=prefix,
    suffix=suffix,
    input_variables=["input", "chat_history", "agent_scratchpad"]
)

# 创建ConversationalAgent
agent = ConversationalAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_chain = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory)

它会自动解析对话中的指代,生成明确的工具调用输入,从根源避免模糊查询问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:16:02