design-agent

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CrewAI Agent Design Guide

CrewAI Agent 设计指南

How to design effective agents with the right role, goal, backstory, tools, and configuration.

如何设计具备合适角色、目标、背景故事、工具及配置的高效Agent。

The 80/20 Rule

二八原则

Spend 80% of your effort on task design, 20% on agent design. A well-designed task elevates even a simple agent. But even the best agent cannot rescue a vague, poorly scoped task. Get the task right first (see the
design-task
skill), then refine the agent.

将80%的精力投入到任务设计中,20%投入到Agent设计中。 设计精良的任务能让简单的Agent也发挥出色,但再好的Agent也无法挽救模糊、范围不清的任务。先把任务设计好(参考
design-task
技能),再优化Agent。

1. The Role-Goal-Backstory Framework

1. 角色-目标-背景故事框架

Every agent needs three things: who it is, what it wants, and why it's qualified.
每个Agent都需要三个要素:身份目标资质依据

Role — Who the Agent Is

角色 — Agent的身份

The role defines the agent's area of expertise. Be specific, not generic.
BadGood
Researcher
Senior Data Researcher specializing in {topic}
Writer
Technical Blog Writer for developer audiences
Analyst
Financial Risk Analyst with regulatory compliance expertise
The role directly shapes how the LLM reasons. A "Senior Data Researcher" will produce different output than a "Research Assistant" even with the same task.
角色定义了Agent的专业领域。要具体,不要泛泛而谈。
反面示例正面示例
Researcher
Senior Data Researcher specializing in {topic}
Writer
Technical Blog Writer for developer audiences
Analyst
Financial Risk Analyst with regulatory compliance expertise
角色会直接影响LLM的推理方式。即使任务相同,“资深数据研究员”和“研究助理”产出的结果也会截然不同。

Goal — What the Agent Wants

目标 — Agent的诉求

The goal is the agent's individual objective. It should be outcome-focused with quality standards.
BadGood
Do research
Uncover cutting-edge developments in {topic} and identify the top 5 trends with supporting evidence
Write content
Produce publication-ready technical articles that explain complex topics clearly for non-technical readers
Analyze data
Deliver actionable risk assessments with confidence levels and recommended mitigations
目标是Agent的个体任务目标,应聚焦成果并明确质量标准
反面示例正面示例
Do research
Uncover cutting-edge developments in {topic} and identify the top 5 trends with supporting evidence
Write content
Produce publication-ready technical articles that explain complex topics clearly for non-technical readers
Analyze data
Deliver actionable risk assessments with confidence levels and recommended mitigations

Backstory — Why the Agent Is Qualified

背景故事 — Agent的资质依据

The backstory establishes expertise, experience, values, and working style. It's the agent's "personality prompt."
yaml
backstory: >
  You're a seasoned researcher with 15 years of experience in AI/ML.
  You're known for your ability to find obscure but relevant papers
  and synthesize complex findings into clear, actionable insights.
  You always cite your sources and flag uncertainty explicitly.
What to include in a backstory:
  • Years/depth of experience
  • Specific domain knowledge
  • Working style and values (e.g., "always cites sources", "prefers concise output")
  • Quality standards the agent holds itself to
What NOT to include:
  • Implementation details (tools, models, config)
  • Task-specific instructions (those go in the task description)
  • Arbitrary personality traits that don't affect output quality

背景故事用于建立Agent的专业能力、经验、价值观和工作风格,相当于Agent的“人格提示词”。
yaml
backstory: >
  You're a seasoned researcher with 15 years of experience in AI/ML.
  You're known for your ability to find obscure but relevant papers
  and synthesize complex findings into clear, actionable insights.
  You always cite your sources and flag uncertainty explicitly.
背景故事应包含:
  • 经验年限/深度
  • 特定领域知识
  • 工作风格与价值观(例如:“始终标注来源”、“偏好简洁输出”)
  • Agent自我要求的质量标准
背景故事不应包含:
  • 实现细节(工具、模型、配置)
  • 任务特定指令(这些应放在任务描述中)
  • 对输出质量无影响的任意人格特质

2. Agent Configuration Reference

2. Agent配置参考

Essential Parameters

核心参数

