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

如何在LangChain+Pinecone的JS代码中限制返回的sourceDocs数量?

问题与解决方案:LangChain+Pinecone仅返回最相关的1个SourceDocument

问题描述

我正在使用LangChain搭配Pinecone,当前响应会返回4个sourceDocs,但我只需要最相关的1个。我使用JavaScript开发,不清楚应该在代码的何处设置top_k参数。

原代码如下:

export const makeChain = (vectorStore) => {
  const model = new OpenAI({
    temperature: 0,
    modelName: 'gpt-3.5-turbo', 
  });

  const chain = ConversationalRetrievalQAChain.fromLLM(
    model,
    vectorStore.asRetriever(),
    {
      qaTemplate: QA_PROMPT,
      questionGeneratorTemplate: CONDENSE_PROMPT,
      returnSourceDocuments: true,
    }
  );
  return chain;
};
/* create vectorStore*/
const vectorStore = await PineconeStore.fromExistingIndex(
  new OpenAIEmbeddings({}),
  {
    pineconeIndex: index,
    textKey: 'text',
    namespace: PINECONE_NAME_SPACE, //namespace comes from your config folder
  }
);

//create chain
const chain = makeChain(vectorStore);
//Ask a question using chat history
const response = await chain.call({
  question: sanitizedQuestion,
  chat_history: history || [],
});

解决方案

你需要在调用vectorStore.asRetriever()时传入配置参数,通过k控制返回的最相关文档数量(对应Pinecone的top_k)。具体修改如下:

修改makeChain函数中vectorStore.asRetriever()这一行,添加{ k: 1 }参数:

export const makeChain = (vectorStore) => {
  const model = new OpenAI({
    temperature: 0,
    modelName: 'gpt-3.5-turbo', 
  });

  const chain = ConversationalRetrievalQAChain.fromLLM(
    model,
    // 设置k=1,仅返回最相关的1个文档
    vectorStore.asRetriever({ k: 1 }),
    {
      qaTemplate: QA_PROMPT,
      questionGeneratorTemplate: CONDENSE_PROMPT,
      returnSourceDocuments: true,
    }
  );
  return chain;
};

说明

LangChain的Retriever组件中,k参数用于指定向量检索时返回的匹配文档数量,设置为1后,Pinecone会仅返回与查询最相关的1条文档,最终sourceDocs数组就只会包含1个元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:52:22