Search

Saturday, 1 March 2025

CrewAI: A Comprehensive Tutorial for Building AI Agent Teams

#


i am new to crewai. I want you to build a simple to advanced tutorial on how to use crewai with multiple examples in python. i want details of what each command is

CrewAI is a powerful framework that enables the creation of specialized AI agent teams that work together to accomplish complex tasks. This framework represents a significant advancement in the field of AI orchestration, allowing developers to create collaborative systems where multiple AI agents, each with distinct roles and capabilities, can coordinate their efforts through well-defined processes. As of February 2025, CrewAI has become an increasingly popular tool for developers looking to build sophisticated AI systems that leverage the strengths of multiple specialized agents.

Introduction to CrewAI

CrewAI provides a structured approach to creating collaborative AI systems. At its core, CrewAI operates on the principle that complex problems can be more effectively solved by breaking them down into smaller tasks and assigning these tasks to specialized agents. This division of labor allows each agent to focus on what it does best, ultimately producing higher quality results than a single, general-purpose agent might achieve.

The framework is built around four fundamental components: Agents, Tasks, Tools, and Crews. Agents are the individual AI entities with specific roles and expertise. Tasks represent the discrete units of work to be performed. Tools provide agents with capabilities to interact with the external world or perform specific functions. Finally, Crews orchestrate the collaboration between agents, determining how tasks are assigned and executed^1_1.

CrewAI supports different collaboration processes, including sequential workflows where tasks are completed one after another, and hierarchical structures where manager agents coordinate the work of specialized agents. This flexibility makes CrewAI suitable for a wide range of applications, from research and content creation to data analysis and problem-solving scenarios^1_1.

Prerequisites for Using CrewAI

Before diving into CrewAI development, there are several prerequisites to ensure a smooth experience. First, you'll need a Python environment running at least Python 3.10. Many developers use conda environments to manage their Python installations. While basic Python knowledge is essential, no prior experience with CrewAI is required to begin using the framework^1_1.

For accessing language models, CrewAI is typically used with APIs from providers like OpenAI, Groq, Anthropic, Google Gemini, or SambaNova. You'll need to obtain appropriate API keys from your chosen provider. The framework is designed to work with various language models, allowing developers to select the most appropriate model for their specific use case^1_2.

Getting Started with CrewAI

Installation Process

Installing CrewAI is straightforward using pip, Python's package installer. Open your terminal or command prompt and run the following command:

pip install crewai

For additional tools that enhance CrewAI's capabilities, you can also install the crewai-tools package:

pip install crewai-tools

These packages provide the core functionality and additional utilities that will be used throughout this tutorial^1_5.

Basic Components of CrewAI

To understand how CrewAI works, let's examine its four primary components in detail:

Agents

Agents are the cornerstone of any CrewAI system. Each agent represents an AI entity with a specific role, goal, and backstory. Agents can be equipped with tools that extend their capabilities. When defining an agent, you typically specify:

  • A role that describes the agent's function (e.g., "Senior Research Analyst")
  • A goal that outlines what the agent aims to achieve
  • A backstory that provides context and personality to the agent
  • Optional tools that the agent can use to accomplish tasks^1_3

Tasks

Tasks represent the individual work items that agents need to perform. Each task includes:

  • A description of what needs to be done
  • The agent assigned to complete the task
  • Any context or additional information needed for the task
  • Expected output format or success criteria^1_4

Tools

Tools give agents the ability to interact with external systems or perform specific functions. These can range from web search capabilities to data analysis functions or API interactions. CrewAI provides built-in tools and allows developers to create custom tools to extend agent capabilities^1_3.

Crews

A Crew is the orchestrating entity that brings together agents and tasks. It defines how agents collaborate and in what order tasks are executed. When creating a Crew, you specify:

  • The agents that are part of the crew
  • The tasks to be completed
  • The process type (sequential, hierarchical, etc.)
  • Optional parameters like verbosity for debugging^1_1

Your First CrewAI Application

Let's create a simple CrewAI application to demonstrate the framework's core concepts. This example will create a basic research assistant that searches for information and summarizes it.

import os
from crewai import Agent, Task, Crew, Process
from langchain_openai import ChatOpenAI
from crewai_tools import DuckDuckGoSearchRun

# Initialize the search tool
search_tool = DuckDuckGoSearchRun()