python
Agent(
    role="...",              # Required: agent's expertise area
    goal="...",              # Required: what the agent aims to achieve
    backstory="...",         # Required: context and personality
    llm="openai/gpt-4o",    # Optional: defaults to OPENAI_MODEL_NAME env var or "gpt-4"
    tools=[...],             # Optional: list of tool instances
)
python
Agent(
    role="...",              # 必填:Agent的专业领域
    goal="...",              # 必填:Agent的目标
    backstory="...",         # 必填:背景信息与人格设定
    llm="openai/gpt-4o",    # 可选:默认使用环境变量OPENAI_MODEL_NAME或"gpt-4"
    tools=[...],             # 可选:工具实例列表
)

Execution Control

执行控制

python
Agent(
    ...,
    max_iter=25,             # Max reasoning iterations per task (default: 25)
    max_execution_time=300,  # Timeout in seconds (default: None — no limit)
    max_rpm=10,              # Rate limit: max API calls per minute (default: None)
    max_retry_limit=2,       # Retries on error (default: 2)
    verbose=True,            # Show detailed execution logs (default: False)
)
Tuning
max_iter
:
  • Default 25 is generous — most tasks finish in 3-8 iterations
  • Lower to 10-15 to fail faster when tasks are well-defined
  • If agent consistently hits max_iter, the task is too vague (fix the task, not the limit)
python
Agent(
    ...,
    max_iter=25,             # 每个任务的最大推理迭代次数(默认:25)
    max_execution_time=300,  # 超时时间(秒,默认:None — 无限制)
    max_rpm=10,              # 速率限制:每分钟最大API调用次数(默认:None)
    max_retry_limit=2,       # 错误重试次数(默认:2)
    verbose=True,            # 显示详细执行日志(默认:False)
)
调优
max_iter
  • 默认值25较为宽松——大多数任务在3-8次迭代内即可完成
  • 对于定义清晰的任务,可降低至10-15以快速终止无效执行
  • 如果Agent持续达到max_iter上限,说明任务过于模糊(应优化任务,而非调整限制)

Tool Configuration

工具配置

python
from crewai_tools import SerperDevTool, ScrapeWebsiteTool, FileReadTool

Agent(
    ...,
    tools=[SerperDevTool(), ScrapeWebsiteTool()],  # Agent-level tools
)
Key rules:
  • An agent with no tools will hallucinate data when asked to search, fetch, or read files — always provide tools for tasks that require external data
  • Prefer fewer, focused tools over many tools — too many tools confuses the agent
  • Tools can also be assigned at the task level for task-specific access (see
    design-task
    skill)
  • Agent-level tools are available for all tasks the agent performs; task-level tools override for that specific task
python
from crewai_tools import SerperDevTool, ScrapeWebsiteTool, FileReadTool

Agent(
    ...,
    tools=[SerperDevTool(), ScrapeWebsiteTool()],  # Agent级工具
)
关键规则:
  • 如果Agent没有工具,当需要搜索、获取或读取文件时会生成幻觉数据——对于需要外部数据的任务,务必提供工具
  • 优先选择少量、聚焦的工具而非大量工具——过多工具会让Agent产生困惑
  • 工具也可以在任务层面分配,供特定任务使用(参考
    design-task
    技能)
  • Agent级工具可用于该Agent执行的所有任务;任务级工具会覆盖对应特定任务的工具配置

LLM Selection

LLM选择

python
Agent(
    ...,
    llm="openai/gpt-4o",              # Main reasoning model
    function_calling_llm="openai/gpt-4o-mini",  # Cheaper model for tool calls only
)
Use
function_calling_llm
to save costs: the main
llm
handles reasoning while a cheaper model handles tool-calling mechanics.
python
Agent(
    ...,
    llm="openai/gpt-4o",              # 主推理模型
    function_calling_llm="openai/gpt-4o-mini",  # 仅用于工具调用的低成本模型
)
使用
function_calling_llm
来降低成本:主
llm
负责推理,低成本模型处理工具调用的机械性操作。

Collaboration

协作配置

python
Agent(
    ...,
    allow_delegation=False,  # Default: False — agent works alone
)
Set
allow_delegation=True
only when:
  • The agent is part of a crew with other specialized agents
  • The task genuinely benefits from the agent handing off subtasks
  • You're using hierarchical process where the manager delegates
