跳到主要内容
此示例展示了如何使用 HyDE Retriever,它实现了 这篇论文 中描述的假设文档嵌入 (HyDE)。 概括地说,HyDE 是一种嵌入技术,它接收查询,生成假设性答案,然后嵌入该生成的文档并将其用作最终示例。 因此,为了使用 HyDE,我们需要提供一个基础嵌入模型,以及一个可用于生成这些文档的 LLM。默认情况下,HyDE 类带有一些默认的提示(有关更多详细信息,请参阅论文),但我们也可以创建自己的提示,这些提示应具有一个输入变量 {question}

用法

import { OpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { HydeRetriever } from "@langchain/classic/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: {} }
]
*/

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