# Set up your OpenAI API key
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

# Initialize the language model
llm = ChatOpenAI(model="gpt-4")

# Create the researcher agent
researcher = Agent(
    role="Research Specialist",
    goal="Find accurate and relevant information on given topics",
    backstory="You are an experienced researcher with a talent for finding precise information efficiently.",
    verbose=True,
    llm=llm,
    tools=[search_tool]
)

# Create the writer agent
writer = Agent(
    role="Content Writer",
    goal="Create clear, concise summaries of research findings",
    backstory="You are a skilled writer who excels at synthesizing complex information into readable content.",
    verbose=True,
    llm=llm
)

# Create the research task
research_task = Task(
    description="Research the latest developments in artificial intelligence",
    agent=researcher,
    expected_output="Comprehensive findings on recent AI advancements"
)

# Create the writing task
writing_task = Task(
    description="Create a summary of the research findings on AI developments",
    agent=writer,
    context=[research_task],
    expected_output="A well-structured summary of AI developments"
)

# Create the crew with a sequential process
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    process=Process.sequential,
    verbose=True
)

# Run the crew
result = crew.kickoff()
print(result)

In this example, we've created two agents: a researcher who can search for information using the DuckDuckGo search tool, and a writer who can summarize the research findings. We've defined two tasks: one for research and one for writing. The crew is set up with a sequential process, meaning the research task will be completed before the writing task begins^1_1.

CrewAI Components in Detail

Now that we've seen a basic example, let's explore each component of CrewAI in greater detail.

Agents: The Building Blocks

Agents are the foundation of any CrewAI system. Each agent is defined by its role, goal, and backstory, which together shape how the agent approaches tasks. The role describes the agent's function or position, such as "Data Scientist" or "Marketing Specialist." The goal outlines what the agent aims to achieve, providing direction for its actions. The backstory adds depth and context, influencing the agent's perspective and approach to problem-solving^1_3.

Here's a more detailed example of creating agents:

from crewai import Agent
from langchain_openai import ChatOpenAI

# Initialize the language model
llm = ChatOpenAI(model="gpt-4")

# Create a senior research analyst
senior_researcher = Agent(
    role="Senior Research Analyst",
    goal="Conduct in-depth research on emerging technologies and identify market trends",
    backstory="""You are a veteran research analyst with 15 years of experience in technology research.
    You have a PhD in Computer Science and have published numerous papers on AI and machine learning.
    You're known for your thorough analysis and ability to identify emerging trends before they become mainstream.""",
    verbose=True,
    llm=llm,
    allow_delegation=True
)

# Create a tech content strategist
content_strategist = Agent(
    role="Tech Content Strategist",
    goal="Create engaging and informative content based on research findings",
    backstory="""You are a seasoned content creator specialized in translating complex technical concepts into accessible content.
    With a background in both journalism and computer science, you excel at creating narratives that engage both technical and non-technical audiences.
    Your work has been featured in major tech publications.""",
    verbose=True,
    llm=llm,
    allow_delegation=False
)

In this example, we've created two specialized agents with detailed backstories that inform their approach to tasks. The allow_delegation parameter determines whether an agent can delegate tasks to other agents, which is particularly useful in hierarchical crew processes^1_3.

Tasks: Defining the Work

Tasks represent the specific work items that agents need to complete. Each task includes a description, the agent assigned to complete it, and optionally, context from other tasks and specific tools the agent should use.

Here's an expanded example of task creation:

from crewai import Task

# Create a research task
market_research_task = Task(
    description="""Conduct comprehensive research on the current state of quantum computing.
    Identify key players, recent breakthroughs, market size estimates, and potential applications.
    Focus particularly on developments in the last 6 months.""",
    agent=senior_researcher,
    expected_output="""A detailed report covering:
    1. Current state of quantum computing technology
    2. Key market players and their recent activities
    3. Significant breakthroughs in the last 6 months
    4. Market size estimates and growth projections
    5. Potential commercial applications emerging in the near term""",
    tools=[search_tool]
)