Warning: Delegation without clear task boundaries leads to infinite loops or wasted iterations.
python
Agent(
    ...,
    allow_delegation=False,  # 默认:False — Agent独立工作
)
仅在以下场景设置
allow_delegation=True
  • Agent属于包含其他专业Agent的团队
  • 任务确实能从Agent移交子任务中获益
  • 采用分层流程,由管理者进行任务委派
注意: 若没有清晰的任务边界,委派会导致无限循环或无效迭代。

Planning (Reasoning Before Acting)

规划(行动前推理)

python
from crewai.agents.agent_builder.base_agent import PlanningConfig

Agent(
    ...,
    planning=True,                    # Enable plan-then-execute (default: False)
    planning_config=PlanningConfig(
        max_attempts=3,               # Max planning iterations
    ),
)
Use planning for complex tasks where the agent benefits from thinking through its approach before taking action. Skip it for simple, well-defined tasks.
python
from crewai.agents.agent_builder.base_agent import PlanningConfig

Agent(
    ...,
    planning=True,                    # 启用“先规划后执行”模式(默认:False)
    planning_config=PlanningConfig(
        max_attempts=3,               # 最大规划迭代次数
    ),
)
对于复杂任务,Agent可在行动前梳理思路,此时适合启用规划。简单、定义清晰的任务无需启用。

Code Execution

代码执行

python
Agent(
    ...,
    allow_code_execution=True,        # Enable code execution (default: False)
    code_execution_mode="safe",       # "safe" (Docker) or "unsafe" (direct) — default: "safe"
)
  • "safe"
    requires Docker installed and running — executes in a container
  • "unsafe"
    runs code directly on the host — only use in controlled environments
python
Agent(
    ...,
    allow_code_execution=True,        # 启用代码执行(默认:False)
    code_execution_mode="safe",       # "safe"(Docker容器)或"unsafe"(直接执行)——默认:"safe"
)
  • "safe"
    要求安装并运行Docker——在容器内执行代码
  • "unsafe"
    直接在主机上运行代码——仅在受控环境中使用

Context Window Management

上下文窗口管理

python
Agent(
    ...,
    respect_context_window=True,      # Auto-summarize to stay within limits (default: True)
)
When
True
, the agent automatically summarizes prior context if it approaches the LLM's token limit. When
False
, execution stops with an error on overflow.
python
Agent(
    ...,
    respect_context_window=True,      # 自动总结内容以避免超出限制(默认:True)
)
当设置为
True
时,若接近LLM的token限制,Agent会自动总结之前的上下文。设置为
False
时,超出限制会直接报错终止执行。

Date Injection

日期注入

python
Agent(
    ...,
    inject_date=True,                 # Add current date to task context (default: False)
    date_format="%Y-%m-%d",           # Date format (default: "%Y-%m-%d")
)
Enable for time-sensitive tasks (research, news analysis, scheduling).
python
Agent(
    ...,
    inject_date=True,                 # 将当前日期添加到任务上下文(默认:False)
    date_format="%Y-%m-%d",           # 日期格式(默认:"%Y-%m-%d")
)
对于时间敏感的任务(研究、新闻分析、日程安排),启用该功能。

Agent Guardrails

Agent防护机制

python
def validate_no_pii(result) -> tuple[bool, Any]:
    """Reject output containing PII."""
    if contains_pii(result.raw):
        return (False, "Output contains PII. Remove all personal information and try again.")
    return (True, result)

Agent(
    ...,
    guardrail=validate_no_pii,
    guardrail_max_retries=3,          # default: 3
)
Agent guardrails validate every output the agent produces. The agent retries on failure up to
guardrail_max_retries
.
python
def validate_no_pii(result) -> tuple[bool, Any]:
    """Reject output containing PII."""
    if contains_pii(result.raw):
        return (False, "Output contains PII. Remove all personal information and try again.")
    return (True, result)

Agent(
    ...,
    guardrail=validate_no_pii,
    guardrail_max_retries=3,          # 默认:3
)
Agent防护机制会验证Agent生成的每一个输出。若验证失败,Agent会重试,最多重试
guardrail_max_retries
次。

Knowledge Sources

知识源

python
from crewai.knowledge.source.text_file_knowledge_source import TextFileKnowledgeSource

Agent(
    ...,
    knowledge_sources=[
        TextFileKnowledgeSource(file_paths=["company_handbook.txt"]),
    ],
    embedder={
        "provider": "openai",
        "config": {"model": "text-embedding-3-small"},
    },
)
Knowledge sources give agents access to domain-specific data via RAG. Use when agents need to reference large documents, policies, or datasets.

