尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Mastra RAG 实战:用 createBedrockKBTool() 将 Amazon Bedrock 托管知识库接入 Agent

Mastra RAG 实战:用 createBedrockKBTool() 将 Amazon Bedrock 托管知识库接入 Agent Mastra RAG 实战用 createBedrockKBTool() 将 Amazon Bedrock 托管知识库接入 Agent【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastraMastra 的mastra/rag包通过createBedrockKBTool()提供了一套开箱即用的 RAG 工具用于直接查询 Amazon Bedrock Managed Knowledge Base托管知识库无需自建向量数据库即可让 Mastra Agent 在推理时检索 S3、Web、Confluence、SharePoint 等多源文档。读完本文你将掌握该工具的完整配置参数、两种检索模式Agentic 与标准托管检索的底层实现、用户级访问控制的接入方式以及对应的 IAM 权限与 SDK 版本要求。工具概览createBedrockKBTool()的实现在 packages/rag/src/tools/bedrock-knowledge-base.ts并从 packages/rag/src/tools/index.ts 一并从包根入口mastra/rag导出因此既可以从mastra/rag直接导入也可以在需要时按类型导入BedrockKBToolOptions、BedrockKBResult等类型。该工具的核心特性对应仓库内 BEDROCK_MANAGED_KB.md 文档包括托管检索无需向量库向量的存储、索引与检索基础设施全部由 AWS 托管Agentic 检索默认启用带查询分解query decomposition与托管重排managed reranking的 AgenticRetrieveStream自动回退当 Agentic 检索失败时自动降级为标准的RetrieveCommand托管检索多数据源支持S3、Web、Confluence、SharePoint、Salesforce 等兼容 Mastra 工具接口返回标准 MastracreateTool工具可直接挂到Agent的tools上。快速开始以下示例来自仓库文档展示如何将 Bedrock 知识库工具挂载到 Agentimport { Agent } from mastra/core; import { createBedrockKBTool } from mastra/rag; const kbTool createBedrockKBTool({ knowledgeBaseId: YOUR_KB_ID, region: us-east-1, }); const agent new Agent({ name: research-agent, tools: { kb: kbTool }, instructions: Use the knowledge base to answer questions., });工具也可以脱离 Agent 直接执行参见 packages/rag/src/tools/README.mdimport { createBedrockKBTool } from mastra/rag; const kbTool createBedrockKBTool({ knowledgeBaseId: ABCDEFGHIJ, region: us-west-2, }); const results await kbTool.execute({ queryText: What are our policies? });配置参数详解工厂函数接收BedrockKBToolOptions其默认值在 bedrock-knowledge-base.ts 中通过解构赋值给出参数类型说明默认值knowledgeBaseIdstring要查询的 Bedrock Knowledge Base ID必填无regionstring知识库所在 AWS 区域环境变量AWS_REGION否则us-east-1numberOfResultsnumber返回的最大结果数5useAgenticRetrievalboolean是否使用 AgenticRetrieveStream查询分解 托管重排失败时回退标准检索true设置USE_AGENTIC_RETRIEVALfalse时关闭userIdstring用于文档级访问控制的默认 AWS 用户 ID请求上下文中的userId优先无需要注意useAgenticRetrieval的默认值判断逻辑是process.env.USE_AGENTIC_RETRIEVAL ! false见 源码 L68即只有显式设置为字符串false才会关闭其他取值均视为开启。环境变量变量说明默认值AWS_REGION知识库所在的 AWS 区域us-east-1AWS_ACCESS_KEY_IDAWS Access Key无AWS_SECRET_ACCESS_KEYAWS Secret Key无USE_AGENTIC_RETRIEVAL是否启用 Agentic 检索true# 关闭 Agentic 检索改用标准托管检索 export USE_AGENTIC_RETRIEVALfalse两种检索模式的底层实现Agentic 检索默认开启时工具构造AgenticRetrieveStreamCommand见 源码 L92-L136const command new AgenticRetrieveStreamCommand({ messages: [{ content: { text: query }, role: user }], retrievers: [ { configuration: { knowledgeBase: { knowledgeBaseId, retrievalOverrides: { maxNumberOfResults: numberOfResults }, }, }, }, ], agenticRetrieveConfiguration: { foundationModelType: MANAGED, rerankingModelType: MANAGED, }, userContext: getUserContext(userId), });该模式面向复杂查询Bedrock 会自动将查询分解为子查询、多轮检索并用托管模型重排结果。响应是流式的源码通过for await (const event of response.stream)逐事件收集event.result.results。关于结果字段的映射源码刻意保持“不虚构”Agentic 结果的source仅当metadata中存在_source_uri字符串时才提取见 getMetadataSource且Agentic API 本身不返回 score 字段因此该路径下score为undefined。标准托管检索回退或显式关闭当useAgenticRetrieval为false或 Agentic 调用抛错时工具走managedRetrieve见 源码 L74-L90const command new RetrieveCommand({ knowledgeBaseId, retrievalQuery: { text: query }, retrievalConfiguration: { managedSearchConfiguration: { numberOfResults } }, userContext: getUserContext(userId), });标准检索单遍直查返回retrievalResults每条结果携带content.text、score与metadata。回退发生时会在控制台输出警告Agentic retrieval failed, falling back to managed retrieve。结果到 source 的映射规则无论哪条路径工具都会把 Bedrock 的location信息归一化为source字段。getSourceUri见 源码 L30-L38依次检查s3Location.uri、webLocation.url、confluenceLocation.url、salesforceLocation.url、sharePointLocation.url、customDocumentLocation.id。单元测试 验证了 S3 场景location: { type: S3, s3Location: { uri: s3://bucket/doc.txt } }会被映射为source: s3://bucket/doc.txt并原样保留score: 0.92与metadata。输入与输出 Schema工具由 Mastra 的createTool创建工具 ID 为bedrock_knowledge_base_${knowledgeBaseId}如bedrock_knowledge_base_kb-123描述面向 Agent 说明其用途“Retrieves relevant documents from an Amazon Bedrock Knowledge Base...”。输入 Schema源码 L48-L50字段类型必填说明queryTextstring是用于在知识库中检索相关文档的查询文本输出 Schema返回{ results: BedrockKBResult[] }其中BedrockKBResult各字段为字段类型说明contentstring检索到的文本片段内容sourcestring \| undefined来源 URI若 Bedrock 提供了 location 或 metadata 中的_source_uriscorenumber \| undefined标准检索返回的相关性分数Agentic API 不返回该字段metadataRecordstring, unknown检索结果附带的元数据当知识库没有命中时工具返回空列表{ results: [] }这一行为在 测试用例 中有明确验证。基于用户的访问控制userId对于启用文档级访问控制的知识库工具支持传递userId作为 Bedrock 请求的userContext.userId。取值优先级为请求上下文中的userId 工具构造时配置的默认userId见 execute 逻辑 L144-L152const userId context?.requestContext?.get(userId) ?? defaultUserId;在 Agent 调用侧的使用方式import { RequestContext } from mastra/core/request-context; const requestContext new RequestContext(); requestContext.set(userId, user-123); await agent.generate(Find my private documents, { requestContext });注意getUserContext只对非空字符串生效空字符串视为未提供。两条优先级规则均有对应测试上下文 userId 覆盖默认值 与 无上下文时回退到配置的 userId。IAM 权限要求运行该工具的 AWS 身份至少需要以下权限来自 BEDROCK_MANAGED_KB.md 的 IAM 配置段{ Effect: Allow, Action: [bedrock:Retrieve, bedrock:AgenticRetrieveStream], Resource: arn:aws:bedrock:region:account-id:knowledge-base/kb-id }如果同时启用 Agentic 检索两个 Action 都不可少仅使用标准检索时至少需要bedrock:Retrieve。Resource建议按实际区域、账号与知识库 ID 收紧而不是通配。SDK 要求与适用前提aws-sdk/client-bedrock-agent-runtime 3.1000AgenticRetrieveStreamCommand约在 3.1000 才可用。当前仓库中 packages/rag/package.json 已将其作为正式依赖锁定在^3.1076.0因此通过mastra/rag引入时无需单独安装该 SDKmastra/core当前mastra/rag的 peer 依赖声明为1.0.0-0 2.0.0-0zod^3.25.0 || ^4.0.0工具输入/输出 Schema 基于 zod运行时要求 Node.js 22.13.0mastra/rag的engines声明客户端初始化时携带自定义 User-Agent[mastra, bedrock-kb]见 源码 L72便于在 AWS 侧识别来源前提是先在 AWS 侧建好 Managed Knowledge Base数据源索引由 Bedrock 托管本文档不涉及知识库本身的创建流程。行为验证从测试用例看实现边界packages/rag/src/tools/bedrock-knowledge-base.test.ts 通过 mockBedrockAgentRuntimeClient覆盖了关键路径可作为行为契约参考工具契约ID 形如bedrock_knowledge_base_kb-123描述包含 “Amazon Bedrock Knowledge Base”输入/输出 Schema 均已定义标准检索映射retrievalResults正确映射出content/source/score/metadataAgentic 结果映射从流式事件中提取result.resultssource仅来自metadata._source_uri且不虚构 score 或 location失败回退Agentic 调用抛错后会发起第二次请求走RetrieveCommand且最终返回标准检索结果空结果无命中时返回{ results: [] }userId 透传上下文userId优先于默认值均正确写入命令的userContext。官方参考该工具的完整 API 参考参数表、输入/输出 Schema、检索模式说明收录于仓库文档 docs/src/content/en/reference/tools/bedrock-kb-tool.mdx与本文内容互为印证。如需进一步了解 Bedrock 知识库的构建与检索 API请查阅 AWS 官方 Bedrock 文档Managed Knowledge Base 与 Agentic Retrieval 章节。【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表