CrewAI Basics
9 examples to get you started with CrewAI - 6 basic and 3 intermediate.
You will build a small Researcher → Writer pipeline, then tighten tasks, tools, process, and run controls.
Install with pip install crewai (add crewai[tools] when you need the tools package). Set a provider API key such as OPENAI_API_KEY (or configure another LLM - verify at build).
Prerequisites
- Python 3.10+ and a working LLM API key for your chosen provider.
- Comfort with the CrewAI mental model: Agent, Task, Crew.
- Optional:
pip install 'crewai[tools]'for search and file tools used in later examples.
Basic Examples
1. Define Two Specialist Agents
Create a Researcher and a Writer with distinct goals.
from crewai import Agent
researcher = Agent(
role="Research Analyst",
goal="Collect accurate, citable notes on the topic",
backstory="You prefer primary sources and short bullet notes over essays.",
verbose=True,
)
writer = Agent(
role="Technical Writer",
goal="Turn research notes into a clear brief for engineers",
backstory="You write tight markdown with headings and no fluff.",
verbose=True,
)- Roles name the job; goals define success; backstories bias style and caution.
- Keep tools off until a role truly needs them.
verbose=Trueprints step traces while you learn.
Related: Defining Agent Roles, Goals, and Backstories - role recipe
2. Attach Two Tasks With a Handoff
Wire research into writing with context.
from crewai import Task
research_task = Task(
description=(
"Research {topic}. List 5 key facts with why each matters. "
"Note uncertainty explicitly."
),
expected_output="Markdown bullets: fact, why it matters, confidence.",
agent=researcher,
)
write_task = Task(
description=(
"Using the research notes, write a 3-paragraph engineering brief on {topic}. "
"Audience: senior developers. End with 3 open questions."
),
expected_output="Markdown brief with three paragraphs and three questions.",
agent=writer,
context=[research_task],
)expected_outputis the acceptance test written in English.context=[research_task]injects the research output into the writer.{topic}is filled at kickoff, not hard-coded.
Related: The CrewAI Mental Model: Roles, Tasks, and Crews - task contracts
3. Assemble a Sequential Crew and Kick Off
Run the two-step pipeline.
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential,
verbose=True,
)
result = crew.kickoff(inputs={"topic": "offline evals for tool-using agents"})
print(result.raw)
print(result.tasks_output) # intermediate + final task outputs- Sequential order follows the
taskslist. result.rawis the primary completed output string.- Inspect
tasks_outputwhen the final brief looks thin - the research step may be the failure.
Related: Sequential vs Hierarchical Crew Processes - process choice
4. Bound Agent Loops Early
Cap iterations so a stuck tool loop cannot run forever.
researcher = Agent(
role="Research Analyst",
goal="Collect accurate notes quickly",
backstory="You stop when you have five solid facts.",
max_iter=8,
max_retry_limit=2,
verbose=True,
)max_iterforces a best-effort answer after too many internal steps.- Pair agent caps with product-level timeouts and spend limits.
- Lower caps for demos; raise carefully when tools are slow but necessary.
Related: Debugging a Crew That Won't Converge on an Answer - thrash checklist
5. Add a Least-Privilege Tool to One Agent
Give search only to the researcher.
import os
from crewai import Agent
from crewai_tools import SerperDevTool # requires SERPER_API_KEY
search = SerperDevTool()
researcher = Agent(
role="Research Analyst",
goal="Find current facts with web search",
backstory="You verify claims before writing them down.",
tools=[search],
verbose=True,
)
writer = Agent(
role="Technical Writer",
goal="Write from provided notes only",
backstory="You do not invent sources. You rewrite notes.",
tools=[], # intentional
verbose=True,
)- Tool allowlists should match the role, not the whole company API surface.
- Writers that can search will often re-research instead of drafting.
- Keep secrets in env vars, never in prompts.
Related: Building a Custom Tool for a CrewAI Agent - custom tools
6. Read Structured Crew Output
Use the CrewOutput fields you actually need.
result = crew.kickoff(inputs={"topic": "agent memory design"})
print("--- final ---")
print(result.raw)
for task_out in result.tasks_output:
print(task_out.agent, "=>", (task_out.raw or "")[:200])
print("tokens:", result.token_usage)
# If you enabled structured output on a task, also check result.pydantic / json_dict- Always log per-task outputs in development.
- Token usage is your early cost signal for multi-agent pipelines.
- Prefer saving
output_fileon tasks when humans must review artifacts.
Related: CrewAI Best Practices - production habits
Intermediate Examples
7. Hierarchical Process With a Manager Model
Let a manager assign and review when ownership should be dynamic.
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.hierarchical,
manager_llm="gpt-4o", # or a configured LLM instance; required for hierarchical
verbose=True,
)
result = crew.kickoff(inputs={"topic": "RAG evaluation metrics"})
print(result.raw)- Hierarchical needs
manager_llmor a custommanager_agent. - Expect extra tokens for planning and validation.
- Start sequential; switch only when static assignment fails the product shape.
Related: Sequential vs Hierarchical Crew Processes - when to switch
8. Enable Shared Crew Memory
Persist facts across tasks (and later runs, depending on storage).
from crewai import Crew, Process, Memory
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential,
memory=True, # or memory=Memory(...) for tuned scoring / storage
verbose=True,
)
crew.kickoff(inputs={"topic": "CrewAI knowledge sources"})memory=Trueuses unified memory defaults (embedder + storage - verify at build).- Memory is not a substitute for clear
context=[...]handoffs on critical artifacts. - Reset local memory in tests so evals stay reproducible.
Related: CrewAI 1.14's Pluggable Memory, Knowledge, and RAG Backends - backends
9. Save the Writer Output and Replay Mindset
Persist the deliverable and think in task IDs for debugging.
write_task = Task(
description="Write a 3-paragraph brief on {topic} from the research notes.",
expected_output="Markdown brief saved for review.",
agent=writer,
context=[research_task],
output_file="output/topic_brief.md",
)
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential,
verbose=True,
output_log_file="crew_run.json", # JSON if filename ends with .json
)
result = crew.kickoff(inputs={"topic": "agent observability"})
print("wrote", "output/topic_brief.md", "final chars", len(result.raw or ""))
# CLI later: crewai log-tasks-outputs / crewai replay -t <task_id> (verify at build)- Files and logs beat scrolling terminal transcripts.
- Replay from a task after a failed tail step instead of re-running expensive research.
- Treat outputs as reviewable artifacts, not disposable chat.
Related: Debugging a Crew That Won't Converge on an Answer - converge checklist
Stack versions: Pins from the category manifest (verify at build): OpenRouter (~315+ models, July 2026 pricing/fees); LangGraph 1.0+; CrewAI 1.14+; Microsoft Agent Framework 1.0; Vercel AI SDK 6; Pydantic AI (latest); LlamaIndex (latest); OpenAI Agents SDK (latest + MCP); MCP (Linux Foundation governance); A2A (HTTP+SSE+JSON-RPC 2.0); Solana
@solana/web3.js+@solana/spl-token.