python
from crewai.knowledge.source.text_file_knowledge_source import TextFileKnowledgeSource

Agent(
    ...,
    knowledge_sources=[
        TextFileKnowledgeSource(file_paths=["company_handbook.txt"]),
    ],
    embedder={
        "provider": "openai",
        "config": {"model": "text-embedding-3-small"},
    },
)
知识源通过RAG技术让Agent能够访问特定领域的数据。当Agent需要参考大型文档、政策或数据集时使用。

3. YAML Configuration (Recommended)

3. YAML配置(推荐)

Define agents in
agents.yaml
for clean separation of config and code:
yaml
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
    with supporting evidence and source citations
  backstory: >
    You're a seasoned researcher with 15 years of experience.
    Known for finding obscure but relevant sources and
    synthesizing complex findings into clear insights.
    You always cite your sources and flag uncertainty.
  # Optional overrides (uncomment as needed):
  # llm: openai/gpt-4o
  # max_iter: 15
  # max_rpm: 10
  # allow_delegation: false
  # verbose: true
Then wire in
crew.py
:
python
@CrewBase
class MyCrew:
    agents_config = "config/agents.yaml"
    tasks_config = "config/tasks.yaml"

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config["researcher"],
            tools=[SerperDevTool()],
        )
Critical: The method name (
def researcher
) must match the YAML key (
researcher:
). Mismatch causes
KeyError
.

agents.yaml
中定义Agent,实现配置与代码的清晰分离:
yaml
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
    with supporting evidence and source citations
  backstory: >
    You're a seasoned researcher with 15 years of experience.
    Known for finding obscure but relevant sources and
    synthesizing complex findings into clear insights.
    You always cite your sources and flag uncertainty.
  # 可选覆盖配置(按需取消注释):
  # llm: openai/gpt-4o
  # max_iter: 15
  # max_rpm: 10
  # allow_delegation: false
  # verbose: true
然后在
crew.py
中引入:
python
@CrewBase
class MyCrew:
    agents_config = "config/agents.yaml"
    tasks_config = "config/tasks.yaml"

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config["researcher"],
            tools=[SerperDevTool()],
        )
关键注意点: 方法名(
def researcher
)必须与YAML中的键名(
researcher:
)一致。不匹配会导致
KeyError
错误。

4. Agent.kickoff() — Direct Agent Execution

4. Agent.kickoff() — 直接执行Agent

Use
Agent.kickoff()
when you need one agent with tools and reasoning, without crew overhead. This is the most common pattern in Flows.
当你需要一个具备工具和推理能力的独立Agent,且不需要团队 overhead 时,使用
Agent.kickoff()
。这是Flows中最常见的模式。

Basic Usage

基础用法

python
from crewai import Agent
from crewai_tools import SerperDevTool

researcher = Agent(
    role="Senior Research Analyst",
    goal="Find comprehensive, factual information with source citations",
    backstory="Expert researcher known for thorough, evidence-based analysis.",
    tools=[SerperDevTool()],
    llm="openai/gpt-4o",
)
python
from crewai import Agent
from crewai_tools import SerperDevTool

researcher = Agent(
    role="Senior Research Analyst",
    goal="Find comprehensive, factual information with source citations",
    backstory="Expert researcher known for thorough, evidence-based analysis.",
    tools=[SerperDevTool()],
    llm="openai/gpt-4o",
)

Pass a string prompt — the agent reasons, uses tools, and returns a result

传入字符串提示词——Agent会进行推理、使用工具并返回结果

result = researcher.kickoff("What are the latest developments in quantum computing?") print(result.raw) # str — the agent's full response print(result.usage_metrics) # token usage stats
undefined
result = researcher.kickoff("What are the latest developments in quantum computing?") print(result.raw) # str — Agent的完整响应 print(result.usage_metrics) # token使用统计
undefined

With Structured Output

结构化输出

python
from pydantic import BaseModel

class ResearchFindings(BaseModel):
    key_trends: list[str]
    sources: list[str]
    confidence: float

result = researcher.kickoff(
    "Research the latest AI agent frameworks",
    response_format=ResearchFindings,
)
python
from pydantic import BaseModel

class ResearchFindings(BaseModel):
    key_trends: list[str]
    sources: list[str]
    confidence: float

