LangChain中loadQAStuffChain未按要求返回‘I don't know’求助
解决LangChain QAStuffChain无上下文时固定回复"I don't know"的问题
核心问题分析
你的代码不生效有两个关键原因:
loadQAStuffChain的第二个参数接收的是配置对象,而非直接传入PromptTemplate- 自定义模板里用了
{text}作为上下文变量,但QAStuffChain默认使用的变量名是{context},变量不匹配导致LLM无法读取上下文内容
修正后的代码
const ignorePrompt = PromptTemplate.fromTemplate( "Given the text: {context}, answer the question: {question}. If the answer is not in the text or you don't know it, type: \"I don't know\"" ); // 正确传递prompt到配置对象中 const chain = loadQAStuffChain(llm, { prompt: ignorePrompt }); console.log("chain loaded");
额外优化建议
- 测试时用极端场景验证:比如上下文仅包含"猫喜欢吃鱼",提问"狗喜欢吃什么",确认是否返回"I don't know"
- 若LLM仍不遵循指令,可强化模板话术,比如改为:
const ignorePrompt = PromptTemplate.fromTemplate( "You must only answer based on the given context: {context}. Answer the question: {question}. If the answer is not in the context or you have no idea, strictly output only: \"I don't know\"" );
内容的提问来源于stack exchange,提问作者Aaryan Anjan
相关产品推荐
相关产品推荐

