Node.js中ConversationalRetrievalQAChain集成BufferMemory报错求助
解决Node.js中LangChain ConversationalRetrievalQAChain的Memory类型错误问题
问题原因
你遇到的类型错误是因为ConversationalRetrievalQAChain.fromLLM的第三个参数不支持直接传入memory对象。Node.js版LangChain的API设计和Python版存在差异,官方文档示例可能未同步更新,导致按文档写法出现类型不匹配。
解决方案
方案一:手动维护对话历史(最可靠)
ConversationalRetrievalQAChain本身需要在每次调用时传入chat_history参数,而非通过memory绑定到链上。你可以手动用变量保存对话记录,每次调用时将历史传入:
// 初始化对话历史数组 let chatHistory = []; // 第一次提问 const firstQuestion = "What did the president say about Justice Breyer?"; const res = await chain.call({ question: firstQuestion, chat_history: chatHistory.join("\n") }); console.log(res); // 更新对话历史 chatHistory.push(`Human: ${firstQuestion}`); chatHistory.push(`Assistant: ${res.text}`); // 跟进提问 const followUpQuestion = "Was that nice?"; const followUpRes = await chain.call({ question: followUpQuestion, chat_history: chatHistory.join("\n") }); console.log(followUpRes); // 更新对话历史 chatHistory.push(`Human: ${followUpQuestion}`); chatHistory.push(`Assistant: ${followUpRes.text}`);
方案二:适配Chain的Memory集成(针对特定版本)
如果你的LangChain版本支持,也可以通过创建带Memory的QA链,再结合ConversationalRetrieval逻辑,但这种方式兼容性较差,推荐优先用方案一。示例代码如下:
// 创建基础QA链并绑定Memory const qaChain = new RetrievalQAChain({ llm: model, retriever: vectorStore.asRetriever(), memory: new BufferMemory({ memoryKey: "chat_history" }) }); // 基于QA链创建ConversationalRetrieval链 const chain = new ConversationalRetrievalQAChain({ retriever: vectorStore.asRetriever(), questionGeneratorChain: new LLMChain({ llm: model, prompt: ConversationalRetrievalQAChain.getQuestionGeneratorPrompt() }), qaChain });
额外注意点
- 你代码中在
if块内重新定义了const question,会覆盖外部变量,建议改名(比如firstQuestion)避免冲突。 - 若使用流式输出,需要确保对话历史的更新逻辑和流式回调兼容,避免出现历史记录不完整的情况。
内容的提问来源于stack exchange,提问作者Wajeeh Aslam
相关产品推荐
相关产品推荐

