在 CrewAI 框架中,Task 是由 Agent 完成的特定任务。 任务提供了执行所需的所有必要细节,例如描述、负责的智能体、所需工具等,从而支持各种复杂度的操作。 CrewAI 中的任务可以是协作性的,需要多个智能体共同工作。这是通过任务属性来管理,并由 Crew 的流程进行协调,从而增强团队合作和效率。CrewAI AMP 在 Crew Studio 中包含了一个可视化任务构建器,可简化复杂任务的创建和链接。您无需编写代码,即可直观地设计任务流程并进行实时测试。
可视化任务构建器支持:
- 拖放式任务创建
- 可视化任务依赖和流程
- 实时测试和验证
- 轻松共享和协作
任务执行流程
任务可以通过两种方式执行
- 顺序执行:任务按照定义的顺序执行
- 层级执行:任务根据智能体的角色和专业知识进行分配
执行流程在创建 crew 时定义
crew = Crew(
agents=[agent1, agent2],
tasks=[task1, task2],
process=Process.sequential # or Process.hierarchical
)
任务属性
| 属性 | 参数 | 类型 | 描述 |
|---|
| 描述 | 描述 | str | 对任务内容的清晰、简洁的陈述。 |
| 预期输出 | expected_output | str | 对任务完成后的样子的详细描述。 |
| 名称 (可选) | name | Optional[str] | 任务的名称标识符。 |
| 智能体 (可选) | agent | Optional[BaseAgent] | 负责执行任务的智能体。 |
| 工具 (可选) | tools | List[BaseTool] | 智能体在此任务中被限制使用的工具/资源。 |
| 上下文 (可选) | context | Optional[List["Task"]] | 其输出将被用作此任务上下文的其他任务。 |
| 异步执行 (可选) | async_execution | Optional[bool] | 任务是否应异步执行。默认为 False。 |
| 人工输入 (可选) | human_input | Optional[bool] | 任务是否需要人类审查智能体的最终答案。默认为 False。 |
| Markdown (可选) | markdown | Optional[bool] | 任务是否应指示智能体以 Markdown 格式返回最终答案。默认为 False。 |
| 配置 (可选) | config | Optional[Dict[str, Any]] | 特定于任务的配置参数。 |
| 输出文件 (可选) | output_file | Optional[str] | 用于存储任务输出的文件路径。 |
| 创建目录 (可选) | create_directory | Optional[bool] | 如果 output_file 的目录不存在,是否创建该目录。默认为 True。 |
| 输出 JSON (可选) | output_json | Optional[Type[BaseModel]] | 用于构建 JSON 输出结构的 Pydantic 模型。 |
| 输出 Pydantic (可选) | output_pydantic | Optional[Type[BaseModel]] | 用于任务输出的 Pydantic 模型。 |
| 回调 (可选) | callback | Optional[Any] | 任务完成后执行的函数/对象。 |
| 护栏 (可选) | guardrail | Optional[Callable] | 在进入下一个任务之前验证任务输出的函数。 |
| 护栏最大重试次数 (可选) | guardrail_max_retries | Optional[int] | 当护栏验证失败时,最大重试次数。默认为 3。 |
任务属性 max_retries 已被弃用,并将在 v1.0.0 中移除。请改用 guardrail_max_retries 来控制护栏失败时的重试次数。
创建任务
在 CrewAI 中创建任务有两种方式:使用 YAML 配置(推荐) 或在代码中直接定义。
YAML 配置(推荐)
使用 YAML 配置提供了一种更清晰、更易于维护的任务定义方式。我们强烈建议在您的 CrewAI 项目中使用这种方法来定义任务。 按照安装部分所述创建您的 CrewAI 项目后,导航至 src/latest_ai_development/config/tasks.yaml 文件,并修改模板以匹配您的特定任务需求。YAML 文件中的变量(如 {topic})在运行 crew 时将被您的输入值替换crew.kickoff(inputs={'topic': 'AI Agents'})
以下是使用 YAML 配置任务的示例
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2025.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst
markdown: true
output_file: report.md
要在您的代码中使用此 YAML 配置,请创建一个继承自 CrewBase 的 crew 类
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'], # type: ignore[index]
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'], # type: ignore[index]
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'] # type: ignore[index]
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'] # type: ignore[index]
)
@crew
def crew(self) -> Crew:
return Crew(
agents=[
self.researcher(),
self.reporting_analyst()
],
tasks=[
self.research_task(),
self.reporting_task()
],
process=Process.sequential
)
您在 YAML 文件(agents.yaml 和 tasks.yaml)中使用的名称应与 Python 代码中的方法名相匹配。
直接代码定义(替代方法)
或者,您可以在代码中直接定义任务,而不使用 YAML 配置
from crewai import Task
research_task = Task(
description="""
Conduct a thorough research about AI Agents.
Make sure you find any interesting and relevant information given
the current year is 2025.
""",
expected_output="""
A list with 10 bullet points of the most relevant information about AI Agents
""",
agent=researcher
)
reporting_task = Task(
description="""
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
""",
expected_output="""
A fully fledge reports with the mains topics, each with a full section of information.
""",
agent=reporting_analyst,
markdown=True, # Enable markdown formatting for the final output
output_file="report.md"
)
直接指定一个 agent 进行分配,或者让 hierarchical CrewAI 的流程根据角色、可用性等来决定。
任务输出
理解任务输出对于构建有效的 AI 工作流至关重要。CrewAI 通过 TaskOutput 类提供了一种结构化的方式来处理任务结果,该类支持多种输出格式,并且可以轻松地在任务之间传递。 在 CrewAI 框架中,任务的输出被封装在 TaskOutput 类中。该类提供了一种结构化的方式来访问任务的结果,包括原始输出、JSON 和 Pydantic 模型等多种格式。 默认情况下,TaskOutput 将只包含 raw 输出。只有当原始的 Task 对象分别配置了 output_pydantic 或 output_json 时,TaskOutput 才会包含 pydantic 或 json_dict 输出。任务输出属性
| 属性 | 参数 | 类型 | 描述 |
|---|
| 描述 | 描述 | str | 任务的描述。 |
| 摘要 | summary | Optional[str] | 任务摘要,根据描述的前 10 个词自动生成。 |
| 原始输出 | raw | str | 任务的原始输出。这是输出的默认格式。 |
| Pydantic | pydantic | Optional[BaseModel] | 表示任务结构化输出的 Pydantic 模型对象。 |
| JSON 字典 | json_dict | Optional[Dict[str, Any]] | 表示任务 JSON 输出的字典。 |
| 智能体 | agent | str | 执行任务的智能体。 |
| 输出格式 | output_format | OutputFormat | 任务输出的格式,选项包括 RAW、JSON 和 Pydantic。默认为 RAW。 |
任务方法和属性
| 方法/属性 | 描述 |
|---|
| json | 如果输出格式为 JSON,则返回任务输出的 JSON 字符串表示。 |
| to_dict | 将 JSON 和 Pydantic 输出转换为字典。 |
| str | 返回任务输出的字符串表示,优先顺序为 Pydantic、JSON,然后是原始输出。 |
访问任务输出
任务执行后,可以通过 Task 对象的 output 属性访问其输出。TaskOutput 类提供了多种与该输出交互和呈现的方式。
# Example task
task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
# Execute the crew
crew = Crew(
agents=[research_agent],
tasks=[task],
verbose=True
)
result = crew.kickoff()
# Accessing the task output
task_output = task.output
print(f"Task Description: {task_output.description}")
print(f"Task Summary: {task_output.summary}")
print(f"Raw Output: {task_output.raw}")
if task_output.json_dict:
print(f"JSON Output: {json.dumps(task_output.json_dict, indent=2)}")
if task_output.pydantic:
print(f"Pydantic Output: {task_output.pydantic}")
markdown 参数可为任务输出启用自动 Markdown 格式化。当设置为 True 时,任务将指示智能体使用正确的 Markdown 语法格式化最终答案。
# Example task with markdown formatting enabled
formatted_task = Task(
description="Create a comprehensive report on AI trends",
expected_output="A well-structured report with headers, sections, and bullet points",
agent=reporter_agent,
markdown=True # Enable automatic markdown formatting
)
当 markdown=True 时,智能体将收到额外的指令以使用以下格式进行输出
- 使用
# 表示标题
- 使用
**text** 表示粗体文本
- 使用
*text* 表示斜体文本
- 使用
- 或 * 表示项目符号
- 使用
`code` 表示行内代码
- 使用
```language 表示代码块
使用 Markdown 的 YAML 配置
analysis_task:
description: >
Analyze the market data and create a detailed report
expected_output: >
A comprehensive analysis with charts and key findings
agent: analyst
markdown: true # Enable markdown formatting
output_file: analysis.md
Markdown 输出的优点
- 格式一致:确保所有输出都遵循正确的 Markdown 约定
- 可读性更佳:通过标题、列表和强调来结构化内容
- 文档就绪:输出可直接用于文档系统
- 跨平台兼容性:Markdown 被广泛支持
当 markdown=True 时,Markdown 格式化指令会自动添加到任务提示中,因此您无需在任务描述中指定格式要求。
任务依赖和上下文
任务可以使用 context 属性来依赖其他任务的输出。例如
research_task = Task(
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
agent=researcher
)
analysis_task = Task(
description="Analyze the research findings and identify key trends",
expected_output="Analysis report of AI trends",
agent=analyst,
context=[research_task] # This task will wait for research_task to complete
)
任务护栏
任务护栏提供了一种在任务输出传递给下一个任务之前对其进行验证和转换的方法。此功能有助于确保数据质量,并在智能体的输出不符合特定标准时向其提供反馈。 护栏通过包含自定义验证逻辑的 Python 函数实现,让您能够完全控制验证过程,并确保结果可靠、确定。基于函数的护栏
要向任务添加基于函数的护栏,请通过 guardrail 参数提供一个验证函数
from typing import Tuple, Union, Dict, Any
from crewai import TaskOutput
def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate blog content meets requirements."""
try:
# Check word count
word_count = len(result.split())
if word_count > 200:
return (False, "Blog content exceeds 200 words")
# Additional validation logic here
return (True, result.strip())
except Exception as e:
return (False, "Unexpected error during validation")
blog_task = Task(
description="Write a blog post about AI",
expected_output="A blog post under 200 words",
agent=blog_agent,
guardrail=validate_blog_content # Add the guardrail function
)
护栏函数要求
-
函数签名:
- 必须接受一个参数(任务输出)
- 应返回一个
(bool, Any) 元组
- 建议使用类型提示,但不是必需的
-
返回值:
- 成功时:返回一个
(bool, Any) 元组。例如:(True, validated_result)
- 失败时:返回一个
(bool, str) 元组。例如:(False, "解释失败的错误消息")
错误处理最佳实践
- 结构化错误响应:
from crewai import TaskOutput, LLMGuardrail
def validate_with_context(result: TaskOutput) -> Tuple[bool, Any]:
try:
# Main validation logic
validated_data = perform_validation(result)
return (True, validated_data)
except ValidationError as e:
return (False, f"VALIDATION_ERROR: {str(e)}")
except Exception as e:
return (False, str(e))
-
错误类别:
- 使用特定的错误代码
- 包含相关上下文
- 提供可操作的反馈
-
验证链:
from typing import Any, Dict, List, Tuple, Union
from crewai import TaskOutput
def complex_validation(result: TaskOutput) -> Tuple[bool, Any]:
"""Chain multiple validation steps."""
# Step 1: Basic validation
if not result:
return (False, "Empty result")
# Step 2: Content validation
try:
validated = validate_content(result)
if not validated:
return (False, "Invalid content")
# Step 3: Format validation
formatted = format_output(validated)
return (True, formatted)
except Exception as e:
return (False, str(e))
处理护栏结果
当护栏返回 (False, error) 时
- 错误被发送回智能体
- 智能体尝试修复问题
- 该过程重复进行,直到
- 护栏返回
(True, result)
- 达到最大重试次数 (
guardrail_max_retries)
带重试处理的示例
from typing import Optional, Tuple, Union
from crewai import TaskOutput, Task
def validate_json_output(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate and parse JSON output."""
try:
# Try to parse as JSON
data = json.loads(result)
return (True, data)
except json.JSONDecodeError as e:
return (False, "Invalid JSON format")
task = Task(
description="Generate a JSON report",
expected_output="A valid JSON object",
agent=analyst,
guardrail=validate_json_output,
guardrail_max_retries=3 # Limit retry attempts
)
从任务中获取结构化一致的输出
同样重要的是要注意,一个 crew 的最终任务的输出将成为该 crew 本身的最终输出。
使用 output_pydantic
output_pydantic 属性允许您定义任务输出应遵循的 Pydantic 模型。这确保输出不仅是结构化的,而且是根据 Pydantic 模型进行验证的。 以下是演示如何使用 output_pydantic 的示例:import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
class Blog(BaseModel):
title: str
content: str
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A compelling blog title and well-written content.",
agent=blog_agent,
output_pydantic=Blog,
)
# Instantiate your crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Accessing Properties Directly from the Pydantic Model
print("Accessing Properties - Option 2")
title = result.pydantic.title
content = result.pydantic.content
print("Title:", title)
print("Content:", content)
# Option 3: Accessing Properties Using the to_dict() Method
print("Accessing Properties - Option 3")
output_dict = result.to_dict()
title = output_dict["title"]
content = output_dict["content"]
print("Title:", title)
print("Content:", content)
# Option 4: Printing the Entire Blog Object
print("Accessing Properties - Option 5")
print("Blog:", result)
在此示例中
- 定义了一个名为 Blog 的 Pydantic 模型,其中包含 title 和 content 字段。
- 任务 task1 使用 output_pydantic 属性指定其输出应符合 Blog 模型。
- 执行 crew 后,您可以如所示以多种方式访问结构化输出。
访问输出的解释
- 字典式索引:您可以使用 result[“field_name”] 直接访问字段。这是因为 CrewOutput 类实现了 getitem 方法。
- 直接从 Pydantic 模型访问:直接从 result.pydantic 对象访问属性。
- 使用 to_dict() 方法:将输出转换为字典并访问字段。
- 打印整个对象:只需打印 result 对象即可查看结构化输出。
使用 output_json
output_json 属性允许您以 JSON 格式定义预期输出。这确保任务的输出是有效的 JSON 结构,可以轻松地在您的应用程序中进行解析和使用。 以下是演示如何使用 output_json 的示例:import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
# Define the Pydantic model for the blog
class Blog(BaseModel):
title: str
content: str
# Define the agent
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
# Define the task with output_json set to the Blog model
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A JSON object with 'title' and 'content' fields.",
agent=blog_agent,
output_json=Blog,
)
# Instantiate the crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
# Kickoff the crew to execute the task
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Printing the Entire Blog Object
print("Accessing Properties - Option 2")
print("Blog:", result)
在此示例中
- 定义了一个名为 Blog 的 Pydantic 模型,其中包含 title 和 content 字段,用于指定 JSON 输出的结构。
- 任务 task1 使用 output_json 属性来表示它期望一个符合 Blog 模型的 JSON 输出。
- 执行 crew 后,您可以如所示以两种方式访问结构化的 JSON 输出。
访问输出的解释
- 使用字典式索引访问属性:您可以使用 result[“field_name”] 直接访问字段。这是可能的,因为 CrewOutput 类实现了 getitem 方法,允许您像处理字典一样处理输出。在此选项中,我们从结果中检索 title 和 content。
- 打印整个博客对象:通过打印 result,您可以获得 CrewOutput 对象的字符串表示。由于 str 方法被实现为返回 JSON 输出,这将以表示博客对象的格式化字符串显示整个输出。
通过使用 output_pydantic 或 output_json,您可以确保您的任务以一致且结构化的格式生成输出,从而更轻松地在您的应用程序中或跨多个任务处理和利用数据。
利用 CrewAI 工具包 和 LangChain 工具 中的工具,以增强任务性能和智能体交互。
import os
os.environ["OPENAI_API_KEY"] = "Your Key"
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
from crewai import Agent, Task, Crew
from crewai_tools import SerperDevTool
research_agent = Agent(
role='Researcher',
goal='Find and summarize the latest AI news',
backstory="""You're a researcher at a large company.
You're responsible for analyzing data and providing insights
to the business.""",
verbose=True
)
# to perform a semantic search for a specified query from a text's content across the internet
search_tool = SerperDevTool()
task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
crew = Crew(
agents=[research_agent],
tasks=[task],
verbose=True
)
result = crew.kickoff()
print(result)
这演示了具有特定工具的任务如何覆盖智能体的默认设置,以实现量身定制的任务执行。
引用其他任务
在 CrewAI 中,一个任务的输出会自动传递给下一个任务,但您可以具体定义哪些任务(包括多个任务)的输出应该用作另一个任务的上下文。 当您有一个任务依赖于另一个并非紧随其后执行的任务的输出时,这非常有用。这是通过任务的 context 属性完成的:# ...
research_ai_task = Task(
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
)
research_ops_task = Task(
description="Research the latest developments in AI Ops",
expected_output="A list of recent AI Ops developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
)
write_blog_task = Task(
description="Write a full blog post about the importance of AI and its latest news",
expected_output="Full blog post that is 4 paragraphs long",
agent=writer_agent,
context=[research_ai_task, research_ops_task]
)
#...
异步执行
您可以将任务定义为异步执行。这意味着 crew 在继续下一个任务时不会等待它完成。这对于需要很长时间才能完成的任务,或者对于执行后续任务不关键的任务非常有用。 然后,您可以使用 context 属性在未来的任务中定义它应该等待异步任务的输出完成。#...
list_ideas = Task(
description="List of 5 interesting ideas to explore for an article about AI.",
expected_output="Bullet point list of 5 ideas for an article.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
list_important_history = Task(
description="Research the history of AI and give me the 5 most important events.",
expected_output="Bullet point list of 5 important events.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
write_article = Task(
description="Write an article about AI, its history, and interesting ideas.",
expected_output="A 4 paragraph article about AI.",
agent=writer,
context=[list_ideas, list_important_history] # Will wait for the output of the two tasks to be completed
)
#...
回调机制
回调函数在任务完成后执行,允许根据任务的结果触发操作或通知。
# ...
def callback_function(output: TaskOutput):
# Do something after the task is completed
# Example: Send an email to the manager
print(f"""
Task completed!
Task: {output.description}
Output: {output.raw}
""")
research_task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool],
callback=callback_function
)
#...
访问特定任务的输出
一旦一个 crew 运行完成,您可以通过任务对象的 output 属性访问特定任务的输出
# ...
task1 = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
#...
crew = Crew(
agents=[research_agent],
tasks=[task1, task2, task3],
verbose=True
)
result = crew.kickoff()
# Returns a TaskOutput object with the description and results of the task
print(f"""
Task completed!
Task: {task1.output.description}
Output: {task1.output.raw}
""")
在任务中指定工具可以动态调整智能体的能力,突显了 CrewAI 的灵活性。
错误处理和验证机制
在创建和执行任务时,有一些验证机制可以确保任务属性的健壮性和可靠性。这些机制包括但不限于
- 确保每个任务只设置一种输出类型,以保持清晰的输出预期。
- 防止手动分配
id 属性,以维护唯一标识符系统的完整性。
这些验证有助于维护 crewAI 框架内任务执行的一致性和可靠性。
保存文件时创建目录
create_directory 参数控制 CrewAI 在将任务输出保存到文件时是否应自动创建目录。此功能对于组织输出和确保文件路径结构正确特别有用,尤其是在处理复杂的项目层次结构时。
默认行为
默认情况下,create_directory=True,这意味着 CrewAI 将自动在输出文件路径中创建任何缺失的目录
# Default behavior - directories are created automatically
report_task = Task(
description='Generate a comprehensive market analysis report',
expected_output='A detailed market analysis with charts and insights',
agent=analyst_agent,
output_file='reports/2025/market_analysis.md', # Creates 'reports/2025/' if it doesn't exist
markdown=True
)
禁用目录创建
如果您想防止自动创建目录并确保目录已存在,请设置 create_directory=False
# Strict mode - directory must already exist
strict_output_task = Task(
description='Save critical data that requires existing infrastructure',
expected_output='Data saved to pre-configured location',
agent=data_agent,
output_file='secure/vault/critical_data.json',
create_directory=False # Will raise RuntimeError if 'secure/vault/' doesn't exist
)
YAML 配置
您也可以在您的 YAML 任务定义中配置此行为
analysis_task:
description: >
Generate quarterly financial analysis
expected_output: >
A comprehensive financial report with quarterly insights
agent: financial_analyst
output_file: reports/quarterly/q4_2024_analysis.pdf
create_directory: true # Automatically create 'reports/quarterly/' directory
audit_task:
description: >
Perform compliance audit and save to existing audit directory
expected_output: >
A compliance audit report
agent: auditor
output_file: audit/compliance_report.md
create_directory: false # Directory must already exist
自动创建目录 (create_directory=True)
- 开发和原型设计环境
- 使用基于日期的文件夹动态生成报告
- 目录结构可能变化的自动化工作流
- 具有用户特定文件夹的多租户应用程序
手动目录管理 (create_directory=False)
- 具有严格文件系统控制的生产环境
- 目录必须预先配置的安全敏感应用程序
- 具有特定权限要求的系统
- 需要审计目录创建的合规环境
错误处理
当 create_directory=False 且目录不存在时,CrewAI 将引发 RuntimeError
try:
result = crew.kickoff()
except RuntimeError as e:
# Handle missing directory error
print(f"Directory creation failed: {e}")
# Create directory manually or use fallback location
观看下面的视频,了解如何在 CrewAI 中使用结构化输出
任务是 CrewAI 中智能体行动的驱动力。通过正确定义任务及其结果,您可以为您的 AI 智能体有效工作(无论是独立工作还是作为协作单元)奠定基础。为任务配备适当的工具,理解执行过程,并遵循稳健的验证实践,对于最大化 CrewAI 的潜力至关重要,确保智能体为它们的任务做好充分准备,并确保任务按预期执行。