主题
代码解释器
CodeInterpreterTool是一个强大的工具,旨在安全、隔离的环境中执行 Python 3 代码。
CodeInterpreterTool
WARNING
已弃用: CodeInterpreterTool 已从 crewai-tools 中移除。Agent 上的 allow_code_execution 和 code_execution_mode 参数也已弃用。请使用专用的沙箱服务 —— E2B 或 Modal —— 来安全、隔离地执行代码。
描述
CodeInterpreterTool 让 CrewAI 智能体能够执行其自主生成的 Python 3 代码。这一功能尤其有价值,因为它允许智能体创建代码、执行代码、获取结果,并利用这些信息来指导后续的决策与行动。
使用此工具有以下几种方式:
Docker 容器(推荐)
这是首选方案。代码在安全、隔离的 Docker 容器中运行,无论其内容如何都能确保安全。 请确保你的系统中已安装并运行 Docker。如果尚未安装,可以从这里安装。
沙箱环境
如果 Docker 不可用——无论是未安装还是出于任何原因无法访问——代码将在一个受限的 Python 环境中执行,该环境称为沙箱。 该环境非常有限,对许多模块和内置函数都有严格限制。
不安全执行
不建议用于生产环境 此模式允许执行任意 Python 代码,包括对 sys、os.. 等模块的危险调用。查看如何启用此模式
日志
CodeInterpreterTool 会将所选的执行策略记录到 STDOUT
安装
要使用此工具,你需要安装 CrewAI 工具包:
shell
pip install 'crewai[tools]'示例
以下示例演示了如何配合 CrewAI 智能体使用 CodeInterpreterTool:
python
from crewai import Agent, Task, Crew, Process
from crewai_tools import CodeInterpreterTool
# Initialize the tool
code_interpreter = CodeInterpreterTool()
# Define an agent that uses the tool
programmer_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 code
coding_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 crew
crew = Crew(
agents=[programmer_agent],
tasks=[coding_task],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()你也可以在创建智能体时直接启用代码执行:
python
from crewai import Agent
# Create an agent with code execution enabled
programmer_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
python
from crewai_tools import CodeInterpreterTool
code = """
import os
os.system("ls -la")
"""
CodeInterpreterTool(unsafe_mode=True).run(code=code)参数
CodeInterpreterTool 在初始化时接受以下参数:
- user_dockerfile_path:可选。用于代码解释器容器的自定义 Dockerfile 路径。
- user_docker_base_url:可选。用于运行容器的 Docker 守护进程 URL。
- unsafe_mode:可选。是否直接在宿主机上运行代码,而不是在 Docker 容器或沙箱中运行。默认为
False。请谨慎使用! - default_image_tag:可选。默认 Docker 镜像标签。默认为
code-interpreter:latest
在智能体中使用该工具时,智能体需要提供:
- code:必填。要执行的 Python 3 代码。
- libraries_used:可选。代码中使用且需要安装的库列表。默认为
[]
智能体集成示例
下面是一个更详细的示例,展示如何将 CodeInterpreterTool 与 CrewAI 智能体集成:
python
from crewai import Agent, Task, Crew
from crewai_tools import CodeInterpreterTool
# Initialize the tool
code_interpreter = CodeInterpreterTool()
# Define an agent that uses the tool
data_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 agent
analysis_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 task
crew = Crew(
agents=[data_analyst],
tasks=[analysis_task],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()实现细节
CodeInterpreterTool 使用 Docker 创建一个安全的代码执行环境:
python
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 容器
- 安装智能体指定的任何必需库
- 在容器中执行 Python 代码
- 返回代码执行的输出
- 通过停止并移除容器进行清理
安全注意事项
默认情况下,CodeInterpreterTool 在隔离的 Docker 容器中运行代码,这提供了一层安全保障。不过,仍有一些安全注意事项需要牢记:
- Docker 容器可以访问当前工作目录,因此敏感文件可能会被访问。
- 如果 Docker 容器不可用而又需要安全地运行代码,代码将在沙箱环境中执行。出于安全考虑,不允许安装任意库
unsafe_mode参数允许代码直接在宿主机上执行,只应在可信环境中使用。- 允许智能体安装任意库时要小心,因为它们可能包含恶意代码。
结论
CodeInterpreterTool 为 CrewAI 智能体提供了一种在相对安全的环境中执行 Python 代码的强大方式。通过让智能体编写并运行代码,它显著扩展了智能体解决问题的能力,特别是对于涉及数据分析、计算或其他计算型工作的任务。对于需要执行用代码表达比用自然语言更高效的复杂操作的智能体来说,该工具尤其有用。