Velamuvi AIAcademy
CrewAI

Lesson 2 of 5 · CrewAI

Agents, Tasks and Crews

Configure CrewAI agents, tasks and crews: delegation and iteration limits, task context, Pydantic structured output, guardrails, CrewOutput and YAML projects.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Configure agents with limits and delegation settings
  • Pass one task's output to another with context
  • Get structured results with output_pydantic
  • Check task results with guardrails that send work back
  • Read a crew's results and organise larger crews in YAML

A two-agent crew

This crew writes a short blog article. A researcher lists the key facts; a writer turns them into an article with a title and a body, which must be at most 80 words:

from pydantic import BaseModel
from crewai import LLM, Agent, Crew, Process, Task, TaskOutput

llm = LLM(model="anthropic/MODEL_NAME")

class Article(BaseModel):
    title: str
    body: str

def at_most_80_words(output: TaskOutput) -> tuple[bool, str]:
    """A guardrail: (True, result) accepts the output; (False, message) sends it back to the agent."""
    words = len(output.pydantic.body.split()) if output.pydantic else len(output.raw.split())
    if words > 80:
        return False, f"The body has {words} words. Cut it to 80 or fewer."
    return True, output.raw

researcher = Agent(
    role="Product researcher",
    goal="Collect accurate, checkable facts about bike maintenance",
    backstory="You run the workshop at Velamuvi Bikes and know what goes wrong with e-bikes.",
    llm=llm, allow_delegation=False, max_iter=5,
)
writer = Agent(
    role="Blog writer",
    goal="Write friendly, practical articles for e-bike owners",
    backstory="You write the Velamuvi Bikes blog for people new to cycling.",
    llm=llm, allow_delegation=False,
)

research = Task(
    description="List the 3 most important things e-bike owners should do to look after {part}.",
    expected_output="3 bullet points, each with one concrete action.",
    agent=researcher,
)
write = Task(
    description="Write a short blog article about looking after {part}, using the research.",
    expected_output="An article with a title and a body of at most 80 words.",
    agent=writer,
    context=[research],                  # this task receives the research task's output
    output_pydantic=Article,             # the result is parsed into an Article
    guardrail=at_most_80_words,          # checked before the task counts as done
)

crew = Crew(agents=[researcher, writer], tasks=[research, write], process=Process.sequential)
result = crew.kickoff(inputs={"part": "the battery"})

for task_output in result.tasks_output:
    preview = task_output.raw.replace("\n", " ")[:60]
    print(f"[{task_output.agent}] {preview}...")
print("Title:", result.pydantic.title)
print("Body words:", len(result.pydantic.body.split()))
Output
[Product researcher] - Keep the charge between 20% and 80% for daily use. - Store...
[Blog writer] {"title": "Make your e-bike battery last", "body": "Keep you...
Title: Make your e-bike battery last
Body words: 46

Agent settings

Beyond role, goal and backstory, a few settings matter in almost every crew:

  • llm: the model for this agent. Different agents can use different models, such as a cheaper one for research and a stronger one for writing.
  • allow_delegation: whether the agent may hand work to other agents in the crew. Leave it off unless you want that; delegation adds model calls and makes runs less predictable.
  • max_iter: the most reasoning-and-tool steps the agent may take on one task before it must answer. A safety limit against loops.
  • max_execution_time, max_rpm: limits on time and on requests per minute.
  • verbose=True: print the agent's steps while you develop.

Task settings

  • context=[other_task] gives a task the outputs of earlier tasks. In a sequential crew, each task automatically sees the previous one's output; context lets you choose exactly which outputs it gets.
  • output_pydantic=Article parses the result into a Pydantic object, available as result.pydantic (output_json gives a dictionary instead).
  • guardrail=function checks the result before the task counts as done.
  • output_file="article.md" saves the result to a file.
  • human_input=True asks a person to review the result in the terminal before it's accepted.

Guardrails that send work back

In a test run of this crew, the writer's first draft had 108 words: the guardrail rejected it with “The body has 108 words. Cut it to 80 or fewer.”, and the second draft passed with 46. Here's that loop in plain Python:

Try it yourselfPython
# How a task guardrail works, in plain Python: check the agent's output; if it fails, send the
# guardrail's message back to the agent and try again, up to a limit.
drafts = iter([
    "Charge it often. " * 30,                                         # far too long
    "Keep the charge between 20% and 80%. Store it indoors.",         # good
])

def agent(task, feedback=None):                    # stands in for the writer agent
    if feedback:
        print(f"   (agent receives feedback: {feedback})")
    return next(drafts)

def max_40_words(output):
    words = len(output.split())
    return (True, output) if words <= 40 else (False, f"{words} words; cut it to 40 or fewer.")

def run_task(task, guardrail, max_retries=3):
    feedback = None
    for attempt in range(1, max_retries + 2):
        output = agent(task, feedback)
        ok, result = guardrail(output)
        print(f"attempt {attempt}: {'accepted' if ok else 'rejected'}")
        if ok:
            return result
        feedback = result
    raise RuntimeError("guardrail still failing after retries")

print("Final:", run_task("Write battery tips", max_40_words))

CrewAI retries up to guardrail_max_retries times (3 by default) and raises an error if the output still fails, so a broken task never silently passes bad work along.

Reading the result

kickoff returns a CrewOutput:

  • .raw: the final task's text.
  • .pydantic or .json_dict: the final task's structured output, if requested.
  • .tasks_output: every task's output, with the agent that produced it.
  • .token_usage: tokens used across the crew, for tracking cost.

Larger crews in YAML

For real projects, crewai create crew name generates a project where agents and tasks are defined in config/agents.yaml and config/tasks.yaml, and a Python class decorated with @CrewBase wires them together. Keeping prompts in YAML makes them easy to review and change without touching code.

Common mistakes

Practice exercise

Write a task guardrail: CrewAI accepts the output on (True, value) and sends the message back to the agent on (False, message).

Your solutionPython
def check_post(output):
    # Return (True, output) if the post mentions "battery" (any capitalisation) AND has at most
    # 25 words. Otherwise return (False, "<problem>") where <problem> is "missing battery" or
    # "too long" (check "missing battery" first).
    pass

for post in ["Battery tips: charge to 80%, store indoors.",
             "Tyre tips: check pressure weekly.",
             "battery " * 30]:
    print(check_post(post)[0], check_post(post)[1][:45])
Knowledge check

A task guardrail returns (False, 'Too long: cut it to 80 words'). What does CrewAI do?

Summary

  • Agents take settings such as llm, allow_delegation, max_iter and max_rpm.
  • Tasks can receive context from earlier tasks, return output_pydantic objects, be checked by guardrails, save to an output_file or ask for human_input.
  • Guardrails return (True, value) to accept or (False, message) to send work back.
  • CrewOutput gives .raw, .pydantic, .tasks_output and .token_usage.
  • Larger projects keep agents and tasks in YAML with @CrewBase.

Next: tools in CrewAI.

Finished reading? Tick it off to track your progress.