# Create a content creation task that depends on the research
content_creation_task = Task(
    description="""Create an engaging blog post based on the quantum computing research findings.
    The blog should be accessible to a technical audience with some background in computing but not necessarily in quantum physics.
    Include practical implications for businesses in the technology sector.""",
    agent=content_strategist,
    context=[market_research_task],
    expected_output="""A 1500-word blog post with:
    - An attention-grabbing introduction
    - Clear explanations of key quantum computing concepts
    - Discussion of recent breakthroughs
    - Analysis of business implications
    - Forward-looking conclusion with insights on industry direction"""
)

In this example, the content creation task includes the market research task in its context, meaning the content strategist will have access to the research findings when creating the blog post. We've also specified detailed expected outputs to guide the agents in producing the desired results^1_3.

Tools: Extending Agent Capabilities

Tools provide agents with the ability to interact with external systems or perform specific functions. CrewAI offers built-in tools through the crewai-tools package and allows developers to create custom tools as needed.

Here's an example of creating and using custom tools:

from crewai import Agent, Task
from crewai_tools import SerperDevTool
import requests

# Initialize a search tool using SerperDev
search_tool = SerperDevTool()

# Create a custom tool for weather data
def get_weather(location):
    """
    Gets the current weather for a specified location.

    Args:
        location (str): The city and optionally state/country

    Returns:
        str: A description of the current weather
    """
    api_key = "your-weather-api-key"
    base_url = "https://api.weatherapi.com/v1/current.json"

    params = {
        "key": api_key,
        "q": location,
        "aqi": "no"
    }

    response = requests.get(base_url, params=params)

    if response.status_code == 200:
        data = response.json()
        temp_c = data["current"]["temp_c"]
        temp_f = data["current"]["temp_f"]
        condition = data["current"]["condition"]["text"]

        return f"Current weather in {location}: {condition}, {temp_c}°C ({temp_f}°F)"
    else:
        return f"Error fetching weather data: {response.status_code}"

# Create a researcher agent with both tools
weather_researcher = Agent(
    role="Weather Analyst",
    goal="Provide accurate weather information and related insights",
    backstory="You are a meteorologist with expertise in analyzing weather patterns and their implications.",
    verbose=True,
    llm=ChatOpenAI(model="gpt-4"),
    tools=[search_tool, get_weather]
)

# Create a task that uses the weather tool
weather_analysis_task = Task(
    description="Research the current weather in Tokyo and analyze how it compares to seasonal norms.",
    agent=weather_researcher,
    expected_output="A comprehensive weather report for Tokyo with historical context"
)

In this example, we've created a custom weather tool using Python's requests library and integrated it alongside the SerperDev search tool. The weather analyst agent can use both tools to complete the weather analysis task^1_3.

Crews: Orchestrating Collaboration

Crews are the orchestrating entities that bring together agents and tasks. CrewAI supports different collaboration processes, including sequential, where tasks are completed in order, and hierarchical, where a manager agent coordinates the work of other agents.

Let's explore these different processes:

from crewai import Crew, Process
from langchain_openai import ChatOpenAI

# Create a sequential crew
sequential_crew = Crew(
    agents=[senior_researcher, content_strategist],
    tasks=[market_research_task, content_creation_task],
    process=Process.sequential,
    verbose=True
)

# Create a hierarchical crew with a manager
manager_llm = ChatOpenAI(model="gpt-4")

hierarchical_crew = Crew(
    agents=[senior_researcher, content_strategist],
    tasks=[market_research_task, content_creation_task],
    process=Process.hierarchical,
    manager_llm=manager_llm,
    verbose=True
)

# Run the crews
sequential_result = sequential_crew.kickoff()
hierarchical_result = hierarchical_crew.kickoff()

print("Sequential Result:", sequential_result)
print("Hierarchical Result:", hierarchical_result)

In the sequential process, tasks are completed in the order they are defined. In the hierarchical process, a manager (powered by the specified manager_llm) coordinates the work, potentially reassigning tasks or modifying the workflow based on interim results. The hierarchical process can be more adaptable but requires a capable language model for the manager role^1_1.

Advanced CrewAI Examples

Now that we understand the core components of CrewAI, let's build more advanced examples to demonstrate the framework's capabilities.

Example 1: Meeting Preparation Crew

This example creates a crew that helps prepare for an important meeting by researching the meeting topic, gathering information about participants, and creating a briefing document.

import os
from crewai import Agent, Task, Crew, Process
from langchain_openai import ChatOpenAI
from crewai_tools import DuckDuckGoSearchRun, WikipediaSearchRun

