news 2026/9/6 16:08:17

CrewAI 接入 AWS Bedrock Code Interpreter:构建安全隔离的代码执行 Agent 工具链

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
CrewAI 接入 AWS Bedrock Code Interpreter:构建安全隔离的代码执行 Agent 工具链

CrewAI 接入 AWS Bedrock Code Interpreter:构建安全隔离的代码执行 Agent 工具链

【免费下载链接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.项目地址: https://gitcode.com/GitHub_Trending/cr/crewAI

本文围绕 CrewAI 的 AWS Bedrock Code Interpreter 工具包(位于lib/crewai-tools包中的crewai_tools.aws.bedrock.code_interpreter模块)展开。读完后,你将能够:在 CrewAI Agent 中接入 AWS Bedrock AgentCore 的远程代码解释器环境,让 Agent 安全地执行 Python 代码、运行 Shell 命令、管理文件,并通过thread_id实现多会话隔离;同时理解工具包底层的懒加载会话机制、流式输出解析与资源清理的实现原理,避免云端会话泄漏。

一、模块定位与整体架构

该工具包是crewai_toolsaws子包的一部分,与 Browser 工具包、Agent 调用工具、知识库检索工具、S3 读写工具并列,统一通过crewai_tools.aws对外导出:

  • 入口导出:crewai_tools/aws/init.py 中create_code_interpreter_toolkit被列为公开 API;
  • 模块导出:code_interpreter/init.py 暴露CodeInterpreterToolkitcreate_code_interpreter_toolkit两个符号;
  • 核心实现:全部集中在 code_interpreter_toolkit.py 一个文件内(约 600 行)。

它的价值在于:Agent 不再在本地进程里执行模型生成的代码,而是把代码发送到 AWS 侧的 Bedrock AgentCore Code Interpreter 沙箱中运行,获得一个安全、隔离、有文件系统与 Shell 能力的远程执行环境,适用于数据分析、脚本调试、批量文件处理等场景。

从源码结构看,整个工具包可以拆成三层:

  1. 输入 Schema 层:9 个 PydanticBaseModel(如ExecuteCodeInputWriteFilesInput),为每个工具定义参数名、类型、默认值与描述。这些描述会进入 LLM 的工具调用提示词,直接影响 Agent 传参的准确性;
  2. Tool 类层:9 个继承自crewai.tools.BaseTool的工具类,每个工具的_run方法负责取/建对应会话并调用底层CodeInterpreter.invoke(method=..., params=...)_arun则直接委托给同步实现(源码注释说明底层同步 API 是线程安全的);
  3. Toolkit 会话管理层CodeInterpreterToolkit负责按thread_id懒加载并缓存多个CodeInterpreter会话,并提供cleanup()回收资源。

二、安装与前置条件

工具包依赖独立的第三方包bedrock-agentcore,在 pyproject.toml 中以bedrock可选依赖(extra)声明,版本约束为bedrock-agentcore>=1.18.1,<2.0.0,同时附带playwrightnest-asynciobeautifulsoup4(这些是 Bedrock 浏览器工具等整个 extra 共用的依赖)。

安装命令(来自原 README):

uv add crewai-tools bedrock-agentcore

使用前提(原 README "Requirements" 部分):

  • 拥有可访问Bedrock AgentCore API的 AWS 账户;
  • 正确配置了 AWS 凭据(标准 AWS 凭据链即可,如环境变量、~/.aws/credentials、IAM Role);
  • region参数需与你的 AgentCore 资源所在区域一致,所有示例默认使用us-west-2

三、九大内置工具与底层方法映射

工具包共提供 9 个工具。下表把每个工具的名称、输入参数与它实际调用的 Bedrock AgentCore 方法对应起来(依据 code_interpreter_toolkit.py 中各_run实现的invoke(method=..., params=...)调用):

工具名 (name)输入参数对应 AgentCore 方法说明
execute_codecodelanguage(默认"python")、clear_context(默认False)、thread_idexecuteCode执行代码;clear_context=True时清空执行上下文
execute_commandcommandthread_idexecuteCommand在沙箱内运行 Shell 命令
read_filespaths: list[str]thread_idreadFiles批量读取文件内容
list_filesdirectory_path(默认"")、thread_idlistFiles列出目录内容
delete_filespaths: list[str]thread_idremoveFiles批量删除文件(注意方法名与工具名不同)
write_filesfiles: list[dict](含path/text字段)、thread_idwriteFiles创建或更新文件,参数字段名为content
start_command_executioncommandthread_idstartCommandExecution异步启动长时命令
get_tasktask_idthread_idgetTask查询异步任务状态
stop_tasktask_idthread_idstopTask停止运行中的任务

