CrewAI智能体开发:代码解释器
CodeInterpreterTool 是一款强大的工具,专为在安全的隔离环境中执行 Python 3 代码而设计。
CodeInterpreterTool
描述CodeInterpreterTool 使 CrewAI 智能体能够执行它们自主生成的 Python 3 代码。此功能特别有价值,因为它允许智能体编写代码、执行代码、获取结果,并利用这些信息来辅助后续的决策和行动。使用此工具有几种方式:
Docker 容器(推荐)这是首选方案。代码在安全的隔离 Docker 容器中运行,无论代码内容如何都能确保安全。请确保您的系统中已安装并运行 Docker。如果没有,您可以从 此处 安装。
沙箱环境如果 Docker 不可用(无论是未安装还是由于任何原因无法访问),代码将在受限的 Python 环境(称为沙箱)中执行。该环境受到严格限制,对许多模块和内置函数都有严格的约束。
非安全执行不建议用于生产环境 此模式允许执行任何 Python 代码,包括对 sys, os.. 及类似模块的危险调用。查看 如何启用此模式。
日志记录CodeInterpreterTool 会将选定的执行策略记录到标准输出 (STDOUT)。
安装要使用此工具,您需要安装 CrewAI tools 软件包。
pip install 'crewai[tools]'
示例以下示例演示了如何在 CrewAI 智能体中使用 CodeInterpreterTool。
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)
该工具执行以下步骤:
- 验证 Docker 镜像是否存在,必要时进行构建。
- 创建一个挂载了当前工作目录的 Docker 容器。
- 安装智能体指定的任何所需库。
- 在容器中执行 Python 代码。
- 返回代码执行的输出。
- 通过停止并移除容器进行清理。
安全考虑默认情况下,CodeInterpreterTool 在隔离的 Docker 容器中运行代码,这提供了一层安全保护。然而,仍有一些安全事项需要注意:
- Docker 容器可以访问当前工作目录,因此敏感文件可能会被访问。
- 如果 Docker 容器不可用且需要安全运行代码,它将在沙箱环境中执行。出于安全原因,不允许安装任意库。
unsafe_mode参数允许在宿主机上直接执行代码,这应仅在受信任的环境中使用。- 允许智能体安装任意库时要保持谨慎,因为它们可能包含恶意代码。
结论CodeInterpreterTool 为 CrewAI 智能体提供了一种在相对安全的环境中执行 Python 代码的强大方式。通过让智能体具备编写和运行代码的能力,它显著扩展了它们解决问题的能力,特别是对于涉及数据分析、计算或其他计算密集型工作的任务。对于需要执行比自然语言更高效的代码操作的智能体,此工具尤为有用。
《AI提示工程必知必会》为读者提供了丰富的AI提示工程知识与实战技能。《AI提示工程必知必会》主要内容包括各类提示词的应用,如问答式、指令式、状态类、建议式、安全类和感谢类提示词,以及如何通过实战演练掌握提示词的使用技巧;使用提示词进行文本摘要、改写重述、语法纠错、机器翻译等语言处理任务,以及在数据挖掘、程序开发等领域的应用;AI在绘画创作上的应用,百度文心一言和阿里通义大模型这两大智能平台的特性与功能,以及市场调研中提示词的实战应用。通过阅读《AI提示工程必知必会》,读者可掌握如何有效利用AI提示工程提升工作效率,创新工作流程,并在职场中脱颖而出。

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)