diff --git a/docs/guides/agents/crafting-effective-agents.mdx b/docs/guides/agents/crafting-effective-agents.mdx new file mode 100644 index 000000000..411b78f65 --- /dev/null +++ b/docs/guides/agents/crafting-effective-agents.mdx @@ -0,0 +1,454 @@ +--- +title: Crafting Effective Agents +description: Learn best practices for designing powerful, specialized AI agents that collaborate effectively to solve complex problems. +icon: robot +--- + +# Crafting Effective Agents + +## The Art and Science of Agent Design + +At the heart of CrewAI lies the agent - a specialized AI entity designed to perform specific roles within a collaborative framework. While creating basic agents is simple, crafting truly effective agents that produce exceptional results requires understanding key design principles and best practices. + +This guide will help you master the art of agent design, enabling you to create specialized AI personas that collaborate effectively, think critically, and produce high-quality outputs tailored to your specific needs. + +### Why Agent Design Matters + +The way you define your agents significantly impacts: + +1. **Output quality**: Well-designed agents produce more relevant, high-quality results +2. **Collaboration effectiveness**: Agents with complementary skills work together more efficiently +3. **Task performance**: Agents with clear roles and goals execute tasks more effectively +4. **System scalability**: Thoughtfully designed agents can be reused across multiple crews and contexts + +Let's explore best practices for creating agents that excel in these dimensions. + +## The 80/20 Rule: Focus on Tasks Over Agents + +When building effective AI systems, remember this crucial principle: **80% of your effort should go into designing tasks, and only 20% into defining agents**. + +Why? Because even the most perfectly defined agent will fail with poorly designed tasks, but well-designed tasks can elevate even a simple agent. This means: + +- Spend most of your time writing clear task instructions +- Define detailed inputs and expected outputs +- Add examples and context to guide execution +- Dedicate the remaining time to agent role, goal, and backstory + +This doesn't mean agent design isn't important - it absolutely is. But task design is where most execution failures occur, so prioritize accordingly. + +## Core Principles of Effective Agent Design + +### 1. The Role-Goal-Backstory Framework + +The most powerful agents in CrewAI are built on a strong foundation of three key elements: + +#### Role: The Agent's Specialized Function + +The role defines what the agent does and their area of expertise. When crafting roles: + +- **Be specific and specialized**: Instead of "Writer," use "Technical Documentation Specialist" or "Creative Storyteller" +- **Align with real-world professions**: Base roles on recognizable professional archetypes +- **Include domain expertise**: Specify the agent's field of knowledge (e.g., "Financial Analyst specializing in market trends") + +**Examples of effective roles:** +```yaml +role: "Senior UX Researcher specializing in user interview analysis" +role: "Full-Stack Software Architect with expertise in distributed systems" +role: "Corporate Communications Director specializing in crisis management" +``` + +#### Goal: The Agent's Purpose and Motivation + +The goal directs the agent's efforts and shapes their decision-making process. Effective goals should: + +- **Be clear and outcome-focused**: Define what the agent is trying to achieve +- **Emphasize quality standards**: Include expectations about the quality of work +- **Incorporate success criteria**: Help the agent understand what "good" looks like + +**Examples of effective goals:** +```yaml +goal: "Uncover actionable user insights by analyzing interview data and identifying recurring patterns, unmet needs, and improvement opportunities" +goal: "Design robust, scalable system architectures that balance performance, maintainability, and cost-effectiveness" +goal: "Craft clear, empathetic crisis communications that address stakeholder concerns while protecting organizational reputation" +``` + +#### Backstory: The Agent's Experience and Perspective + +The backstory gives depth to the agent, influencing how they approach problems and interact with others. Good backstories: + +- **Establish expertise and experience**: Explain how the agent gained their skills +- **Define working style and values**: Describe how the agent approaches their work +- **Create a cohesive persona**: Ensure all elements of the backstory align with the role and goal + +**Examples of effective backstories:** +```yaml +backstory: "You have spent 15 years conducting and analyzing user research for top tech companies. You have a talent for reading between the lines and identifying patterns that others miss. You believe that good UX is invisible and that the best insights come from listening to what users don't say as much as what they do say." + +backstory: "With 20+ years of experience building distributed systems at scale, you've developed a pragmatic approach to software architecture. You've seen both successful and failed systems and have learned valuable lessons from each. You balance theoretical best practices with practical constraints and always consider the maintenance and operational aspects of your designs." + +backstory: "As a seasoned communications professional who has guided multiple organizations through high-profile crises, you understand the importance of transparency, speed, and empathy in crisis response. You have a methodical approach to crafting messages that address concerns while maintaining organizational credibility." +``` + +### 2. Specialists Over Generalists + +Agents perform significantly better when given specialized roles rather than general ones. A highly focused agent delivers more precise, relevant outputs: + +**Generic (Less Effective):** +```yaml +role: "Writer" +``` + +**Specialized (More Effective):** +```yaml +role: "Technical Blog Writer specializing in explaining complex AI concepts to non-technical audiences" +``` + +**Specialist Benefits:** +- Clearer understanding of expected output +- More consistent performance +- Better alignment with specific tasks +- Improved ability to make domain-specific judgments + +### 3. Balancing Specialization and Versatility + +Effective agents strike the right balance between specialization (doing one thing extremely well) and versatility (being adaptable to various situations): + +- **Specialize in role, versatile in application**: Create agents with specialized skills that can be applied across multiple contexts +- **Avoid overly narrow definitions**: Ensure agents can handle variations within their domain of expertise +- **Consider the collaborative context**: Design agents whose specializations complement the other agents they'll work with + +### 4. Setting Appropriate Expertise Levels + +The expertise level you assign to your agent shapes how they approach tasks: + +- **Novice agents**: Good for straightforward tasks, brainstorming, or initial drafts +- **Intermediate agents**: Suitable for most standard tasks with reliable execution +- **Expert agents**: Best for complex, specialized tasks requiring depth and nuance +- **World-class agents**: Reserved for critical tasks where exceptional quality is needed + +Choose the appropriate expertise level based on task complexity and quality requirements. For most collaborative crews, a mix of expertise levels often works best, with higher expertise assigned to core specialized functions. + +## Practical Examples: Before and After + +Let's look at some examples of agent definitions before and after applying these best practices: + +### Example 1: Content Creation Agent + +**Before:** +```yaml +role: "Writer" +goal: "Write good content" +backstory: "You are a writer who creates content for websites." +``` + +**After:** +```yaml +role: "B2B Technology Content Strategist" +goal: "Create compelling, technically accurate content that explains complex topics in accessible language while driving reader engagement and supporting business objectives" +backstory: "You have spent a decade creating content for leading technology companies, specializing in translating technical concepts for business audiences. You excel at research, interviewing subject matter experts, and structuring information for maximum clarity and impact. You believe that the best B2B content educates first and sells second, building trust through genuine expertise rather than marketing hype." +``` + +### Example 2: Research Agent + +**Before:** +```yaml +role: "Researcher" +goal: "Find information" +backstory: "You are good at finding information online." +``` + +**After:** +```yaml +role: "Academic Research Specialist in Emerging Technologies" +goal: "Discover and synthesize cutting-edge research, identifying key trends, methodologies, and findings while evaluating the quality and reliability of sources" +backstory: "With a background in both computer science and library science, you've mastered the art of digital research. You've worked with research teams at prestigious universities and know how to navigate academic databases, evaluate research quality, and synthesize findings across disciplines. You're methodical in your approach, always cross-referencing information and tracing claims to primary sources before drawing conclusions." +``` + +## Crafting Effective Tasks for Your Agents + +While agent design is important, task design is critical for successful execution. Here are best practices for designing tasks that set your agents up for success: + +### The Anatomy of an Effective Task + +A well-designed task has two key components that serve different purposes: + +#### Task Description: The Process +The description should focus on what to do and how to do it, including: +- Detailed instructions for execution +- Context and background information +- Scope and constraints +- Process steps to follow + +#### Expected Output: The Deliverable +The expected output should define what the final result should look like: +- Format specifications (markdown, JSON, etc.) +- Structure requirements +- Quality criteria +- Examples of good outputs (when possible) + +### Task Design Best Practices + +#### 1. Single Purpose, Single Output +Tasks perform best when focused on one clear objective: + +**Bad Example (Too Broad):** +```yaml +task_description: "Research market trends, analyze the data, and create a visualization." +``` + +**Good Example (Focused):** +```yaml +# Task 1 +research_task: + description: "Research the top 5 market trends in the AI industry for 2024." + expected_output: "A markdown list of the 5 trends with supporting evidence." + +# Task 2 +analysis_task: + description: "Analyze the identified trends to determine potential business impacts." + expected_output: "A structured analysis with impact ratings (High/Medium/Low)." + +# Task 3 +visualization_task: + description: "Create a visual representation of the analyzed trends." + expected_output: "A description of a chart showing trends and their impact ratings." +``` + +#### 2. Be Explicit About Inputs and Outputs +Always clearly specify what inputs the task will use and what the output should look like: + +**Example:** +```yaml +analysis_task: + description: > + Analyze the customer feedback data from the CSV file. + Focus on identifying recurring themes related to product usability. + Consider sentiment and frequency when determining importance. + expected_output: > + A markdown report with the following sections: + 1. Executive summary (3-5 bullet points) + 2. Top 3 usability issues with supporting data + 3. Recommendations for improvement +``` + +#### 3. Include Purpose and Context +Explain why the task matters and how it fits into the larger workflow: + +**Example:** +```yaml +competitor_analysis_task: + description: > + Analyze our three main competitors' pricing strategies. + This analysis will inform our upcoming pricing model revision. + Focus on identifying patterns in how they price premium features + and how they structure their tiered offerings. +``` + +#### 4. Use Structured Output Tools +For machine-readable outputs, specify the format clearly: + +**Example:** +```yaml +data_extraction_task: + description: "Extract key metrics from the quarterly report." + expected_output: "JSON object with the following keys: revenue, growth_rate, customer_acquisition_cost, and retention_rate." +``` + +## Common Mistakes to Avoid + +Based on lessons learned from real-world implementations, here are the most common pitfalls in agent and task design: + +### 1. Unclear Task Instructions + +**Problem:** Tasks lack sufficient detail, making it difficult for agents to execute effectively. + +**Example of Poor Design:** +```yaml +research_task: + description: "Research AI trends." + expected_output: "A report on AI trends." +``` + +**Improved Version:** +```yaml +research_task: + description: > + Research the top emerging AI trends for 2024 with a focus on: + 1. Enterprise adoption patterns + 2. Technical breakthroughs in the past 6 months + 3. Regulatory developments affecting implementation + + For each trend, identify key companies, technologies, and potential business impacts. + expected_output: > + A comprehensive markdown report with: + - Executive summary (5 bullet points) + - 5-7 major trends with supporting evidence + - For each trend: definition, examples, and business implications + - References to authoritative sources +``` + +### 2. "God Tasks" That Try to Do Too Much + +**Problem:** Tasks that combine multiple complex operations into one instruction set. + +**Example of Poor Design:** +```yaml +comprehensive_task: + description: "Research market trends, analyze competitor strategies, create a marketing plan, and design a launch timeline." +``` + +**Improved Version:** +Break this into sequential, focused tasks: +```yaml +# Task 1: Research +market_research_task: + description: "Research current market trends in the SaaS project management space." + expected_output: "A markdown summary of key market trends." + +# Task 2: Competitive Analysis +competitor_analysis_task: + description: "Analyze strategies of the top 3 competitors based on the market research." + expected_output: "A comparison table of competitor strategies." + context: [market_research_task] + +# Continue with additional focused tasks... +``` + +### 3. Misaligned Description and Expected Output + +**Problem:** The task description asks for one thing while the expected output specifies something different. + +**Example of Poor Design:** +```yaml +analysis_task: + description: "Analyze customer feedback to find areas of improvement." + expected_output: "A marketing plan for the next quarter." +``` + +**Improved Version:** +```yaml +analysis_task: + description: "Analyze customer feedback to identify the top 3 areas for product improvement." + expected_output: "A report listing the 3 priority improvement areas with supporting customer quotes and data points." +``` + +### 4. Not Understanding the Process Yourself + +**Problem:** Asking agents to execute tasks that you yourself don't fully understand. + +**Solution:** +1. Try to perform the task manually first +2. Document your process, decision points, and information sources +3. Use this documentation as the basis for your task description + +### 5. Premature Use of Hierarchical Structures + +**Problem:** Creating unnecessarily complex agent hierarchies where sequential processes would work better. + +**Solution:** Start with sequential processes and only move to hierarchical models when the workflow complexity truly requires it. + +### 6. Vague or Generic Agent Definitions + +**Problem:** Generic agent definitions lead to generic outputs. + +**Example of Poor Design:** +```yaml +agent: + role: "Business Analyst" + goal: "Analyze business data" + backstory: "You are good at business analysis." +``` + +**Improved Version:** +```yaml +agent: + role: "SaaS Metrics Specialist focusing on growth-stage startups" + goal: "Identify actionable insights from business data that can directly impact customer retention and revenue growth" + backstory: "With 10+ years analyzing SaaS business models, you've developed a keen eye for the metrics that truly matter for sustainable growth. You've helped numerous companies identify the leverage points that turned around their business trajectory. You believe in connecting data to specific, actionable recommendations rather than general observations." +``` + +## Advanced Agent Design Strategies + +### Designing for Collaboration + +When creating agents that will work together in a crew, consider: + +- **Complementary skills**: Design agents with distinct but complementary abilities +- **Handoff points**: Define clear interfaces for how work passes between agents +- **Constructive tension**: Sometimes, creating agents with slightly different perspectives can lead to better outcomes through productive dialogue + +For example, a content creation crew might include: + +```yaml +# Research Agent +role: "Research Specialist for technical topics" +goal: "Gather comprehensive, accurate information from authoritative sources" +backstory: "You are a meticulous researcher with a background in library science..." + +# Writer Agent +role: "Technical Content Writer" +goal: "Transform research into engaging, clear content that educates and informs" +backstory: "You are an experienced writer who excels at explaining complex concepts..." + +# Editor Agent +role: "Content Quality Editor" +goal: "Ensure content is accurate, well-structured, and polished while maintaining consistency" +backstory: "With years of experience in publishing, you have a keen eye for detail..." +``` + +### Creating Specialized Tool Users + +Some agents can be designed specifically to leverage certain tools effectively: + +```yaml +role: "Data Analysis Specialist" +goal: "Derive meaningful insights from complex datasets through statistical analysis" +backstory: "With a background in data science, you excel at working with structured and unstructured data..." +tools: [PythonREPLTool, DataVisualizationTool, CSVAnalysisTool] +``` + +### Tailoring Agents to LLM Capabilities + +Different LLMs have different strengths. Design your agents with these capabilities in mind: + +```yaml +# For complex reasoning tasks +analyst: + role: "Data Insights Analyst" + goal: "..." + backstory: "..." + llm: openai/gpt-4o + +# For creative content +writer: + role: "Creative Content Writer" + goal: "..." + backstory: "..." + llm: anthropic/claude-3-opus +``` + +## Testing and Iterating on Agent Design + +Agent design is often an iterative process. Here's a practical approach: + +1. **Start with a prototype**: Create an initial agent definition +2. **Test with sample tasks**: Evaluate performance on representative tasks +3. **Analyze outputs**: Identify strengths and weaknesses +4. **Refine the definition**: Adjust role, goal, and backstory based on observations +5. **Test in collaboration**: Evaluate how the agent performs in a crew setting + +## Conclusion + +Crafting effective agents is both an art and a science. By carefully defining roles, goals, and backstories that align with your specific needs, and combining them with well-designed tasks, you can create specialized AI collaborators that produce exceptional results. + +Remember that agent and task design is an iterative process. Start with these best practices, observe your agents in action, and refine your approach based on what you learn. And always keep in mind the 80/20 rule - focus most of your effort on creating clear, focused tasks to get the best results from your agents. + + +Congratulations! You now understand the principles and practices of effective agent design. Apply these techniques to create powerful, specialized agents that work together seamlessly to accomplish complex tasks. + + +## Next Steps + +- Experiment with different agent configurations for your specific use case +- Learn about [building your first crew](/guides/crews/first-crew) to see how agents work together +- Explore [CrewAI Flows](/guides/flows/first-flow) for more advanced orchestration \ No newline at end of file diff --git a/docs/guides/crews/first-crew.mdx b/docs/guides/crews/first-crew.mdx index 767c5166a..8aa384112 100644 --- a/docs/guides/crews/first-crew.mdx +++ b/docs/guides/crews/first-crew.mdx @@ -6,9 +6,31 @@ icon: users-gear # Build Your First Crew -In this guide, we'll walk through creating a research crew that will help us research and analyze a topic, then create a comprehensive report. This is a practical example of how AI agents can collaborate to accomplish complex tasks. +## Unleashing the Power of Collaborative AI +Imagine having a team of specialized AI agents working together seamlessly to solve complex problems, each contributing their unique skills to achieve a common goal. This is the power of CrewAI - a framework that enables you to create collaborative AI systems that can accomplish tasks far beyond what a single AI could achieve alone. +In this guide, we'll walk through creating a research crew that will help us research and analyze a topic, then create a comprehensive report. This practical example demonstrates how AI agents can collaborate to accomplish complex tasks, but it's just the beginning of what's possible with CrewAI. + +### What You'll Build and Learn + +By the end of this guide, you'll have: + +1. **Created a specialized AI research team** with distinct roles and responsibilities +2. **Orchestrated collaboration** between multiple AI agents +3. **Automated a complex workflow** that involves gathering information, analysis, and report generation +4. **Built foundational skills** that you can apply to more ambitious projects + +While we're building a simple research crew in this guide, the same patterns and techniques can be applied to create much more sophisticated teams for tasks like: + +- Multi-stage content creation with specialized writers, editors, and fact-checkers +- Complex customer service systems with tiered support agents +- Autonomous business analysts that gather data, create visualizations, and generate insights +- Product development teams that ideate, design, and plan implementation + +Let's get started building your first crew! + +### Prerequisites Before starting, make sure you have: @@ -18,7 +40,7 @@ Before starting, make sure you have: ## Step 1: Create a New CrewAI Project -First, let's create a new CrewAI project using the CLI: +First, let's create a new CrewAI project using the CLI. This command will set up a complete project structure with all the necessary files, allowing you to focus on defining your agents and their tasks rather than setting up boilerplate code. ```bash crewai create crew research_crew @@ -39,7 +61,7 @@ This will generate a project with the basic structure needed for your crew. The ## Step 2: Explore the Project Structure -Let's take a moment to understand the project structure created by the CLI: +Let's take a moment to understand the project structure created by the CLI. CrewAI follows best practices for Python projects, making it easy to maintain and extend your code as your crews become more complex. ``` research_crew/ @@ -60,11 +82,17 @@ research_crew/ └── tasks.yaml ``` -This structure follows best practices for Python projects and makes it easy to organize your code. +This structure follows best practices for Python projects and makes it easy to organize your code. The separation of configuration files (in YAML) from implementation code (in Python) makes it easy to modify your crew's behavior without changing the underlying code. ## Step 3: Configure Your Agents -Let's modify the `agents.yaml` file to define two specialized agents: a researcher and an analyst. +Now comes the fun part - defining your AI agents! In CrewAI, agents are specialized entities with specific roles, goals, and backstories that shape their behavior. Think of them as characters in a play, each with their own personality and purpose. + +For our research crew, we'll create two agents: +1. A **researcher** who excels at finding and organizing information +2. An **analyst** who can interpret research findings and create insightful reports + +Let's modify the `agents.yaml` file to define these specialized agents: ```yaml # src/research_crew/config/agents.yaml @@ -95,9 +123,17 @@ analyst: llm: openai/gpt-4o-mini ``` +Notice how each agent has a distinct role, goal, and backstory. These elements aren't just descriptive - they actively shape how the agent approaches its tasks. By crafting these carefully, you can create agents with specialized skills and perspectives that complement each other. + ## Step 4: Define Your Tasks -Now, let's modify the `tasks.yaml` file to define the research and analysis tasks: +With our agents defined, we now need to give them specific tasks to perform. Tasks in CrewAI represent the concrete work that agents will perform, with detailed instructions and expected outputs. + +For our research crew, we'll define two main tasks: +1. A **research task** for gathering comprehensive information +2. An **analysis task** for creating an insightful report + +Let's modify the `tasks.yaml` file: ```yaml # src/research_crew/config/tasks.yaml @@ -136,9 +172,13 @@ analysis_task: output_file: output/report.md ``` +Note the `context` field in the analysis task - this is a powerful feature that allows the analyst to access the output of the research task. This creates a workflow where information flows naturally between agents, just as it would in a human team. + ## Step 5: Configure Your Crew -Now, let's modify the `crew.py` file to set up our research crew: +Now it's time to bring everything together by configuring our crew. The crew is the container that orchestrates how agents work together to complete tasks. + +Let's modify the `crew.py` file: ```python # src/research_crew/crew.py @@ -189,9 +229,17 @@ class ResearchCrew(): ) ``` +In this code, we're: +1. Creating the researcher agent and equipping it with the SerperDevTool to search the web +2. Creating the analyst agent +3. Setting up the research and analysis tasks +4. Configuring the crew to run tasks sequentially (the analyst will wait for the researcher to finish) + +This is where the magic happens - with just a few lines of code, we've defined a collaborative AI system where specialized agents work together in a coordinated process. + ## Step 6: Set Up Your Main Script -Let's modify the `main.py` file to run our crew: +Now, let's set up the main script that will run our crew. This is where we provide the specific topic we want our crew to research. ```python #!/usr/bin/env python @@ -223,6 +271,8 @@ if __name__ == "__main__": run() ``` +This script prepares the environment, specifies our research topic, and kicks off the crew's work. The power of CrewAI is evident in how simple this code is - all the complexity of managing multiple AI agents is handled by the framework. + ## Step 7: Set Up Your Environment Variables Create a `.env` file in your project root with your API keys: @@ -249,13 +299,13 @@ This command will: ## Step 9: Run Your Crew -Now, run your crew using the CrewAI CLI: +Now for the exciting moment - it's time to run your crew and see AI collaboration in action! ```bash crewai run ``` -Your crew will start working! The researcher will gather information about the specified topic, and the analyst will create a comprehensive report based on that research. +When you run this command, you'll see your crew spring to life. The researcher will gather information about the specified topic, and the analyst will then create a comprehensive report based on that research. You'll see the agents' thought processes, actions, and outputs in real-time as they work together to complete their tasks. ## Step 10: Review the Output @@ -266,6 +316,8 @@ Once the crew completes its work, you'll find the final report in the `output/re 3. Analysis and insights 4. Recommendations or future considerations +Take a moment to appreciate what you've accomplished - you've created a system where multiple AI agents collaborated on a complex task, each contributing their specialized skills to produce a result that's greater than what any single agent could achieve alone. + ## Exploring Other CLI Commands CrewAI offers several other useful CLI commands for working with crews: @@ -285,29 +337,54 @@ crewai reset-memories # Replay from a specific task crewai replay -t - -# View the latest task outputs -crewai log-tasks-outputs ``` -## Customizing Your Crew +## The Art of the Possible: Beyond Your First Crew -You can customize your crew in several ways: +What you've built in this guide is just the beginning. The skills and patterns you've learned can be applied to create increasingly sophisticated AI systems. Here are some ways you could extend this basic research crew: -1. **Add more agents**: Create additional specialized roles like a fact-checker or editor -2. **Modify the process**: Change from `Process.sequential` to `Process.hierarchical` for more complex workflows -3. **Add custom tools**: Create and add specialized tools for your agents -4. **Change the topic**: Update the `topic` parameter in the `inputs` dictionary to research different subjects +### Expanding Your Crew + +You could add more specialized agents to your crew: +- A **fact-checker** to verify research findings +- A **data visualizer** to create charts and graphs +- A **domain expert** with specialized knowledge in a particular area +- A **critic** to identify weaknesses in the analysis + +### Adding Tools and Capabilities + +You could enhance your agents with additional tools: +- Web browsing tools for real-time research +- CSV/database tools for data analysis +- Code execution tools for data processing +- API connections to external services + +### Creating More Complex Workflows + +You could implement more sophisticated processes: +- Hierarchical processes where manager agents delegate to worker agents +- Iterative processes with feedback loops for refinement +- Parallel processes where multiple agents work simultaneously +- Dynamic processes that adapt based on intermediate results + +### Applying to Different Domains + +The same patterns can be applied to create crews for: +- **Content creation**: Writers, editors, fact-checkers, and designers working together +- **Customer service**: Triage agents, specialists, and quality control working together +- **Product development**: Researchers, designers, and planners collaborating +- **Data analysis**: Data collectors, analysts, and visualization specialists ## Next Steps Now that you've built your first crew, you can: -1. Experiment with different agent configurations -2. Try more complex task structures -3. Implement custom tools for your agents -4. Explore [CrewAI Flows](/guides/flows/first-flow) for more advanced workflows +1. Experiment with different agent configurations and personalities +2. Try more complex task structures and workflows +3. Implement custom tools to give your agents new capabilities +4. Apply your crew to different topics or problem domains +5. Explore [CrewAI Flows](/guides/flows/first-flow) for more advanced workflows with procedural programming -Congratulations! You've successfully built your first CrewAI crew that can research and analyze any topic you provide. +Congratulations! You've successfully built your first CrewAI crew that can research and analyze any topic you provide. This foundational experience has equipped you with the skills to create increasingly sophisticated AI systems that can tackle complex, multi-stage problems through collaborative intelligence. \ No newline at end of file diff --git a/docs/guides/flows/first-flow.mdx b/docs/guides/flows/first-flow.mdx index b030931c3..d3c346c76 100644 --- a/docs/guides/flows/first-flow.mdx +++ b/docs/guides/flows/first-flow.mdx @@ -6,8 +6,40 @@ icon: diagram-project # Build Your First Flow +## Taking Control of AI Workflows with Flows + +CrewAI Flows represent the next level in AI orchestration - combining the collaborative power of AI agent crews with the precision and flexibility of procedural programming. While crews excel at agent collaboration, flows give you fine-grained control over exactly how and when different components of your AI system interact. + 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. +### What Makes Flows Powerful + +Flows enable you to: + +1. **Combine different AI interaction patterns** - Use crews for complex collaborative tasks, direct LLM calls for simpler operations, and regular code for procedural logic +2. **Build event-driven systems** - Define how components respond to specific events and data changes +3. **Maintain state across components** - Share and transform data between different parts of your application +4. **Integrate with external systems** - Seamlessly connect your AI workflow with databases, APIs, and user interfaces +5. **Create complex execution paths** - Design conditional branches, parallel processing, and dynamic workflows + +### What You'll Build and Learn + +By the end of this guide, you'll have: + +1. **Created a sophisticated content generation system** that combines user input, AI planning, and multi-agent content creation +2. **Orchestrated the flow of information** between different components of your system +3. **Implemented event-driven architecture** where each step responds to the completion of previous steps +4. **Built a foundation for more complex AI applications** that you can expand and customize + +This guide creator flow demonstrates fundamental patterns that can be applied to create much more advanced applications, such as: + +- Interactive AI assistants that combine multiple specialized subsystems +- Complex data processing pipelines with AI-enhanced transformations +- Autonomous agents that integrate with external services and APIs +- Multi-stage decision-making systems with human-in-the-loop processes + +Let's dive in and build your first flow! + ## Prerequisites Before starting, make sure you have: @@ -18,7 +50,7 @@ Before starting, make sure you have: ## Step 1: Create a New CrewAI Flow Project -First, let's create a new CrewAI Flow project using the CLI: +First, let's create a new CrewAI Flow project using the CLI. This command sets up a scaffolded project with all the necessary directories and template files for your flow. ```bash crewai create flow guide_creator_flow @@ -33,7 +65,7 @@ This will generate a project with the basic structure needed for your flow. ## Step 2: Understanding the Project Structure -The generated project has the following structure: +The generated project has the following structure. Take a moment to familiarize yourself with it, as understanding this structure will help you create more complex flows in the future. ``` guide_creator_flow/ @@ -52,23 +84,28 @@ guide_creator_flow/ └── custom_tool.py ``` -We'll modify this structure to create our guide creator flow. +This structure provides a clear separation between different components of your flow: +- The main flow logic in the `main.py` file +- Specialized crews in the `crews` directory +- Custom tools in the `tools` directory + +We'll modify this structure to create our guide creator flow, which will orchestrate the process of generating comprehensive learning guides. ## Step 3: Add a Content Writer Crew -Let's use the CrewAI CLI to add a content writer crew: +Our flow will need a specialized crew to handle the content creation process. Let's use the CrewAI CLI to add a content writer crew: ```bash crewai flow add-crew content-crew ``` -This command will automatically create the necessary directories and template files. +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: +Now, let's modify the generated files for the content writer crew. We'll set up two specialized agents - a writer and a reviewer - that will collaborate to create high-quality content for our guide. -1. First, update the agents configuration file: +1. First, update the agents configuration file to define our content creation team: ```yaml # src/guide_creator_flow/crews/content_crew/config/agents.yaml @@ -98,7 +135,9 @@ content_reviewer: llm: openai/gpt-4o-mini ``` -2. Next, update the tasks configuration file: +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: ```yaml # src/guide_creator_flow/crews/content_crew/config/tasks.yaml @@ -156,7 +195,9 @@ review_section_task: - write_section_task ``` -3. Now, update the crew implementation file: +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: ```python # src/guide_creator_flow/crews/content_crew/content_crew.py @@ -205,13 +246,19 @@ class ContentCrew(): ) ``` +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. + ## Step 5: Create the Flow -Now, let's create our flow in the `main.py` file. This flow will: -1. Get user input for a topic +Now comes the exciting part - creating the flow that will orchestrate the entire guide creation process. This is where we'll combine regular Python code, direct LLM calls, and our content creation crew into a cohesive system. + +Our flow will: +1. Get user input for a topic and audience level 2. Make a direct LLM call to create a structured guide outline -3. Process each section in parallel using the content writer crew -4. Combine everything into a final document +3. Process each section sequentially using the content writer crew +4. Combine everything into a final comprehensive document + +Let's create our flow in the `main.py` file: ```python #!/usr/bin/env python @@ -371,6 +418,18 @@ if __name__ == "__main__": kickoff() ``` +Let's analyze what's happening in this flow: + +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. We use the `@listen()` decorator to establish event-driven relationships between 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. + ## Step 6: Set Up Your Environment Variables Create a `.env` file in your project root with your API keys: @@ -389,30 +448,29 @@ crewai install ## Step 8: Run Your Flow -Now, run your flow using the CrewAI CLI: +Now it's time to see your flow in action! Run it using the CrewAI CLI: ```bash crewai flow kickoff ``` -Your flow will: +When you run this command, you'll see your flow spring to life: +1. It will prompt you for a topic and audience level +2. It will create a structured outline for your guide +3. It will process each section, with the content writer and reviewer collaborating on each +4. Finally, it will compile everything into a comprehensive guide -1. Prompt you for a topic and target audience -2. Make a direct LLM call to create a structured guide outline -3. Process each section in parallel using the content writer crew -4. Combine everything into a final comprehensive guide - -This demonstrates the power of flows to orchestrate different types of operations, including user input, direct LLM interactions, and crew-based processing. +This demonstrates the power of flows to orchestrate complex processes involving multiple components, both AI and non-AI. ## Step 9: Visualize Your Flow -You can also generate a visualization of your flow: +One of the powerful features of flows is the ability to visualize their structure: ```bash crewai flow plot ``` -This will create an HTML file that shows the structure of your flow, which can be helpful for understanding and debugging. +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. ## Step 10: Review the Output @@ -421,6 +479,44 @@ Once the flow completes, you'll find two files in the `output` directory: 1. `guide_outline.json`: Contains the structured outline of the guide 2. `complete_guide.md`: The comprehensive guide with all sections +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. + +## The Art of the Possible: Beyond Your First Flow + +What you've learned in this guide provides a foundation for creating much more sophisticated AI systems. Here are some ways you could extend this basic flow: + +### Enhancing User Interaction + +You could create more interactive flows with: +- Web interfaces for input and output +- Real-time progress updates +- Interactive feedback and refinement loops +- Multi-stage user interactions + +### Adding More Processing Steps + +You could expand your flow with additional steps for: +- Research before outline creation +- Image generation for illustrations +- Code snippet generation for technical guides +- Final quality assurance and fact-checking + +### Creating More Complex Flows + +You could implement more sophisticated flow patterns: +- Conditional branching based on user preferences or content type +- Parallel processing of independent sections +- Iterative refinement loops with feedback +- Integration with external APIs and services + +### Applying to Different Domains + +The same patterns can be applied to create flows for: +- **Interactive storytelling**: Create personalized stories based on user input +- **Business intelligence**: Process data, generate insights, and create reports +- **Product development**: Facilitate ideation, design, and planning +- **Educational systems**: Create personalized learning experiences + ## Key Features Demonstrated This guide creator flow demonstrates several powerful features of CrewAI: @@ -431,98 +527,78 @@ This guide creator flow demonstrates several powerful features of CrewAI: 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 ## Understanding the Flow Structure -Let's break down the key components of this flow: +Let's break down the key components of flows to help you understand how to build your own: ### 1. Direct LLM Calls -The flow uses CrewAI's `LLM` class to make direct calls to the language model: +Flows allow you to make direct calls to language models when you need simple, structured responses: ```python -llm = LLM(model="openai/gpt-4o-mini") -response = llm.call(prompt) +llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline) +response = llm.call(messages=messages) ``` -This is more efficient than using a crew when you need a simple, structured response. +This is more efficient than using a crew when you need a specific, structured output. -### 2. Asynchronous Processing +### 2. Event-Driven Architecture -The flow uses async/await to process multiple sections in parallel: +Flows use decorators to establish relationships between components: ```python -@listen(create_guide_outline) -async def write_sections(self, outline): +@start() +def get_user_input(self): + # First step in the flow # ... - section_tasks = [] - for section in outline.sections: - task = self.write_section(section, outline.target_audience) - section_tasks.append(task) - sections_content = await asyncio.gather(*section_tasks) +@listen(get_user_input) +def create_guide_outline(self, state): + # This runs when get_user_input completes # ... ``` -This significantly speeds up the guide creation process. +This creates a clear, declarative structure for your application. -### 3. Multi-Agent Crews +### 3. State Management -The flow uses a crew with multiple specialized agents: +Flows maintain state across steps, making it easy to share data: ```python -# Content creation crew with writer and reviewer -@agent -def content_writer(self) -> Agent: - return Agent( - config=self.agents_config['content_writer'], - verbose=True - ) - -@agent -def content_reviewer(self) -> Agent: - return Agent( - config=self.agents_config['content_reviewer'], - verbose=True - ) +class GuideCreatorState(BaseModel): + topic: str = "" + audience_level: str = "" + guide_outline: GuideOutline = None + sections_content: Dict[str, str] = {} ``` -This demonstrates how flows can orchestrate crews with multiple specialized agents that work together on complex tasks. +This provides a type-safe way to track and transform data throughout your flow. -### 4. Context-Aware Sequential Processing +### 4. Crew Integration -The flow processes sections in order, providing previous sections as context: +Flows can seamlessly integrate with crews for complex collaborative tasks: ```python -# Getting previous sections for context -previous_sections_text = "" -if self.state.completed_sections: - previous_sections_text = "# Previously Written Sections\n\n" - for title in self.state.completed_sections: - previous_sections_text += f"## {title}\n\n" - previous_sections_text += self.state.sections_content.get(title, "") + "\n\n" +result = ContentCrew().crew().kickoff(inputs={ + "section_title": section.title, + # ... +}) ``` -This ensures coherence and continuity throughout the guide. - -## Customizing Your Flow - -You can customize your flow in several ways: - -1. **Add more user inputs**: Collect additional information about the desired guide -2. **Enhance the outline**: Modify the LLM prompt to create more detailed outlines -3. **Add more crews**: Use different crews for different parts of the guide -4. **Add review steps**: Include a review and refinement step for the final guide +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: -1. Experiment with more complex flow structures -2. Try using `@router()` to create conditional branches +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 or services +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. +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. \ No newline at end of file diff --git a/docs/introduction.mdx b/docs/introduction.mdx index 5d9d5232b..416ead45a 100644 --- a/docs/introduction.mdx +++ b/docs/introduction.mdx @@ -10,8 +10,8 @@ icon: handshake CrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario: -- **CrewAI Crews**: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals. -- **CrewAI Flows**: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively. +- **[CrewAI Crews](/guides/crews/first-crew)**: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals. +- **[CrewAI Flows](/guides/flows/first-flow)**: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively. With over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation. @@ -93,21 +93,21 @@ With over 100,000 developers certified through our community courses, CrewAI is ## When to Use Crews vs. Flows - Understanding when to use Crews versus Flows is key to maximizing the potential of CrewAI in your applications. + Understanding when to use [Crews](/guides/crews/first-crew) versus [Flows](/guides/flows/first-flow) is key to maximizing the potential of CrewAI in your applications. | Use Case | Recommended Approach | Why? | |:---------|:---------------------|:-----| -| **Open-ended research** | Crews | When tasks require creative thinking, exploration, and adaptation | -| **Content generation** | Crews | For collaborative creation of articles, reports, or marketing materials | -| **Decision workflows** | Flows | When you need predictable, auditable decision paths with precise control | -| **API orchestration** | Flows | For reliable integration with multiple external services in a specific sequence | -| **Hybrid applications** | Combined approach | Use Flows to orchestrate overall process with Crews handling complex subtasks | +| **Open-ended research** | [Crews](/guides/crews/first-crew) | When tasks require creative thinking, exploration, and adaptation | +| **Content generation** | [Crews](/guides/crews/first-crew) | For collaborative creation of articles, reports, or marketing materials | +| **Decision workflows** | [Flows](/guides/flows/first-flow) | When you need predictable, auditable decision paths with precise control | +| **API orchestration** | [Flows](/guides/flows/first-flow) | For reliable integration with multiple external services in a specific sequence | +| **Hybrid applications** | Combined approach | Use [Flows](/guides/flows/first-flow) to orchestrate overall process with [Crews](/guides/crews/first-crew) handling complex subtasks | ### Decision Framework -- **Choose Crews when:** You need autonomous problem-solving, creative collaboration, or exploratory tasks -- **Choose Flows when:** You require deterministic outcomes, auditability, or precise control over execution +- **Choose [Crews](/guides/crews/first-crew) when:** You need autonomous problem-solving, creative collaboration, or exploratory tasks +- **Choose [Flows](/guides/flows/first-flow) when:** You require deterministic outcomes, auditability, or precise control over execution - **Combine both when:** Your application needs both structured processes and pockets of autonomous intelligence ## Why Choose CrewAI? diff --git a/docs/mint.json b/docs/mint.json index 5a36dd37d..4b034304e 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -61,6 +61,29 @@ "quickstart" ] }, + { + "group": "Guides", + "pages": [ + { + "group": "Agents", + "pages": [ + "guides/agents/crafting-effective-agents" + ] + }, + { + "group": "Crews", + "pages": [ + "guides/crews/first-crew" + ] + }, + { + "group": "Flows", + "pages": [ + "guides/flows/first-flow" + ] + } + ] + }, { "group": "Core Concepts", "pages": [