两个值得注意的实现细节:

1. 所有工具都带thread_id参数(默认"default"。这是多会话隔离的基石:工具包内部维护_code_interpreters: dict[str, CodeInterpreter]字典,每个thread_id对应一个独立的远程会话。不同thread_id之间的变量、文件与执行上下文互不干扰——你可以让一个线程做数据清洗、另一个线程做可视化,而彼此不会覆盖对方的工作区。

2. 输出统一经extract_output_from_stream()解析。该函数遍历响应中的stream事件,对result.content逐项处理:type == "text"的条目直接拼接文本;type == "resource"的条目若是带text的文件资源,则去掉file://前缀并格式化为==== File: <路径> ====的代码块输出,其他资源则序列化为 JSON。这意味着当 Agent 在沙箱里生成图片、CSV 等文件并被返回为资源时,工具能以 Agent 可理解的结构化文本呈现,而不是原始二进制。

四、基础用法:单 Agent 执行代码

以下示例完整继承自原 README:创建一个代码解释器工具包、一个使用 Bedrock 上 Claude 模型的 Agent,让它编写并自测一个阶乘函数。

from crewai import Agent, Task, Crew, LLM from crewai_tools.aws import create_code_interpreter_toolkit # Create the code interpreter toolkit toolkit, code_tools = create_code_interpreter_toolkit(region="us-west-2") # Create the Bedrock LLM llm = LLM( model="bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0", region_name="us-west-2", ) # Create a CrewAI agent that uses the code interpreter tools developer_agent = Agent( role="Python Developer", goal="Create and execute Python code to solve problems.", backstory="You're a skilled Python developer with expertise in data analysis.", tools=code_tools, llm=llm ) # Create a task for the agent coding_task = Task( description="Write a Python function that calculates the factorial of a number and test it. Do not use any imports from outside the Python standard library.", expected_output="The Python function created, and the test results.", agent=developer_agent ) # Create and run the crew crew = Crew( agents=[developer_agent], tasks=[coding_task] ) result = crew.kickoff() print(f"\n***Final result:***\n\n{result}") # Clean up resources when done import asyncio asyncio.run(toolkit.cleanup())

关键点解析:

  • create_code_interpreter_toolkit(region="us-west-2")返回二元组(toolkit, tools)注意此时并不会创建任何远程会话——源码_setup_tools()只实例化 9 个工具对象,真正的CodeInterpreter会话直到第一次工具调用时才由_get_or_create_interpreter()创建(内部调用CodeInterpreter(region=self.region)start())。这种懒加载意味着即使创建了工具包但 Agent 从未触发代码执行,也不会产生任何云端会话开销;
  • tools=code_tools表示把全部 9 个工具一次性交给 Agent,适合"全能开发者"型角色;
  • 任务描述里显式约束"不使用标准库以外的 import",是为了确保沙箱内无需额外依赖即可运行,这也是在远程受限环境中编写任务描述的一个实用技巧。

五、进阶用法:按名称精确装配工具

当 Crew 里有多个 Agent、职责不同时,更细粒度的做法是只把与角色匹配的工具子集交给对应 Agent。toolkit.get_tools_by_name()返回{工具名: 工具实例}字典,可按名取用:

from crewai import Agent, Task, Crew, LLM from crewai_tools.aws import create_code_interpreter_toolkit # Create the code interpreter toolkit toolkit, code_tools = create_code_interpreter_toolkit(region="us-west-2") tools_by_name = toolkit.get_tools_by_name() # Create the Bedrock LLM llm = LLM( model="bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0", region_name="us-west-2", ) # Create agents with specific tools code_agent = Agent( role="Code Developer", goal="Write and execute code", backstory="You write and test code to solve complex problems.", tools=[ # Use specific tools by name tools_by_name["execute_code"], tools_by_name["execute_command"], tools_by_name["read_files"], tools_by_name["write_files"] ], llm=llm ) file_agent = Agent( role="File Manager", goal="Manage files in the environment", backstory="You help organize and manage files in the code environment.", tools=[ # Use specific tools by name tools_by_name["list_files"], tools_by_name["read_files"], tools_by_name["write_files"], tools_by_name["delete_files"] ], llm=llm ) # Create tasks for the agents coding_task = Task( description="Write a Python script to analyze data from a CSV file. Do not use any imports from outside the Python standard library.", expected_output="The Python function created.", agent=code_agent ) file_task = Task( description="Organize the created files into separate directories.", agent=file_agent ) # Create and run the crew crew = Crew( agents=[code_agent, file_agent], tasks=[coding_task, file_task] ) result = crew.kickoff() print(f"\n***Final result:***\n\n{result}") # Clean up code interpreter resources when done import asyncio asyncio.run(toolkit.cleanup())

这种拆分带来三个实际好处:

  1. 提示词更聚焦:Agent 每次推理看到的工具清单更短,参数混淆概率更低;
  2. 权限最小化:文件管理 Agent 拿不到execute_code,即使被提示词注入也难以在沙箱里执行任意代码;
  3. 共享同一工作区:两个 Agent 的工具都使用默认thread_id="default",因此code_agent写入的 CSV 与脚本,file_agent能在同一个沙箱会话中直接看到并整理——这是多 Agent 协作的天然基础。若需要彼此隔离的工作区,则给不同 Agent 的任务/工具调用显式传不同的thread_id

六、实战示例:数据分析全流程

下面这个示例(同样继承自原 README)展示了"生成数据 → 统计分析 → 可视化 → 落盘"的完整数据工程链路,全部只依赖 Python 标准库:

from crewai import Agent, Task, Crew, LLM from crewai_tools.aws import create_code_interpreter_toolkit # Create toolkit and tools toolkit, code_tools = create_code_interpreter_toolkit(region="us-west-2") # Create the Bedrock LLM llm = LLM( model="bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0", region_name="us-west-2", ) # Create a data analyst agent analyst_agent = Agent( role="Data Analyst", goal="Analyze data using Python", backstory="You're an expert data analyst who uses Python for data processing.", tools=code_tools, llm=llm ) # Create a task for the agent analysis_task = Task( description=""" For all of the below, do not use any imports from outside the Python standard library. 1. Create a sample dataset with random data 2. Perform statistical analysis on the dataset 3. Generate visualizations of the results 4. Save the results and visualizations to files """, agent=analyst_agent ) # Create and run the crew crew = Crew( agents=[analyst_agent], tasks=[analysis_task] ) result = crew.kickoff() print(f"\n***Final result:***\n\n{result}") # Clean up resources import asyncio asyncio.run(toolkit.cleanup())

注意第 4 步"保存结果与可视化到文件":Agent 会通过write_files(或在代码中写文件)把产物留在沙箱文件系统中,之后可以随时用read_files取回分析结论,或用list_files检查目录结构。而第 3 步生成的图表若以资源形式返回,extract_output_from_stream()会将其格式化为==== File: <uri> ====文本块,让 LLM 能"看到"文件路径与内容。

七、资源清理:防止云端会话泄漏

原 README 特别强调"始终在用完时清理资源"。对照源码 cleanup() 的实现,其行为是:

  • 传入thread_id:只stop()并移除该线程对应的会话,失败仅记录 warning 不抛异常;
  • 不传参数(None):遍历所有已创建的会话逐个stop(),最后清空整个_code_interpreters字典。
import asyncio # Clean up all code interpreter sessions asyncio.run(toolkit.cleanup())

由于 Code Interpreter 是远程托管会话,不清理就意味着持续计费与占用的沙箱实例。建议将其放进脚本的try/finallyatexit中,保证异常路径也能回收。此外每个工具_run的实现都捕获了异常并返回"Error executing code: ..."这类字符串形式的错误信息而非抛出异常——这对 Agent 友好(错误会进入对话上下文供模型自我修正),但也意味着程序层面不应假设"工具返回非空字符串 = 执行成功",重要场景应在 Agent 结果中校验关键输出。

八、关键参数速查与最佳实践

参数/方法默认值说明
create_code_interpreter_toolkit(region=...)"us-west-2"必须与 AgentCore 资源所在区域一致
thread_id(所有工具)"default"会话隔离键;同 ID 共享上下文与文件系统
language(execute_code)"python"代码语言标识
clear_context(execute_code)FalseTrue时清空该线程执行上下文,适合切换任务场景
directory_path(list_files)""(根目录)要列出的沙箱内目录
toolkit.cleanup(thread_id=None)全部会话按需清理单个或全部会话
toolkit.get_tools()/get_tools_by_name()取工具列表 / 按名取工具字典

最佳实践汇总:

  1. 区域对齐toolkitregionLLM(region_name=...)通常应指向同一区域,避免跨区权限问题;
  2. 懒加载特性可利用:创建工具包本身零云端开销,适合在应用启动时预构建、按需触发的架构;
  3. 多 Agent 分工:按角色用get_tools_by_name()装配最小工具集;需要并行且互不污染的工作区时用不同thread_id
  4. 错误即上下文:工具失败会返回错误字符串供 Agent 自我重试,编写 Task 时可提示模型"如果执行报错,先检查依赖与语法再重试";
  5. 收尾必清理asyncio.run(toolkit.cleanup())作为脚本最后一行(或finally块)调用。

九、适用边界说明

结合仓库现状补充两点边界:

  • 从源码结构看,本模块的会话管理完全委托给bedrock-agentcore包的CodeInterpreter客户端(在 code_interpreter_toolkit.py 中于首次使用时延迟导入),CrewAI 侧只封装工具协议与线程会话映射,因此 AgentCore 会话本身的配额、超时与计费规则以 AWS 侧配置为准;
  • lib/crewai-tools/tests/目录中未发现针对该模块的专用单元测试,集成验证以 README 中的三个端到端示例为主要参照;该功能属于crewai-toolsbedrock可选依赖集,未安装bedrock-agentcore时相关导入会失败,按需安装即可。

核心文件索引:README | 核心实现 | aws 包导出 | 依赖声明

【免费下载链接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.项目地址: https://gitcode.com/GitHub_Trending/cr/crewAI

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/6 16:07:53

React Router 6.4 架构决策:如何把 Remix 分层到 React Router 6.4 之上

React Router 6.4 架构决策&#xff1a;如何把 Remix 分层到 React Router 6.4 之上 【免费下载链接】react-router Declarative routing for React 项目地址: https://gitcode.com/GitHub_Trending/re/react-router 本篇基于 React Router 仓库中的架构决策记录 0007-r…

作者头像 李华
网站建设 2026/9/6 16:06:22

计算机网络实验报告高分攻略:抓包、路由与Socket编程实战

简介&#xff1a;这份实验报告来自广东工业大学计算机学院&#xff0c;完整覆盖计算机网络课程中两个基础实验模块&#xff1a;Windows 下常用网络命令&#xff08;Ping、IPconfig、Netsh、Tracert、Netstat、Arp、Nslookup&#xff09;和协议分析软件基础&#xff08;Wireshar…

作者头像 李华
网站建设 2026/9/6 15:59:38

WavLM 完整使用指南:加载模型、提取特征到语音任务全流程

WavLM 完整使用指南&#xff1a;加载模型、提取特征到语音任务全流程 【免费下载链接】unilm Large-scale Self-supervised Pre-training Across Tasks, Languages, and Modalities 项目地址: https://gitcode.com/GitHub_Trending/un/unilm 如果你需要把一段 16kHz 的语…

作者头像 李华
网站建设 2026/9/6 15:58:40

重型机械行业成本管理模式分析与落地实践

简介&#xff1a;一份聚焦重型机械制造领域的成本管理专题分析文档&#xff0c;以昆明重型机械工业总公司为案例&#xff0c;面向机械制造企业管理人员、成本会计及工业经济研究者。内容聚焦成本管理现状诊断、问题成因剖析与系统成本管理模式构建&#xff0c;强调作业成本法、…

作者头像 李华
网站建设 2026/9/6 15:58:08

EBOM到MBOM转换全攻略:核心逻辑、五步操作与避坑指南

简介&#xff1a;针对企业信息化中EBOM到MBOM转换难点的专业资料&#xff0c;面向PDM/ERP实施顾问、制造企业工艺与设计人员。文档以Windchill系统为背景&#xff0c;梳理BOM定义与分类&#xff0c;剖析现有EBOM管理存在的问题&#xff0c;并通过对比超级EBOM、单一EBOM含可选件…

作者头像 李华