跳转到内容

编码代理

CrewAI Agents 现在具备了强大的编写和执行代码的能力,这显著增强了它们的 问题解决能力。这个功能特别适合那些需要计算或程序化解决方案的任务。

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

示例如下:

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

  2. 错误处理:代码执行功能包含错误处理。如果执行的代码抛出异常,agent 会 收到错误信息,并可以尝试修正代码或提供替代方案。max_retry_limit 参数 默认值为 2,用于控制任务的最大重试次数。

  3. 依赖项:要使用代码执行功能,你需要安装 crewai_tools 包。如果未安装, agent 会记录一条信息: "Coding tools not available. Install crewai_tools."

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

  1. 任务分析

    agent 会分析任务,并判断是否需要执行代码。

  2. 代码构思

    它会构思解决问题所需的 Python 代码。

  3. 代码执行

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

  4. 结果解释

    agent 会解释结果,并将其纳入回复,或用于进一步解决问题。

下面是一个创建具备代码执行能力的 agent 并在任务中使用它的详细示例:

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 代码来完成数据分析任务。