时间加权检索器
时间加权检索器是一种在考虑相似性的同时还考虑时间新旧程度的检索器。其评分算法如下:
let score = (1.0 - this.decayRate) ** hoursPassed + vectorRelevance;
值得注意的是,上面的 hoursPassed 指的是自检索器中的对象上次被访问以来的时间,而不是自其创建以来的时间。这意味着频繁访问的对象会保持“新鲜”,并获得更高的评分。
this.decayRate 是一个介于 0 和 1 之间的可配置小数。数值越低表示文档会被“记住”更长时间,而数值越高则会显著提升最近访问文档的权重。
请注意,如果将衰减率设置为恰好 0 或 1,则 hoursPassed 将变得无关紧要,此时该检索器等效于标准的向量检索器。
使用方法
以下示例展示了如何使用向量存储初始化一个 TimeWeightedVectorStoreRetriever。
需要注意的是,由于需要元数据,所有文档都必须使用检索器上的 addDocuments 方法添加到背后的向量存储中,而不是直接使用向量存储本身的方法。
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- Yarn
- pnpm
npm install @langchain/openai @langchain/core
yarn add @langchain/openai @langchain/core
pnpm add @langchain/openai @langchain/core
import { TimeWeightedVectorStoreRetriever } from "langchain/retrievers/time_weighted";
import { MemoryVectorStore } from "langchain/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: {} }
]
*/
API Reference:
- TimeWeightedVectorStoreRetriever from
langchain/retrievers/time_weighted - MemoryVectorStore from
langchain/vectorstores/memory - OpenAIEmbeddings from
@langchain/openai
相关内容
Related
- Retriever conceptual guide
- Retriever how-to guides