# Initialize tools
search_tool = DuckDuckGoSearchRun()
wiki_tool = WikipediaSearchRun()

# Set up language model
llm = ChatOpenAI(model="gpt-4")

# Create specialized agents
topic_researcher = Agent(
    role="Topic Research Specialist",
    goal="Research comprehensive information on meeting topics",
    backstory="""You are an expert researcher who specializes in quickly gathering and synthesizing 
    information on any topic. You're known for your ability to identify key points and emerging trends.""",
    verbose=True,
    llm=llm,
    tools=[search_tool, wiki_tool]
)

people_researcher = Agent(
    role="People Intelligence Analyst",
    goal="Gather relevant information about meeting participants",
    backstory="""You specialize in researching professional backgrounds and recent activities
    of business professionals and organizations. You focus on public information that would
    be relevant in a business context.""",
    verbose=True,
    llm=llm,
    tools=[search_tool]
)

briefing_writer = Agent(
    role="Executive Briefing Specialist",
    goal="Create concise, actionable briefing documents",
    backstory="""You are an experienced communication professional who excels at creating
    clear, concise briefing documents for executives. You know how to highlight the most
    important information and provide actionable insights.""",
    verbose=True,
    llm=llm
)

# Define tasks with a meeting context
meeting_info = {
    "topic": "Renewable Energy Investments",
    "participants": ["Jane Smith, CEO of GreenTech Innovations", "Michael Chen, Investment Director at Future Fund"],
    "meeting_date": "March 15, 2025"
}

# Create tasks
topic_research_task = Task(
    description=f"""Research the latest developments in {meeting_info['topic']}.
    Focus on market trends, recent major investments, regulatory changes, and technological breakthroughs.
    Identify key points that would be relevant for an investment discussion.""",
    agent=topic_researcher,
    expected_output="A comprehensive research brief on renewable energy investments"
)

participant_research_task = Task(
    description=f"""Research the professional backgrounds and recent activities of these participants:
    {meeting_info['participants']}.
    For each person, identify their career history, recent professional announcements or achievements,
    stated positions on renewable energy, and any relevant connections or collaborations.""",
    agent=people_researcher,
    expected_output="Detailed profiles of each meeting participant with relevant insights"
)

briefing_creation_task = Task(
    description=f"""Create a comprehensive briefing document for a meeting on {meeting_info['topic']} with
    {', '.join(meeting_info['participants'])} scheduled for {meeting_info['meeting_date']}.
    The briefing should include:
    1. An executive summary
    2. Key points about the topic
    3. Relevant information about each participant
    4. Suggested talking points
    5. Potential areas of mutual interest
    Use the research provided by the other agents to inform this briefing.""",
    agent=briefing_writer,
    context=[topic_research_task, participant_research_task],
    expected_output="A complete meeting briefing document in a professional format"
)

# Create the crew
meeting_prep_crew = Crew(
    agents=[topic_researcher, people_researcher, briefing_writer],
    tasks=[topic_research_task, participant_research_task, briefing_creation_task],
    process=Process.sequential,
    verbose=True
)

# Run the crew
briefing = meeting_prep_crew.kickoff()
print(briefing)

This example demonstrates how CrewAI can be used for complex workflows involving multiple specialized agents. The topic researcher and people researcher gather different types of information, which the briefing writer then synthesizes into a comprehensive document. The sequential process ensures that the briefing creation task has access to the results of both research tasks^1_1.

Example 2: Market Analysis Crew with Hierarchical Process

This example creates a market analysis crew using a hierarchical process, where a manager agent coordinates the work of specialized analysts.

import os
from crewai import Agent, Task, Crew, Process
from langchain_openai import ChatOpenAI
from crewai_tools import DuckDuckGoSearchRun, SerperDevTool

# Initialize tools
search_tool = DuckDuckGoSearchRun()
serper_tool = SerperDevTool()

# Set up language model
llm = ChatOpenAI(model="gpt-4")
manager_llm = ChatOpenAI(model="gpt-4")

# Create specialized agents
industry_analyst = Agent(
    role="Industry Analyst",
    goal="Analyze industry trends and competitive landscape",
    backstory="""You are an experienced industry analyst with deep expertise in market dynamics
    and competitive analysis. You excel at identifying trends and understanding the forces
    shaping different industries.""",
    verbose=True,
    llm=llm,
    tools=[search_tool, serper_tool]
)