result = researcher.kickoff(
    "Research the latest AI agent frameworks",
    response_format=ResearchFindings,
)

Access via .pydantic (NOT directly — Agent.kickoff wraps the result)

通过.pydantic访问(注意:Agent.kickoff()会封装结果,不能直接访问)

print(result.pydantic.key_trends) # list[str] print(result.pydantic.confidence) # float print(result.raw) # raw string version

> **Note:** `Agent.kickoff()` returns `LiteAgentOutput` — access structured output via `result.pydantic`. This differs from `LLM.call()` which returns the Pydantic object directly.
print(result.pydantic.key_trends) # list[str] print(result.pydantic.confidence) # float print(result.raw) # 原始字符串版本

> **注意:** `Agent.kickoff()`返回`LiteAgentOutput`——需通过`result.pydantic`访问结构化输出。这与直接返回Pydantic对象的`LLM.call()`不同。

With File Inputs

文件输入

python
result = researcher.kickoff(
    "Analyze this document and summarize the key findings",
    input_files={"document": FileInput(path="report.pdf")},
)
python
result = researcher.kickoff(
    "Analyze this document and summarize the key findings",
    input_files={"document": FileInput(path="report.pdf")},
)

Async Variant

异步版本

python
result = await researcher.kickoff_async(
    "Research quantum computing breakthroughs",
    response_format=ResearchFindings,
)
python
result = await researcher.kickoff_async(
    "Research quantum computing breakthroughs",
    response_format=ResearchFindings,
)

Agent.kickoff() in Flows (Recommended Pattern)

Flows中的Agent.kickoff()(推荐模式)

The most powerful pattern is orchestrating multiple
Agent.kickoff()
calls inside a Flow. The Flow handles state and sequencing; each agent handles its specific step:
python
from crewai import Agent
from crewai.flow.flow import Flow, listen, start
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
from pydantic import BaseModel

class ResearchState(BaseModel):
    topic: str = ""
    research: str = ""
    analysis: str = ""
    report: str = ""

class ResearchFlow(Flow[ResearchState]):

    @start()
    def gather_data(self):
        researcher = Agent(
            role="Senior Researcher",
            goal="Find comprehensive data with sources",
            backstory="Expert at finding and validating information.",
            tools=[SerperDevTool(), ScrapeWebsiteTool()],
        )
        result = researcher.kickoff(f"Research: {self.state.topic}")
        self.state.research = result.raw

    @listen(gather_data)
    def analyze(self):
        analyst = Agent(
            role="Data Analyst",
            goal="Extract actionable insights from raw research",
            backstory="Skilled at pattern recognition and synthesis.",
        )
        result = analyst.kickoff(
            f"Analyze this research and extract key insights:\n\n{self.state.research}"
        )
        self.state.analysis = result.raw

    @listen(analyze)
    def write_report(self):
        writer = Agent(
            role="Report Writer",
            goal="Create clear, well-structured reports",
            backstory="Technical writer who makes complex topics accessible.",
        )
        result = writer.kickoff(
            f"Write a comprehensive report from this analysis:\n\n{self.state.analysis}"
        )
        self.state.report = result.raw

flow = ResearchFlow()
flow.kickoff(inputs={"topic": "AI agents"})
print(flow.state.report)
When to use Agent.kickoff() vs Crew.kickoff():
  • Use
    Agent.kickoff()
    when each step is a distinct agent and the Flow controls sequencing
  • Use
    Crew.kickoff()
    when multiple agents need to collaborate on related tasks within a single step

最强大的模式是在Flow中编排多个
Agent.kickoff()
调用。Flow负责状态管理和执行顺序;每个Agent处理其特定步骤:
python
from crewai import Agent
from crewai.flow.flow import Flow, listen, start
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
from pydantic import BaseModel

class ResearchState(BaseModel):
    topic: str = ""
    research: str = ""
    analysis: str = ""
    report: str = ""

