HNSWLib
仅适用于 Node.js。
HNSWLib 是一个可以保存到文件的内存向量存储,它使用 HNSWLib 库。
本指南提供了使用 HNSWLib 向量存储
的快速概述。如需了解所有 HNSWLib 功能和配置的详细文档,请访问 API
参考文档。
概览
集成详情
| 类 | 包 | 支持 PY | 包的最新版本 |
|---|---|---|---|
HNSWLib | @langchain/community | ❌ | ![]() |
安装
要使用 HNSWLib 向量存储,你需要安装 @langchain/community 集成包,并将
hnswlib-node
包作为对等依赖项。
本指南还将使用 OpenAI
嵌入,这要求你安装
@langchain/openai 集成包。如果你愿意,也可以使用
其他支持的嵌入模型。
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- yarn
- pnpm
npm i @langchain/community hnswlib-node @langchain/openai @langchain/core
yarn add @langchain/community hnswlib-node @langchain/openai @langchain/core
pnpm add @langchain/community hnswlib-node @langchain/openai @langchain/core
在 Windows 上,你可能需要先安装 Visual Studio 才能正确构建 hnswlib-node 包。
凭据
由于 HNSWLib 是在本地运行的,因此你不需要任何凭据来使用它。
如果你在本指南中使用 OpenAI 嵌入,则还需要设置你的 OpenAI 密钥:
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
如果你想对模型调用进行自动跟踪,也可以通过取消注释以下内容来设置你的 LangSmith API 密钥:
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
实例化
import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const vectorStore = await HNSWLib.fromDocuments([], embeddings);
管理向量存储
向向量存储中添加项目
import type { Document } from "@langchain/core/documents";
const document1: Document = {
pageContent: "The powerhouse of the cell is the mitochondria",
metadata: { source: "https://example.com" },
};
const document2: Document = {
pageContent: "Buildings are made out of brick",
metadata: { source: "https://example.com" },
};
const document3: Document = {
pageContent: "Mitochondria are made out of lipids",
metadata: { source: "https://example.com" },
};
const document4: Document = {
pageContent: "The 2024 Olympics are in Paris",
metadata: { source: "https://example.com" },
};
const documents = [document1, document2, document3, document4];
await vectorStore.addDocuments(documents);
目前不支持单个文档的删除和 ID 功能。
查询向量存储
一旦您的向量存储创建完成并添加了相关文档,在运行链或代理时很可能需要对其进行查询。
直接查询
执行一个简单的相似性搜索可以按照以下方式:
const filter = (doc) => doc.metadata.source === "https://example.com";
const similaritySearchResults = await vectorStore.similaritySearch(
"biology",
2,
filter
);
for (const doc of similaritySearchResults) {
console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* Mitochondria are made out of lipids [{"source":"https://example.com"}]
过滤器是可选的,必须是一个谓词函数,以文档作为输入,并根据是否应返回该文档返回
true 或 false。 如果你想执行相似性搜索并获取相应的得分,可以运行:
const similaritySearchWithScoreResults =
await vectorStore.similaritySearchWithScore("biology", 2, filter);
for (const [doc, score] of similaritySearchWithScoreResults) {
console.log(
`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(
doc.metadata
)}]`
);
}
* [SIM=0.835] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.852] Mitochondria are made out of lipids [{"source":"https://example.com"}]
通过转换为检索器进行查询
您还可以将向量存储转换为检索器,以便在您的链中更方便地使用。
const retriever = vectorStore.asRetriever({
// Optional filter
filter: filter,
k: 2,
});
await retriever.invoke("biology");
[
{
pageContent: 'The powerhouse of the cell is the mitochondria',
metadata: { source: 'https://example.com' }
},
{
pageContent: 'Mitochondria are made out of lipids',
metadata: { source: 'https://example.com' }
}
]
检索增强生成的用法
有关如何将此向量存储用于检索增强生成(RAG)的指南,请参阅以下部分:
保存到文件/从文件加载
HNSWLib 支持将你的索引保存到文件中,然后在以后重新加载:
// Save the vector store to a directory
const directory = "your/directory/here";
await vectorStore.save(directory);
// Load the vector store from the same directory
const loadedVectorStore = await HNSWLib.load(directory, new OpenAIEmbeddings());
// vectorStore and loadedVectorStore are identical
await loadedVectorStore.similaritySearch("hello world", 1);
删除已保存的索引
你可以使用 .delete 方法来清除保存到指定目录的索引:
// Load the vector store from the same directory
const savedVectorStore = await HNSWLib.load(directory, new OpenAIEmbeddings());
await savedVectorStore.delete({ directory });
API 参考文档
如需详细了解所有 HNSWLib 的功能和配置,请前往 API
参考文档。
Related
- Vector store conceptual guide
- Vector store how-to guides
