Skip to main content
LangChain 提供了一个内存中的临时向量存储,它在内存中存储嵌入向量,并通过精确的线性搜索来查找最相似的嵌入向量。默认的相似度度量是余弦相似度,但可以更改为 ml-distance 支持的任何相似度度量。 由于它主要用于演示,目前还不支持 ID 或删除功能。 本指南提供了快速入门 MemoryVectorStore 向量存储 的简要概述。

概述

集成详情

支持 Python版本
MemoryVectorStorelangchainNPM - 版本

设置

要使用内存向量存储,你需要安装 langchain 包: 本指南还将使用 OpenAI 嵌入,这需要你安装 @langchain/openai 集成包。你也可以根据需要选择使用 其他支持的嵌入模型
npm install langchain @langchain/openai @langchain/core

凭证

使用内存向量存储不需要任何凭证。 如果你在本指南中使用 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 { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";

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

const vectorStore = new MemoryVectorStore(embeddings);

管理向量存储

向向量存储添加项目

import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "细胞的动力源是线粒体",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "建筑物由砖块构成",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "线粒体由脂质构成",
  metadata: { source: "https://example.com" }
};

const documents = [document1, document2, document3];

await vectorStore.addDocuments(documents);

查询向量存储

一旦你的向量存储创建完成并添加了相关文档,你很可能会希望在运行链或代理时查询它。

直接查询

执行简单的相似性搜索可以按如下方式进行:
const filter = (doc) => doc.metadata.source === "https://example.com";

const similaritySearchResults = await vectorStore.similaritySearch("生物学", 2, filter)

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* 细胞的动力源是线粒体 [{"source":"https://example.com"}]
* 线粒体由脂质构成 [{"source":"https://example.com"}]
过滤器是可选的,必须是一个谓词函数,它接收一个文档作为输入,并根据文档是否应返回来返回 truefalse 如果你想执行相似性搜索并获取相应的分数,可以运行:
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("生物学", 2, filter)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [相似度=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
* [相似度=0.165] 细胞的动力源是线粒体 [{"source":"https://example.com"}]
* [相似度=0.148] 线粒体由脂质构成 [{"source":"https://example.com"}]

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

你也可以将向量存储转换为 检索器,以便在你的链中更轻松地使用:
const retriever = vectorStore.asRetriever({
  // 可选过滤器
  filter: filter,
  k: 2,
});

await retriever.invoke("生物学");
[
  Document {
    pageContent: '细胞的动力源是线粒体',
    metadata: { source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: '线粒体由脂质构成',
    metadata: { source: 'https://example.com' },
    id: undefined
  }
]

最大边际相关性

此向量存储还支持最大边际相关性(MMR),这是一种首先通过经典相似性搜索获取更多结果(由 searchKwargs.fetchK 指定),然后根据多样性重新排序并返回前 k 个结果的技术。这有助于防止冗余信息:
const mmrRetriever = vectorStore.asRetriever({
  searchType: "mmr",
  searchKwargs: {
    fetchK: 10,
  },
  // 可选过滤器
  filter: filter,
  k: 2,
});

await mmrRetriever.invoke("生物学");
[
  Document {
    pageContent: '细胞的动力源是线粒体',
    metadata: { source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: '建筑物由砖块构成',
    metadata: { source: 'https://example.com' },
    id: undefined
  }
]

用于检索增强生成

有关如何使用此向量存储进行检索增强生成(RAG)的指南,请参阅以下部分: