HyDE 检索器
¥HyDE Retriever
此示例展示了如何使用 HyDE Retriever,它实现了 此论文 中描述的假设文档嵌入 (HyDE)。
¥This example shows how to use the HyDE Retriever, which implements Hypothetical Document Embeddings (HyDE) as described in this paper.
从高层次来看,HyDE 是一种嵌入技术,它接受查询,生成假设答案,然后嵌入生成的文档并将其用作最终示例。
¥At a high level, HyDE is an embedding technique that takes queries, generates a hypothetical answer, and then embeds that generated document and uses that as the final example.
为了使用 HyDE,我们需要提供一个基础的嵌入模型,以及一个可用于生成这些文档的 LLM。默认情况下,HyDE 类自带一些默认提示(更多详情请参阅论文),但我们也可以创建自己的提示,该提示应包含单个输入变量 {question}
。
¥In order to use HyDE, we therefore need to provide a base embedding model, as well as an LLM that can be used to generate those documents. By default, the HyDE class comes with some default prompts to use (see the paper for more details on them), but we can also create our own, which should have a single input variable {question}
.
用法
¥Usage
- npm
- Yarn
- pnpm
npm install @langchain/openai @langchain/core
yarn add @langchain/openai @langchain/core
pnpm add @langchain/openai @langchain/core
import { OpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { HydeRetriever } from "langchain/retrievers/hyde";
import { Document } from "@langchain/core/documents";
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.invoke("What is my favourite food?");
console.log(results);
/*
[
Document { pageContent: 'My favourite food is pasta.', metadata: {} }
]
*/
API Reference:
- OpenAI from
@langchain/openai
- OpenAIEmbeddings from
@langchain/openai
- MemoryVectorStore from
langchain/vectorstores/memory
- HydeRetriever from
langchain/retrievers/hyde
- Document from
@langchain/core/documents
相关
¥Related
检索器 概念指南
¥Retriever conceptual guide
检索器 操作指南
¥Retriever how-to guides