class ResearchFlow(Flow[ResearchState]):

    @start()
    def gather_data(self):
        researcher = Agent(
            role="Senior Researcher",
            goal="Find comprehensive data with sources",
            backstory="Expert at finding and validating information.",
            tools=[SerperDevTool(), ScrapeWebsiteTool()],
        )
        result = researcher.kickoff(f"Research: {self.state.topic}")
        self.state.research = result.raw

    @listen(gather_data)
    def analyze(self):
        analyst = Agent(
            role="Data Analyst",
            goal="Extract actionable insights from raw research",
            backstory="Skilled at pattern recognition and synthesis.",
        )
        result = analyst.kickoff(
            f"Analyze this research and extract key insights:\n\n{self.state.research}"
        )
        self.state.analysis = result.raw

    @listen(analyze)
    def write_report(self):
        writer = Agent(
            role="Report Writer",
            goal="Create clear, well-structured reports",
            backstory="Technical writer who makes complex topics accessible.",
        )
        result = writer.kickoff(
            f"Write a comprehensive report from this analysis:\n\n{self.state.analysis}"
        )
        self.state.report = result.raw

flow = ResearchFlow()
flow.kickoff(inputs={"topic": "AI agents"})
print(flow.state.report)
何时使用Agent.kickoff() vs Crew.kickoff():
  • 当每个步骤由独立Agent完成,且Flow控制执行顺序时,使用
    Agent.kickoff()
  • 当多个Agent需要在单个步骤中协作完成相关任务时,使用
    Crew.kickoff()

5. Specialist vs Generalist Agents

5. 专业Agent vs 通用Agent

Always prefer specialists. An agent that does one thing well outperforms one that does many things acceptably.
始终优先选择专业Agent。 擅长单一任务的Agent表现优于能完成多个任务但表现平平的Agent。

When to Use a Specialist

何时使用专业Agent

  • Task requires deep domain knowledge
  • Output quality matters more than speed
  • The task is complex enough to benefit from focused expertise
  • 任务需要深厚的领域知识
  • 输出质量比速度更重要
  • 任务足够复杂,能从聚焦的专业能力中获益

When a Generalist Is Acceptable

何时通用Agent可接受

  • Simple tasks with clear instructions
  • Prototyping where you'll specialize later
  • Tasks that truly span multiple domains equally
  • 简单且指令清晰的任务
  • 原型开发阶段,后续会进行专业化调整
  • 任务确实需要同时涉及多个领域

Specialist Design Pattern

专业Agent设计模式

Instead of one "Content Writer" agent, create:
  • technical_writer
    — deep technical accuracy, code examples
  • copywriter
    — persuasive, audience-focused marketing copy
  • editor
    — grammar, consistency, style guide enforcement
Each specialist has a narrow role, specific goal, and backstory that reinforces their expertise.

不要创建一个“内容写手”Agent,而是拆分出:
  • technical_writer
    — 注重技术准确性,提供代码示例
  • copywriter
    — 撰写有说服力、以受众为中心的营销文案
  • editor
    — 负责语法、一致性和风格指南的执行
每个专业Agent都有狭窄的角色、特定的目标,以及能强化其专业能力的背景故事。

6. Agent Interaction Patterns

6. Agent交互模式

Sequential (Default)

顺序模式(默认)

Agents work one after another. Each agent receives prior agents' outputs as context.
Researcher → Writer → Editor
Best for: linear pipelines where each step builds on the last.
Agent依次工作。每个Agent会接收前序Agent的输出作为上下文。
研究员 → 写手 → 编辑
最适合:线性流水线,每个步骤都基于前序步骤的结果。

Hierarchical

分层模式

A manager agent delegates and validates. Task assignment is dynamic.
python
Crew(
    agents=[researcher, writer, editor],
    tasks=[research_task, writing_task, editing_task],
    process=Process.hierarchical,
    manager_llm="openai/gpt-4o",
)
Best for: complex workflows where task assignment depends on intermediate results.
由一个管理者Agent进行任务委派和验证。任务分配是动态的。
python
Crew(
    agents=[researcher, writer, editor],
    tasks=[research_task, writing_task, editing_task],
    process=Process.hierarchical,
    manager_llm="openai/gpt-4o",
)
最适合:复杂工作流,任务分配取决于中间结果。

Agent-to-Agent Delegation

Agent间委派

When
allow_delegation=True
, an agent can ask another crew agent for help:
python
lead_researcher = Agent(
    role="Lead Researcher",
    goal="Coordinate research efforts",
    backstory="...",
    allow_delegation=True,  # Can delegate to other agents in the crew
)
The agent will automatically discover other crew members and delegate subtasks as needed.

