跳转到主要内容

CodeInterpreterTool

描述

CodeInterpreterTool 使 CrewAI 智能体能够执行它们自主生成的 Python 3 代码。 此功能特别有价值,因为它允许智能体创建代码、执行代码、获取结果,并利用这些信息来指导后续的决策和行动。 有几种方法可以使用此工具: 这是首选方案。代码在一个安全、隔离的 Docker 容器中运行,无论其内容如何,都能确保安全。请确保您的系统上已安装并运行 Docker。如果您没有安装,可以从此处安装。

沙盒环境

如果 Docker 不可用——无论是未安装还是因任何原因无法访问——代码将在一个受限制的 Python 环境(称为沙盒)中执行。这个环境非常有限,对许多模块和内置函数都有严格的限制。

不安全执行

不建议在生产环境中使用 此模式允许执行任何 Python 代码,包括对 sys、os 等模块的危险调用。查看如何启用此模式。

日志记录

CodeInterpreterTool 会将所选的执行策略记录到 STDOUT(标准输出)。

安装

要使用此工具,您需要安装 CrewAI 工具包。
pip install 'crewai[tools]'

示例

以下示例演示了如何将 CodeInterpreterTool 与 CrewAI 智能体一起使用。
代码
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()
您还可以在创建智能体时直接启用代码执行。
代码
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

代码
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 智能体集成。
代码
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 创建一个安全的代码执行环境。
代码
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)
该工具执行以下步骤:
  1. 验证 Docker 镜像是否存在,如果不存在则构建它。
  2. 创建一个挂载了当前工作目录的 Docker 容器。
  3. 安装智能体指定的任何必需库。
  4. 在容器中执行 Python 代码。
  5. 返回代码执行的输出。
  6. 通过停止并移除容器进行清理。

安全注意事项

默认情况下,CodeInterpreterTool 在隔离的 Docker 容器中运行代码,这提供了一层安全保障。但是,仍需注意一些安全问题:
  1. Docker 容器可以访问当前工作目录,因此敏感文件可能会被访问。
  2. 如果 Docker 容器不可用且代码需要安全运行,它将在沙盒环境中执行。出于安全原因,不允许安装任意库。
  3. unsafe_mode 参数允许代码直接在主机上执行,这只应在受信任的环境中使用。
  4. 在允许智能体安装任意库时要谨慎,因为它们可能包含恶意代码。

结论

CodeInterpreterTool 为 CrewAI 智能体提供了一种在相对安全的环境中执行 Python 代码的强大方式。通过使智能体能够编写和运行代码,它极大地扩展了它们的解决问题能力,特别是对于涉及数据分析、计算或其他计算工作的任务。对于需要执行那些用代码比用自然语言更高效表达的复杂操作的智能体来说,此工具尤其有用。