
pgai Vectorizer 快速上手用 VoyageAI 嵌入在 PostgreSQL 中自动构建语义搜索与重排序【免费下载链接】pgaiA suite of tools to develop RAG, semantic search, and other AI applications more easily with PostgreSQL项目地址: https://gitcode.com/GitHub_Trending/pg/pgai本文基于 pgai 仓库的官方文档 Vectorizer quick start with VoyageAI 展开完整走通本地 Docker 环境搭建 → 安装 pgai 扩展 → 用 VoyageAI 创建 Vectorizer 自动嵌入 → 语义搜索 → Reranker 重排序的全流程并结合仓库中的 SQL 函数定义017-voyageai.sql、004-embedding.sql与 Worker 端嵌入器源码embedders/voyageai.py解释每个参数在底层是如何生效的。读完后你可以照搬文中的docker-compose.yml与 SQL 语句在自己的一台机器上跑起一套 VoyageAI 驱动的自动嵌入 语义搜索管道。前置条件与本地开发环境要跟随本教程你需要一个 Voyage AI 账户的 API Key以及本机安装了 Docker / Docker Compose。pgai 的 Vectorizer 采用数据库内声明 后台 Worker 异步执行的架构CREATE一个 vectorizer 只是在数据库里登记配置真正调用 VoyageAI API 生成向量的是独立的vectorizer worker进程。因此本地环境需要两个服务官方 TimescaleDB 镜像内置 pgai、pgvectorscale 与 timescaledb 扩展pgai 官方的timescale/pgai-vectorizer-workerWorker 镜像。仓库自带了一份几乎相同的最小化 compose 文件可直接参考 examples/docker_compose_pgai/docker-compose.yml。官方教程给出的完整配置如下注意VOYAGE_API_KEY需要同时给db与vectorizer-worker两个服务因为数据库内函数和 Worker 都可能发起 API 调用name: pgai services: db: image: timescale/timescaledb-ha:pg17 environment: POSTGRES_PASSWORD: postgres VOYAGE_API_KEY: your-api-key ports: - 5432:5432 volumes: - data:/home/postgres/pgdata/data vectorizer-worker: image: timescale/pgai-vectorizer-worker:latest environment: PGAI_VECTORIZER_WORKER_DB_URL: postgres://postgres:postgresdb:5432/postgres VOYAGE_API_KEY: your-api-key command: [ --poll-interval, 5s ] volumes: data:几点说明PGAI_VECTORIZER_WORKER_DB_URL是 Worker 连接数据库的地址容器网络中数据库主机名即db--poll-interval 5s表示 Worker 每 5 秒轮询一次是否有待处理的 vectorizer 任务。自托管场景下 schedulingTimescaleDB 后台作业默认是关闭的Worker 的轮询机制就是唯一的执行驱动详见 Vectorizer 概览 的 Control the vectorizer run time 一节与 Worker 文档API Key 通过环境变量注入Key 名称VOYAGE_API_KEY与 pgai 内置的默认密钥名一致——源码中ai.voyageai模块定义了DEFAULT_KEY_NAME VOYAGE_API_KEY见 ai/voyageai.py。启动并安装扩展# 1. 启动服务 docker compose up -d # 2. 用 worker 镜像内的 CLI 把 pgai 安装进数据库 docker compose run --rm --entrypoint python -m pgai install -d postgres://postgres:postgresdb:5432/postgres vectorizer-worker启用扩展、建表并灌入示例数据连接数据库docker compose exec -it db psql或本地psql postgres://postgres:postgreslocalhost:5432/postgres先启用扩展CREATE EXTENSION IF NOT EXISTS ai CASCADE;接着创建示例的blog表并插入 5 条数据这也是官方教程使用的完整样例CREATE TABLE blog ( id SERIAL PRIMARY KEY, title TEXT, authors TEXT, contents TEXT, metadata JSONB ); INSERT INTO blog (title, authors, contents, metadata) VALUES (Getting Started with PostgreSQL, John Doe, PostgreSQL is a powerful, open source object-relational database system..., {tags: [database, postgresql, beginner], read_time: 5, published_date: 2024-03-15}), (10 Tips for Effective Blogging, Jane Smith, Mike Johnson, Blogging can be a great way to share your thoughts and expertise..., {tags: [blogging, writing, tips], read_time: 8, published_date: 2024-03-20}), (The Future of Artificial Intelligence, Dr. Alan Turing, As we look towards the future, artificial intelligence continues to evolve..., {tags: [AI, technology, future], read_time: 12, published_date: 2024-04-01}), (Healthy Eating Habits for Busy Professionals, Samantha Lee, Maintaining a healthy diet can be challenging for busy professionals..., {tags: [health, nutrition, lifestyle], read_time: 6, published_date: 2024-04-05}), (Introduction to Cloud Computing, Chris Anderson, Cloud computing has revolutionized the way businesses operate..., {tags: [cloud, technology, business], read_time: 10, published_date: 2024-04-10});创建 VoyageAI VectorizerVectorizer 是 pgai 的核心概念声明式地指定对哪张表的哪个列做嵌入、用哪个模型、存到哪里之后由 Worker 自动生成并持续同步向量。SELECT ai.create_vectorizer( blog::regclass, loading ai.loading_column(contents), embedding ai.embedding_voyageai( voyage-3.5-lite, -- or voyage-3.5, voyage-3-large, voyage-code-3, etc. 1024 -- default dimensions for voyage-3.5-lite ), destination ai.destination_table(blog_contents_embeddings) );四个关键参数loading_column(contents)从contents列读取待嵌入文本长文本会自动切块一条博客可能产生多条向量embedding_voyageai(model, dimensions)VoyageAI 嵌入配置模型名与目标维度destination_table(blog_contents_embeddings)嵌入存储目标会创建..._store存储表和一个同名的查询视图未指定chunking/formatting/indexing时使用默认值。从源码结构看ai.embedding_voyageai并不直接调 API而是一个配置构造器它定义在 004-embedding.sql 中签名为(model, dimensions, input_type, api_key_name)返回一段 JSONB 配置implementation: voyageai, config_type: embedding其中input_type默认document只允许query/document否则抛异常api_key_name默认VOYAGE_API_KEY。create_vectorizer把这份 JSONB 存入 vectorizer 元数据表Worker 侧再据此实例化 Python 的VoyageAIembedderembedders/voyageai.py真正发起 API 调用。这个SQL 声明 → JSONB 配置 → Python 执行的分离设计正是自托管 Worker 与 Timescale Cloud 后台作业可以共用同一份 vectorizer 定义的原因。Worker 端 embedder 还有两个对批量任务影响很大的内部细节见 embedders/voyageai.py 与 L98-L103每批最多 128 个 chunk_max_chunks_per_batch每批 token 上限按模型区分voyage-3.5-lite/voyage-3-lite为 1,000,000voyage-3.5/voyage-3/voyage-2为 320,000其余专业与旧模型保守取 120,000并且会用 VoyageAI 客户端自带的 tokenizer 精确统计每个文档的 token 数来切批。可用模型模型定位维度voyage-3.5-lite成本与延迟优化1M tokens/request——官方推荐1024voyage-3.5通用优化320K tokens/request1024voyage-3-large通用与多语言最佳120K tokens/request1024voyage-code-3代码检索专用120K tokens/request1024voyage-finance-2金融领域优化1024voyage-law-2法律文档优化1024voyage-3-lite旧模型120K tokens/request512灵活维度output_dimensionvoyage-3.x 系列支持 Matryoshka套娃嵌入可以指定output_dimension截短向量降低存储与检索开销。官方文档给出的示例-- Use 256 dimensions for 75% storage reduction SELECT ai.create_vectorizer( blog::regclass, loading ai.loading_column(contents), embedding ai.embedding_voyageai( voyage-3.5-lite, 1024, -- Schema dimensions output_dimension 256 -- Actual embedding dimensions ), destination ai.destination_table(blog_embeddings_compact) );维度取舍建议引自原文档256 维检索最快、存储省 75%、精度损失很小512 维性能与精度均衡1024 维为默认、精度最高2048 维用于复杂任务的最大精度。Worker 端的VoyageAIembedder 类确实实现了output_dimension字段并在调用 API 时透传给 Voyage 接口见 embedders/voyageai.py。需要注意的是当前仓库中 SQL 侧ai.embedding_voyageai的函数签名只暴露了model、dimensions、input_type、api_key_name四个参数004-embedding.sql实际使用时请以你所安装版本提供的签名为准。量化output_dtype用output_dtype可以减少网络带宽与 API 传输成本-- Use int8 quantization for 4x bandwidth reduction SELECT ai.create_vectorizer( blog::regclass, loading ai.loading_column(contents), embedding ai.embedding_voyageai( voyage-3.5-lite, 1024, output_dtype int8 -- Options: float, int8, uint8, binary, ubinary ), destination ai.destination_table(blog_embeddings_quantized) );量化选项取值说明float默认不压缩每维 4 字节int8整数量化传输体积约 1/4uint8无符号整数量化传输体积约 1/4binary最大压缩约 1/32每维 1 bitubinary无符号 binary约 1/32原文档特别强调了一点这里保留量化向量在存入 PostgreSQL 前会自动转换回 float因此省的是网络带宽和传输成本而不是数据库存储成本。同样地Worker 端 embedder 的output_dtype字段会在 API 调用参数中原样透传embedders/voyageai.py。观察 Worker 处理过程创建 vectorizer 后跟踪 Worker 日志即可看到它拾取并处理任务docker compose logs -f vectorizer-worker输出类似vectorizer-worker-1 | 2024-10-23 12:56:36 [info ] running vectorizer vectorizer_id1Worker 处理完成后blog_contents_embeddings_store表中会填充向量blog_contents_embeddings视图会自动把源表列与嵌入数据 join 起来。语义搜索用 cosine 距离找最相似的 chunk现在可以跑教程中的标准搜索查询——查询词先用数据库内函数ai.voyageai_embed实时嵌入再与表中向量做余弦距离排序SELECT chunk, embedding ai.voyageai_embed(voyage-3.5-lite, good food) as distance FROM blog_contents_embeddings ORDER BY distance;是 pgvector 的余弦距离算子越小越相似。结果引自原文档的运行输出ChunkDistanceMaintaining a healthy diet can be challenging for busy professionals...0.6102883386268212Blogging can be a great way to share your thoughts and expertise...0.7245166465928164PostgreSQL is a powerful, open source object-relational database system...0.7789760644464416As we look towards the future, artificial intelligence continues to evolve...0.9036547272308249Cloud computing has revolutionized the way businesses operate...0.9131323552491029good food 命中了健康饮食相关文章语义搜索生效。从源码结构看ai.voyageai_embed在 017-voyageai.sql 中以 plpython3u 实现完整签名为(model, input_text, input_type, api_key, api_key_name, verbose)标记为immutable parallel safe security invoker。它通过ai.secrets.get_secret按api_key→api_key_name→ 默认名VOYAGE_API_KEY的顺序解析密钥再调用 ai/voyageai.py 中同步的embed()函数同样支持truncation、output_dimension、output_dtype透传。同文件还定义了数组版重载可一次嵌入多条文本。这意味着你既可以在应用侧嵌入查询词也可以像上面这样全在 SQL 内完成嵌入与检索。用 VoyageAI Reranker 重排序Voyage AI 还提供 reranker把初检结果按与查询的相关度重新排序进一步提升 Top-K 精度。pgai 暴露了两个 SQL 函数定义见 017-voyageai.sqlai.voyageai_rerank(...)返回原始 JSONB 响应ai.voyageai_rerank_simple(...)基于前者做jsonb_to_recordset展开返回index / document / relevance_score三列的表函数可直接在 SQL 里ORDER BY。基本用法SELECT * FROM ai.voyageai_rerank_simple( rerank-2.5, What are best practices for healthy eating?, ARRAY[ Maintaining a healthy diet can be challenging for busy professionals..., Blogging can be a great way to share your thoughts and expertise..., PostgreSQL is a powerful, open source object-relational database system..., As we look towards the future, artificial intelligence continues to evolve..., Cloud computing has revolutionized the way businesses operate... ], api_key your-api-key ) ORDER BY relevance_score DESC;indexdocumentrelevance_score0Maintaining a healthy diet can be challenging...0.91561Blogging can be a great way to share...0.23414Cloud computing has revolutionized...0.1023.........用 top_k 截断结果SELECT * FROM ai.voyageai_rerank_simple( rerank-2.5-lite, healthy eating, ARRAY[...], api_key your-api-key, top_k 3 ) ORDER BY relevance_score DESC;可用 Reranker 模型引自原文档模型上下文长度适用rerank-2.532K tokens质量优先支持多语言/指令当前代推荐rerank-2.5-lite32K tokens延迟与质量平衡当前代推荐rerank-216K tokens旧版rerank-2-lite8K tokens旧版rerank-18K tokens旧版rerank-lite-14K tokens旧版两个函数的 SQL 签名均为(model, query, documents, api_key, api_key_name, top_k, truncation, verbose)。Python 侧的rerank()实现ai/voyageai.py会把 API 响应整理为resultsindex/document/relevance_score 列表加total_tokens的字典voyageai_rerank_simple再把其中的results数组展开成行并INNER JOIN原始 documents 数组以还原每行文档文本——这也解释了为什么返回的index列对应输入数组的下标。Reranker 与语义搜索的分工语义搜索嵌入从大规模数据集中快速初检候选重排序对候选集做精细的相关度打分。典型工作流先用向量检索取 top 100 候选再用 reranker 精排出最相关的 5–10 条。仓库中的验证与延伸示例测试tests/vectorizer/cli/test_voyageai_vectorizer.py 用voyage-3-lite512 维创建 vectorizer 并用 VCR 录制回放 API 请求验证 Worker 处理后的行数与插入数一致另有专门用例验证缺少VOYAGE_API_KEY环境变量时 Worker 会以ApiKeyNotFoundError失败退出exit code 1——如果你本地跑 Worker 时嵌入一直不成功这通常是 Key 未注入vectorizer-worker服务的表现。评测示例examples/evaluations/voyage_vectorizer 提供了一套领域模型对比脚本用voyage-finance-21024 维与 OpenAI 嵌入在 SEC 财报数据集上做检索质量评测其 compose 文件与本文教程结构一致可作为换模型重跑的模板。深入配置更完整的 loading / embedding / chunking / formatting / indexing 参数说明见 Vectorizer API 参考与 Vectorizer 概览。小结到这里你已经在自托管 PostgreSQL 上拥有了一个由 pgai 自动创建并持续同步嵌入的存储表 视图一个可随源数据变化自动增删向量的 VoyageAI vectorizer以及基于ai.voyageai_embed的语义搜索和ai.voyageai_rerank_simple的重排序能力。同一套向量资产可以直接支撑语义搜索、RAG 检索等任意 AI 应用。完整教程原文见 docs/vectorizer/quick-start-voyage.md。【免费下载链接】pgaiA suite of tools to develop RAG, semantic search, and other AI applications more easily with PostgreSQL项目地址: https://gitcode.com/GitHub_Trending/pg/pgai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考