文档索引
获取完整文档索引: https://docs.crewai.com.cn/llms.txt
在深入了解之前,请使用此文件来浏览所有可用页面。
CrewAI 智能体现在具备了编写和执行代码的强大能力,这显著增强了它们的问题解决能力。该功能对于需要计算或程序化解决方案的任务特别有用。
启用代码执行
要为智能体启用代码执行,请在创建智能体时将 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
)
请注意,allow_code_execution 参数的默认值为 False。
重要注意事项
-
模型选择:强烈建议在启用代码执行时使用能力更强的模型,例如 Claude 3.5 Sonnet 和 GPT-4。这些模型对编程概念有更好的理解,更有可能生成正确且高效的代码。
-
错误处理:代码执行功能包含错误处理机制。如果执行的代码引发异常,智能体将接收到错误消息,并可以尝试修正代码或提供替代解决方案。
max_retry_limit 参数(默认值为 2)控制任务的最大重试次数。
-
依赖项:要使用代码执行功能,您需要安装
crewai_tools 包。如果未安装,智能体将记录一条信息:“Coding tools not available. Install crewai_tools.”
代码执行流程
当启用了代码执行功能的智能体遇到需要编程的任务时
代码构建
它构建解决问题所需的 Python 代码。
代码执行
代码被发送到内部代码执行工具(CodeInterpreterTool)。
结果解读
智能体解读结果并将其整合到响应中,或将其用于进一步的问题解决。
用法示例
以下是创建一个具备代码执行能力的智能体并将其用于任务的详细示例
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 代码来执行数据分析任务。