CrewAI Tutorial 2026: Build Multi-Agent Systems That Work Together

Create coordinated AI agent teams with CrewAI to tackle complex tasks—research, analysis, content creation—that single agents cannot handle alone

返回教程列表
进阶35 分钟

CrewAI Tutorial 2026: Build Multi-Agent Systems That Work Together

Create coordinated AI agent teams with CrewAI to tackle complex tasks—research, analysis, content creation—that single agents cannot handle alone

Complete tutorial for building multi-agent AI systems using CrewAI in 2026. Covers agent role design, task delegation, crew orchestration, tool integration, and building production workflows where multiple specialized AI agents collaborate on complex tasks.

crewaimulti-agentai-agentlangchainpython

CrewAI Tutorial 2026: Build Multi-Agent Systems That Work Together

Complex tasks often require specialized expertise working in coordination. A research project needs a researcher, analyst, and writer. A software project needs an architect, coder, and reviewer. CrewAI lets you build teams of specialized AI agents that collaborate just like human teams.

What Makes CrewAI Different

CrewAI goes beyond single-agent frameworks by providing:

  • Role-based agents: Each agent has expertise, goals, and backstory
  • Task delegation: Tasks automatically route to the right agent
  • Sequential/parallel execution: Control workflow dependencies
  • Memory sharing: Agents build on each other's outputs
  • Built-in tools: Web search, file I/O, code execution
  • Installation

    bash
    pip install crewai crewai-tools
    

    Core Concepts

    Agents

    Each agent has role, goal, backstory, and optionally tools:

    python
    from crewai import Agent
    from crewai_tools import SerperDevTool, FileReadTool

    Research agent

    researcher = Agent( role='Senior Research Analyst', goal='Find accurate, current information on topics and synthesize insights', backstory="""You are an experienced research analyst with 15 years finding and verifying information across industries. You are known for thoroughness, citing sources, and distinguishing facts from speculation.""", tools=[SerperDevTool()], # Web search capability llm='gpt-4o', verbose=True, memory=True )

    Writer agent

    writer = Agent( role='Expert Content Writer', goal='Transform research into engaging, well-structured content', backstory="""You are a professional writer specializing in technology and business. You excel at making complex topics accessible and creating content that informs and persuades sophisticated audiences.""", llm='claude-3-5-sonnet', verbose=True )

    Critic agent

    critic = Agent( role='Content Quality Reviewer', goal='Ensure accuracy, quality, and completeness of all content', backstory="""You have a rigorous editorial background. You catch factual errors, logical gaps, unsupported claims, and quality issues before publication.""", llm='gpt-4o', verbose=True )

    Tasks

    python
    from crewai import Task

    Research task

    research_task = Task( description="""Research the current state of [TOPIC] in 2026. Find: 1. Latest developments and news (past 3 months) 2. Key players and their positions 3. Statistical data and market size 4. Expert opinions from 3 different perspectives 5. Potential challenges and opportunities Cite all sources with URLs.""", agent=researcher, expected_output="A comprehensive research report with citations, 800-1000 words" )

    Writing task (depends on research)

    writing_task = Task( description="""Using the research provided, write an article on [TOPIC]. Requirements: - Target audience: [DESCRIBE AUDIENCE] - Tone: Professional but accessible - Length: 1500-2000 words - Structure: Introduction, 4 main sections, conclusion - Include: Specific examples, data points, actionable insights - SEO keyword: [TARGET KEYWORD]""", agent=writer, expected_output="A complete, publication-ready article", context=[research_task] # Receives research output as context )

    Review task

    review_task = Task( description="""Review the article and provide feedback: Check for: 1. Factual accuracy (verify against research) 2. Logical flow and structure 3. Unsupported claims 4. Grammar and clarity issues 5. SEO optimization Output: The improved article with your changes, plus a brief changelog.""", agent=critic, expected_output="Final polished article with changelog", context=[research_task, writing_task] )

    Crew

    python
    from crewai import Crew, Process

    Assemble the crew

    article_crew = Crew( agents=[researcher, writer, critic], tasks=[research_task, writing_task, review_task], process=Process.sequential, # Each task waits for previous verbose=True, memory=True # Shared memory across agents )

    Run the crew

    result = article_crew.kickoff(inputs={ 'topic': 'AI-powered customer service automation', 'audience': 'mid-market SaaS founders', 'keyword': 'AI customer service 2026' })

    print(result.raw) # Final output

    Real-World Example: Competitive Intelligence Crew

    python
    from crewai import Agent, Task, Crew, Process
    from crewai_tools import SerperDevTool, ScrapeWebsiteTool

    web_search = SerperDevTool() web_scraper = ScrapeWebsiteTool()

    Specialized agents for competitive intelligence

    data_collector = Agent( role='Competitive Intelligence Data Collector', goal='Gather comprehensive data on competitor companies', backstory='Expert in finding public information about companies: funding, hiring, product changes, PR.', tools=[web_search, web_scraper], llm='gpt-4o' )

    strategic_analyst = Agent( role='Strategic Business Analyst', goal='Analyze competitive landscape and identify strategic implications', backstory='Former McKinsey consultant with expertise in technology market analysis.', llm='claude-3-5-sonnet' )

    report_writer = Agent( role='Executive Report Writer', goal='Create concise, actionable executive reports', backstory='Specialized in writing C-suite ready reports that drive decisions.', llm='gpt-4o' )

    Tasks

    collect_task = Task( description="""For each competitor: {competitors} Collect: - Recent product launches or updates - Pricing changes - New partnerships or integrations - Hiring signals (job postings in strategic areas) - Marketing positioning changes - Funding news Time period: Last 90 days""", agent=data_collector, expected_output="Structured data per competitor with sources" )

    analyze_task = Task( description="""Analyze the collected competitive data. Our company context: {our_company_context} Provide: 1. Competitive threats (immediate vs. long-term) 2. Opportunities to differentiate 3. Market positioning gaps 4. Recommended strategic responses""", agent=strategic_analyst, context=[collect_task] )

    report_task = Task( description="Create a 1-page executive competitive intelligence report. Include: executive summary, key findings table, top 3 action items, and outlook.", agent=report_writer, context=[collect_task, analyze_task], output_file="competitive_report.md" # Auto-saves output )

    Run

    comp_intel_crew = Crew( agents=[data_collector, strategic_analyst, report_writer], tasks=[collect_task, analyze_task, report_task], process=Process.sequential )

    result = comp_intel_crew.kickoff(inputs={ 'competitors': ['Company A', 'Company B', 'Company C'], 'our_company_context': 'B2B SaaS for mid-market retail companies' })

    Parallel Crew Execution

    python
    

    Hierarchical process: manager delegates to agents

    manager = Agent( role='Project Manager', goal='Coordinate the team to complete projects efficiently', llm='gpt-4o', allow_delegation=True # Can assign tasks to other agents )

    parallel_crew = Crew( agents=[manager, researcher, writer, seo_analyst], tasks=[main_task], # Manager breaks it down and delegates process=Process.hierarchical, manager_llm='gpt-4o' )

    Adding Custom Tools

    python
    from crewai_tools import BaseTool
    from typing import Type
    from pydantic import BaseModel, Field

    class DatabaseQueryInput(BaseModel): query: str = Field(description="The SQL query to execute")

    class DatabaseQueryTool(BaseTool): name: str = "Database Query Tool" description: str = "Execute SQL queries against the company database" args_schema: Type[BaseModel] = DatabaseQueryInput def _run(self, query: str) -> str: # Connect to your actual database conn = get_database_connection() result = conn.execute(query).fetchall() return str(result)

    Give to data analyst agent

    data_analyst = Agent( role='Data Analyst', tools=[DatabaseQueryTool()], ... )

    Measuring Crew Performance

    python
    import time

    start = time.time() result = crew.kickoff(inputs=inputs) elapsed = time.time() - start

    print(f"Execution time: {elapsed:.0f}s") print(f"Token usage: {result.token_usage}") print(f"Tasks completed: {len(result.tasks_output)}")

    When to Use Multi-Agent vs Single Agent

    Use Multi-Agent WhenUse Single Agent When

    Task requires different expertiseSimple, focused task Quality review is criticalSpeed is more important Parallel workstreams existSingle domain Research + synthesis + writingOne-step transformation

    Conclusion

    CrewAI excels at knowledge work that humans typically do in teams. The competitive intelligence example above is production-ready—companies run it weekly to track competitor movements. Start with 2-3 agents on well-defined tasks before adding complexity.

    相关工具

    crewaiopenailangchainpython