SupabaseVectorStore
Supabase 是一个开源的 Firebase 替代方案。Supabase 构建在 PostgreSQL 之上,提供了强大的 SQL 查询功能,并能够与现有的工具和框架实现简单接口。
LangChain.js 支持使用 Supabase Postgres 数据库作为向量存储,使用
pgvector 扩展。更多信息请参考
Supabase
博客文章。
本指南提供了关于 Supabase 向量存储
的快速入门概览。有关 SupabaseVectorStore
所有功能和配置的详细文档,请前往 API
参考文档。
概述
集成详情
| 类 | 包 | Python 支持 | 包的最新版本 |
|---|---|---|---|
SupabaseVectorStore | @langchain/community | ✅ | ![]() |
配置
要使用 Supabase 向量存储,你需要设置一个 Supabase 数据库并安装
@langchain/community 集成包。你还需要安装官方的
@supabase/supabase-js
SDK 作为对等依赖。
本指南还将使用 OpenAI
嵌入,这要求你安装
@langchain/openai 集成包。如果需要,你也可以使用
其他支持的嵌入模型。
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- yarn
- pnpm
npm i @langchain/community @langchain/core @supabase/supabase-js @langchain/openai
yarn add @langchain/community @langchain/core @supabase/supabase-js @langchain/openai
pnpm add @langchain/community @langchain/core @supabase/supabase-js @langchain/openai
创建数据库后,运行以下 SQL 语句来设置
pgvector
并创建必要的表和函数:
-- 启用 pgvector 扩展以处理嵌入向量
create extension vector;
-- 创建一个表来存储你的文档
create table documents (
id bigserial primary key,
content text, -- 对应 Document.pageContent
metadata jsonb, -- 对应 Document.metadata
embedding vector(1536) -- 1536 适用于 OpenAI 嵌入,根据需要更改
);
-- 创建一个函数用于搜索文档
create function match_documents (
query_embedding vector(1536),
match_count int DEFAULT null,
filter jsonb DEFAULT '{}'
) returns table (
id bigint,
content text,
metadata jsonb,
embedding jsonb,
similarity float
)
language plpgsql
as $$
#variable_conflict use_column
begin
return query
select
id,
content,
metadata,
(embedding::text)::jsonb as embedding,
1 - (documents.embedding <=> query_embedding) as similarity
from documents
where metadata @> filter
order by documents.embedding <=> query_embedding
limit match_count;
end;
$$;
凭据
完成上述操作后,请设置 SUPABASE_PRIVATE_KEY 和 SUPABASE_URL
环境变量:
process.env.SUPABASE_PRIVATE_KEY = "your-api-key";
process.env.SUPABASE_URL = "your-supabase-db-url";
如果你在本指南中使用 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 { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";
import { OpenAIEmbeddings } from "@langchain/openai";
import { createClient } from "@supabase/supabase-js";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const supabaseClient = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_PRIVATE_KEY
);
const vectorStore = new SupabaseVectorStore(embeddings, {
client: supabaseClient,
tableName: "documents",
queryName: "match_documents",
});
管理向量存储
向向量存储中添加条目
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 filter = { 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"}]
如果你想执行相似性搜索并获得相应的分数,可以运行:
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.165] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.148] Mitochondria are made out of lipids [{"source":"https://example.com"}]
元数据查询构建器过滤
你也可以使用类似 Supabase JavaScript
库
的查询构建器风格进行过滤,而不必传递一个对象。请注意,由于大多数过滤属性都在
metadata 列中,你需要使用箭头操作符(-> 表示整数,->>
表示文本),具体定义请参阅 Postgrest API
文档,并指定属性的数据类型(例如,该列应类似于
metadata->some_int_prop_name::int)。
import { SupabaseFilterRPCCall } from "@langchain/community/vectorstores/supabase";
const funcFilter: SupabaseFilterRPCCall = (rpc) =>
rpc.filter("metadata->>source", "eq", "https://example.com");
const funcFilterSearchResults = await vectorStore.similaritySearch(
"biology",
2,
funcFilter
);
for (const doc of funcFilterSearchResults) {
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 retriever = vectorStore.asRetriever({
// Optional filter
filter: filter,
k: 2,
});
await retriever.invoke("biology");
[
Document {
pageContent: 'The powerhouse of the cell is the mitochondria',
metadata: { source: 'https://example.com' },
id: undefined
},
Document {
pageContent: 'Mitochondria are made out of lipids',
metadata: { source: 'https://example.com' },
id: undefined
}
]
检索增强生成的用法
有关如何将此向量存储用于检索增强生成(RAG)的指南,请参阅以下部分:
API 参考文档
要详细了解所有 SupabaseVectorStore 的功能和配置,请前往 API
参考文档。
Related
- Vector store conceptual guide
- Vector store how-to guides
