时间加权检索器
时间加权检索器是一种除了相似性之外,还会考虑时间近因性的检索器。评分算法是
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 参考
- TimeWeightedVectorStoreRetriever 来自
langchain/retrievers/time_weighted
- MemoryVectorStore 来自
langchain/vectorstores/memory
- OpenAIEmbeddings 来自
@langchain/openai