ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

VoltAgent 集成 Pinecone 向量数据库:构建双模式 RAG 知识检索 Agent 实战指南

VoltAgent 集成 Pinecone 向量数据库:构建双模式 RAG 知识检索 Agent 实战指南 人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载导读本文基于 VoltAgent 官方示例 examples/with-pinecone完整讲解如何在 VoltAgent 中接入 Pinecone 向量数据库为 Agent 赋予基于语义相似度的知识检索RAGRetrieval-Augmented Generation能力。示例同时提供了两种检索模式自动检索每次交互自动执行语义搜索与工具化检索由 LLM 自行决定何时查询知识库并自动完成索引创建、文档嵌入与向量检索的完整链路。读完本文你将掌握如何在 VoltAgent 中编写自定义 Retriever、配置 Pinecone 索引、注入环境变量以及理解BaseRetriever与retriever.tool两种接入方式背后的源码原理。示例概述Pinecone VoltAgent 能做什么本示例演示 VoltAgent 与 Pinecone 向量数据库的集成面向需要高级知识管理与检索的场景。示例内置了一个预加载的知识库——包含 VoltAgent、Pinecone、RAG、向量数据库、TypeScript 等主题的样例文档——并在运行时自动完成以下工作自动创建索引检测 Pinecone 中是否已存在目标索引不存在则自动创建自动填充知识库使用 OpenAItext-embedding-3-small模型为样例文档生成向量并写入索引语义向量检索对用户查询做同样嵌入后在 Pinecone 中执行高相似度向量搜索来源追踪将命中文档的 ID 与相似度分数写入上下文context.get(references)便于 Agent 与用户追溯答案出处。整个示例的核心文件只有两个入口文件组装 Memory、两个 Agent 与 Hono 服务器检索器实现Pinecone 客户端初始化、索引管理、嵌入生成与PineconeRetriever类。前置条件在开始之前需要准备以下资源Pinecone 账号注册并登录 Pinecone 控制台Pinecone API Key从控制台获取用于初始化pinecone-database/pinecone客户端OpenAI API Key示例使用 OpenAI 同时承担两类职责——生成文档/查询的嵌入向量text-embedding-3-small以及作为 Agent 的语言模型openai/gpt-4o-mini。示例依赖清单可参见 package.json其中与 VoltAgent 相关的核心依赖为voltagent/coreAgent 与 Retriever 框架、voltagent/libsql持久化记忆、voltagent/logger日志、voltagent/server-honoHTTP 服务以及pinecone-database/pinecone、openai两个第三方客户端。快速开始第 1 步创建项目。使用 VoltAgent 官方脚手架指定with-pinecone示例模板npm create voltagent-applatest -- --example with-pinecone cd with-pinecone第 2 步配置环境变量。复制环境变量模板并填入密钥cp .env.example .env编辑.env添加 API KeyPINECONE_API_KEYyour_pinecone_api_key_here OPENAI_API_KEYyour_openai_api_key_here说明入口依赖.env文件读取密钥。项目的dev脚本为tsx watch --env-file.env ./src即运行时会显式加载.env中的变量若没有正确配置上述两个 KeyPinecone 客户端与 OpenAI 客户端将拿到空字符串索引初始化和检索都会失败。第 3 步安装依赖并运行npm install npm run dev启动成功后控制台会输出提示说明两个 Agent 已就绪并建议尝试类似这样的提问What is VoltAgent?Tell me about vector databasesHow does Pinecone work?What is RAG?环境变量一览变量是否必填说明PINECONE_API_KEY是你的 Pinecone API KeyOPENAI_API_KEY是你的 OpenAI API Key用于生成嵌入向量与 LLM 调用从源码看两个 Key 的使用位置分别为 retriever/index.tsPinecone 客户端并额外设置了sourceTag: voltagent和同一文件中的 OpenAI 客户端初始化apiKey: process.env.OPENAI_API_KEY || 。入口代码剖析如何组装一个带检索能力的 Agentsrc/index.ts 展示了 VoltAgent 的核心装配流程依次包含四步日志、记忆、Agent、服务器。1. 日志使用createPinoLogger创建名为with-pinecone的 Pino 日志实例级别为info。2. 持久化记忆示例使用 LibSQL 作为记忆存储且两个 Agent 共享同一份记忆import { Agent, Memory, VoltAgent } from voltagent/core; import { LibSQLMemoryAdapter } from voltagent/libsql; const memory new Memory({ storage: new LibSQLMemoryAdapter({ url: file:./.voltagent/memory.db, }), });记忆数据被持久化到本地 SQLite 文件.voltagent/memory.db这保证了 Agent 重启后仍能保留跨会话的上下文。3. 两个 Agent分别演示直接挂载 Retriever与把 Retriever 包装成 Tool两种模式// Agent 1: 自动检索 —— 每次交互自动搜索知识库 const agentWithRetriever new Agent({ name: Assistant with Retriever, instructions: A helpful assistant that can retrieve information from the Pinecone knowledge base using semantic search to provide better answers. I automatically search for relevant information when needed., model: openai/gpt-4o-mini, retriever: retriever, memory, }); // Agent 2: 工具化检索 —— LLM 自行决定何时搜索 const agentWithTools new Agent({ name: Assistant with Tools, instructions: A helpful assistant that can search the Pinecone knowledge base using tools. The agent will decide when to search for information based on user questions., model: openai/gpt-4o-mini, tools: [retriever.tool], memory, });关键差异在于agentWithRetriever通过retriever字段挂载对应 README 中说的Automatic retrievalAgent 在生成回答前会自动把检索结果注入系统消息agentWithTools通过tools: [retriever.tool]挂载对应tool-based retrieval检索行为变成 LLM 可自主调用的工具函数。4. HTTP 服务通过honoServer暴露 Agent 能力监听3141端口new VoltAgent({ agents: { agentWithRetriever, agentWithTools }, logger, server: honoServer({ port: 3141 }), });两种检索模式背后的源码原理理解两种模式的差异需要看 VoltAgent 核心包中BaseRetriever的实现。BaseRetriever一个实例两种用法抽象基类 BaseRetriever 定义在packages/core/src/retriever/retriever.ts。它要求子类实现retrieve(input, options): Promisestring并在构造函数中自动完成两件事自动创建工具调用createRetrieverTool生成this.tool工具名称默认search_knowledge描述默认为 Searches for relevant information in the knowledge base based on the query.。因此retriever.tool无需任何额外配置即可直接塞进tools数组绑定方法上下文将retrieve显式bind到实例上保证从对象解构或作为回调传入时this不丢失。RetrieverOptions见 types.ts支持自定义toolName、toolDescription与logger同时允许子类扩展任意自有配置项。createRetrieverToolRetriever 到 AgentTool 的桥接createRetrieverTool 位于packages/core/src/retriever/tools/index.ts是工具化检索的核心。它用zod定义工具参数query字符串描述为 The search query to find relevant information并在execute内调用retriever.retrieve(query, options)同时把调用方的options含logger、userId、conversationId等完整透传给retriever记录RETRIEVER_SEARCH_STARTED / COMPLETED / FAILED日志事件支持通过getObservabilityAttributes()为 OpenTelemetry span 附加检索器属性。这也解释了为什么tools: [retriever.tool]能直接工作——createRetrieverTool返回的就是标准的AgentTool。Agent 侧的自动检索流程当通过retriever字段挂载时Agent 在生成系统消息阶段调用getRetrieverContext见 agent.ts将用户输入字符串、UIMessage[]或BaseMessage[]统一归一化为检索器可处理的输入创建名为retriever.search的 OpenTelemetry 子 span调用retriever.retrieve(...)并把结果拼装进系统提示词格式为Relevant Context:\n检索内容见 enrichInstructions。因此自动检索本质上是在每次生成前把语义检索结果作为上下文固定注入而工具化检索则由 LLM 根据问题相关性决定是否触发搜索。前者答案更稳定地基于知识库后者更省 Token、更灵活。Pinecone 检索器实现详解retriever/index.ts 是本示例的核心包含索引管理、文档填充与检索器实现三个部分。1. 自动索引管理initializeIndex()函数实现不存在即创建的幂等逻辑const pc new Pinecone({ apiKey: process.env.PINECONE_API_KEY || , sourceTag: voltagent, }); const indexName voltagent-knowledge-base; // 先探测索引是否存在 try { await pc.describeIndex(indexName); indexExists true; } catch (_error) { // 不存在则创建 } if (!indexExists) { await pc.createIndex({ name: indexName, dimension: 1536, // OpenAI text-embedding-3-small dimension metric: cosine, spec: { serverless: { cloud: aws, region: us-east-1, }, }, waitUntilReady: true, }); }随后通过describeIndexStats()检查totalRecordCount若索引为空则为样例文档生成嵌入并upsert若已有数据则直接跳过填充避免重复写入。2. 嵌入与写入文档向量化使用 OpenAI 官方 SDKconst embeddingResponse await openai.embeddings.create({ model: text-embedding-3-small, input: record.metadata.text, });每个文档的metadata包含text原始内容、category分类、topic主题三个字段这些元数据后续可用于过滤与展示。写入使用index.upsert(recordsWithEmbeddings)批量提交。3. 语义检索retrieveDocuments(query, topK 3)完成查询向量化与相似度搜索const searchResults await index.query({ vector: queryVector, topK, includeMetadata: true, includeValues: false, }); return ( searchResults.matches?.map((match) ({ content: match.metadata?.text || , metadata: match.metadata || {}, score: match.score || 0, id: match.id, })) || [] );检索结果被格式化为{ content, metadata, score, id }结构供后续注入上下文。4. PineconeRetriever自定义 Retriever 的标准范式PineconeRetriever继承自BaseRetriever其retrieve方法展示了自定义检索器的标准写法输入归一化兼容string与BaseMessage[]两种输入——对消息数组取最后一条提取其中type text的内容片段拼接为搜索文本执行检索调用retrieveDocuments(searchText, 3)取 Top-3 结果写入引用若调用方传入options.context一个Map则将结果映射为{ id, title, source, score, category }并context.set(references, references)——这正是 README 中Source Tracking的来源运行时可通过context.get(references)查看使用了哪些文档及对应分数格式化输出将每条结果拼接为带Document N (ID: ..., Score: ..., Category: ...)前缀的文本块交给 LLM 作为Relevant Context无结果时返回 No relevant documents found in the knowledge base.。文件末尾export const retriever new PineconeRetriever();导出单例供入口文件直接引用。自定义接入你自己的知识库添加自有文档修改 retriever/index.ts 中的sampleRecords数组即可替换/扩充知识库const sampleRecords [ { id: your_doc_1, metadata: { text: Your document content here..., category: your_category, topic: your_topic, }, }, // Add more documents... ];values字段无需手填源码中置空示例会在初始化阶段用 OpenAI 嵌入模型自动生成。注意由于索引在totalRecordCount 0时才填充若要强制重新灌入新文档需要先清空或更换索引。调整索引配置索引创建参数同样在 retriever/index.ts 中配置await pc.createIndex({ name: indexName, dimension: 1536, // OpenAI text-embedding-3-small dimension metric: cosine, // or euclidean, dotproduct spec: { serverless: { cloud: aws, // or gcp, azure region: us-east-1, // choose your preferred region }, }, waitUntilReady: true, });关键参数说明dimension向量维度必须与嵌入模型输出维度一致。示例使用 OpenAItext-embedding-3-small1536 维更换嵌入模型时必须同步修改metric相似度度量方式cosine余弦相似度对向量模长不敏感语义检索最常用、euclidean欧氏距离、dotproduct点积三选一spec.serverlessServerless 部署配置cloud可选aws/gcp/azureregion选择就近区域以降低延迟waitUntilReady设为true时阻塞等待索引就绪后再继续写入。检索行为调优retrieveDocuments的topK参数默认3控制每次注入上下文的文档条数可根据知识库规模与 Token 预算调整index.query还可补充filter条件利用metadata做元数据过滤如按category限定检索范围README 中提到的Metadata filtering capabilities即指此能力。运行验证与排查建议启动npm run dev后首次运行时控制台应依次出现索引探测、索引创建/填充日志Creating new index...、Populating index with sample documents...、Successfully upserted N documents向两个 Agent 提问 What is RAG? 这类与知识库强相关的问题对比自动检索与工具化检索的行为差异通过context.get(references)查看命中文档的id与score验证来源追踪是否生效。常见问题排查方向索引初始化失败检查PINECONE_API_KEY与OPENAI_API_KEY是否正确写入.env并确认 Pinecone 控制台已开通对应云与区域检索结果为空确认索引中totalRecordCount大于 0若使用新索引可删除索引后重启示例触发重新填充维度不匹配更换嵌入模型后需同步修改createIndex的dimension否则upsert会报错。延伸阅读核心抽象 BaseRetriever 与 Retriever 类型定义工具化桥接 createRetrieverToolAgent 侧自动注入检索上下文 getRetrieverContext核心框架测试 retriever.spec.ts验证默认工具名search_knowledge、自定义toolName/toolDescription及tool属性暴露同仓库内还有更多检索相关示例可供对照例如 examples/with-retrieval、examples/with-voltops-retrieval以及独立封装的 packages/rag。总结本示例用最小的代码量呈现了 VoltAgent × Pinecone 的完整 RAG 落地路径一条PineconeRetriever继承BaseRetriever同时支撑自动检索与工具化检索两种模式配合自动索引管理、OpenAI 嵌入、引用追踪与持久化记忆构成了一个可直接扩展为生产级知识问答 Agent 的骨架。理解BaseRetriever/createRetrieverTool/ Agent 系统消息注入这三层机制后你可以轻松将其替换为任意向量数据库或检索后端。赞分享人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载相关推荐LangChain.js 集成 Pinecone 向量数据库langchain/pinecone 完整实战指南LangChain.js 集成 Pinecone 向量数据库langchain/pinecone 完整实战指南 langchain/pinecone 是人工智能大模型AI AgentAI 应用RAG工具调用Wallaby错误处理终极指南如何快速调试和优化测试用例Wallaby错误处理终极指南如何快速调试和优化测试用例 Wallaby是Elixir生态系统中强大的并发浏览器测试框架专为Web应用测试设计。然而即使是测试质量保障向量数据库双雄对决Pinecone与Weaviate Java集成实战指南向量数据库双雄对决Pinecone与Weaviate Java集成实战指南 你是否在Java项目中纠结于向量数据库 Vector Database 的选型面文档知识库上一篇装好就能玩的开源桌宠 VPet摸头、喂食、还能嵌进你自己的软件下一篇mobiledevice安装教程在Linux系统上编译与配置的详细指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表