Task 任务

Task 是交给某个 Agent 的具体作业:写清做什么、做成什么样。Crew 的 Process 决定任务是按列表顺序执行,还是由经理 Agent 分配。


必填与常用字段

字段说明
description任务做什么(可含 {placeholder},由 crew.kickoff(inputs=...) 填充)
expected_output完成态长什么样——比 description 更具体
agent负责的 Agent(顺序流程应指定;层级流程可由经理分配)
context其它 Task 列表,其输出作为本任务上下文
output_file把结果写入文件;create_directory 默认 True
markdown要求最终答案为 Markdown
human_input最终答案需人工审阅
async_execution异步执行(默认 False
tools本任务可用工具(覆盖 / 限制 Agent 工具集)
output_pydantic / output_json用 Pydantic 模型约束结构化输出
guardrail / guardrails校验输出;失败重试见 guardrail_max_retries(默认 3)

max_retries 已弃用,请用 guardrail_max_retries

from crewai import Task

research = Task(
    description="Conduct thorough research about {topic}. Prefer primary sources.",
    expected_output="Bullet list of the most relevant facts about {topic}.",
    agent=researcher,
)

report = Task(
    description="Expand the research into a short briefing for engineers.",
    expected_output="Markdown with sections: summary, findings, risks. No wrapping code fence.",
    agent=writer,
    context=[research],
    markdown=True,
    output_file="output/report.md",
)

顺序流程中,后一个任务默认能看到前面任务的输出;用 context 可以显式指定依赖,避免隐式串味。


JSONC 中的任务

crew.jsonctasks 数组即执行顺序(process"sequential" 时):

{
  "name": "Research Crew",
  "agents": ["researcher", "reporting_analyst"],
  "tasks": [
    {
      "name": "research_task",
      "description": "Conduct thorough research about {topic}.",
      "expected_output": "A list of the most relevant information about {topic}.",
      "agent": "researcher"
    },
    {
      "name": "reporting_task",
      "description": "Review the research and expand it into a detailed report.",
      "expected_output": "A polished markdown report without fenced code blocks.",
      "agent": "reporting_analyst",
      "context": ["research_task"],
      "markdown": true,
      "output_file": "report.md"
    }
  ],
  "inputs": { "topic": "AI Agents" }
}

context 只能引用已经定义过的任务名,禁止前向引用。条件任务在 JSON 里用 "type": "ConditionalTask"condition(进阶,见官方 Tasks 文档)。


TaskOutput

执行后通过 task.output 读取。常用属性:raw(默认)、pydanticjson_dict(仅当配置了对应 output 模型)、agentmessagesCrewOutput.tasks_output 是全部任务的列表。

写好 expected_output 比加长 description 更有效:模型把「完成定义」当验收标准。需要固定 JSON 时用 output_pydantic,不要只在 prompt 里说「请输出 JSON」。


执行方式(与 Process 的关系)

from crewai import Crew, Process

crew = Crew(
    agents=[researcher, writer],
    tasks=[research, report],
    process=Process.sequential,  # 或 Process.hierarchical
)
  • Sequential:按 tasks 列表顺序;上一任务输出进入后续上下文。
  • Hierarchical:经理分配任务;Crew 上必须设 manager_llmmanager_agent。详见 Crew 与 Process

人机协同:任务级 human_input=True,或在 Flow 里用官方文档中的 @human_feedback(需 CrewAI ≥ 1.8.0)。不要把未在文档出现的装饰器名写进代码。


下一步

评论