How to Build Multi-Agent AI with CrewAI in Python, Ending With a Crew Inside a Flow

This tutorial takes 13 steps to build a three-agent research, writing and editing crew on CrewAI’s v1.15 line and then run it inside a Flow, the starting shape CrewAI’s docs recommend for a production app, as summarised in the Professionals Toolkit guide to CrewAI examples, with Flow mechanics taken from the CrewAI Flows documentation. It runs on Python 3.10 to 3.13. A detail older guides do not reflect is that crewai create crew now scaffolds a JSON project, per the CrewAI README on GitHub, not the YAML layout older guides show, and several tools and memory classes those guides rely on have changed or gone. The version, scaffold, removal and Flow claims below were checked against the cited pages on 15 November 2026; the code is adapted from the classic scaffold and was not run for this article.

Older guides sayCurrent behaviourSinceSource
Any recent Python worksCrewAI needs Python >=3.10 and <3.14. On 3.14 or later, pip silently resolves to a much older CrewAI release that then fails to build.CurrentCrewAI README, Real Python
crewai create crew gives crew.py plus config/agents.yaml and tasks.yamlThe default is JSON-first: agents/*.jsonc and crew.jsonc. The YAML layout needs the --classic flag.CurrentCrewAI README
Run code with CodeInterpreterToolRemoved. Use an E2B or Daytona sandbox tool, each with its own account.April 2026Professionals Toolkit
Configure short-term, long-term and entity memoryOne unified Memory class replaces the three.March 2026Professionals Toolkit
Tool results are cachedTool-result caching is opt-in.July 2026Professionals Toolkit
Read cost from kickoff().token_usageFor a Flow, flow.usage_metrics aggregates all LLM calls; token_usage reflects only the last crew output.CurrentFlows docs
Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

Steps 1 to 3: a Python CrewAI accepts, keys kept out of code, and a scaffold you can follow

Step 1: check Python, then install

Check the interpreter before installing anything. Real Python’s CrewAI tutorial warns that on Python 3.14 or later the install will silently resolve to a much older CrewAI release and then fail to build. The README gives the supported range as Python >=3.10 and <3.14, says CrewAI uses UV for dependency management, and installs the CLI with uv tool install crewai. The repository is MIT licensed and, on the README page, shows about 60.9k stars and 9.2k forks.

python3 --version        # must report 3.10 to 3.13
uv tool install crewai
crewai version

Step 2: put the keys in .env

CrewAI is model-agnostic. Real Python lists OpenAI, Anthropic’s Claude, Mistral, Groq and Ollama for local models among the options. Two key requirements trip people up: the quickstart needs an LLM key plus a Serper.dev key for web search, and the first-flow guide’s outline call uses an OpenAI model, so it needs an OpenAI key even when your agents run on another provider (both per the Professionals Toolkit guide). Keep keys in a .env file in the project root and keep that file out of version control. Never paste a key into a Python file.

# .env  (project root)
OPENAI_API_KEY=paste-your-key-here
SERPER_API_KEY=paste-your-key-here
echo ".env" >> .gitignore

If you would rather set keys in your shell for the current session, export them instead, and add the Anthropic or Google key only if your agents use that provider. For a local model through Ollama, pull the model first.

export OPENAI_API_KEY="sk-your-openai-key-here"
export ANTHROPIC_API_KEY="sk-ant-your-anthropic-key-here"
export GOOGLE_API_KEY="your-google-api-key-here"

ollama pull <model-name>

Step 3: pick the scaffold on purpose

Plain crewai create crew makes a JSON-first project: agents live in agents/*.jsonc, tasks and crew-level settings live in crew.jsonc, and crewai run loads that JSON directly. The older layout with crew.py, config/agents.yaml and config/tasks.yaml is still available with --classic, so older tutorials are dated rather than broken. This build uses --classic because the Flow in Step 12 imports the crew as a Python class, which the crew.py layout provides. If you stay on the JSON scaffold, the same fields apply, but you run it with crewai run instead.

crewai create crew research_crew --classic
cd research_crew
crewai install

One safety point applies to either layout. CrewAI’s docs say JSON crew projects execute local Python when custom tools or python references load, as the Professionals Toolkit guide notes, so run a downloaded project only if you trust where it came from.

Steps 4 to 6: a researcher, a writer, an editor, and a task chain that passes context

Step 4: define the three agents

An agent needs three required arguments. Real Python puts it this way: The role tells the agent what it is. The goal guides what it tries to accomplish. The backstory provides context that shapes how it responds. Write them in config/agents.yaml. The {topic} variable is filled at run time. A third agent, the editor, checks the writer’s draft against the research. For the model, set the llm value to the provider-prefixed model ID from your provider’s current model list rather than copying an ID from an old tutorial.

# src/research_crew/config/agents.yaml

researcher:
  role: Senior Research Analyst
  goal: Gather accurate, current information on {topic} from multiple sources and synthesize it, citing where each fact came from.
  backstory: You have experience in fact-checking. Your ability to compare sources means you verify claims against more than one source before reporting them.
  llm: "provider/model-id"
  verbose: true

writer:
  role: Technical Content Writer
  goal: Turn the research brief on {topic} into a clear article that can be published over any channel without sacrificing accuracy.
  backstory: You write for developers and never state a fact that is not in the brief.
  llm: "provider/model-id"
  verbose: true

editor:
  role: Senior Editor
  goal: Edit the article on {topic} for factual accuracy, clarity and readability. Ensure every claim traces back to the research brief.
  backstory: You have an editing background in journalism and technical writing. You trust your ability to catch unsupported claims, and you do not sign off without thorough verification. You never invent or add facts of your own.
  llm: "provider/model-id"
  verbose: true

verbose: true prints the agent’s reasoning to your terminal. Real Python recommends it for debugging and turning it off in production because it creates a lot of noise.

Step 5: chain the tasks

Under a sequential process, per Real Python, the researcher’s output automatically flows into the writer’s task as context, and the final output comes from the last task. Listing the dependency in context makes the link explicit. Be specific in expected_output; vague tasks are what send agents into loops.

# src/research_crew/config/tasks.yaml

research_task:
  description: Research {topic}. Cover recent developments, key figures with sources, and how it compares with alternatives.
  expected_output: A research brief of verified facts, each with its source.
  agent: researcher

writing_task:
  description: Using only the research brief, write a structured technical article about {topic}.
  expected_output: A publication-ready article in Markdown with headings and no unsupported claims.
  agent: writer
  context:
    - research_task

editing_task:
  description: Review the article against a brief of verified facts and fix any claim the brief does not support.
  expected_output: A final article in Markdown in which every claim is supported by the research brief.
  agent: editor
  context:
    - research_task
    - writing_task

On the JSON scaffold, the same brace-wrapped variables such as {topic} go in agent and task text, defaults sit under inputs in crew.jsonc, and crewai run prompts for any value still missing, according to the README.

Step 6: wire the crew and run it

# src/research_crew/crew.py

from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task


@CrewBase
class ResearchCrew:
    agents_config = "config/agents.yaml"
    tasks_config = "config/tasks.yaml"

    @agent
    def researcher(self) -> Agent:
        return Agent(config=self.agents_config["researcher"], allow_delegation=False)

    @agent
    def writer(self) -> Agent:
        return Agent(config=self.agents_config["writer"], allow_delegation=False)

    @agent
    def editor(self) -> Agent:
        return Agent(config=self.agents_config["editor"], allow_delegation=False)

    @task
    def research_task(self) -> Task:
        return Task(config=self.tasks_config["research_task"])

    @task
    def writing_task(self) -> Task:
        return Task(config=self.tasks_config["writing_task"])

    @task
    def editing_task(self) -> Task:
        return Task(
            config=self.tasks_config["editing_task"],
            output_file="output/final_article.md",
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True,
        )

main.py keeps one shared inputs dictionary. The train() function is the classic scaffold’s training hook and is not used anywhere else in this article.

# src/research_crew/main.py

import sys

from research_crew.crew import ResearchCrew

inputs = {"topic": "multi-agent AI frameworks"}


def run():
    result = ResearchCrew().crew().kickoff(inputs=inputs)
    print(result.raw)
    print(result.token_usage)


def train():
    try:
        ResearchCrew().crew().train(
            n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs
        )
    except Exception as e:
        raise Exception(f"Training failed: {e}")


if __name__ == "__main__":
    run()
crewai run
python -m research_crew.main   # same run without the CLI wrapper, inside the project environment

Sequential is the right default. CrewAI’s docs, as summarised by Professionals Toolkit, say to move to the hierarchical process only when complexity demands it, and delegation is off by default; allow_delegation=False above just makes that explicit. If the run fails with a task-configuration error, the method names in crew.py must match the keys in tasks.yaml exactly.

Steps 7 to 9: search tools after CodeInterpreterTool, a custom tool, and typed output

Step 7: give the researcher search and scraping

Web search through SerperDevTool needs the Serper.dev key from Step 2. Do not follow any guide that gives the agent CodeInterpreterTool: it was removed in April 2026, and an example that ran code with it now needs an E2B or Daytona sandbox tool instead, each with its own account, per Professionals Toolkit. Keep each agent’s tool list short; every tool is one more thing the model has to read and choose between.

pip install 'crewai[tools]'   # run inside the project environment
from crewai_tools import ScrapeWebsiteTool, SerperDevTool

# inside ResearchCrew in crew.py, replacing the earlier researcher method
    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config["researcher"],
            tools=[SerperDevTool(), ScrapeWebsiteTool()],
            allow_delegation=False,
        )

Step 8: write a custom tool

A custom tool is a BaseTool subclass with a Pydantic input schema, or a function wrapped in @tool. The description is what the agent reads to decide when to call it, so describe the use case, not the implementation. This one has no network access, which keeps it safe to run anywhere.

# src/research_crew/tools/custom_tool.py

from typing import Type

from crewai.tools import BaseTool
from pydantic import BaseModel, Field


class WordCountInput(BaseModel):
    text: str = Field(..., description="The text to count words in")


class WordCountTool(BaseTool):
    name: str = "Word Counter"
    description: str = "Counts the words in a draft. Use it to check length requirements."
    args_schema: Type[BaseModel] = WordCountInput

    def _run(self, text: str) -> str:
        return f"Word count: {len(text.split())}"

Attach it with tools=[WordCountTool()] on the writer. Tools that load custom Python are exactly what the security note in Step 3 refers to, so read any tool file in a project you did not write.

A tool that calls an external API follows the same pattern, with a request inside _run. This stock-price lookup is adapted from the earlier version of this guide and was not run here. Set QUOTE_API_URL to your own market-data provider and match the response field names to what that provider returns, because the names below are an assumption. Give every network call a timeout, and attach the tool to the researcher, which is the agent that gathers outside data.

# src/research_crew/tools/custom_tool.py (continued)

import requests

QUOTE_API_URL = "https://your-quote-provider.example/quote"


class StockPriceInput(BaseModel):
    symbol: str = Field(..., description="Ticker symbol, for example a listed company's ticker")


class StockPriceTool(BaseTool):
    name: str = "Stock Price Lookup"
    description: str = "Looks up the latest price and the change from the previous close for a ticker symbol. Use it when the research needs a current market figure."
    args_schema: Type[BaseModel] = StockPriceInput

    def _run(self, symbol: str) -> str:
        url = f"{QUOTE_API_URL}/{symbol}"
        headers = {"User-Agent": "research-crew"}
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        data = response.json()
        meta = data["chart"]["result"][0]["meta"]
        price = meta["regularMarketPrice"]
        prev_close = meta["chartPreviousClose"]
        change = price - prev_close
        return (
            f"{symbol}: {price} "
            f"({change:+.2f} from the previous close)"
        )

Step 9: return a typed object from the research task

When a downstream system needs predictable fields, define a Pydantic model and set it as the task’s output. The docs also say a direct LLM call is more efficient than a crew when you only need one structured output, as Professionals Toolkit reports, so use this where a crew is already doing the research.

from pydantic import BaseModel, Field


class Finding(BaseModel):
    fact: str = Field(description="One specific finding")
    source: str = Field(description="URL or publication name")


class ResearchReport(BaseModel):
    summary: str
    findings: list[Finding]


# inside ResearchCrew in crew.py, replacing the earlier research_task method
    @task
    def research_task(self) -> Task:
        return Task(
            config=self.tasks_config["research_task"],
            output_pydantic=ResearchReport,
        )

# after kickoff: result.pydantic.findings[0].fact

Steps 10 and 11: unified Memory, guardrails, and the extra calls they cause

Step 10: add memory only when runs repeat

Memory was rebuilt in March 2026 into one unified Memory class, which replaces the separate short-term, long-term and entity memories that older code configures (Professionals Toolkit). Any snippet that sets up those three types individually predates the change. The first run of this crew needs no memory at all. Add it once the same crew runs repeatedly on related topics, and take the current parameters from the current CrewAI documentation rather than from a tutorial written before March 2026.

Step 11: guardrails, limits and caching

Task guardrails can be Python functions or plain-language rules checked by the agent’s LLM, and a failed check retries the task up to three times by default (Professionals Toolkit). Each retry is another set of LLM calls, so a strict guardrail on a long task is a cost decision as well as a quality one; the next section puts numbers on it. Two settings bound the damage: max_iter on an agent caps its reasoning loops, and max_rpm on the crew caps requests per minute against your provider’s rate limit. Since July 2026 tool-result caching is opt-in, so repeated search calls are not reused unless you enable caching. Switch verbose off before you deploy.

Steps 12 and 13: the crew inside a Flow, measured with usage_metrics, then deployed

Step 12: wrap the crew in a Flow

CrewAI’s docs recommend starting a production app with a Flow and running a crew inside one of its steps (Professionals Toolkit). The Flows documentation defines the pieces: @start() marks entry points, a method decorated with @listen() runs when the method it names emits output, state can be a typed Pydantic model shared across methods, and the value kickoff() returns is the output of the last method to complete. DocuSign’s outreach case study follows this shape: a deterministic Flow that controls sequencing, errors and state, with five agents inside it (Professionals Toolkit).

# src/research_crew/flow.py

from pathlib import Path

from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel

from research_crew.crew import ResearchCrew


class ArticleState(BaseModel):
    topic: str = ""
    article: str = ""


class ArticleFlow(Flow[ArticleState]):
    @start()
    def choose_topic(self):
        self.state.topic = "multi-agent AI frameworks"

    @listen(choose_topic)
    def run_crew(self):
        result = ResearchCrew().crew().kickoff(inputs={"topic": self.state.topic})
        self.state.article = result.raw
        return result.raw

    @listen(run_crew)
    def save(self):
        out = Path("output")
        out.mkdir(exist_ok=True)
        (out / "article.md").write_text(self.state.article, encoding="utf-8")
        return "saved"


if __name__ == "__main__":
    flow = ArticleFlow()
    flow.kickoff()
    print(flow.usage_metrics)

The last line is the point of measuring at Flow level. In the docs’ words, flow.usage_metrics is not the same as flow.kickoff().token_usage: the latter returns the usage of the last @listen method that returned a crew output, while usage_metrics aggregates every LLM call in the run. Use usage_metrics for budgeting.

Step 13: choose where it runs

You can self-host the Flow on your own server or use CrewAI’s cloud. The free Basic plan on CrewAI AMP covers 2 automations and 50 workflow executions a month, with no additional executions (Professionals Toolkit), which suits a prototype and not a scheduled production job. Self-hosting means putting the Flow behind your own service, for example a REST API, and storing job state outside process memory. Whichever you pick, run with verbose off and read usage_metrics after every run.

Why one three-task crew can cost 15 times the input of a direct call

Real Python’s summary is that API costs multiply quickly since each agent makes separate LLM calls. The multiplication has two parts: each task makes several calls, and each task’s prompt carries the earlier tasks’ output as context. The model below is a calculation from stated assumptions, not a measurement of any run.

Assume a base prompt of P = 1,500 tokens, an output of O = 1,000 tokens per call, and that each task’s output is carried into every later task’s prompt. With three tasks, one call each, the inputs are 1,500, then 2,500, then 3,500, which sum to 7,500. If every task makes k calls and each call re-sends the same prompt, input scales with k: 22,500 at k = 3 and 37,500 at k = 5. A single direct call is 1,500. A fourth task at k = 3 sends 4,500 tokens per call, so it adds 13,500 to the 22,500 and brings the total to 36,000. Output is bounded above by calls times 1,000.

ScenarioLLM callsInput tokensOutput tokens (upper bound)Input vs one direct call
One direct call11,5001,0001x
Three tasks, k = 137,5003,0005x
Three tasks, k = 3922,5009,00015x
Three tasks, k = 51537,50015,00025x
Four tasks, k = 31236,00012,00024x

To turn tokens into money, take input tokens divided by one million times your provider’s input rate, plus output tokens divided by one million times its output rate, using the rates on the provider’s current pricing page. Then replace the assumptions: run the Flow once and read flow.usage_metrics. The model is a floor in one respect, because tool loops grow context inside a task, guardrail retries (up to three by default) repeat a task, and a hierarchical manager adds calls of its own. The levers that follow from it are a cheaper model on the agent whose work is simplest, tighter task descriptions to bring k down, max_iter caps, and a direct LLM call wherever one structured answer is all you need.

Crew, Flow, direct call or LangGraph: which constraint decides

Real Python’s guidance is that CrewAI’s sweet spot is workflows where agents have clear responsibilities and work in a predictable sequence, and that if you need fine-grained state management with branching logic, LangGraph gives you more control. The README frames the same split from CrewAI’s side: Crews for autonomous collaboration, Flows for event-driven control with native support for Crews. The table keys each case to the constraint that decides it.

Binding constraintUseBasis
Agents with clear roles working in a fixed orderA sequential CrewReal Python
One structured answer, no collaborationA direct LLM callCrewAI docs via Professionals Toolkit
Production app that needs controlled sequencing, errors and stateA Flow with the Crew inside one stepCrewAI docs via Professionals Toolkit; DocuSign case
Workflow complexity that calls for a manager model or agentHierarchical process, only thenCrewAI docs via Professionals Toolkit
Fine-grained state with branching logicLangGraphReal Python

Failures on a fresh v1.15 install and the check for each

SymptomLikely causeCheck or fix
ModuleNotFoundError, or an old CrewAI version installsWrong interpreter, or Python 3.14 or later resolving to an old releaseRun python3 --version and confirm the environment is on 3.10 to 3.13
AuthenticationErrorKey unset, expired, or .env not in the project rootConfirm the file location and variable name; restart the shell
Agent loops or ramblesVague task or loop cap too highTighten expected_output; lower max_iter
Rate-limit errorsRequests per minute above your provider’s limitSet max_rpm on the crew
Writer ignores the researchTask order wrong or dependency missingList the research task first; add it to context in tasks.yaml
Token limit exceededContext window overflow from long outputsSet respect_context_window=True on agents
Tool execution timeoutExternal API slow or unreachableAdd a timeout parameter to the tool and implement retry logic
Typed output fails validationSchema stricter than the model can satisfySimplify the model and add field descriptions
CodeInterpreterTool import failsTool removed in April 2026Use an E2B or Daytona sandbox tool
Short-term, long-term or entity memory setup failsReplaced by one Memory class in March 2026Follow the current Memory documentation
Reported tokens look too lowReading kickoff().token_usage on a FlowRead flow.usage_metrics instead
crewai run asks for inputA {topic}-style variable has no default under inputsSet the default in crew.jsonc, or answer the prompt
Sofia Lindström

Sofia Lindström

Security and privacy

Sofia Lindström writes about security and privacy for Tech Insider: software vulnerabilities and the updates that fix them, data breaches, privacy rules and how products handle personal data. She works from vendor advisories, official vulnerability catalogues and the documents behind each story.

View all articles