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

整合ConversationalRetrievalQAChain与APIChain后Agent响应异常求助

问题分析与解决方案

核心原因

ConversationalRetrievalQAChain 运行时需要**对话历史(chat_history)**作为必填输入参数,但默认的ChainTool只会把Agent传入的input作为question传递给Chain,缺少chat_history字段,导致Chain无法正常执行逻辑。而RetrievalQAChain不需要对话历史,所以能和APIChain正常配合。

解决方案

1. 自定义Tool处理对话历史传递

不要直接使用ChainTool,手动实现自定义Tool,将Agent上下文里的对话历史传递给ConversationalRetrievalQAChain:

const { Tool } = require("langchain/tools");

// 自定义QA工具,处理对话历史
const customQATool = new Tool({
  name: "qa",
  description: "useful for when you need to ask questions based on existing knowledge base, requires chat history context.",
  async func(input, runManager) {
    // 从Agent上下文提取对话历史
    const chatHistory = runManager?.parentRun?.inputs?.chat_history || [];
    // 调用ConversationalRetrievalQAChain,传入question和chat_history
    const result = await qaChain.call({
      question: input,
      chat_history: chatHistory.map(item => `${item.role}: ${item.content}`).join("\n"),
    });
    return result.text;
  },
});

// API工具可继续使用ChainTool
const apiChainTool = new ChainTool({
  name: "weather-api",
  description: "useful for when you need to ask questions about weather of a city.",
  chain: apiChain,
});

2. 调用Agent时传入对话历史

确保调用executor.call时,传入完整的对话历史参数:

// 初始化对话历史(首次调用可为空数组)
let chatHistory = [];

// 用户输入示例
const userInput = "北京今天的天气如何?";

// 调用Agent执行器
const res = await executor.call({
  input: userInput,
  chat_history: chatHistory,
});

// 更新对话历史
chatHistory.push({ role: "user", content: userInput });
chatHistory.push({ role: "assistant", content: res.output });

console.log(res);

3. 调整Agent配置(可选)

使用chat-conversational-react-description类型Agent时,可通过agentArgs自定义prompt,确保对话历史被纳入思考逻辑:

const executor = await initializeAgentExecutorWithOptions(tools, model, {
  agentType: 'chat-conversational-react-description',
  verbose: true,
  agentArgs: {
    systemMessage: `你是一个助手,可以使用提供的工具回答问题。对话历史会帮助你理解上下文:{chat_history}`,
  },
});

验证要点

  • 单独测试自定义Tool是否能正确传递对话历史给ConversationalRetrievalQAChain
  • 查看Agent的verbose日志,确认是否正确选择对应工具
  • 确保chat_history格式符合ConversationalRetrievalQAChain要求(通常为字符串数组或拼接后的字符串)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:53:29