Skip to main content
兼容性:仅在 Node.js 上可用。
Faiss 是一个用于高效相似度搜索和密集向量聚类的库。 LangChain.js 支持使用 Faiss 作为本地运行的向量存储,并可以保存到文件。它还提供了从 LangChain Python 实现 中读取已保存文件的功能。 本指南提供了 Faiss 向量存储 入门的快速概述。有关所有 FaissStore 功能和配置的详细文档,请参阅 API 参考

概述

集成详细信息

设置

要使用 Faiss 向量存储,您需要安装 @langchain/community 集成包,并安装 faiss-node 包作为对等依赖项。 本指南还将使用 OpenAI 嵌入,这需要您安装 @langchain/openai 集成包。如果您愿意,也可以使用 其他支持的嵌入模型
npm install @langchain/community faiss-node @langchain/openai @langchain/core

凭据

由于 Faiss 在本地运行,因此您不需要任何凭据即可使用它。 如果您在本指南中使用 OpenAI 嵌入,您还需要设置您的 OpenAI 密钥:
OPENAI_API_KEY = "YOUR_API_KEY";
如果您想获得模型调用的自动跟踪,还可以通过取消注释下方内容来设置您的 LangSmith API 密钥:
// LANGSMITH_TRACING="true"
// LANGSMITH_API_KEY="your-api-key"

实例化

import { FaissStore } from "@langchain/community/vectorstores/faiss";
import { OpenAIEmbeddings } from "@langchain/openai";

const embeddings = new OpenAIEmbeddings({
  model: "text-embedding-3-small",
});

const vectorStore = new FaissStore(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, { ids: ["1", "2", "3", "4"] });
[ '1', '2', '3', '4' ]

从向量存储中删除项目

await vectorStore.delete({ ids: ["4"] });

查询向量存储

一旦您的向量存储已创建并且相关文档已添加,您很可能希望在运行链或代理期间查询它。

直接查询

执行简单的相似度搜索可以按如下方式完成:
const similaritySearchResults = await vectorStore.similaritySearch("biology", 2);

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"}]
目前不支持按元数据过滤。 如果您想执行相似度搜索并接收相应的分数,您可以运行:
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2);

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
* [SIM=1.671] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=1.705] Mitochondria are made out of lipids [{"source":"https://example.com"}]

通过转换为检索器进行查询

您还可以将向量存储转换为 检索器,以便在链中更轻松地使用。
const retriever = vectorStore.asRetriever({
  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) 的指南,请参阅以下部分:

合并索引

Faiss 还支持合并现有索引:
// Create an initial vector store
const initialStore = await FaissStore.fromTexts(
  ["Hello world", "Bye bye", "hello nice world"],
  [{ id: 2 }, { id: 1 }, { id: 3 }],
  new OpenAIEmbeddings()
);

// Create another vector store from texts
const newStore = await FaissStore.fromTexts(
  ["Some text"],
  [{ id: 1 }],
  new OpenAIEmbeddings()
);

// merge the first vector store into vectorStore2
await newStore.mergeFrom(initialStore);

// You can also create a new vector store from another FaissStore index
const newStore2 = await FaissStore.fromIndex(
  newStore,
  new OpenAIEmbeddings()
);

await newStore2.similaritySearch("Bye bye", 1);

将索引保存到文件并重新加载

要将索引持久保存到磁盘,请使用 .save 和静态 .load 方法:
// Create a vector store through any method, here from texts as an example
const persistentStore = await FaissStore.fromTexts(
  ["Hello world", "Bye bye", "hello nice world"],
  [{ id: 2 }, { id: 1 }, { id: 3 }],
  new OpenAIEmbeddings()
);

// Save the vector store to a directory
const directory = "your/directory/here";

await persistentStore.save(directory);

// Load the vector store from the same directory
const loadedVectorStore = await FaissStore.load(
  directory,
  new OpenAIEmbeddings()
);

// vectorStore and loadedVectorStore are identical
const result = await loadedVectorStore.similaritySearch("hello world", 1);
console.log(result);

从 Python 读取保存的文件

要启用从 LangChain Python 实现 读取已保存文件的功能,您需要安装 pickleparser 包。
npm install pickleparser
然后,您可以使用 .loadFromPython 静态方法:
// The directory of data saved from Python
const directoryWithSavedPythonStore = "your/directory/here";

// Load the vector store from the directory
const pythonLoadedStore = await FaissStore.loadFromPython(
  directoryWithSavedPythonStore,
  new OpenAIEmbeddings()
);

// Search for the most similar document
await pythonLoadedStore.similaritySearch("test", 2);

API 参考

有关所有 FaissStore 功能和配置的详细文档,请参阅 API 参考