financial_analyst = Agent(
    role="Financial Analyst",
    goal="Analyze financial data and investment opportunities",
    backstory="""You are a sharp financial analyst with expertise in evaluating company financials,
    market valuations, and investment potential. You have a strong background in financial modeling.""",
    verbose=True,
    llm=llm,
    tools=[search_tool]
)

consumer_insights_analyst = Agent(
    role="Consumer Insights Specialist",
    goal="Understand consumer behavior and preferences",
    backstory="""You specialize in analyzing consumer trends, preferences, and behaviors.
    You have expertise in interpreting consumer data and identifying emerging patterns in how
    people interact with products and services.""",
    verbose=True,
    llm=llm,
    tools=[search_tool]
)

report_writer = Agent(
    role="Market Report Writer",
    goal="Create comprehensive market analysis reports",
    backstory="""You are a skilled writer who specializes in creating clear, insightful market analysis
    reports. You excel at synthesizing complex information from multiple sources into coherent narratives.""",
    verbose=True,
    llm=llm
)

# Define the market to analyze
market_to_analyze = "Electric Vehicles in Europe"

# Create tasks
industry_analysis_task = Task(
    description=f"""Conduct a comprehensive industry analysis of the {market_to_analyze} market.
    Include:
    - Current market size and growth projections
    - Key players and their market shares
    - Recent mergers, acquisitions, and partnerships
    - Regulatory environment and upcoming policy changes
    - Technological trends and innovations""",
    agent=industry_analyst,
    expected_output="A detailed industry analysis report with quantitative and qualitative insights"
)

financial_analysis_task = Task(
    description=f"""Perform financial analysis of major companies in the {market_to_analyze} market.
    Include:
    - Valuation metrics for key players
    - Profitability analysis
    - Investment trends and major funding rounds
    - Risk assessment
    - Growth opportunities from a financial perspective""",
    agent=financial_analyst,
    expected_output="A comprehensive financial analysis with key metrics and investment insights"
)

consumer_analysis_task = Task(
    description=f"""Analyze consumer behavior and preferences in the {market_to_analyze} market.
    Include:
    - Demographic profiles of current and potential customers
    - Key purchasing factors and decision drivers
    - Consumer pain points and unmet needs
    - Emerging trends in consumer preferences
    - Brand perception and loyalty factors""",
    agent=consumer_insights_analyst,
    expected_output="An in-depth consumer analysis with segmentation and behavioral insights"
)

report_creation_task = Task(
    description=f"""Create a comprehensive market analysis report for the {market_to_analyze} market.
    Synthesize the industry analysis, financial analysis, and consumer insights into a cohesive report.
    The report should provide a holistic view of the market with actionable insights.""",
    agent=report_writer,
    context=[industry_analysis_task, financial_analysis_task, consumer_analysis_task],
    expected_output="A complete market analysis report with executive summary, key findings, and strategic recommendations"
)

# Create the crew with hierarchical process
market_analysis_crew = Crew(
    agents=[industry_analyst, financial_analyst, consumer_insights_analyst, report_writer],
    tasks=[industry_analysis_task, financial_analysis_task, consumer_analysis_task, report_creation_task],
    process=Process.hierarchical,
    manager_llm=manager_llm,
    verbose=True
)

# Run the crew
market_report = market_analysis_crew.kickoff()
print(market_report)

This example demonstrates the use of a hierarchical process, where the manager (powered by manager_llm) coordinates the work of the specialized analysts. The hierarchical approach allows for more dynamic task allocation and can adapt if one analysis reveals information that should influence the direction of another analysis^1_1.

CrewAI CLI Commands

CrewAI provides a command-line interface (CLI) for interacting with crews and flows. The CLI offers commands for creating, running, testing, and managing CrewAI projects. Here's a detailed breakdown of the available commands:

Creating a New Crew or Flow

The create command allows you to create a new crew or flow project with the basic structure already set up:

crewai create crew my_new_crew

This command creates a new crew project named my_new_crew with the necessary directory structure and template files. Similarly, you can create a flow project:

crewai create flow my_new_flow

