Skip to main content

HyDE Retriever

本示例展示了如何使用HyDE Retriever,其实现了Hypothetical Document Embeddings(HyDE),具体内容参见这篇论文

在更高的层次上,HyDE是一种嵌入技术,它接受查询,生成假定答案,然后将生成的文档嵌入并将其用作最终示例。

为了使用HyDE,我们需要提供基础嵌入模型以及可用于生成这些文档的LLM。默认情况下,HyDE类带有一些默认提示(有关它们的详细信息,请参见论文),但我们也可以创建自己的提示,这些提示应该有一个单一的输入变量 {question}

用法

import { OpenAI } from "langchain/llms/openai";
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { HydeRetriever } from "langchain/retrievers/hyde";
import { Document } from "langchain/document";

const embeddings = new OpenAIEmbeddings();
const vectorStore = new MemoryVectorStore(embeddings);
const llm = new OpenAI();
const retriever = new HydeRetriever({
vectorStore,
llm,
k: 1,
});

await vectorStore.addDocuments(
[
"My name is John.",
"My name is Bob.",
"My favourite food is pizza.",
"My favourite food is pasta.",
].map((pageContent) => new Document({ pageContent }))
);

const results = await retriever.getRelevantDocuments(
"What is my favourite food?"
);

console.log(results);
/*
[
Document { pageContent: 'My favourite food is pasta.', metadata: {} }
]
*/