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

LangChain+VectorDB搭建问答系统后,ChatGPT无法调用通用知识库排查

问题原因及解决方案

问题根源

默认的RetrievalQAChain使用的prompt会强制模型仅基于检索到的文档上下文回答问题,如果上下文里没有相关信息,就要求模型直接回答“我不知道”,完全限制了模型调用自身通用知识库的能力。

解决方案

修改RetrievalQAChain的prompt,允许模型在检索不到相关文档时,使用自身的通用知识来回答问题。具体步骤如下:

  1. 导入PromptTemplate类
  2. 自定义prompt模板,移除“不知道就说不知道”的限制,明确允许结合自身知识
  3. 创建RetrievalQAChain时传入自定义prompt

完整修改后的代码示例

import {OpenAI} from "langchain/llms/openai";
import {RetrievalQAChain} from "langchain/chains";
import {PromptTemplate} from "langchain/prompts"; // 新增导入

const openAIApiKey = '...';
const model = new OpenAI({temperature: 0, openAIApiKey});

// 自定义prompt模板
const customPrompt = PromptTemplate.fromTemplate(`
Use the following pieces of context to answer the user's question.
If the context doesn't provide enough information to answer, you can use your own general knowledge to respond.

Context:
{context}

Question:
{question}

Answer:
`);

// 创建chain时传入自定义prompt
const chain = RetrievalQAChain.fromLLM(model, vectorDB.asRetriever(), {
  prompt: customPrompt,
});

额外说明

  • 如果检索器完全找不到和问题相关的文档,返回的context会是空内容,此时模型就会自动调用自身的通用知识库回答。
  • 你也可以调整检索器的参数(比如vectorDB.asRetriever({k: 2}))来控制返回的文档数量,避免无关文档干扰回答。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:32:21