When running the create command, the CLI will prompt you to select an LLM provider and enter your API key. The supported providers include OpenAI, Groq, Anthropic, Google Gemini, and SambaNova, among others^1_2.

Running a Crew

The run command executes the crew defined in your project:

crewai run

This command looks for a crew definition in your project and runs it with the default configuration. Make sure to execute this command from your project's root directory^1_2.

Chatting with Your Crew

The chat command starts an interactive session with your crew:

crewai chat

This command launches a chat interface where you can interact with your crew. An AI assistant will guide you through providing necessary inputs, and you can continue the conversation after receiving results. To use this command, you need to set the chat_llm property in your crew definition:

@crew
def crew(self) -> Crew:
    return Crew(
        agents=self.agents,
        tasks=self.tasks,
        process=Process.sequential,
        verbose=True,
        chat_llm="gpt-4o"  # LLM for chat orchestration
    )

Training a Crew

The train command allows you to train your crew for a specified number of iterations:

crewai train -n 10 -f my_training_data.pkl

This command trains the crew for 10 iterations and saves the training data to my_training_data.pkl. The -n parameter specifies the number of iterations (default is 5), and the -f parameter specifies the file to save the training data to (default is trained_agents_data.pkl)^1_2.

Testing a Crew

The test command runs tests on your crew and evaluates the results:

crewai test -n 5 -m gpt-3.5-turbo

This command tests the crew for 5 iterations using the GPT-3.5 Turbo model. The -n parameter specifies the number of iterations (default is 3), and the -m parameter specifies the model to use for testing (default is gpt-4o-mini)^1_2.

Replaying Crew Execution

The replay command allows you to replay the crew execution from a specific task:

crewai replay -t task_123456

This command replays the crew execution from the task with ID task_123456, including all subsequent tasks. This can be useful for debugging or for picking up where a previous execution left off^1_2.

Logging Task Outputs

The log-tasks-outputs command retrieves the outputs of the most recent crew execution:

crewai log-tasks-outputs

This command displays the outputs of all tasks from the latest crew execution, which can be helpful for reviewing results or debugging issues^1_2.

Resetting Memories

The reset-memories command allows you to reset different types of crew memories:

crewai reset-memories --long --short

This command resets both long-term and short-term memories. You can specify different memory types to reset:

  • -l, --long: Reset long-term memory
  • -s, --short: Reset short-term memory
  • -e, --entities: Reset entities memory
  • -k, --kickoff-outputs: Reset latest kickoff task outputs
  • -a, --all: Reset all memories

Resetting memories can be useful when starting a new session or when troubleshooting issues related to contextual information^1_2.

Checking CrewAI Version

The version command displays the installed version of CrewAI:

crewai version

You can also check the version of installed CrewAI tools:

crewai version --tools

This information can be helpful when troubleshooting issues or ensuring compatibility with examples and documentation^1_2.

CrewAI Best Practices and Advanced Techniques

As you become more familiar with CrewAI, consider these best practices and advanced techniques to maximize the effectiveness of your crews:

Designing Effective Agents

When creating agents, be specific about their roles, goals, and backstories. The more detailed and specialized these elements are, the more effectively the agent can perform its assigned tasks. Consider the agent's expertise, perspective, and limitations when defining its characteristics.

For example, instead of creating a generic "Researcher" agent, create a "Quantum Computing Research Specialist" with a background in physics and a goal to identify emerging applications in specific industries. This specificity helps the agent generate more relevant and insightful outputs.

Structuring Tasks for Optimal Results

Break complex problems into smaller, manageable tasks with clear descriptions and expected outputs. Consider the dependencies between tasks and structure them accordingly. For sequential processes, order tasks so that each builds on the information gathered in previous steps.

Provide sufficient context in task descriptions, including any constraints, priorities, or specific requirements. The expected output field is particularly important for guiding the agent toward producing the desired result.

Choosing the Right Process

The choice between sequential and hierarchical processes depends on the nature of your project:

  • Use sequential processes for linear workflows where tasks have clear dependencies.
  • Use hierarchical processes for complex projects that may require adaptive task allocation or where the optimal workflow isn't known in advance.

In hierarchical processes, the manager LLM plays a crucial role in coordinating the work. Choose a capable model for this role to ensure effective management of the crew.

Implementing Custom Tools