allow_delegation=True
时,Agent可以向团队中的其他Agent请求帮助:
python
lead_researcher = Agent(
    role="Lead Researcher",
    goal="Coordinate research efforts",
    backstory="...",
    allow_delegation=True,  # 可以向团队中的其他Agent委派任务
)
Agent会自动发现团队中的其他成员,并根据需要委派子任务。

7. Common Agent Design Mistakes

7. 常见Agent设计错误

MistakeImpactFix
Generic role like "Assistant"Agent produces unfocused, shallow outputUse specific expertise: "Senior Financial Analyst"
No tools for data-gathering tasksAgent hallucinates data instead of searchingAlways add tools when the task requires external info
Too many tools (10+)Agent gets confused choosing between toolsLimit to 3-5 relevant tools per agent
Backstory full of task instructionsAgent mixes personality with task executionKeep backstory about WHO the agent is; task details go in the task
allow_delegation=True
by default
Agents waste iterations delegating triviallyOnly enable when delegation genuinely helps
max_iter too high for simple tasksAgent loops unnecessarily on vague tasksLower max_iter; fix the task description instead
No guardrail on critical outputBad output passes through uncheckedAdd guardrails for outputs that feed into production systems
Using expensive LLM for tool callsUnnecessary cost for mechanical operationsSet
function_calling_llm
to a cheaper model

错误影响修复方案
使用“助手”这类通用角色Agent产出的内容缺乏聚焦,深度不足使用具体的专业角色:如“资深金融分析师”
数据收集任务未配置工具Agent会生成幻觉数据而非真实搜索对于需要外部数据的任务,务必添加工具
工具过多(10+个)Agent在选择工具时会产生困惑每个Agent最多保留3-5个相关工具
背景故事中包含任务指令Agent会混淆人格设定与任务执行逻辑背景故事仅描述Agent的身份;任务细节放在任务描述中
默认启用
allow_delegation=True
Agent会在琐碎任务上浪费迭代次数仅在委派确实能带来收益时启用
简单任务设置过高的max_iterAgent会在模糊任务上进行不必要的循环降低max_iter;优化任务描述而非调整限制
关键输出未配置防护机制不良输出会直接通过验证对于会输入到生产系统的输出,添加防护机制
使用昂贵LLM处理工具调用为机械性操作支付不必要的成本
function_calling_llm
设置为低成本模型

8. Agent Design Checklist

8. Agent设计检查清单

Before deploying an agent, verify:
  • Role is specific and domain-focused (not "Assistant" or "Helper")
  • Goal includes desired outcome AND quality standards
  • Backstory establishes expertise and working style
  • Tools are assigned for any task requiring external data
  • No excess tools — 3-5 per agent maximum
  • max_iter is tuned for expected task complexity (10-15 for simple, 20-25 for complex)
  • max_execution_time is set for production agents to prevent hangs
  • Guardrails are configured for critical outputs
  • LLM is appropriate for task complexity (don't use GPT-4 for classification)
  • Delegation is disabled unless genuinely needed

部署Agent前,请验证:
  • 角色具体且聚焦领域(不是“助手”或“帮手”)
  • 目标包含预期成果和质量标准
  • 背景故事明确了专业能力和工作风格
  • 对于需要外部数据的任务,已分配工具
  • 没有多余工具——每个Agent最多3-5个
  • max_iter
    已根据任务复杂度调优(简单任务10-15,复杂任务20-25)
  • 生产环境Agent已设置
    max_execution_time
    以防止挂起
  • 关键输出已配置防护机制
  • LLM与任务复杂度匹配(不要用GPT-4做分类任务)
  • 除非确实需要,否则委派功能已禁用

References

参考资料

For deeper dives into specific topics, see:
  • Custom Tools — building your own tools with
    @tool
    decorator and
    BaseTool
    subclass
  • Memory & Knowledge — memory configuration, knowledge sources, embedder setup, scoping
For related skills:
  • getting-started — project scaffolding, choosing the right abstraction, Flow architecture
  • design-task — task description/expected_output best practices, guardrails, structured output, dependencies
如需深入了解特定主题,请查看:
  • Custom Tools — 使用
    @tool
    装饰器和
    BaseTool
    子类构建自定义工具
  • Memory & Knowledge — 内存配置、知识源、嵌入模型设置、范围界定
相关技能:
  • getting-started — 项目脚手架搭建、选择合适的抽象层、Flow架构
  • design-task — 任务描述/预期输出最佳实践、防护机制、结构化输出、依赖管理