戰(zhàn)詳解:為 Agent 接入 Amazon Bedrock 知識(shí)庫檢索)
CrewAI BedrockKBRetrieverTool 實(shí)戰(zhàn)詳解為 Agent 接入 Amazon Bedrock 知識(shí)庫檢索【免費(fèi)下載鏈接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.項(xiàng)目地址: https://gitcode.com/GitHub_Trending/cr/crewAI本文基于 CrewAI 倉庫中crewai-tools包的 Bedrock 知識(shí)庫工具文檔lib/crewai-tools/src/crewai_tools/aws/bedrock/knowledge_base/README.md及其對(duì)應(yīng)源碼實(shí)現(xiàn)撰寫。讀完后你將掌握BedrockKBRetrieverTool的安裝與配置、全部構(gòu)造參數(shù)的取值規(guī)則與校驗(yàn)邏輯、在 CrewAI Agent 中的接入方式以及該工具底層對(duì)bedrock-agent-runtime.retrieve()的調(diào)用鏈與響應(yīng)解析機(jī)制。1. 工具定位與核心能力BedrockKBRetrieverTool讓 CrewAI 智能體能夠用自然語言查詢natural language query從 Amazon Bedrock 知識(shí)庫中檢索信息是典型的 RAG檢索增強(qiáng)生成接入點(diǎn)Agent 負(fù)責(zé)推理與任務(wù)編排知識(shí)庫檢索負(fù)責(zé)提供來自企業(yè)私有數(shù)據(jù)的事實(shí)依據(jù)。工具實(shí)現(xiàn)在 retriever_tool.py類定義繼承自crewai.tools.BaseTool并暴露給 LLM 的輸入 Schema 只有一個(gè)字段class BedrockKBRetrieverToolInput(BaseModel): Input schema for BedrockKBRetrieverTool. query: str Field( ..., descriptionThe query to retrieve information from the knowledge base )也就是說Agent 側(cè)只需要生成一句查詢語句工具內(nèi)部完成其余所有工作。工具在包內(nèi)的導(dǎo)出路徑為 knowledge_base/init.py并向上聚合到 bedrock/init.py 與 aws/init.py因此既可以從crewai_tools.aws.bedrock.knowledge_base導(dǎo)入也可以直接從crewai_tools.aws導(dǎo)入。2. 安裝與環(huán)境要求2.1 安裝pip install crewai[tools]2.2 前置條件已配置 AWS 憑據(jù)環(huán)境變量或 AWS CLI 均可依賴boto3與python-dotenv包。源碼層面工具聲明了package_dependencies: list[str] Field(default_factorylambda: [boto3])且模塊導(dǎo)入時(shí)執(zhí)行l(wèi)oad_dotenv()因此.env文件中的配置會(huì)自動(dòng)被加載具備目標(biāo) Amazon Bedrock 知識(shí)庫的訪問權(quán)限。2.3 環(huán)境變量BEDROCK_KB_IDyour-knowledge-base-id # 可作為 knowledge_base_id 參數(shù)的替代 AWS_REGIONyour-aws-region # 默認(rèn) us-east-1 AWS_ACCESS_KEY_IDyour-access-key # AWS 鑒權(quán)所需 AWS_SECRET_ACCESS_KEYyour-secret-key # AWS 鑒權(quán)所需從源碼看__init__中的參數(shù)回退邏輯為self.knowledge_base_id knowledge_base_id or os.getenv(BEDROCK_KB_ID)即構(gòu)造參數(shù)優(yōu)先未顯式傳入時(shí)才回退到BEDROCK_KB_ID環(huán)境變量見 retriever_tool.py#L59-L60。Region 的解析鏈為AWS_REGION→AWS_DEFAULT_REGION→ 兜底u(yù)s-east-1見 retriever_tool.py#L194-L200。3. 在 CrewAI Agent 中的完整用法以下示例繼承自工具 README展示初始化工具 → 掛載到 Agent → 定義 Task → 運(yùn)行 Crew的完整鏈路from crewai import Agent, Task, Crew from crewai_tools.aws.bedrock.knowledge_base.retriever_tool import BedrockKBRetrieverTool # 初始化工具 kb_tool BedrockKBRetrieverTool( knowledge_base_idyour-kb-id, number_of_results5 ) # 創(chuàng)建使用該工具的 CrewAI Agent researcher Agent( roleKnowledge Base Researcher, goalFind information about company policies, backstoryI am a researcher specialized in retrieving and analyzing company documentation., tools[kb_tool], verboseTrue ) # 為 Agent 創(chuàng)建任務(wù) research_task Task( descriptionFind our companys remote work policy and summarize the key points., agentresearcher ) # 創(chuàng)建包含該 Agent 的 Crew crew Crew( agents[researcher], tasks[research_task], verbose2 ) # 運(yùn)行 result crew.kickoff() print(result)工具初始化后其description會(huì)被動(dòng)態(tài)改寫為Retrieves information from Amazon Bedrock Knowledge Base {knowledge_base_id} given a query這樣 Agent 在決策是否調(diào)用工具時(shí)能明確感知具體查詢的是哪個(gè)知識(shí)庫。4. 參數(shù)詳解與校驗(yàn)規(guī)則4.1 構(gòu)造參數(shù)參數(shù)類型必填默認(rèn)值說明knowledge_base_idstr是*None知識(shí)庫唯一標(biāo)識(shí)0–10 位字母數(shù)字字符可用環(huán)境變量BEDROCK_KB_ID替代number_of_resultsint否5返回的最大結(jié)果數(shù)retrieval_configurationdict否None自定義知識(shí)庫查詢配置guardrail_configurationdict否None內(nèi)容過濾Guardrail設(shè)置next_tokenstr否None分頁游標(biāo)用于獲取下一批結(jié)果* 若通過BEDROCK_KB_ID環(huán)境變量提供則構(gòu)造參數(shù)可省略。4.2 參數(shù)校驗(yàn)邏輯源碼級(jí)_validate_parameters()在__init__末尾被調(diào)用校驗(yàn)失敗會(huì)拋出BedrockValidationError定義于 exceptions.py繼承自BedrockError基類。具體約束見 retriever_tool.py#L89-L124knowledge_base_id非空、必須是字符串、長(zhǎng)度 ≤ 10、僅允許字母數(shù)字字符next_token若非空必須是字符串、長(zhǎng)度在 1–2048 之間、不能包含空格number_of_results必須是整數(shù)且 0。4.3 retrieval_configuration 的自動(dòng)生成如果沒有顯式傳入retrieval_configuration工具會(huì)根據(jù)number_of_results自動(dòng)構(gòu)造def _build_retrieval_configuration(self) - dict[str, Any]: vector_search_config {} if self.number_of_results is not None: vector_search_config[numberOfResults] self.number_of_results return {vectorSearchConfiguration: vector_search_config}即默認(rèn)等價(jià)于{vectorSearchConfiguration: {numberOfResults: 5}}。5. 高級(jí)用法自定義檢索配置與 Guardrail5.1 混合檢索HYBRID顯式傳入retrieval_configuration時(shí)工具會(huì)原樣使用該配置不再自動(dòng)構(gòu)造kb_tool BedrockKBRetrieverTool( knowledge_base_idyour-kb-id, retrieval_configuration{ vectorSearchConfiguration: { numberOfResults: 10, overrideSearchType: HYBRID } } ) policy_expert Agent( rolePolicy Expert, goalAnalyze company policies in detail, backstoryI am an expert in corporate policy analysis with deep knowledge of regulatory requirements., tools[kb_tool] )5.2 內(nèi)容過濾Guardrail與分頁guardrail_configuration與next_token分別映射到 Bedrock API 的guardrailConfiguration與nextToken字段用于對(duì)檢索內(nèi)容做合規(guī)過濾和分批拉取kb_tool BedrockKBRetrieverTool( knowledge_base_idkb123, guardrail_configuration{ guardrailIdentifier: your-guardrail-id, guardrailVersion: DRAFT, trace: ENABLED, } )響應(yīng)中的guardrailAction字段會(huì)回傳 Guardrail 的處理動(dòng)作便于在 Agent 側(cè)感知內(nèi)容是否被干預(yù)。6. 底層調(diào)用鏈_run()的完整執(zhí)行流程_run(query)是 Agent 調(diào)用工具時(shí)的實(shí)際入口執(zhí)行流程可拆解為六步見 retriever_tool.py#L183-L250懶加載 boto3import boto3失敗時(shí)拋出ImportError提示執(zhí)行uv add boto3創(chuàng)建客戶端boto3.client(bedrock-agent-runtime, region_name...)AWS 鑒權(quán)由 SDK 自動(dòng)從環(huán)境讀取組裝請(qǐng)求參數(shù)retrieve_params { knowledgeBaseId: self.knowledge_base_id, retrievalQuery: {text: query}, } if self.retrieval_configuration: retrieve_params[retrievalConfiguration] self.retrieval_configuration if self.guardrail_configuration: retrieve_params[guardrailConfiguration] self.guardrail_configuration if self.next_token: retrieve_params[nextToken] self.next_token發(fā)起檢索bedrock_agent_runtime.retrieve(**retrieve_params)逐條后處理對(duì)response[retrievalResults]中每條記錄調(diào)用_process_retrieval_result()標(biāo)準(zhǔn)化序列化返回結(jié)果為空時(shí)返回{message: No results found for the given query.}否則輸出results列表如響應(yīng)中存在nextToken、guardrailAction則一并透?jìng)髯罱K以json.dumps(..., indent2)返回給 Agent。異常處理分兩層botocore.exceptions.ClientError會(huì)被解包出Code與Message后拋出BedrockKnowledgeBaseError(Error ({code}): {message})其他異常統(tǒng)一包裝為BedrockKnowledgeBaseError(Unexpected error: ...)。這兩個(gè)異常類型均定義在 exceptions.py 中可在業(yè)務(wù)代碼中精確捕獲知識(shí)庫錯(cuò)誤而不影響其他工具調(diào)用。7. 響應(yīng)格式與來源映射機(jī)制7.1 標(biāo)準(zhǔn)化響應(yīng)工具對(duì)外返回 JSON 字符串{ results: [ { content: Retrieved text content, content_type: text, source_type: S3, source_uri: s3://bucket/document.pdf, score: 0.95, metadata: { additional: metadata } } ], nextToken: pagination-token, guardrailAction: NONE }字段說明content/content_type檢索片段文本及其類型默認(rèn)textsource_type/source_uri數(shù)據(jù)源類型與定位地址見 7.2 的映射表score相關(guān)性分?jǐn)?shù)僅當(dāng) API 返回時(shí)存在metadata知識(shí)庫附加元數(shù)據(jù)僅當(dāng)返回時(shí)存在此外_process_retrieval_result()還會(huì)把二進(jìn)制片段映射為byte_content來自byteContent、結(jié)構(gòu)化行映射為row_content來自row用于 SQL 等非文本數(shù)據(jù)源。7.2 八種數(shù)據(jù)源的 URI 映射_process_retrieval_result()內(nèi)置了一張 Bedrock 位置類型 → 工具輸出類型 → URI 取字段的映射表見 retriever_tool.py#L144-L153Bedrock 位置字段輸出 source_typeURI 取值字段s3LocationS3uriconfluenceLocationConfluenceurlsalesforceLocationSalesforceurlsharePointLocationSharePointurlwebLocationWeburlcustomDocumentLocationCustomDocumentidkendraDocumentLocationKendraDocumenturisqlLocationSQLquery這意味著該工具天然覆蓋 Bedrock 知識(shí)庫支持的多種數(shù)據(jù)源Amazon S3、Confluence、Salesforce、SharePoint、網(wǎng)頁、自定義文檔位置、Amazon Kendra 與 SQL 數(shù)據(jù)庫Agent 拿到的每條結(jié)果都帶有可追溯的來源信息。8. 典型應(yīng)用場(chǎng)景工具 README 歸納了五類落地場(chǎng)景均圍繞讓 Agent 的推理扎根于企業(yè)真實(shí)數(shù)據(jù)展開企業(yè)知識(shí)集成Agent 直接訪問組織私有知識(shí)而不暴露敏感數(shù)據(jù)基于內(nèi)部政策、流程與文檔做決策領(lǐng)域?qū)<抑R(shí)無需微調(diào)模型即可讓 Agent 接入法律、醫(yī)療、技術(shù)等垂直領(lǐng)域知識(shí)庫復(fù)用 AWS 環(huán)境中已有的知識(shí)資產(chǎn)數(shù)據(jù)驅(qū)動(dòng)決策以實(shí)際業(yè)務(wù)數(shù)據(jù)為回答依據(jù)減少幻覺可擴(kuò)展的信息訪問無需將數(shù) TB 級(jí)知識(shí)嵌入模型按任務(wù)動(dòng)態(tài)檢索相關(guān)片段合規(guī)與治理Agent 的回答對(duì)齊已批準(zhǔn)的內(nèi)部文檔且source_uri/metadata可形成可審計(jì)的信息來源記錄配合 Guardrail 進(jìn)一步控制訪問邊界。9. 小結(jié)BedrockKBRetrieverTool的實(shí)現(xiàn)非常聚焦一個(gè)query輸入 Schema、五條構(gòu)造參數(shù)、一次retrieve()調(diào)用、一套八源映射的結(jié)果標(biāo)準(zhǔn)化邏輯。它的工程價(jià)值在于把 Bedrock 知識(shí)庫檢索封裝成 CrewAI 工具協(xié)議BaseTool下的普通成員——Agent 通過tools[kb_tool]即可掛載無需感知 boto3 細(xì)節(jié)而參數(shù)校驗(yàn)、錯(cuò)誤包裝、來源映射等健壯性邏輯保證了它在生產(chǎn)鏈路中可預(yù)測(cè)、可調(diào)試。相關(guān)源碼索引工具實(shí)現(xiàn)retriever_tool.py異常定義exceptions.py模塊文檔README.md【免費(fèi)下載鏈接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.項(xiàng)目地址: https://gitcode.com/GitHub_Trending/cr/crewAI創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考