CrewAI Tutorial (Python): parsing structured output for intermediate developers
This tutorial shows you how to make a CrewAI agent return structured data you can parse reliably in Python. You need this when free-form LLM text is too brittle for downstream code, especially if you're feeding results into APIs, databases, or validation layers.
What You'll Need
- •Python 3.10+
- •
crewai - •
crewai-toolsis optional for this tutorial - •An OpenAI API key set as
OPENAI_API_KEY - •A terminal with
pip - •Basic familiarity with CrewAI agents, tasks, and crews
Step-by-Step
- •Start by installing the package and setting up a minimal project. For structured output, we’ll use Pydantic models because they give you typed validation instead of string parsing.
pip install crewai pydantic
export OPENAI_API_KEY="your-api-key"
- •Define the schema you want the agent to return. Keep it tight and explicit; the more precise your fields are, the easier it is to parse and validate the output.
from pydantic import BaseModel, Field
from typing import List
class CustomerRiskProfile(BaseModel):
customer_id: str = Field(..., description="Unique customer identifier")
risk_level: str = Field(..., description="Low, medium, or high")
reasons: List[str] = Field(..., description="Reasons supporting the risk level")
next_action: str = Field(..., description="Recommended follow-up action")
- •Build an agent and task that instructs the model to produce that schema. The key detail here is
output_pydantic, which tells CrewAI to parse the response into your model instead of leaving it as raw text.
from crewai import Agent, Task, Crew, Process
analyst = Agent(
role="Risk Analyst",
goal="Assess customer risk from short case notes",
backstory="You work in a regulated environment and return only structured outputs.",
verbose=True,
)
task = Task(
description=(
"Review this customer note and produce a risk profile:\n"
"Customer ID: CUST-1042\n"
"Note: Multiple failed payment attempts and a recent address change."
),
expected_output="A valid CustomerRiskProfile object.",
agent=analyst,
output_pydantic=CustomerRiskProfile,
)
crew = Crew(
agents=[analyst],
tasks=[task],
process=Process.sequential,
)
- •Run the crew and read the parsed object directly. If the model follows the schema correctly, you get a Pydantic instance back and can access fields without manual JSON cleanup.
result = crew.kickoff()
profile = result.pydantic
print(profile)
print(profile.customer_id)
print(profile.risk_level)
print(profile.reasons)
print(profile.next_action)
- •Add defensive validation for production use. Even with structured output enabled, you should handle invalid responses cleanly so your pipeline does not fail unpredictably.
from pydantic import ValidationError
try:
result = crew.kickoff()
profile = result.pydantic
except ValidationError as e:
print("Schema validation failed:")
print(e)
except Exception as e:
print("Crew execution failed:")
print(e)
Testing It
Run the script and confirm that result.pydantic is a real CustomerRiskProfile instance, not a string blob. The printed fields should match your schema exactly, including the list of reasons.
If you get raw text instead of a parsed object, check that output_pydantic is set on the task and that your model fields are concrete enough for the LLM to follow. Also verify your API key is present in the environment before launching Python.
For a stronger test, intentionally make one field stricter, such as changing risk_level to an enum-like set of values in your prompt or model design. Then rerun and see whether CrewAI still returns valid structured data consistently.
Next Steps
- •Move from Pydantic parsing to tool-assisted workflows where agents fetch data before generating structured output.
- •Add enums and nested models for more complex schemas like claims triage or KYC review.
- •Wrap this pattern in a reusable service layer so every agent in your app returns validated objects instead of free-form text.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit