Build Your First Flow - CrewAI
Build Your First Flow - CrewAI
Flows
In this guide, we’ll walk through creating a powerful CrewAI Flow that generates a
comprehensive learning guide on any topic. This tutorial will demonstrate how Flows
provide structured, event-driven control over your AI workflows by combining regular
code, direct LLM calls, and crew-based processing.
This guide creator flow demonstrates fundamental patterns that can be applied to create
much more advanced applications, such as:
Prerequisites
Before starting, make sure you have:
This will generate a project with the basic structure needed for your flow.
This structure provides a clear separation between different components of your flow:
We’ll modify this structure to create our guide creator flow, which will orchestrate the
process of generating comprehensive learning guides.
This command automatically creates the necessary directories and template files for your
crew. The content writer crew will be responsible for writing and reviewing sections of
our guide, working within the overall flow orchestrated by our main application.
Step 4: Configure the Content Writer Crew
Now, let’s modify the generated files for the content writer crew. We’ll set up two
specialized
Flows agents - a First
Build Your writer and a reviewer - that will collaborate to create high-quality
Flow
content for our guide.
1. First, update the agents configuration file to define our content creation team:
# src/guide_creator_flow/crews/content_crew/config/agents.yaml
content_writer:
role: >
Educational Content Writer
goal: >
Create engaging, informative content that thoroughly explains the assigned
and provides valuable insights to the reader
backstory: >
You are a talented educational writer with expertise in creating clear, eng
content. You have a gift for explaining complex concepts in accessible lang
and organizing information in a way that helps readers build their understa
llm: openai/gpt-4o-mini
content_reviewer:
role: >
Educational Content Reviewer and Editor
goal: >
Ensure content is accurate, comprehensive, well-structured, and maintains
consistency with previously written sections
backstory: >
You are a meticulous editor with years of experience reviewing educational
content. You have an eye for detail, clarity, and coherence. You excel at
improving content while maintaining the original author's voice and ensurin
consistent quality across multiple sections.
llm: openai/gpt-4o-mini
These agent definitions establish the specialized roles and perspectives that will shape
how our AI agents approach content creation. Notice how each agent has a distinct
purpose and expertise.
2. Next, update the tasks configuration file to define the specific writing and reviewing
tasks:
# src/guide_creator_flow/crews/content_crew/config/tasks.yaml
write_section_task:
description: >
Flows Build Your First Flow
Write a comprehensive section on the topic: "{section_title}"
Format your content in Markdown with appropriate headings, lists, and empha
Make sure your content maintains consistency with previously written sectio
and builds upon concepts that have already been explained.
expected_output: >
A well-structured, comprehensive section in Markdown format that thoroughly
explains the topic and is appropriate for the target audience.
agent: content_writer
review_section_task:
description: >
Review and improve the following section on "{section_title}":
{draft_content}
These task definitions provide detailed instructions to our agents, ensuring they produce
content that meets our quality standards. Note how the context parameter in the review
task creates a workflow where the reviewer has access to the writer’s output.
3. Now, update the crew implementation file to define how our agents and tasks work
together:
# src/guide_creator_flow/crews/content_crew/content_crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
Flows Build Your First Flow
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class ContentCrew():
"""Content writing crew"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def content_writer(self) -> Agent:
return Agent(
config=self.agents_config['content_writer'], # type: ignore[index]
verbose=True
)
@agent
def content_reviewer(self) -> Agent:
return Agent(
config=self.agents_config['content_reviewer'], # type: ignore[index
verbose=True
)
@task
def write_section_task(self) -> Task:
return Task(
config=self.tasks_config['write_section_task'] # type: ignore[index
)
@task
def review_section_task(self) -> Task:
return Task(
config=self.tasks_config['review_section_task'], # type: ignore[ind
context=[self.write_section_task()]
)
@crew
def crew(self) -> Crew:
"""Creates the content writing crew"""
return Crew(
agents=self.agents,
Flows Buildtasks=self.tasks,
Your First Flow
process=Process.sequential,
verbose=True,
)
This crew definition establishes the relationship between our agents and tasks, setting up
a sequential process where the content writer creates a draft and then the reviewer
improves it. While this crew can function independently, in our flow it will be orchestrated
as part of a larger system.
class GuideOutline(BaseModel):
title: str = Field(description="Title of the guide")
introduction: str = Field(description="Introduction to the topic")
target_audience: str = Field(description="Description of the target audienc
sections: List[Section] = Field(description="List of sections in the guide"
conclusion: str = Field(description="Conclusion or summary of the guide")
class GuideCreatorFlow(Flow[GuideCreatorState]):
"""Flow for creating a comprehensive guide on any topic"""
@start()
def get_user_input(self):
"""Get input from the user about the guide topic and audience"""
print("\n=== Create Your Comprehensive Guide ===\n")
@listen(get_user_input)
def create_guide_outline(self, state):
"""Create a structured outline for the guide using a direct LLM call"""
print("Creating guide outline...")
@listen(create_guide_outline)
def write_and_compile_guide(self, outline):
"""Write all sections and compile the guide"""
print("Writing guide sections and compiling...")
completed_sections = []
# Add conclusion
guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
def kickoff():
"""Run the guide creator flow"""
GuideCreatorFlow().kickoff()
print("\n=== Flow Complete ===")
print("Your comprehensive guide is ready in the output directory.")
print("Open output/complete_guide.md to view it.")
def plot():
"""Generate a visualization of the flow"""
flow = GuideCreatorFlow()
flow.plot("guide_creator_flow")
print("Flow visualization saved to guide_creator_flow.html")
if __name__ == "__main__":
kickoff()
1. We define Pydantic models for structured data, ensuring type safety and clear data
representation
2. We create a state class to maintain data across different steps of the flow
3. We implement three main flow steps:
Getting user input with the @start() decorator
Creating a guide outline with a direct LLM call
Processing sections with our content crew
4. Flows
We use the
Build@listen() decorator to establish event-driven relationships between
Your First Flow
steps
This is the power of flows - combining different types of processing (user interaction,
direct LLM calls, crew-based tasks) into a coherent, event-driven system.
OPENAI_API_KEY=your_openai_api_key
crewai install
When you run this command, you’ll see your flow spring to life:
This will create an HTML file that shows the structure of your flow, including the
relationships between different steps and the data that flows between them. This
visualization can be invaluable for understanding and debugging complex flows.
Take a moment to review these files and appreciate what you’ve built - a system that
combines user input, direct AI interactions, and collaborative agent work to produce a
complex, high-quality output.
1. User interaction: The flow collects input directly from the user
2. Flows Build
Direct LLM YourUses
calls: First Flow
the LLM class for efficient, single-purpose AI interactions
3. Structured data with Pydantic: Uses Pydantic models to ensure type safety
4. Sequential processing with context: Writes sections in order, providing previous
sections for context
5. Multi-agent crews: Leverages specialized agents (writer and reviewer) for content
creation
6. State management: Maintains state across different steps of the process
7. Event-driven architecture: Uses the @listen decorator to respond to events
This is more efficient than using a crew when you need a specific, structured output.
2. Event-Driven Architecture
Flows use decorators to establish relationships between components:
@start()
def get_user_input(self):
# First step in the flow
Flows Build Your First Flow
# ...
@listen(get_user_input)
def create_guide_outline(self, state):
# This runs when get_user_input completes
# ...
3. State Management
Flows maintain state across steps, making it easy to share data:
class GuideCreatorState(BaseModel):
topic: str = ""
audience_level: str = ""
guide_outline: GuideOutline = None
sections_content: Dict[str, str] = {}
This provides a type-safe way to track and transform data throughout your flow.
4. Crew Integration
Flows can seamlessly integrate with crews for complex collaborative tasks:
result = ContentCrew().crew().kickoff(inputs={
"section_title": section.title,
# ...
})
This allows you to use the right tool for each part of your application - direct LLM calls for
simple tasks and crews for complex collaboration.
Next Steps
Now that you’ve built your first flow, you can:
Flows Build Your First Flow
1. Experiment with more complex flow structures and patterns
2. Try using @router() to create conditional branches in your flows
3. Explore the and_ and or_ functions for more complex parallel execution
4. Connect your flow to external APIs, databases, or user interfaces
5. Combine multiple specialized crews in a single flow
Congratulations! You’ve successfully built your first CrewAI Flow that combines regular
code, direct LLM calls, and crew-based processing to create a comprehensive guide. These
foundational skills enable you to create increasingly sophisticated AI applications that can
tackle complex, multi-stage problems through a combination of procedural control and
collaborative intelligence.
Powered by Mintlify