Skip to content

Chapter 3 · Agent Deep Dive: Role Design Methodology ​

Chapter goals: Master the prompt engineering principles behind role / goal / backstory, learn to prevent agent runaway with max_iter, max_rpm, max_execution_time, and build a reusable role-design checklist.

3.1 Where Do role / goal / backstory Actually Go? ​

Many tutorials say "these three fields define the role" but don't explain the mechanism. In reality, CrewAI assembles them into the agent's system prompt: role determines what the model "is", goal determines "what to achieve", and backstory provides background and behavioral style. All subsequent decisions (how to decompose a task, whether to use tools, what output style to adopt) are constrained by these three text blocks.

python
import os
from crewai import Agent, LLM

deepseek = LLM(
    model="openai/deepseek-chat",
    base_url="https://api.deepseek.com/v1",
    api_key=os.getenv("DEEPSEEK_API_KEY"),
)

analyst = Agent(
    role="Data Quality Auditor",
    goal="Identify口径 inconsistencies and outliers in data reports, and classify by severity",
    backstory=(
        "You have 12 years of experience in financial data governance, "
        "and have zero tolerance for 'the same metric with two different algorithms.' "
        "Your conclusions always include evidence row numbers."
    ),
    llm=deepseek,
)

The division of labor among the three can be summarized as:

  • role: job title. Should be specific enough to "picture this person's daily actions"; avoid vague words like "assistant" or "expert";
  • goal: a determinable objective. Preferably includes "what to produce + quality standard" rather than "do your best";
  • backstory: the carrier of personality and constraints. Industry experience, catchphrases, and red-line rules all go here — this is the best place to inject domain knowledge.

3.2 Good Role vs Bad Role: Side-by-Side Comparison ​

Same "write a weekly report" requirement, two approaches:

python
# ❌ Anti-pattern: all three fields are correct but empty filler
bad_agent = Agent(
    role="Assistant",
    goal="Write a good weekly report",
    backstory="You are a helpful AI.",
    llm=deepseek,
)

# ✅ Best practice: specific, measurable, with style constraints
good_agent = Agent(
    role="SaaS Team Weekly Report Writer",
    goal=(
        "Organize this week's raw work records into a one-page weekly report: "
        "progress (3-5 items), risks (0-3 items), next-week plan (3 items), "
        "each starting with a verb, no more than 40 characters per item"
    ),
    backstory=(
        "You were trained in the Pyramidal Principle at a consulting firm, "
        "and despise information-free expressions like 'made progress' or 'continued to optimize'; "
        "if the raw records lack data support, you will explicitly mark [TBD]."
    ),
    llm=deepseek,
)

The root of the difference: the numbers and structure in goal give the model an executable template, and the red lines in backstory give the model permission to refuse fabrication. Models are very good at following explicit rules — as long as the rules are truly explicit.

3.3 Execution Control Parameters: Preventing Agent Runaway ​

Agents run autonomous loops: think → act → observe, repeating. An undefended loop = burning money + timeout. The official API provides four critical gatekeepers:

ParameterDefaultPurpose
max_iter20Maximum rounds of the think-act cycle; forces a best-effort answer once hit
max_execution_timeNoneMax seconds for a single task; aborts on timeout
max_rpmNoneMax requests per minute; prevents hitting vendor rate limits
max_retry_limit2Max retries on error
python
analyst = Agent(
    role="Data Quality Auditor",
    goal="...",
    backstory="...",
    llm=deepseek,
    max_iter=15,                         # Cap at 15 think-act cycles
    max_execution_time=120,              # 2 minutes max per task
    max_rpm=30,                          # 30 requests/minute to stay under DeepSeek limits
    max_retry_limit=1,                   # Retry once, then fail fast
)

3.4 Verbose, Storytelling, and Tool Binding ​

  • verbose=True prints each step — indispensable during learning; turn off in production to reduce log noise;
  • allow_delegation=True lets an agent delegate a sub-task to another agent in the same Crew — key for hierarchical process;
  • tools=[...] binds tools the agent can call during execution.
python
from crewai.tools import tool

@tool("Search Web")
def search_web(query: str) -> str:
    """Search the web for the latest information on a topic."""
    # ... actual search implementation ...
    return results

researcher = Agent(
    role="Web Researcher",
    goal="Find authoritative sources on the given topic",
    backstory="Expert web researcher with 8 years experience.",
    llm=deepseek,
    tools=[search_web],                    # Agent can call this tool
    allow_delegation=True,                 # Can delegate to other agents
    verbose=True,
)

3.5 Agent Design Checklist ​

Before defining any agent, answer these questions:

  • [ ] role is a concrete job title, not a generic label;
  • [ ] goal specifies what to produce and quality criteria, not just "do well";
  • [ ] backstory contains domain knowledge, style constraints, and explicit red lines;
  • [ ] max_iter is set to prevent infinite loops;
  • [ ] tools are only bound if the agent genuinely needs them (fewer tools = fewer selection errors);
  • [ ] verbose is True during development, False in production.

3.6 Chapter Summary ​

  • role / goal / backstory are assembled into the system prompt; each has a distinct responsibility;
  • Good roles are specific and measurable; bad roles are vague filler;
  • max_iter, max_execution_time, max_rpm, max_retry_limit are the four safety gates;
  • allow_delegation enables cross-agent task handoff; tools=[...] binds callable tools.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. Where do role, goal, and backstory end up in CrewAI?

2. Which parameter prevents an agent from entering an infinite think-act loop?

3. What is the purpose of allow_delegation=True?

4. Why should tools only be bound to agents that genuinely need them?

🛠️ Hands-On Exercises ​

  1. Design three agents for a "news briefing" pipeline: researcher, analyst, writer. Write role/goal/backstory for each and run a sequential crew.
  2. Intentionally set max_iter=2 and observe what happens when the task is complex — does the agent return a partial answer or fail?
  3. Add a tool (e.g., a simple web search stub) to one agent and verify it appears in the verbose log when called.

Roles are now solid. Next, we go deep into Task design and context passing.