介绍

CrewAI 代理现在拥有编写和执行代码的强大能力,显著增强了它们解决问题的能力。此功能对于需要计算或编程解决方案的任务特别有用。

启用代码执行

要为代理启用代码执行,请在创建代理时将allow_code_execution参数设置为True

这是一个例子:

Code
from crewai import Agent

coding_agent = Agent(
    role="Senior Python Developer",
    goal="Craft well-designed and thought-out code",
    backstory="You are a senior Python developer with extensive experience in software architecture and best practices.",
    allow_code_execution=True
)

请注意,allow_code_execution 参数默认为 False

重要注意事项

  1. 模型选择: 强烈建议在启用代码执行时使用更强大的模型,如Claude 3.5 Sonnet和GPT-4。 这些模型对编程概念有更好的理解,更有可能生成正确且高效的代码。

  2. 错误处理: 代码执行功能包括错误处理。如果执行的代码引发异常,代理将收到错误消息,并可以尝试更正代码或提供替代解决方案。max_retry_limit 参数,默认值为 2,控制任务的最大重试次数。

  3. 依赖项: 要使用代码执行功能,您需要安装crewai_tools包。如果未安装,代理将记录一条信息消息: “编码工具不可用。请安装crewai_tools。”

代码执行过程

当启用了代码执行的代理遇到需要编程的任务时:

1

任务分析

代理分析任务并确定需要执行代码。

2

代码公式

它制定了解决问题所需的Python代码。

3

代码执行

代码被发送到内部代码执行工具(CodeInterpreterTool)。

4

结果解释

代理解释结果并将其纳入其响应中,或用于进一步解决问题。

示例用法

以下是一个详细的示例,展示了如何创建一个具有代码执行能力的代理并在任务中使用它:

Code
from crewai import Agent, Task, Crew

# Create an agent with code execution enabled
coding_agent = Agent(
    role="Python Data Analyst",
    goal="Analyze data and provide insights using Python",
    backstory="You are an experienced data analyst with strong Python skills.",
    allow_code_execution=True
)

# Create a task that requires code execution
data_analysis_task = Task(
    description="Analyze the given dataset and calculate the average age of participants.",
    agent=coding_agent
)

# Create a crew and add the task
analysis_crew = Crew(
    agents=[coding_agent],
    tasks=[data_analysis_task]
)

# Execute the crew
result = analysis_crew.kickoff()

print(result)

在这个例子中,coding_agent 可以编写并执行 Python 代码来执行数据分析任务。

这个页面有帮助吗?