Create custom tools to extend your agents' capabilities and connect them to external systems. Tools can range from simple API calls to complex data processing functions. When designing tools, consider:

  • Input validation to ensure agents provide the necessary parameters
  • Error handling to gracefully manage failed operations
  • Clear documentation to help agents understand how to use the tool
  • Rate limiting and caching for tools that interact with external APIs

Here's an example of a more sophisticated custom tool implementation:

from typing import List
import requests
from crewai.tools import BaseTool

class StockPriceTool(BaseTool):
    name: str = "Stock Price Tool"
    description: str = "Get historical and current stock price information"

    def _run(self, ticker: str, timeframe: str = "1d") -> str:
        """
        Get stock price information for a given ticker.

        Args:
            ticker (str): The stock ticker symbol (e.g., AAPL, MSFT)
            timeframe (str): The timeframe for historical data (1d, 5d, 1mo, 3mo, 6mo, 1y, 5y)

        Returns:
            str: Stock price information in a readable format
        """
        try:
            # Validate inputs
            ticker = ticker.strip().upper()
            if not ticker:
                return "Error: Please provide a valid ticker symbol."

            valid_timeframes = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "5y"]
            if timeframe not in valid_timeframes:
                return f"Error: Timeframe must be one of {', '.join(valid_timeframes)}"

            # Make API request
            api_key = "your-api-key-here"
            base_url = "https://financialmodelingprep.com/api/v3"

            # Get current price
            current_url = f"{base_url}/quote/{ticker}?apikey={api_key}"
            current_response = requests.get(current_url)

            if current_response.status_code != 200:
                return f"Error fetching data: {current_response.status_code}"

            current_data = current_response.json()

            if not current_data:
                return f"No data found for ticker {ticker}"

            # Get historical data
            historical_url = f"{base_url}/historical-price-full/{ticker}?timeseries=5&apikey={api_key}"
            historical_response = requests.get(historical_url)

            if historical_response.status_code != 200:
                return f"Error fetching historical data: {historical_response.status_code}"

            historical_data = historical_response.json()

            # Format response
            result = f"Stock information for {ticker}:\n\n"
            result += f"Current price: ${current_data[^1_0]['price']:.2f}\n"
            result += f"Change: {current_data[^1_0]['change']:.2f} ({current_data[^1_0]['changesPercentage']:.2f}%)\n"
            result += f"Market Cap: ${current_data[^1_0]['marketCap']:,.2f}\n"
            result += f"52-week range: ${current_data[^1_0]['yearLow']:.2f} - ${current_data[^1_0]['yearHigh']:.2f}\n\n"

            result += "Recent price history:\n"
            for i, day in enumerate(historical_data['historical'][:5]):
                result += f"{day['date']}: Open ${day['open']:.2f}, Close ${day['close']:.2f}, Volume {day['volume']:,}\n"

            return result

        except Exception as e:
            return f"Error processing request: {str(e)}"

This tool fetches both current and historical stock price information, performs input validation, handles errors, and formats the output in a readable format. By implementing tools like this, you can significantly enhance your agents' capabilities^1_3.

Conclusion

CrewAI represents a significant advancement in the field of AI orchestration, enabling developers to create collaborative systems of specialized agents that can tackle complex problems more effectively than single agents. By breaking down complex tasks into manageable components and assigning them to specialized agents, CrewAI leverages the strengths of different AI models and approaches.

Throughout this tutorial, we've explored the fundamental components of CrewAI, including agents, tasks, tools, and crews. We've examined different collaboration processes, from sequential to hierarchical, and built progressively more complex examples to demonstrate the framework's capabilities. We've also covered the CLI commands available for creating, running, and managing CrewAI projects.

As the field of AI continues to evolve, frameworks like CrewAI will likely play an increasingly important role in building sophisticated AI systems that can solve real-world problems. By understanding and applying the concepts covered in this tutorial, you'll be well-equipped to leverage CrewAI's capabilities and create powerful AI agent teams for a wide range of applications.

Whether you're building a research assistant, a content creation system, or a complex data analysis pipeline, CrewAI provides the foundation for orchestrating collaborative AI workflows. As you gain experience with the framework, you'll discover new ways to combine agents, tasks, and tools to solve increasingly complex problems.


Sunday, 16 February 2025

0037 - Reorder Linked List

0037_Reorder Linked List