跳到主要内容
时间加权检索器是一种除了相似度之外还考虑了时效性的检索器。其评分算法为
let score = (1.0 - this.decayRate) ** hoursPassed + vectorRelevance;
值得注意的是,上述的 hoursPassed 指的是检索器中的对象最后一次被访问的时间,而不是它被创建的时间。这意味着经常被访问的对象会保持“新鲜”并获得更高的分数。 this.decayRate 是一个介于 0 和 1 之间的可配置小数。数字越小,表示文档被“记住”的时间越长,而数字越大则强烈地倾向于更近期访问的文档。 请注意,将衰减率精确设置为 0 或 1 会使 hoursPassed 不相关,并使此检索器等同于标准向量查找。

用法

此示例展示了如何使用向量存储来初始化 TimeWeightedVectorStoreRetriever。需要注意的是,由于所需的元数据,所有文档必须使用检索器addDocuments 方法添加到后端向量存储中,而不是向量存储本身。
import { TimeWeightedVectorStoreRetriever } from "@langchain/classic/retrievers/time_weighted";
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";

const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());

const retriever = new TimeWeightedVectorStoreRetriever({
  vectorStore,
  memoryStream: [],
  searchKwargs: 2,
});

const documents = [
  "My name is John.",
  "My name is Bob.",
  "My favourite food is pizza.",
  "My favourite food is pasta.",
  "My favourite food is sushi.",
].map((pageContent) => ({ pageContent, metadata: {} }));

// All documents must be added using this method on the retriever (not the vector store!)
// so that the correct access history metadata is populated
await retriever.addDocuments(documents);

const results1 = await retriever.invoke("What is my favourite food?");

console.log(results1);

/*
[
  Document { pageContent: 'My favourite food is pasta.', metadata: {} }
]
 */

const results2 = await retriever.invoke("What is my favourite food?");

console.log(results2);

/*
[
  Document { pageContent: 'My favourite food is pasta.', metadata: {} }
]
 */

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.