代码解释器
CodeInterpreterTool
Section titled “CodeInterpreterTool”CodeInterpreterTool 让 CrewAI agents 能够执行它们自主生成的 Python 3 代码。这个功能尤其有价值,因为它允许 agents 创建代码、执行代码、获取结果,并利用这些信息来指导后续决策和行动。
这个工具有几种使用方式:
Docker 容器(推荐)
Section titled “Docker 容器(推荐)”这是首选方案。代码会在安全、隔离的 Docker 容器中运行,无论内容如何都能确保安全。 请确保你的系统已安装并运行 Docker。如果没有,可以从 这里 安装。
Sandbox 环境
Section titled “Sandbox 环境”如果 Docker 不可用 - 无论是未安装还是由于其他原因无法访问 - 代码将会在一个受限的 Python 环境中执行,也就是 sandbox。 这个环境非常有限,对许多模块和内置函数都施加了严格限制。
不建议用于生产环境
这种模式允许执行任意 Python 代码,包括对 sys, os.. 等模块的危险调用以及类似操作。查看这里 了解如何启用该模式
CodeInterpreterTool 会将所选执行策略记录到 STDOUT。
要使用这个工具,需要安装 CrewAI tools 包:
pip install 'crewai[tools]'下面的示例展示了如何在 CrewAI agent 中使用 CodeInterpreterTool:
from crewai import Agent, Task, Crew, Processfrom crewai_tools import CodeInterpreterTool
# Initialize the toolcode_interpreter = CodeInterpreterTool()
# Define an agent that uses the toolprogrammer_agent = Agent( role="Python Programmer", goal="Write and execute Python code to solve problems", backstory="An expert Python programmer who can write efficient code to solve complex problems.", tools=[code_interpreter], verbose=True,)
# Example task to generate and execute codecoding_task = Task( description="Write a Python function to calculate the Fibonacci sequence up to the 10th number and print the result.", expected_output="The Fibonacci sequence up to the 10th number.", agent=programmer_agent,)
# Create and run the crewcrew = Crew( agents=[programmer_agent], tasks=[coding_task], verbose=True, process=Process.sequential,)result = crew.kickoff()你也可以在创建 agent 时直接启用代码执行:
from crewai import Agent
# Create an agent with code execution enabledprogrammer_agent = Agent( role="Python Programmer", goal="Write and execute Python code to solve problems", backstory="An expert Python programmer who can write efficient code to solve complex problems.", allow_code_execution=True, # This automatically adds the CodeInterpreterTool verbose=True,)启用 unsafe_mode
Section titled “启用 unsafe_mode”from crewai_tools import CodeInterpreterTool
code = """import osos.system("ls -la")"""
CodeInterpreterTool(unsafe_mode=True).run(code=code)CodeInterpreterTool 在初始化时接受以下参数:
- user_dockerfile_path:可选。用于代码解释器容器的自定义 Dockerfile 路径。
- user_docker_base_url:可选。用于运行容器的 Docker daemon URL。
- unsafe_mode:可选。是否直接在宿主机上运行代码,而不是在 Docker 容器或 sandbox 中运行。默认值为
False。请谨慎使用! - default_image_tag:可选。默认 Docker 镜像标签。默认值为
code-interpreter:latest
当与 agent 一起使用时,agent 需要提供:
- code:必填。要执行的 Python 3 代码。
- libraries_used:可选。代码中使用且需要安装的库列表。默认值为
[]
Agent 集成示例
Section titled “Agent 集成示例”下面给出一个更详细的示例,展示如何将 CodeInterpreterTool 集成到 CrewAI agent 中:
from crewai import Agent, Task, Crewfrom crewai_tools import CodeInterpreterTool
# Initialize the toolcode_interpreter = CodeInterpreterTool()
# Define an agent that uses the tooldata_analyst = Agent( role="Data Analyst", goal="Analyze data using Python code", backstory="""You are an expert data analyst who specializes in using Python to analyze and visualize data. You can write efficient code to process large datasets and extract meaningful insights.""", tools=[code_interpreter], verbose=True,)
# Create a task for the agentanalysis_task = Task( description=""" Write Python code to: 1. Generate a random dataset of 100 points with x and y coordinates 2. Calculate the correlation coefficient between x and y 3. Create a scatter plot of the data 4. Print the correlation coefficient and save the plot as 'scatter.png'
Make sure to handle any necessary imports and print the results. """, expected_output="The correlation coefficient and confirmation that the scatter plot has been saved.", agent=data_analyst,)
# Run the taskcrew = Crew( agents=[data_analyst], tasks=[analysis_task], verbose=True, process=Process.sequential,)result = crew.kickoff()CodeInterpreterTool 使用 Docker 创建一个安全的代码执行环境:
class CodeInterpreterTool(BaseTool): name: str = "Code Interpreter" description: str = "Interprets Python3 code strings with a final print statement." args_schema: Type[BaseModel] = CodeInterpreterSchema default_image_tag: str = "code-interpreter:latest"
def _run(self, **kwargs) -> str: code = kwargs.get("code", self.code) libraries_used = kwargs.get("libraries_used", [])
if self.unsafe_mode: return self.run_code_unsafe(code, libraries_used) else: return self.run_code_safety(code, libraries_used)该工具会执行以下步骤:
- 验证 Docker 镜像是否存在,必要时构建镜像
- 创建一个挂载了当前工作目录的 Docker 容器
- 安装 agent 指定的任何必需库
- 在容器中执行 Python 代码
- 返回代码执行输出
- 停止并移除容器以完成清理
安全注意事项
Section titled “安全注意事项”默认情况下,CodeInterpreterTool 会在隔离的 Docker 容器中运行代码,这提供了一层安全保障。不过,仍有一些安全注意事项需要留意:
- Docker 容器可以访问当前工作目录,因此敏感文件可能会被访问到。
- 如果 Docker 容器不可用,而代码仍需安全运行,它会在 sandbox 环境中执行。出于安全原因,不允许安装任意库。
unsafe_mode参数允许代码直接在宿主机上执行,只应在受信任环境中使用。- 当允许 agents 安装任意库时要格外谨慎,因为其中可能包含恶意代码。
CodeInterpreterTool 为 CrewAI agents 提供了一种在相对安全的环境中执行 Python 代码的强大方式。通过让 agents 能够编写并运行代码,它显著扩展了解决问题的能力,尤其适用于数据分析、计算或其他计算类任务。对于那些需要执行复杂操作、且用代码比自然语言更高效表达的 agents,这个工具尤其有用。