Wednesday, December 02, 2026

Building an Autonomous Drone Inspection System with Multi-Agent AI and the Blackboard Pattern

 



Introduction

Imagine you are managing a fleet of drones tasked with inspecting hundreds of miles of power lines, bridges, and solar farms. Coordinating these drones manually would be overwhelming. You would need to constantly decide which drone goes where, monitor battery levels, reassign tasks when drones need charging, and ensure no area gets inspected twice. This is exactly the kind of problem that multi-agent AI systems excel at solving.

In this tutorial, we are going to build something genuinely exciting: an autonomous drone inspection system where AI agents work together to coordinate a fleet of drones without human micromanagement. You will define a high-level mission like "inspect all bridges in the northern district," and the system will figure out the rest. The system will break down the mission, assign tasks to drones, manage battery levels, and even coordinate multiple drones for complex inspections.

What makes this particularly interesting is that we are not just building a single AI. We are creating a team of AI agents that communicate and collaborate through a shared "Blackboard." Think of it as a smart bulletin board where agents post tasks, claim work, and share discoveries. This architectural pattern has been used in everything from NASA's mission control systems to modern smart city infrastructure.

By the end of this tutorial, you will have a working system that demonstrates some truly fascinating emergent behavior. You will watch as drones autonomously decide when to charge, which tasks to prioritize, and how to collaborate. All of this happens without explicit programming for every scenario.

What is Agentic AI? And Why Should You Care?

Before we dive into code, let's talk about what makes this different from traditional software.

You have probably written plenty of code that follows if-then-else logic: "If battery is low, then return to base." That works fine for simple scenarios, but what happens when you have five drones, twenty tasks, varying priorities, changing weather conditions, and constantly shifting battery levels? The number of possible states explodes, and hardcoding rules for every scenario becomes impossible.

This is where agentic AI comes in. Instead of programming explicit rules for every situation, we create agents that can reason about their goals, make autonomous decisions, adapt to changing conditions, and collaborate without explicit coordination code.

Think of it this way: traditional programming is like giving someone a detailed recipe, while agentic AI is like hiring a skilled chef who understands cooking principles and can adapt to what ingredients are available.

An agentic AI system has several key characteristics. First, it can reason about its goals. A drone agent does not just follow rules. It understands that its goal is to complete inspections while maintaining operational safety. Second, it makes autonomous decisions. When faced with multiple available tasks, the agent evaluates which one makes the most sense given its current battery, location, and the task priorities. Third, it adapts to changing conditions. If a high-priority task appears while a drone is traveling to a low-priority one, the agent can decide whether to change course. Fourth, it collaborates without explicit coordination code. Multiple drones can work on related tasks without us having to program every possible collaboration scenario.

The Big Picture: What We Are Building

Let's walk through what our system does from a user's perspective, then we will dive into how it works.

You open the mission control interface and type: "Inspect all solar panels in Grid Section A5. We had a hailstorm last night and need to check for damage."

Behind the scenes, here is what happens step by step.

First, an Orchestrator Agent powered by a large language model reads your mission and thinks about it. It considers the geographic area, breaks it into manageable zones, estimates how long each inspection will take, and creates a prioritized list of specific tasks.

Second, these tasks get posted to a Blackboard. This is a shared knowledge space that all agents can read and write to. Each task has details like GPS coordinates, what type of infrastructure to inspect, priority level, and estimated duration.

Third, your fleet of Worker Drone Agents are continuously monitoring the Blackboard. Each drone is running its own AI that is thinking: "What is my battery level? Where am I? What tasks are available? Which one should I take?"

Fourth, a drone with eighty percent battery that is already near Grid Section A5 sees a high-priority task and claims it. The Blackboard updates to show that task is now "claimed," so other drones will not duplicate the work.

Fifth, the drone flies to the location, performs the inspection, and uploads photos and sensor data back to the Blackboard, marking the task complete.

Sixth, meanwhile, another drone with twenty-five percent battery sees that it is running low. Even though there are tasks available, its agent decides the smart move is to return to base and charge. It updates its status on the Blackboard so the system knows it is temporarily unavailable.

Seventh, as tasks get completed, you can watch a real-time dashboard showing drone locations, battery levels, tasks in progress, and completed inspections.

The beautiful part? You never told any drone specifically what to do. You just described the mission, and the multi-agent system figured out how to execute it efficiently.

The Blackboard Pattern: Your Agents' Communication Hub

Before we start coding, let's understand the Blackboard pattern, because it is the backbone of how our agents coordinate.

Imagine you are working on a complex project with a team. One way to coordinate would be for everyone to constantly talk to each other: "Hey Sarah, what are you working on? Hey John, did you finish that task? Hey Maria, can you help me with this?" This gets chaotic fast.

A better approach? Put up a big whiteboard in the office where people can post tasks that need doing, write their name next to tasks they are working on, share information they have discovered, and check what everyone else is doing.

This is exactly what the Blackboard pattern does for AI agents. It is a centralized, shared data structure where the Orchestrator posts tasks that need to be done, drones claim tasks by updating the Blackboard, drones post their current status including location, battery, and what they are doing, and completed inspection data gets stored for human review.

The key insight is that agents do not need to know about each other directly. A drone does not need to ask other drones what they are doing. It just checks the Blackboard. This makes the system incredibly scalable. Whether you have three drones or three hundred, the pattern works the same way.

Setting Up Your Development Environment

Let's get your environment ready. We will need a few Python packages that provide the AI and agent frameworks we are building on.

Open your terminal and run the following command:

pip install -U langchain-openai langchain-ollama langchain-community crewai crewai-tools

Let me explain what these packages do. CrewAI is a framework specifically designed for building teams of AI agents. It handles a lot of the complexity of agent coordination, tool usage, and task delegation. LangChain provides integrations with various language models, both cloud-based like OpenAI and local ones like Ollama.

Our Orchestrator Agent needs a language model to understand missions and plan task decompositions. You have two options.

Option one is to use OpenAI, which is the easiest to get started with. If you have an OpenAI API key, you can use GPT-4 or GPT-3.5. Just set your environment variable like this:

export OPENAI_API_KEY='your-api-key-here'

Option two is to use Ollama, which is free and runs locally. If you want to run everything locally without API costs, install Ollama from https://ollama.ai, then run:

ollama pull llama3.2

This downloads a capable open-source language model to your machine. It is completely free and your data never leaves your computer.

For this tutorial, I will show you how to configure the system to work with either option, so choose whichever fits your needs.

Building the Foundation: Configuration and Data Models

Every good system starts with clear data structures. We need to define what a "task" looks like, what information we track about each drone, and how we configure the system.

Let's start with the imports and basic setup:

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from datetime import datetime
from enum import Enum
import json
from uuid import uuid4
import logging
import threading
import time
import random
import math

# Set up logging so we can see what is happening
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

Now let's define our configuration enums. These let us specify what kind of LLM backend we are using:

class LLMBackend(Enum):
    """Which language model backend are we using?"""
    OPENAI = "openai"
    OLLAMA = "ollama"

class GPUArchitecture(Enum):
    """What hardware are we running on? This matters for local models."""
    NVIDIA = "nvidia"
    AMD = "amd"
    APPLE_SILICON = "apple_silicon"
    CPU_ONLY = "cpu"

class DroneState(Enum):
    """All possible states a drone can be in"""
    IDLE = "idle"
    TRAVELING = "traveling"
    INSPECTING = "inspecting"
    RETURNING = "returning"
    CHARGING = "charging"
    OFFLINE = "offline"

The DroneState enum defines all possible states a drone can be in. The IDLE state means the drone is sitting at base and ready for work. The TRAVELING state means the drone is flying to a task location. The INSPECTING state means the drone is actively performing an inspection. The RETURNING state means the drone is flying back to base. The CHARGING state means the drone is plugged in and charging. The OFFLINE state means the drone is not operational.

Now here is our LLM configuration. This tells the system how to connect to whichever language model you are using:

@dataclass
class LLMConfig:
    """Configuration for our language model"""
    backend: LLMBackend
    model_name: str
    temperature: float = 0.7
    max_tokens: int = 2000
    api_key: Optional[str] = None
    base_url: Optional[str] = None
    gpu_architecture: GPUArchitecture = GPUArchitecture.CPU_ONLY
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for easy serialization"""
        return {
            'backend': self.backend.value,
            'model_name': self.model_name,
            'temperature': self.temperature,
            'max_tokens': self.max_tokens,
            'gpu_architecture': self.gpu_architecture.value
        }

The LLMConfig class contains several important fields. The backend field specifies whether we are using OpenAI or Ollama. The model_name field specifies which specific model to use, such as "gpt-4" or "llama3.2". The temperature field controls how creative the model should be, where zero means focused and deterministic, and one means creative and varied. The max_tokens field limits the maximum length of model responses. The api_key field stores the API key for cloud services. The base_url field allows you to specify a custom URL if using a self-hosted model. The gpu_architecture field specifies what hardware we are running on, which matters for local models.

Next, let's define the system-wide configuration. These are the operational parameters that govern how drones behave:

@dataclass
class SystemConfig:
    """Global settings for the entire drone fleet"""
    llm_config: LLMConfig
    max_drones: int = 5
    battery_critical_threshold: float = 20.0
    battery_low_threshold: float = 30.0
    max_flight_time_minutes: float = 25.0
    charging_rate_percent_per_second: float = 1.0
    inspection_time_per_task_seconds: float = 10.0

The SystemConfig class defines global settings for the entire drone fleet. The llm_config field contains the language model configuration. The max_drones field specifies how many drones are in our fleet. The battery_critical_threshold field defines the battery percentage below which a drone MUST return to base. The battery_low_threshold field defines the battery percentage below which a drone SHOULD consider returning to base. The max_flight_time_minutes field specifies the maximum flight time per battery charge. The charging_rate_percent_per_second field specifies how fast batteries charge. The inspection_time_per_task_seconds field specifies how long an inspection takes.

Now for the really important data structures. These define what a task looks like and what information we track about each drone:

@dataclass
class InspectionTask:
    """
    Represents a single inspection task.
    This is what gets posted to the Blackboard for drones to claim.
    """
    task_id: str
    area_coordinates: Dict[str, float]
    infrastructure_type: str
    priority: int
    estimated_duration_minutes: float
    status: str = "pending"
    claimed_by: Optional[str] = None
    created_at: datetime = field(default_factory=datetime.now)
    parent_task_id: Optional[str] = None
    inspection_data: Optional[Dict[str, Any]] = None
    collaboration_id: Optional[str] = None
    collaboration_role: Optional[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert task to dictionary for logging and storage"""
        return {
            'task_id': self.task_id,
            'area_coordinates': self.area_coordinates,
            'infrastructure_type': self.infrastructure_type,
            'priority': self.priority,
            'estimated_duration_minutes': self.estimated_duration_minutes,
            'status': self.status,
            'claimed_by': self.claimed_by,
            'created_at': self.created_at.isoformat() if isinstance(self.created_at, datetime) else str(self.created_at),
            'parent_task_id': self.parent_task_id,
            'collaboration_id': self.collaboration_id,
            'collaboration_role': self.collaboration_role
        }

The InspectionTask class represents a single inspection task. The task_id field is a unique identifier for the task. The area_coordinates field contains GPS coordinates in the format like latitude forty point seven and longitude minus seventy-four point zero. The infrastructure_type field specifies what we are inspecting, such as "bridge", "power_line", or "solar_panel". The priority field is a number from one to ten, where higher numbers indicate more urgent tasks. The estimated_duration_minutes field specifies how long the task will take. The status field can be "pending", "claimed", "in_progress", or "completed". The claimed_by field indicates which drone claimed this task. The created_at field records when the task was created. The parent_task_id field is used if this is a subtask of a larger mission. The inspection_data field stores the results after completion. The collaboration_id field is used for multi-drone tasks. The collaboration_role field specifies roles like "primary" or "observer_1".

@dataclass
class DroneStatus:
    """
    Current status of a drone.
    Drones continuously update this on the Blackboard so other agents know what they are doing.
    """
    drone_id: str
    state: DroneState
    battery_level: float
    current_location: Dict[str, float]
    assigned_task_id: Optional[str] = None
    last_update: datetime = field(default_factory=datetime.now)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert status to dictionary for logging and display"""
        return {
            'drone_id': self.drone_id,
            'state': self.state.value,
            'battery_level': self.battery_level,
            'current_location': self.current_location,
            'assigned_task_id': self.assigned_task_id,
            'last_update': self.last_update.isoformat() if isinstance(self.last_update, datetime) else str(self.last_update)
        }

The DroneStatus class tracks the current status of a drone. The drone_id field is a unique drone identifier. The state field indicates the current state using the DroneState enum, such as idle, traveling, or inspecting. The battery_level field is the current battery percentage from zero to one hundred. The current_location field contains the current GPS coordinates. The assigned_task_id field indicates what task this drone is working on. The last_update field records when this status was last updated.

Why use the dataclass decorator? Python's dataclass decorator automatically generates useful methods like init, repr, and eq for us. It is perfect for these data-holding classes because it reduces boilerplate and makes the code much more readable.

Why use field with default_factory equals datetime.now? This is a subtle but important Python detail. If we wrote created_at colon datetime equals datetime.now(), the timestamp would be set once when the class is defined, and every task would have the same timestamp. By using default_factory equals datetime.now, we are telling Python to call datetime.now() each time a new task is created, giving each task its own unique timestamp.

Utility Functions: The Math Behind Drone Navigation

Before we build the Blackboard, we need some utility functions for calculating distances and estimating flight times. Drones need to know "how far is that task from me?" and "do I have enough battery to get there and back?"

def calculate_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """
    Calculate the distance between two GPS coordinates using the Haversine formula.
    
    The Haversine formula accounts for the spherical shape of the Earth.
    It is more accurate than simple Pythagorean distance, especially over longer distances.
    
    Returns: Distance in kilometers
    """
    R = 6371  # Earth's radius in kilometers
    
    # Convert latitude and longitude from degrees to radians
    lat1_rad = math.radians(lat1)
    lat2_rad = math.radians(lat2)
    delta_lat = math.radians(lat2 - lat1)
    delta_lon = math.radians(lon2 - lon1)
    
    # Haversine formula
    a = (math.sin(delta_lat/2)**2 + 
         math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(delta_lon/2)**2)
    c = 2 * math.asin(math.sqrt(a))
    
    return R * c

def estimate_flight_time(distance_km: float, speed_kmh: float = 50.0) -> float:
    """
    Estimate how long it will take to fly a given distance.
    
    We assume an average drone speed of 50 km/h, but this can be adjusted
    based on your specific drone models and wind conditions.
    
    Returns: Flight time in minutes
    """
    if distance_km <= 0:
        return 0.0
    return (distance_km / speed_kmh) * 60  # Convert hours to minutes

def estimate_battery_usage(distance_km: float, base_usage_per_km: float = 2.0) -> float:
    """
    Estimate how much battery will be consumed flying a given distance.
    
    This is a simplified model. Real battery usage depends on many factors:
    wind conditions, payload weight, temperature, and altitude changes.
    
    For our simulation, we use a simple linear model: 2% battery per kilometer.
    
    Returns: Estimated battery usage as a percentage
    """
    return distance_km * base_usage_per_km

Why the Haversine formula? You might wonder why we do not just use the Pythagorean theorem which is the square root of x squared plus y squared. The problem is that the Earth is a sphere, not a flat plane. Lines of longitude get closer together as you move toward the poles, so a degree of longitude in Alaska represents a much shorter distance than a degree of longitude at the equator. The Haversine formula accounts for this curvature, giving us accurate distances anywhere on Earth.

The Blackboard: Where All the Magic Happens

Now we are getting to the heart of the system. The Blackboard is where all our agents communicate. Let's build it piece by piece, understanding what each method does and why it matters.

class Blackboard:
    """
    The Blackboard is the central nervous system of our multi-agent system.
    
    All agents read from and write to this shared data structure. It maintains
    a queue of tasks that need to be done, the current status of every drone,
    completed tasks and their results, and mission metadata and system state.
    
    Thread Safety: Multiple drone agents will be accessing this simultaneously,
    so we use a threading.Lock to prevent race conditions.
    """
    
    def __init__(self, config: SystemConfig):
        self.config = config
        self.tasks: List[InspectionTask] = []
        self.drones: Dict[str, DroneStatus] = {}
        self.completed_tasks: List[InspectionTask] = []
        self.mission_metadata: Dict[str, Any] = {}
        self._lock = threading.Lock()
        self.logger = logging.getLogger("Blackboard")
        
    def add_task(self, task: InspectionTask) -> None:
        """
        Add a new task to the Blackboard.
        
        This is typically called by the Orchestrator Agent when it decomposes
        a mission into subtasks.
        """
        with self._lock:
            self.tasks.append(task)
            self.logger.info(f"Task {task.task_id} added to blackboard")
    
    def add_tasks(self, tasks: List[InspectionTask]) -> None:
        """Add multiple tasks at once which is more efficient than adding one by one."""
        with self._lock:
            self.tasks.extend(tasks)
            self.logger.info(f"Added {len(tasks)} tasks to blackboard")
    
    def get_available_tasks(self, priority_threshold: int = 0) -> List[InspectionTask]:
        """
        Get all tasks that are available to be claimed.
        
        Drones call this to see what work is available. They can optionally
        filter by priority, for example only show tasks with priority greater than or equal to five.
        
        Returns: List of unclaimed tasks above the priority threshold
        """
        with self._lock:
            available = [
                task for task in self.tasks 
                if task.status == "pending" and task.priority >= priority_threshold
            ]
            return available
    
    def claim_task(self, task_id: str, drone_id: str) -> bool:
        """
        Attempt to claim a task for a specific drone.
        
        This is atomic which means only one drone can successfully claim a task.
        If two drones try to claim the same task simultaneously, only one will succeed.
        
        Returns: True if the claim was successful, False if the task was already claimed
        """
        with self._lock:
            for task in self.tasks:
                if task.task_id == task_id and task.status == "pending":
                    task.status = "claimed"
                    task.claimed_by = drone_id
                    self.logger.info(f"Task {task_id} claimed by {drone_id}")
                    return True
            self.logger.warning(f"Task {task_id} could not be claimed by {drone_id}")
            return False
    
    def complete_task(self, task_id: str, inspection_data: Dict[str, Any]) -> None:
        """
        Mark a task as completed and store the inspection results.
        
        When a drone finishes an inspection, it calls this to upload the data
        such as photos and sensor readings and remove the task from the active queue.
        """
        with self._lock:
            for task in self.tasks:
                if task.task_id == task_id:
                    task.status = "completed"
                    task.inspection_data = inspection_data
                    self.completed_tasks.append(task)
                    self.tasks.remove(task)
                    self.logger.info(f"Task {task_id} completed by {task.claimed_by}")
                    return
            self.logger.warning(f"Attempted to complete task {task_id} but it was not found")
    
    def register_drone(self, drone_status: DroneStatus) -> None:
        """
        Register a new drone with the system.
        
        When a drone agent starts up, it registers itself on the Blackboard
        so other agents know it exists and can see its status.
        """
        with self._lock:
            self.drones[drone_status.drone_id] = drone_status
            self.logger.info(f"Drone {drone_status.drone_id} registered")
    
    def update_drone_status(self, drone_id: str, **kwargs) -> None:
        """
        Update a drone's status.
        
        Drones call this frequently to update their state, battery level, location, etc.
        
        Example: blackboard.update_drone_status("drone_1", state=DroneState.TRAVELING, battery_level=75.5)
        """
        with self._lock:
            if drone_id in self.drones:
                drone = self.drones[drone_id]
                for key, value in kwargs.items():
                    if hasattr(drone, key):
                        setattr(drone, key, value)
                drone.last_update = datetime.now()
            else:
                self.logger.warning(f"Attempted to update unknown drone {drone_id}")
    
    def get_drone_status(self, drone_id: str) -> Optional[DroneStatus]:
        """Get the current status of a specific drone"""
        with self._lock:
            return self.drones.get(drone_id)
    
    def get_all_drones(self) -> List[DroneStatus]:
        """Get the status of all registered drones"""
        with self._lock:
            return list(self.drones.values())
    
    def get_task_by_id(self, task_id: str) -> Optional[InspectionTask]:
        """Retrieve a specific task by its ID searching both active and completed tasks"""
        with self._lock:
            for task in self.tasks:
                if task.task_id == task_id:
                    return task
            for task in self.completed_tasks:
                if task.task_id == task_id:
                    return task
            return None
    
    def get_system_status(self) -> Dict[str, Any]:
        """
        Get a comprehensive overview of the entire system.
        
        This is useful for dashboards and monitoring interfaces.
        """
        with self._lock:
            active_drones = [d for d in self.drones.values() if d.state != DroneState.OFFLINE]
            charging_drones = [d for d in self.drones.values() if d.state == DroneState.CHARGING]
            busy_drones = [d for d in self.drones.values() 
                          if d.state in [DroneState.TRAVELING, DroneState.INSPECTING]]
            
            avg_battery = sum(d.battery_level for d in self.drones.values()) / len(self.drones) if self.drones else 0
            
            return {
                'total_tasks': len(self.tasks),
                'pending_tasks': len([t for t in self.tasks if t.status == "pending"]),
                'claimed_tasks': len([t for t in self.tasks if t.status == "claimed"]),
                'completed_tasks': len(self.completed_tasks),
                'total_drones': len(self.drones),
                'active_drones': len(active_drones),
                'charging_drones': len(charging_drones),
                'busy_drones': len(busy_drones),
                'average_battery': avg_battery
            }

Understanding Thread Safety: Notice how every method that accesses or modifies the Blackboard's data uses "with self._lock:". This is crucial because we will have multiple drone agents running in separate threads, all trying to read and write to the Blackboard simultaneously.

Without the lock, you could have race conditions like this. First, Drone A reads that Task X is available. Second, Drone B reads that Task X is available before Drone A claims it. Third, both drones try to claim Task X. Fourth, both think they succeeded. The lock ensures that only one thread can access the Blackboard at a time, preventing these kinds of bugs.

The Orchestrator Agent: Mission Planning with AI

Now we are going to build the brain of the operation, which is the Orchestrator Agent. This agent uses a large language model to analyze high-level missions and break them down into specific, actionable tasks.

First, let's create the LLM initialization function that works with both OpenAI and Ollama:

def create_llm(config: LLMConfig):
    """
    Create a language model instance based on the configuration.
    
    This function abstracts away the differences between OpenAI and Ollama,
    so the rest of our code does not need to worry about which backend we are using.
    """
    if config.backend == LLMBackend.OPENAI:
        from langchain_openai import ChatOpenAI
        return ChatOpenAI(
            model=config.model_name,
            temperature=config.temperature,
            max_tokens=config.max_tokens,
            api_key=config.api_key
        )
    elif config.backend == LLMBackend.OLLAMA:
        from langchain_community.llms import Ollama
        return Ollama(
            model=config.model_name,
            temperature=config.temperature,
            num_predict=config.max_tokens,
            base_url=config.base_url or "http://localhost:11434"
        )
    else:
        raise ValueError(f"Unsupported LLM backend: {config.backend}")

Now let's build the Orchestrator Agent itself:

class OrchestratorAgent:
    """
    The Orchestrator Agent is responsible for mission planning and task decomposition.
    
    When you give it a high-level mission like "inspect all bridges in the northern district,"
    it uses an LLM to understand the mission requirements, break it down into specific actionable tasks,
    assign priorities based on urgency and importance, estimate durations and resource requirements,
    and post the tasks to the Blackboard for drones to claim.
    """
    
    def __init__(self, blackboard: Blackboard, config: SystemConfig):
        self.blackboard = blackboard
        self.config = config
        self.llm = create_llm(config.llm_config)
        self.logger = logging.getLogger("OrchestratorAgent")
        
    def decompose_mission(self, mission_description: str, mission_area: Dict[str, Any]) -> List[InspectionTask]:
        """
        Take a high-level mission and decompose it into specific tasks.
        
        Args:
            mission_description: Natural language description like "Inspect all solar panels for hail damage"
            mission_area: Geographic bounds with center_lat, center_lon, and radius_km
        
        Returns:
            List of InspectionTask objects ready to be posted to the Blackboard
        """
        self.logger.info(f"Decomposing mission: {mission_description}")
        
        try:
            from crewai import Agent, Task, Crew
            
            planner = Agent(
                role='Mission Planning Specialist',
                goal='Decompose high-level inspection missions into specific actionable drone tasks',
                backstory="""You are an expert in drone operations and infrastructure inspection.
                You understand how to break down complex inspection missions into efficient
                prioritized tasks that can be executed by autonomous drones. You consider factors
                like geographic proximity, infrastructure type, urgency, and resource constraints.""",
                llm=self.llm,
                verbose=True
            )
            
            decomposition_task = Task(
                description=f"""
                Mission: {mission_description}
                Area: Center at ({mission_area['center_lat']}, {mission_area['center_lon']}), radius {mission_area['radius_km']}km
                
                Break this mission into specific inspection tasks. For each task, provide a unique identifier,
                specific GPS coordinates with latitude and longitude, infrastructure type such as bridge or power_line or solar_panel or wind_turbine,
                priority level from one to ten where ten is most urgent, and estimated duration in minutes.
                
                Format your response as a JSON array of tasks with the following structure:
                [
                    {{
                        "task_id": "unique_id",
                        "lat": 40.7128,
                        "lon": -74.0060,
                        "infrastructure_type": "bridge",
                        "priority": 8,
                        "estimated_duration_minutes": 15
                    }}
                ]
                
                Consider grouping nearby inspections together for efficiency, assigning higher priority to critical infrastructure or urgent issues,
                estimating realistic durations based on infrastructure complexity, and creating enough tasks to keep the drone fleet busy
                but not so many that they are overwhelming.
                """,
                agent=planner,
                expected_output="A JSON array of inspection tasks with all required fields"
            )
            
            crew = Crew(
                agents=[planner],
                tasks=[decomposition_task],
                verbose=True
            )
            
            result = crew.kickoff()
            
            result_text = str(result.raw) if hasattr(result, 'raw') else str(result)
            
            result_text = result_text.strip()
            if result_text.startswith('```json'):
                result_text = result_text[7:]
            if result_text.startswith('```'):
                result_text = result_text[3:]
            if result_text.endswith('```'):
                result_text = result_text[:-3]
            result_text = result_text.strip()
            
            subtasks_data = json.loads(result_text)
            
            tasks = []
            for task_data in subtasks_data:
                task = InspectionTask(
                    task_id=task_data.get('task_id', str(uuid4())),
                    area_coordinates={
                        'lat': task_data['lat'],
                        'lon': task_data['lon']
                    },
                    infrastructure_type=task_data['infrastructure_type'],
                    priority=task_data['priority'],
                    estimated_duration_minutes=task_data['estimated_duration_minutes']
                )
                tasks.append(task)
            
            self.logger.info(f"Successfully decomposed mission into {len(tasks)} tasks")
            return tasks
            
        except json.JSONDecodeError as e:
            self.logger.error(f"Failed to parse LLM response as JSON: {e}")
            self.logger.error(f"Raw response: {result_text}")
            return self._fallback_decomposition(mission_description, mission_area)
        except Exception as e:
            self.logger.error(f"Error during mission decomposition: {e}")
            return self._fallback_decomposition(mission_description, mission_area)
    
    def _fallback_decomposition(self, mission_description: str, mission_area: Dict[str, Any]) -> List[InspectionTask]:
        """
        If the LLM fails, fall back to a simple rule-based decomposition.
        
        This ensures the system can still function even if the AI component has issues.
        """
        self.logger.warning("Using fallback decomposition because LLM unavailable")
        
        center_lat = mission_area['center_lat']
        center_lon = mission_area['center_lon']
        radius_km = mission_area['radius_km']
        
        infrastructure_type = "unknown"
        if "bridge" in mission_description.lower():
            infrastructure_type = "bridge"
        elif "solar" in mission_description.lower():
            infrastructure_type = "solar_panel"
        elif "power" in mission_description.lower() or "line" in mission_description.lower():
            infrastructure_type = "power_line"
        elif "wind" in mission_description.lower():
            infrastructure_type = "wind_turbine"
        
        tasks = []
        grid_size = 3
        step = (radius_km * 2) / grid_size / 111
        
        for i in range(grid_size):
            for j in range(grid_size):
                lat = center_lat + (i - grid_size/2) * step
                lon = center_lon + (j - grid_size/2) * step
                
                task = InspectionTask(
                    task_id=f"task_{i}_{j}_{str(uuid4())[:8]}",
                    area_coordinates={'lat': lat, 'lon': lon},
                    infrastructure_type=infrastructure_type,
                    priority=5,
                    estimated_duration_minutes=10.0
                )
                tasks.append(task)
        
        return tasks
    
    def execute_mission(self, mission_description: str, mission_area: Dict[str, Any]) -> str:
        """
        Complete end-to-end mission execution by decomposing the mission into tasks,
        posting tasks to the Blackboard, and returning a mission ID for tracking.
        """
        mission_id = f"mission_{str(uuid4())[:8]}"
        
        tasks = self.decompose_mission(mission_description, mission_area)
        
        self.blackboard.mission_metadata[mission_id] = {
            'description': mission_description,
            'area': mission_area,
            'created_at': datetime.now().isoformat(),
            'task_count': len(tasks),
            'task_ids': [t.task_id for t in tasks]
        }
        
        self.blackboard.add_tasks(tasks)
        
        self.logger.info(f"Mission {mission_id} launched with {len(tasks)} tasks")
        return mission_id

What is happening here? The Orchestrator uses CrewAI to create a specialized "Mission Planning Specialist" agent. This agent has a specific role, goal, and backstory that prime the LLM to think like an expert in drone mission planning.

When we call crew.kickoff(), CrewAI orchestrates the interaction with the LLM, sending the task description and processing the response. The LLM analyzes the mission and generates a structured JSON response with specific tasks.

We then parse this JSON and convert it into InspectionTask objects that get posted to the Blackboard.

The fallback mechanism is important for production systems. If the LLM is unavailable or returns invalid JSON, we can still function using simple rule-based logic.

Worker Drone Agents: Autonomous Decision-Making

Now for the most interesting part, which is the Worker Drone Agents. These are the autonomous agents that control individual drones, making real-time decisions about what to do next.

Each drone agent runs in its own thread and operates as a state machine, continuously evaluating its situation and transitioning between states such as idle, traveling, inspecting, and charging.

class WorkerDroneAgent:
    """
    An autonomous agent that controls a single drone.
    
    This agent monitors the Blackboard for available tasks, decides which tasks to claim based on battery location and priority,
    manages the drone's state machine transitioning between idle traveling inspecting returning and charging,
    makes autonomous decisions about when to charge versus when to take on more work,
    and simulates realistic drone behavior including battery drain, flight time, and inspections.
    """
    
    def __init__(self, drone_id: str, blackboard: Blackboard, config: SystemConfig, 
                 initial_location: Dict[str, float], initial_battery: float = 100.0):
        self.drone_id = drone_id
        self.blackboard = blackboard
        self.config = config
        self.battery_level = initial_battery
        self.current_location = initial_location
        self.home_location = initial_location.copy()
        self.state = DroneState.IDLE
        self.assigned_task: Optional[InspectionTask] = None
        self.logger = logging.getLogger(f"Drone-{drone_id}")
        self._running = False
        self._operation_thread: Optional[threading.Thread] = None
        self._inspection_progress = 0
        
        status = DroneStatus(
            drone_id=self.drone_id,
            state=self.state,
            battery_level=self.battery_level,
            current_location=self.current_location
        )
        self.blackboard.register_drone(status)
        
    def start(self) -> None:
        """Start the drone's autonomous operation loop"""
        if not self._running:
            self._running = True
            self._operation_thread = threading.Thread(target=self._operation_loop, daemon=True)
            self._operation_thread.start()
            self.logger.info(f"Drone {self.drone_id} started at {self.current_location}")
    
    def stop(self) -> None:
        """Stop the drone's operation"""
        self._running = False
        if self._operation_thread:
            self._operation_thread.join(timeout=5.0)
        self.logger.info(f"Drone {self.drone_id} stopped")
    
    def _operation_loop(self) -> None:
        """
        The main autonomous decision-making loop.
        
        This runs continuously, evaluating the drone's current state and deciding what to do next.
        It is the heart of the drone's autonomy.
        """
        while self._running:
            try:
                self._update_blackboard_status()
                
                if self.state == DroneState.IDLE:
                    self._handle_idle_state()
                elif self.state == DroneState.TRAVELING:
                    self._handle_traveling_state()
                elif self.state == DroneState.INSPECTING:
                    self._handle_inspecting_state()
                elif self.state == DroneState.RETURNING:
                    self._handle_returning_state()
                elif self.state == DroneState.CHARGING:
                    self._handle_charging_state()
                
                time.sleep(1.0)
                
            except Exception as e:
                self.logger.error(f"Error in operation loop: {e}")
                time.sleep(5.0)
    
    def _handle_idle_state(self) -> None:
        """
        Behavior when the drone is idle.
        
        Decision logic: First, if battery is critically low, go charge.
        Second, if battery is somewhat low, we should charge unless there are high-priority urgent tasks.
        Third, look for available tasks and select the best one.
        """
        if self.battery_level < self.config.battery_critical_threshold:
            self.logger.warning(f"Battery critically low at {self.battery_level:.1f}%, returning to charge")
            self.state = DroneState.RETURNING
            return
        
        if self.battery_level < self.config.battery_low_threshold:
            urgent_tasks = self.blackboard.get_available_tasks(priority_threshold=8)
            if not urgent_tasks:
                self.logger.info(f"Battery low at {self.battery_level:.1f}%, going to charge")
                self.state = DroneState.RETURNING
                return
        
        available_tasks = self.blackboard.get_available_tasks()
        
        if not available_tasks:
            self.logger.debug(f"No tasks available, staying idle")
            return
        
        best_task = self._select_best_task(available_tasks)
        
        if best_task:
            if self.blackboard.claim_task(best_task.task_id, self.drone_id):
                self.assigned_task = best_task
                self.state = DroneState.TRAVELING
                self.logger.info(f"Claimed task {best_task.task_id}, traveling to {best_task.area_coordinates}")
            else:
                self.logger.debug(f"Failed to claim task {best_task.task_id} because someone else got it first")
    
    def _select_best_task(self, available_tasks: List[InspectionTask]) -> Optional[InspectionTask]:
        """
        Intelligent task selection based on multiple factors.
        
        This is where the drone's decision-making intelligence shows.
        We consider task priority where higher is better, distance to task where closer is better,
        and battery requirements to ensure we can complete it and get home safely.
        
        Returns: The best task for this drone, or None if no suitable task exists
        """
        scored_tasks = []
        
        for task in available_tasks:
            distance_to_task = calculate_distance(
                self.current_location['lat'],
                self.current_location['lon'],
                task.area_coordinates['lat'],
                task.area_coordinates['lon']
            )
            
            distance_to_home = calculate_distance(
                task.area_coordinates['lat'],
                task.area_coordinates['lon'],
                self.home_location['lat'],
                self.home_location['lon']
            )
            
            total_distance = distance_to_task + distance_to_home
            battery_needed = estimate_battery_usage(total_distance)
            battery_needed += task.estimated_duration_minutes * 0.5
            
            if battery_needed > (self.battery_level - 10):
                self.logger.debug(f"Skipping task {task.task_id}: insufficient battery")
                continue
            
            priority_score = task.priority * 10
            distance_score = max(0, 100 - distance_to_task * 2)
            total_score = priority_score + distance_score
            
            scored_tasks.append((total_score, task))
        
        if not scored_tasks:
            return None
        
        scored_tasks.sort(key=lambda x: x[0], reverse=True)
        best_task = scored_tasks[0][1]
        self.logger.debug(f"Selected task {best_task.task_id} with priority {best_task.priority}")
        return best_task
    
    def _handle_traveling_state(self) -> None:
        """
        Simulate traveling to the task location.
        
        In a real system, this would interface with the drone's flight controller.
        For our simulation, we calculate the distance, simulate flight time,
        drain battery proportionally, update location, and transition to inspecting state.
        """
        if not self.assigned_task:
            self.logger.error("In TRAVELING state but no assigned task!")
            self.state = DroneState.IDLE
            return
        
        target_lat = self.assigned_task.area_coordinates['lat']
        target_lon = self.assigned_task.area_coordinates['lon']
        
        distance = calculate_distance(
            self.current_location['lat'],
            self.current_location['lon'],
            target_lat,
            target_lon
        )
        
        flight_time = estimate_flight_time(distance)
        battery_usage = estimate_battery_usage(distance)
        
        self.logger.info(f"Flying to task {self.assigned_task.task_id} distance {distance:.2f}km time {flight_time:.1f}min battery {battery_usage:.1f}%")
        
        time.sleep(2.0)
        
        self.battery_level -= battery_usage
        self.current_location = {'lat': target_lat, 'lon': target_lon}
        
        self.state = DroneState.INSPECTING
        self._inspection_progress = 0
        self.logger.info(f"Arrived at task location, beginning inspection")
    
    def _handle_inspecting_state(self) -> None:
        """
        Simulate performing an inspection.
        
        In a real system, this would capture high-resolution images, collect sensor data such as thermal or LiDAR,
        run AI models for defect detection, and store results.
        
        For our simulation, we simulate the time and battery usage.
        """
        if not self.assigned_task:
            self.logger.error("In INSPECTING state but no assigned task!")
            self.state = DroneState.IDLE
            return
        
        inspection_steps = int(self.config.inspection_time_per_task_seconds)
        self._inspection_progress += 1
        
        progress_percent = (self._inspection_progress / inspection_steps) * 100
        self.logger.debug(f"Inspecting {self.assigned_task.infrastructure_type}: {progress_percent:.0f}% complete")
        
        self.battery_level -= 0.5
        
        if self._inspection_progress >= inspection_steps:
            inspection_data = {
                'drone_id': self.drone_id,
                'timestamp': datetime.now().isoformat(),
                'infrastructure_type': self.assigned_task.infrastructure_type,
                'location': self.assigned_task.area_coordinates,
                'images_captured': random.randint(20, 50),
                'anomalies_detected': random.randint(0, 5),
                'inspection_duration_seconds': inspection_steps,
                'battery_used_percent': inspection_steps * 0.5
            }
            
            self.blackboard.complete_task(self.assigned_task.task_id, inspection_data)
            self.logger.info(f"Inspection complete for task {self.assigned_task.task_id}")
            
            self.assigned_task = None
            self._inspection_progress = 0
            
            if self.battery_level < self.config.battery_low_threshold:
                self.state = DroneState.RETURNING
            else:
                self.state = DroneState.IDLE
    
    def _handle_returning_state(self) -> None:
        """Return to home base for charging."""
        distance_home = calculate_distance(
            self.current_location['lat'],
            self.current_location['lon'],
            self.home_location['lat'],
            self.home_location['lon']
        )
        
        if distance_home < 0.1:
            self.logger.info(f"Arrived at home base, beginning charge")
            self.state = DroneState.CHARGING
            return
        
        flight_time = estimate_flight_time(distance_home)
        battery_usage = estimate_battery_usage(distance_home)
        
        self.logger.info(f"Returning to base distance {distance_home:.2f}km battery {battery_usage:.1f}%")
        
        time.sleep(2.0)
        
        self.battery_level -= battery_usage
        self.current_location = self.home_location.copy()
        self.state = DroneState.CHARGING
    
    def _handle_charging_state(self) -> None:
        """
        Simulate charging the battery.
        
        NOTE: This is a simulation! Real drone charging takes thirty to sixty minutes.
        We are simulating at one percent per second for demonstration purposes.
        """
        if self.battery_level >= 100.0:
            self.battery_level = 100.0
            self.logger.info(f"Fully charged, ready for operations")
            self.state = DroneState.IDLE
            return
        
        self.battery_level = min(100.0, self.battery_level + self.config.charging_rate_percent_per_second)
        self.logger.debug(f"Charging: {self.battery_level:.1f}%")
    
    def _update_blackboard_status(self) -> None:
        """Update our current status on the Blackboard"""
        self.blackboard.update_drone_status(
            self.drone_id,
            state=self.state,
            battery_level=self.battery_level,
            current_location=self.current_location,
            assigned_task_id=self.assigned_task.task_id if self.assigned_task else None
        )

Understanding the State Machine: The drone agent operates as a finite state machine with these states. IDLE means sitting at base and looking for work. TRAVELING means flying to a task location. INSPECTING means performing an inspection. RETURNING means flying back to base. CHARGING means plugged in and charging.

The transitions between states are governed by the drone's autonomous decision-making. For example, when idle, the drone evaluates whether it should charge if battery is low or claim a task if battery is sufficient and tasks are available.

The Intelligence in Task Selection: The _select_best_task method is where the drone's intelligence really shines. It does not just grab the first available task. It considers whether it can complete this task by calculating if it has enough battery to fly there, perform the inspection, and return home safely. It evaluates what the priority is, giving higher priority tasks higher scores. It considers how far away the task is, preferring closer tasks to conserve battery. It combines these factors into a score and picks the highest-scoring task.

This creates emergent behavior where drones naturally distribute themselves efficiently across available tasks without any central coordination.

Infrastructure Simulator for Testing

To test our system without real drones, let's create a simple infrastructure simulator:

class InfrastructureSimulator:
    """
    Simulates infrastructure inspection scenarios for testing.
    
    Generates realistic missions with various infrastructure types and geographic distributions.
    """
    
    def __init__(self, base_location: Dict[str, float]):
        self.base_location = base_location
        self.infrastructure_types = [
            "bridge",
            "power_line",
            "solar_panel",
            "wind_turbine",
            "cell_tower",
            "water_tower"
        ]
    
    def generate_random_mission(self, radius_km: float = 20.0) -> tuple:
        """
        Generate a random inspection mission for testing.
        
        Returns: A tuple containing mission_description and mission_area
        """
        infra_type = random.choice(self.infrastructure_types)
        condition = random.choice([
            "routine inspection",
            "storm damage assessment",
            "maintenance check",
            "emergency inspection"
        ])
        
        mission_description = f"Perform {condition} of all {infra_type}s in the designated area"
        
        lat_offset = (random.random() - 0.5) * 0.1
        lon_offset = (random.random() - 0.5) * 0.1
        
        mission_area = {
            'center_lat': self.base_location['lat'] + lat_offset,
            'center_lon': self.base_location['lon'] + lon_offset,
            'radius_km': radius_km
        }
        
        return mission_description, mission_area

Putting It All Together: The Main System

Now let's create the main function that ties everything together:

def main():
    """
    Main entry point for the autonomous drone inspection system.
    
    This demonstrates the complete system in action.
    """
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('drone_mission.log'),
            logging.StreamHandler()
        ]
    )
    
    logger = logging.getLogger("Main")
    logger.info("Starting Autonomous Drone Inspection System")
    
    llm_config = LLMConfig(
        backend=LLMBackend.OLLAMA,
        model_name="llama3.2",
        temperature=0.7
    )
    
    system_config = SystemConfig(
        llm_config=llm_config,
        max_drones=3,
        battery_critical_threshold=20.0,
        battery_low_threshold=30.0,
        charging_rate_percent_per_second=2.0,
        inspection_time_per_task_seconds=5.0
    )
    
    blackboard = Blackboard(system_config)
    
    orchestrator = OrchestratorAgent(blackboard, system_config)
    
    base_location = {'lat': 40.7128, 'lon': -74.0060}
    
    drones = []
    for i in range(system_config.max_drones):
        drone = WorkerDroneAgent(
            drone_id=f"drone_{i+1}",
            blackboard=blackboard,
            config=system_config,
            initial_location=base_location.copy(),
            initial_battery=random.uniform(60, 100)
        )
        drones.append(drone)
        drone.start()
    
    simulator = InfrastructureSimulator(base_location)
    
    logger.info("=" * 80)
    logger.info("MISSION BRIEFING")
    logger.info("=" * 80)
    
    mission_description, mission_area = simulator.generate_random_mission(radius_km=15.0)
    
    logger.info(f"Mission: {mission_description}")
    logger.info(f"Area: Center ({mission_area['center_lat']:.4f}, {mission_area['center_lon']:.4f}), Radius {mission_area['radius_km']}km")
    logger.info("=" * 80)
    
    mission_id = orchestrator.execute_mission(mission_description, mission_area)
    
    logger.info("=" * 80)
    logger.info("MISSION EXECUTION - MONITORING")
    logger.info("=" * 80)
    
    start_time = time.time()
    max_runtime = 120
    
    while time.time() - start_time < max_runtime:
        status = blackboard.get_system_status()
        
        logger.info("-" * 80)
        logger.info(f"Runtime: {int(time.time() - start_time)}s")
        logger.info(f"Tasks: {status['pending_tasks']} pending, {status['claimed_tasks']} in progress, {status['completed_tasks']} completed")
        logger.info(f"Drones: {status['active_drones']} active, {status['charging_drones']} charging, {status['busy_drones']} busy")
        logger.info(f"Average battery: {status['average_battery']:.1f}%")
        
        for drone_status in blackboard.get_all_drones():
            logger.info(f"   {drone_status.drone_id}: {drone_status.state.value} - {drone_status.battery_level:.1f}% battery")
        
        logger.info("-" * 80)
        
        if status['pending_tasks'] == 0 and status['claimed_tasks'] == 0:
            logger.info("MISSION COMPLETE! All tasks finished.")
            break
        
        time.sleep(10)
    
    logger.info("=" * 80)
    logger.info("MISSION SUMMARY")
    logger.info("=" * 80)
    
    final_status = blackboard.get_system_status()
    logger.info(f"Total tasks completed: {final_status['completed_tasks']}")
    logger.info(f"Total runtime: {int(time.time() - start_time)} seconds")
    logger.info(f"Final fleet battery average: {final_status['average_battery']:.1f}%")
    
    logger.info("Completed Inspections:")
    for task in blackboard.completed_tasks[:5]:
        logger.info(f"  Task {task.task_id}: {task.infrastructure_type} at ({task.area_coordinates['lat']:.4f}, {task.area_coordinates['lon']:.4f})")
        if task.inspection_data:
            logger.info(f"      Images: {task.inspection_data.get('images_captured', 0)}, Anomalies: {task.inspection_data.get('anomalies_detected', 0)}")
    
    logger.info("=" * 80)
    
    logger.info("Shutting down drones...")
    for drone in drones:
        drone.stop()
    
    logger.info("System shutdown complete")

if __name__ == "__main__":
    main()

Running the System

To run the complete system, follow these steps.

First, make sure you have Ollama installed and running if using local LLM. Run this command:

ollama serve

Second, save all the code to a file called drone_inspection_system.py

Third, run the system with this command:

python drone_inspection_system.py

You will see output showing the mission briefing, task decomposition, drones claiming and executing tasks, battery management decisions, and completed inspections with results.

What You Have Built

Congratulations! You have just built a sophisticated multi-agent AI system that demonstrates autonomous decision-making where drones make intelligent decisions about task selection, battery management, and collaboration without human intervention. It shows multi-agent coordination where multiple AI agents including orchestrator and worker drones coordinate through a shared Blackboard without explicit point-to-point communication. It uses LLM-powered planning where the orchestrator uses a language model to understand natural language missions and decompose them into actionable tasks. It includes realistic simulation where the system simulates real-world constraints like battery levels, flight times, and geographic distances. It exhibits emergent behavior where you can watch as the fleet naturally distributes work efficiently without central coordination. This is emergent intelligence from simple rules.

Key Takeaways

The Blackboard Pattern is incredibly powerful for multi-agent systems because it decouples agents from each other. Agents do not need to know about each other. They just read and write to the shared Blackboard.

Agentic AI is not about programming every possible scenario. It is about giving agents goals, constraints, and decision-making capabilities, then letting them figure out how to achieve their objectives.

State Machines are a natural way to model autonomous agents. Each state has clear behaviors, and transitions between states are governed by the agent's decision logic.

LLMs for Planning can understand complex natural language requirements and generate structured plans. This is far more flexible than hardcoded planning algorithms.

Next Steps and Extensions

This system is a foundation you can build on. Here are some ideas for extensions.

First, add real drone integration by replacing the simulation with actual drone APIs such as DJI SDK or PX4. Second, implement computer vision by adding real image analysis for defect detection using models like YOLOv8. Third, add weather integration by pulling real-time weather data and having drones make decisions based on wind and rain. Fourth, implement dynamic replanning where if a drone fails or a high-priority emergency task appears, the orchestrator replans the mission. Fifth, add multi-mission support to allow the system to handle multiple concurrent missions. Sixth, build a web dashboard using React to visualize drone positions on a map in real-time. Seventh, add learning from experience by storing mission outcomes in a database and using that data to improve task estimation and planning. Eighth, implement swarm behaviors with more sophisticated multi-drone coordination patterns.

The possibilities are endless. You now have a solid foundation in multi-agent AI systems and the Blackboard pattern. Go build something amazing!

Tuesday, December 01, 2026

BUILDING YOUR FIRST AGENTIC AI TRAVEL ASSISTANT WITH LANGCHAIN: A BEGINNER'S GUIDE


 

INTRODUCTION: WELCOME TO THE WORLD OF AGENTIC AI

Imagine having a team of specialized assistants working together to help you plan your next vacation. One assistant researches hotels, another checks the weather, a third finds the best restaurants, and a coordinator manages them all. This is exactly what Agentic AI does, except these assistants are intelligent software agents powered by Large Language Models.

In this tutorial, we will build a sophisticated travel planning system from the ground up. You will learn how to create multiple AI agents that collaborate to provide comprehensive travel information for any location in the world. By the end of this guide, you will have a production-ready application that demonstrates the power of multi-agent systems.

The journey ahead is exciting. We will explore how agents communicate, how they use tools to access real-world information, and how they coordinate their efforts to deliver exceptional results. Even if you have never worked with AI agents before, this tutorial will guide you through every concept and every line of code.

UNDERSTANDING THE FUNDAMENTALS: WHAT IS AGENTIC AI?

Before we dive into building our travel assistant, let us establish a solid foundation. Agentic AI represents a paradigm shift from traditional AI applications. Instead of a single monolithic AI system, we create multiple specialized agents that work together like a well-coordinated team.

Think of a traditional AI chatbot as a single employee trying to handle every task in a company. Now imagine replacing that with a team of specialists, each expert in their domain. The marketing specialist handles marketing questions, the technical expert handles technical issues, and a manager coordinates their efforts. This is the essence of Agentic AI.

An agent in this context is an autonomous entity that can perceive its environment, make decisions, and take actions to achieve specific goals. Each agent has access to tools that extend its capabilities beyond just generating text. These tools might query databases, call APIs, perform calculations, or interact with external services.

The magic happens when these agents collaborate. A coordinator agent receives your request, breaks it down into subtasks, delegates to specialist agents, and synthesizes their responses into a coherent answer. This architecture provides several advantages: better specialization where each agent focuses on what it does best, easier maintenance since you can update individual agents without affecting others, improved scalability as you can add new specialist agents without redesigning the entire system, and more reliable results because specialized agents develop deep expertise in their domains.

THE ARCHITECTURE: DESIGNING OUR MULTI-AGENT TRAVEL SYSTEM

Our travel assistant will consist of six distinct agents, each with a specific responsibility. Understanding this architecture is crucial before we write any code.

The Travel Agent serves as the primary interface with users. When you ask about visiting Paris, this agent understands your request, asks clarifying questions if needed, and orchestrates the other agents to gather information. It acts as the conductor of our agent orchestra.

The Information Agent specializes in finding local attractions, hotels, restaurants, and cafes within a twenty-kilometer radius of your destination. This agent knows how to search for the best sightseeing spots and dining experiences.

The General Information Agent handles factual data about locations. It retrieves population statistics, languages spoken, currency information, historical events, and public transportation details. This agent provides the contextual knowledge that helps you understand a destination.

The Map Agent integrates with Google Maps to provide visual representations of locations. It generates map URLs and embeds that help you visualize where things are located.

The Weather Agent fetches current weather conditions and seven-day forecasts. It ensures you know whether to pack an umbrella or sunscreen.

The Collector Agent serves as the final assembler. It gathers outputs from all specialist agents and creates a beautifully formatted comprehensive report. This agent ensures that information is presented in a clear, organized, and user-friendly manner.

Supporting this agent ecosystem, we will implement Redis caching to improve performance and reduce redundant API calls. We will also ensure compatibility with various LLM providers including OpenAI, Anthropic, Google, and local models through Ollama.

SETTING UP YOUR DEVELOPMENT ENVIRONMENT

Before writing code, we need to prepare our development environment. This section walks you through installing all necessary dependencies and configuring your system.

First, ensure you have Python 3.10 or higher installed on your system. You can verify this by opening a terminal and running the command python --version or python3 --version. If you need to install Python, visit the official Python website and download the appropriate version for your operating system.

Create a new directory for your project. Open your terminal and execute these commands:

mkdir agentic-travel-assistant
cd agentic-travel-assistant

Now create a virtual environment to isolate your project dependencies. This prevents conflicts with other Python projects on your system:

python -m venv venv

Activate the virtual environment. On Windows, use:

venv\Scripts\activate

On macOS and Linux, use:

source venv/bin/activate

With your virtual environment activated, install LangChain and related dependencies. Create a file named requirements.txt with the following content:

langchain==0.3.14
langchain-community==0.3.14
langchain-core==0.3.28
langchain-openai==0.2.14
langchain-anthropic==0.3.8
langchain-google-genai==2.0.8
langchain-ollama==0.2.1
redis==5.2.1
requests==2.32.3
python-dotenv==1.0.1
pydantic==2.10.5
pydantic-settings==2.7.0
httpx==0.28.1
geopy==2.4.1
googlemaps==4.10.0

Install these dependencies using pip:

pip install -r requirements.txt

Next, set up Redis for caching. Redis is an in-memory data store that will significantly improve our application's performance by caching API responses and LLM outputs.

If you are on macOS, install Redis using Homebrew:

brew install redis
brew services start redis

On Ubuntu or Debian Linux:

sudo apt-get update
sudo apt-get install redis-server
sudo systemctl start redis

On Windows, you can use Windows Subsystem for Linux or download Redis from the official GitHub repository and follow the Windows installation instructions.

Verify that Redis is running by executing:

redis-cli ping

You should receive the response PONG, indicating that Redis is operational.

Now configure your API keys and environment variables. Create a file named .env in your project directory. This file will store sensitive information like API keys:

OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
GOOGLE_API_KEY=your_google_api_key_here
GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here
WEATHER_API_KEY=your_weather_api_key_here
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
LLM_PROVIDER=openai
LLM_MODEL=gpt-4-turbo-preview
LLM_TEMPERATURE=0.7

Replace the placeholder values with your actual API keys. You can obtain an OpenAI API key from the OpenAI platform, an Anthropic key from Anthropic's console, a Google API key from Google Cloud Console, a Google Maps API key from the Google Maps Platform, and a weather API key from services like WeatherAPI.

Your development environment is now ready. Let us begin building our agentic travel assistant.

UNDERSTANDING LANGCHAIN COMPONENTS: THE BUILDING BLOCKS

Before we construct our multi-agent system, we must understand the fundamental components that LangChain provides. These building blocks will form the foundation of our application.

LangChain organizes AI functionality into several key abstractions. The most important for our purposes are Language Models, Prompts, Tools, and Agents.

Language Models are the AI brains of our system. LangChain supports various LLM providers including OpenAI, Anthropic, Google, and local models through Ollama. We will design our system to work with any of these providers, giving users flexibility in their deployment choices.

Let me show you how to initialize different LLM providers:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-4-turbo-preview",
    temperature=0.7
)

The temperature parameter controls randomness in responses. Lower values like 0.2 produce more deterministic outputs, while higher values like 0.9 encourage creativity. For our travel assistant, we use 0.7 as a balanced middle ground.

Prompts are structured instructions that guide LLM behavior. Instead of sending raw strings to the model, we use prompt templates that can incorporate variables:

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a {role}."),
    ("human", "{question}")
])

This template approach separates the prompt structure from the data, making our code more maintainable.

Tools extend agent capabilities beyond text generation. A tool is a function that an agent can invoke to perform specific actions. LangChain provides a decorator to convert regular Python functions into tools:

from langchain_core.tools import tool

@tool
def get_weather(location: str) -> str:
    """Fetches current weather for a location."""
    return f"Weather data for {location}"

The docstring is crucial because the agent reads it to understand when and how to use this tool. The agent examines all available tools and their descriptions to decide which one to call for a given task.

Agents are autonomous entities that use LLMs to decide which actions to take. An agent follows a reasoning loop: it observes the current state, thinks about what to do next, selects and executes a tool, observes the result, and repeats until the task is complete.

Here is a simple example of creating an agent:

from langchain.agents import create_tool_calling_agent, AgentExecutor

agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)

The AgentExecutor manages the agent's execution loop, handling tool calls and managing conversation flow.

IMPLEMENTING THE FOUNDATION: CONFIGURATION AND UTILITIES

Every robust application needs a solid foundation. We will start by creating configuration management, caching infrastructure, and utility functions that our agents will rely on.

Create a file named config.py in your project directory:

import os
from typing import Optional, Literal
from pydantic import Field
from pydantic_settings import BaseSettings
from dotenv import load_dotenv

load_dotenv()

class Settings(BaseSettings):
    """Application settings loaded from environment variables."""
    
    openai_api_key: Optional[str] = Field(default=None)
    anthropic_api_key: Optional[str] = Field(default=None)
    google_api_key: Optional[str] = Field(default=None)
    google_maps_api_key: str = Field(default="")
    weather_api_key: str = Field(default="")
    
    redis_host: str = Field(default="localhost")
    redis_port: int = Field(default=6379)
    redis_db: int = Field(default=0)
    redis_password: Optional[str] = Field(default=None)
    
    llm_provider: Literal["openai", "anthropic", "google", "ollama"] = Field(default="openai")
    llm_model: str = Field(default="gpt-4-turbo-preview")
    llm_temperature: float = Field(default=0.7, ge=0.0, le=2.0)
    llm_max_tokens: int = Field(default=4096, gt=0)
    
    cache_ttl: int = Field(default=3600, gt=0)
    weather_cache_ttl: int = Field(default=3600, gt=0)
    places_cache_ttl: int = Field(default=86400, gt=0)
    general_info_cache_ttl: int = Field(default=604800, gt=0)
    map_cache_ttl: int = Field(default=2592000, gt=0)
    
    request_timeout: int = Field(default=30, gt=0)
    max_retries: int = Field(default=3, ge=0)
    
    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field(default="INFO")
    
    class Config:
        env_file = ".env"
        case_sensitive = False
        extra = "ignore"

settings = Settings()

Now create a caching module named cache.py:

import json
import hashlib
import logging
from typing import Optional, Any, Dict
import redis
from redis.exceptions import ConnectionError, TimeoutError
from config import settings

logger = logging.getLogger(__name__)

class CacheManager:
    """Manages Redis caching for API responses and LLM outputs."""
    
    def __init__(self):
        """Initialize Redis connection with error handling."""
        try:
            self.redis_client = redis.Redis(
                host=settings.redis_host,
                port=settings.redis_port,
                db=settings.redis_db,
                password=settings.redis_password,
                decode_responses=True,
                socket_timeout=5,
                socket_connect_timeout=5
            )
            self.default_ttl = settings.cache_ttl
            self._test_connection()
            logger.info("Redis cache initialized successfully")
        except (ConnectionError, TimeoutError) as e:
            logger.warning(f"Redis connection failed: {e}. Caching will be disabled.")
            self.redis_client = None
    
    def _test_connection(self):
        """Test Redis connection."""
        if self.redis_client:
            self.redis_client.ping()
    
    def _generate_key(self, prefix: str, data: Dict[str, Any]) -> str:
        """Generate a unique cache key from prefix and data."""
        data_str = json.dumps(data, sort_keys=True)
        hash_digest = hashlib.sha256(data_str.encode()).hexdigest()
        return f"{prefix}:{hash_digest}"
    
    def get(self, prefix: str, data: Dict[str, Any]) -> Optional[Any]:
        """Retrieve cached value if it exists."""
        if not self.redis_client:
            return None
        
        try:
            key = self._generate_key(prefix, data)
            cached = self.redis_client.get(key)
            if cached:
                logger.debug(f"Cache hit for key: {prefix}")
                return json.loads(cached)
            logger.debug(f"Cache miss for key: {prefix}")
            return None
        except Exception as e:
            logger.error(f"Error retrieving from cache: {e}")
            return None
    
    def set(self, prefix: str, data: Dict[str, Any], value: Any, ttl: Optional[int] = None) -> bool:
        """Store value in cache with optional TTL."""
        if not self.redis_client:
            return False
        
        try:
            key = self._generate_key(prefix, data)
            ttl = ttl or self.default_ttl
            self.redis_client.setex(key, ttl, json.dumps(value))
            logger.debug(f"Cached value for key: {prefix} with TTL: {ttl}s")
            return True
        except Exception as e:
            logger.error(f"Error storing in cache: {e}")
            return False
    
    def invalidate(self, prefix: str, data: Dict[str, Any]) -> bool:
        """Remove specific cache entry."""
        if not self.redis_client:
            return False
        
        try:
            key = self._generate_key(prefix, data)
            self.redis_client.delete(key)
            logger.debug(f"Invalidated cache for key: {prefix}")
            return True
        except Exception as e:
            logger.error(f"Error invalidating cache: {e}")
            return False
    
    def clear_all(self) -> bool:
        """Clear all cache entries."""
        if not self.redis_client:
            return False
        
        try:
            self.redis_client.flushdb()
            logger.info("Cleared all cache entries")
            return True
        except Exception as e:
            logger.error(f"Error clearing cache: {e}")
            return False
    
    def health_check(self) -> bool:
        """Check if Redis connection is healthy."""
        if not self.redis_client:
            return False
        
        try:
            self.redis_client.ping()
            return True
        except (ConnectionError, TimeoutError):
            return False
    
    def get_stats(self) -> Dict[str, Any]:
        """Get cache statistics."""
        if not self.redis_client:
            return {"status": "disabled"}
        
        try:
            info = self.redis_client.info()
            return {
                "status": "connected",
                "used_memory": info.get("used_memory_human", "N/A"),
                "connected_clients": info.get("connected_clients", 0),
                "total_keys": self.redis_client.dbsize()
            }
        except Exception as e:
            logger.error(f"Error getting cache stats: {e}")
            return {"status": "error", "error": str(e)}

cache_manager = CacheManager()

Next, create llm_factory.py to handle LLM initialization:

import logging
from typing import Optional
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_ollama import ChatOllama
from langchain_core.language_models.chat_models import BaseChatModel
from config import settings

logger = logging.getLogger(__name__)

class LLMFactory:
    """Factory for creating LLM instances across different providers."""
    
    @staticmethod
    def create_llm(
        provider: Optional[str] = None,
        model: Optional[str] = None,
        temperature: Optional[float] = None,
        max_tokens: Optional[int] = None
    ) -> BaseChatModel:
        """
        Create an LLM instance based on provider.
        
        Args:
            provider: LLM provider (openai, anthropic, google, ollama)
            model: Model name
            temperature: Temperature for generation
            max_tokens: Maximum tokens to generate
            
        Returns:
            Initialized LLM instance
            
        Raises:
            ValueError: If provider is unsupported or API key is missing
        """
        provider = provider or settings.llm_provider
        model = model or settings.llm_model
        temperature = temperature if temperature is not None else settings.llm_temperature
        max_tokens = max_tokens or settings.llm_max_tokens
        
        logger.info(f"Creating LLM: provider={provider}, model={model}")
        
        try:
            if provider == "openai":
                if not settings.openai_api_key:
                    raise ValueError("OpenAI API key not configured")
                return ChatOpenAI(
                    model=model,
                    temperature=temperature,
                    max_tokens=max_tokens,
                    api_key=settings.openai_api_key,
                    request_timeout=settings.request_timeout
                )
            
            elif provider == "anthropic":
                if not settings.anthropic_api_key:
                    raise ValueError("Anthropic API key not configured")
                return ChatAnthropic(
                    model=model,
                    temperature=temperature,
                    max_tokens=max_tokens,
                    api_key=settings.anthropic_api_key,
                    timeout=settings.request_timeout
                )
            
            elif provider == "google":
                if not settings.google_api_key:
                    raise ValueError("Google API key not configured")
                return ChatGoogleGenerativeAI(
                    model=model,
                    temperature=temperature,
                    max_output_tokens=max_tokens,
                    google_api_key=settings.google_api_key,
                    timeout=settings.request_timeout
                )
            
            elif provider == "ollama":
                return ChatOllama(
                    model=model,
                    temperature=temperature,
                    num_predict=max_tokens
                )
            
            else:
                raise ValueError(f"Unsupported LLM provider: {provider}")
                
        except Exception as e:
            logger.error(f"Error creating LLM: {e}")
            raise
    
    @staticmethod
    def create_with_fallback(
        primary_provider: str,
        fallback_provider: str = "ollama",
        **kwargs
    ) -> BaseChatModel:
        """
        Create LLM with fallback support.
        
        Args:
            primary_provider: Primary LLM provider
            fallback_provider: Fallback provider if primary fails
            **kwargs: Additional arguments for LLM creation
            
        Returns:
            LLM instance with fallback capability
        """
        try:
            primary_llm = LLMFactory.create_llm(provider=primary_provider, **kwargs)
            logger.info(f"Primary LLM created: {primary_provider}")
            return primary_llm
        except Exception as e:
            logger.warning(f"Primary LLM creation failed: {e}. Falling back to {fallback_provider}")
            return LLMFactory.create_llm(provider=fallback_provider, **kwargs)

llm_factory = LLMFactory()

BUILDING TOOLS FOR INFORMATION RETRIEVAL

Now we build the tools that our agents will use to gather information. Create a file named tools.py:

import json
import logging
from typing import Dict, Any
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from langchain_core.tools import tool
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut, GeocoderServiceError
import googlemaps
from config import settings
from cache import cache_manager

logger = logging.getLogger(__name__)

geolocator = Nominatim(user_agent="agentic_travel_assistant_v1", timeout=10)

def create_session_with_retries() -> requests.Session:
    """Create a requests session with retry logic."""
    session = requests.Session()
    retry_strategy = Retry(
        total=settings.max_retries,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET", "POST"]
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

http_session = create_session_with_retries()

@tool
def get_weather_forecast(location: str) -> str:
    """
    Get current weather and 7-day forecast for a location.
    
    Args:
        location: City name or address
        
    Returns:
        JSON string with weather information including current conditions and forecast
    """
    cache_key_data = {"location": location}
    cached = cache_manager.get("weather", cache_key_data)
    if cached:
        logger.info(f"Returning cached weather for {location}")
        return json.dumps(cached)
    
    try:
        logger.info(f"Fetching weather for {location}")
        geo_location = geolocator.geocode(location)
        if not geo_location:
            error_result = {"error": f"Could not find coordinates for {location}"}
            return json.dumps(error_result)
        
        lat, lon = geo_location.latitude, geo_location.longitude
        api_key = settings.weather_api_key
        
        url = "https://api.weatherapi.com/v1/forecast.json"
        params = {
            "key": api_key,
            "q": f"{lat},{lon}",
            "days": 7,
            "aqi": "no",
            "alerts": "no"
        }
        
        response = http_session.get(url, params=params, timeout=settings.request_timeout)
        response.raise_for_status()
        data = response.json()
        
        current = data["current"]
        forecast_days = data["forecast"]["forecastday"]
        
        result = {
            "location": location,
            "coordinates": {"latitude": lat, "longitude": lon},
            "current": {
                "temperature_c": current["temp_c"],
                "temperature_f": current["temp_f"],
                "condition": current["condition"]["text"],
                "humidity": current["humidity"],
                "wind_kph": current["wind_kph"],
                "wind_mph": current["wind_mph"],
                "feels_like_c": current["feelslike_c"],
                "feels_like_f": current["feelslike_f"],
                "uv_index": current["uv"]
            },
            "forecast": [
                {
                    "date": day["date"],
                    "max_temp_c": day["day"]["maxtemp_c"],
                    "min_temp_c": day["day"]["mintemp_c"],
                    "max_temp_f": day["day"]["maxtemp_f"],
                    "min_temp_f": day["day"]["mintemp_f"],
                    "avg_temp_c": day["day"]["avgtemp_c"],
                    "avg_temp_f": day["day"]["avgtemp_f"],
                    "condition": day["day"]["condition"]["text"],
                    "chance_of_rain": day["day"]["daily_chance_of_rain"],
                    "max_wind_kph": day["day"]["maxwind_kph"],
                    "max_wind_mph": day["day"]["maxwind_mph"],
                    "avg_humidity": day["day"]["avghumidity"],
                    "uv_index": day["day"]["uv"]
                }
                for day in forecast_days
            ]
        }
        
        cache_manager.set("weather", cache_key_data, result, ttl=settings.weather_cache_ttl)
        logger.info(f"Successfully fetched and cached weather for {location}")
        return json.dumps(result)
        
    except (GeocoderTimedOut, GeocoderServiceError) as e:
        logger.error(f"Geocoding error for {location}: {e}")
        return json.dumps({"error": f"Geocoding service error: {str(e)}"})
    except requests.RequestException as e:
        logger.error(f"Weather API error for {location}: {e}")
        return json.dumps({"error": f"Weather API error: {str(e)}"})
    except Exception as e:
        logger.error(f"Unexpected error fetching weather for {location}: {e}")
        return json.dumps({"error": f"Unexpected error: {str(e)}"})

@tool
def search_places(location: str, place_type: str, radius_km: int = 20) -> str:
    """
    Search for places near a location.
    
    Args:
        location: City name or address to search near
        place_type: Type of place (attractions, hotels, restaurants, cafes)
        radius_km: Search radius in kilometers (default: 20)
        
    Returns:
        JSON string with list of places including names, ratings, and descriptions
    """
    cache_key_data = {"location": location, "place_type": place_type, "radius_km": radius_km}
    cached = cache_manager.get("places", cache_key_data)
    if cached:
        logger.info(f"Returning cached places for {location}/{place_type}")
        return json.dumps(cached)
    
    try:
        logger.info(f"Searching for {place_type} near {location}")
        geo_location = geolocator.geocode(location)
        if not geo_location:
            error_result = {"error": f"Could not find coordinates for {location}"}
            return json.dumps(error_result)
        
        lat, lon = geo_location.latitude, geo_location.longitude
        gmaps = googlemaps.Client(key=settings.google_maps_api_key)
        
        type_mapping = {
            "attractions": "tourist_attraction",
            "hotels": "lodging",
            "restaurants": "restaurant",
            "cafes": "cafe"
        }
        
        google_type = type_mapping.get(place_type.lower(), "point_of_interest")
        radius_meters = radius_km * 1000
        
        places_result = gmaps.places_nearby(
            location=(lat, lon),
            radius=radius_meters,
            type=google_type
        )
        
        places = []
        for place in places_result.get("results", [])[:15]:
            place_info = {
                "name": place.get("name", "Unknown"),
                "rating": place.get("rating", "N/A"),
                "user_ratings_total": place.get("user_ratings_total", 0),
                "address": place.get("vicinity", "Address not available"),
                "types": place.get("types", []),
                "price_level": place.get("price_level", "N/A"),
                "open_now": place.get("opening_hours", {}).get("open_now", "N/A") if "opening_hours" in place else "N/A"
            }
            
            if "geometry" in place and "location" in place["geometry"]:
                place_info["coordinates"] = {
                    "lat": place["geometry"]["location"]["lat"],
                    "lng": place["geometry"]["location"]["lng"]
                }
            
            places.append(place_info)
        
        result = {
            "location": location,
            "place_type": place_type,
            "radius_km": radius_km,
            "count": len(places),
            "places": places
        }
        
        cache_manager.set("places", cache_key_data, result, ttl=settings.places_cache_ttl)
        logger.info(f"Successfully fetched and cached {len(places)} {place_type} for {location}")
        return json.dumps(result)
        
    except (GeocoderTimedOut, GeocoderServiceError) as e:
        logger.error(f"Geocoding error for {location}: {e}")
        return json.dumps({"error": f"Geocoding service error: {str(e)}"})
    except googlemaps.exceptions.ApiError as e:
        logger.error(f"Google Maps API error for {location}: {e}")
        return json.dumps({"error": f"Google Maps API error: {str(e)}"})
    except Exception as e:
        logger.error(f"Unexpected error searching places for {location}: {e}")
        return json.dumps({"error": f"Unexpected error: {str(e)}"})

@tool
def get_general_info(location: str) -> str:
    """
    Get general information about a location including population, language, currency, history.
    
    Args:
        location: City or country name
        
    Returns:
        JSON string with general information and statistics about the location
    """
    cache_key_data = {"location": location}
    cached = cache_manager.get("general_info", cache_key_data)
    if cached:
        logger.info(f"Returning cached general info for {location}")
        return json.dumps(cached)
    
    try:
        logger.info(f"Fetching general information for {location}")
        search_url = "https://en.wikipedia.org/w/api.php"
        
        search_params = {
            "action": "query",
            "format": "json",
            "list": "search",
            "srsearch": location,
            "srlimit": 1
        }
        
        search_response = http_session.get(
            search_url, 
            params=search_params, 
            timeout=settings.request_timeout
        )
        search_response.raise_for_status()
        search_data = search_response.json()
        
        if not search_data.get("query", {}).get("search"):
            error_result = {"error": f"No information found for {location}"}
            return json.dumps(error_result)
        
        page_title = search_data["query"]["search"][0]["title"]
        page_snippet = search_data["query"]["search"][0].get("snippet", "")
        
        content_params = {
            "action": "query",
            "format": "json",
            "titles": page_title,
            "prop": "extracts|info",
            "exintro": True,
            "explaintext": True,
            "inprop": "url"
        }
        
        content_response = http_session.get(
            search_url, 
            params=content_params, 
            timeout=settings.request_timeout
        )
        content_response.raise_for_status()
        content_data = content_response.json()
        
        pages = content_data.get("query", {}).get("pages", {})
        page = next(iter(pages.values()))
        
        extract = page.get("extract", "No description available")
        page_url = page.get("fullurl", "")
        
        summary_length = 2000
        summary = extract[:summary_length] + "..." if len(extract) > summary_length else extract
        
        result = {
            "location": location,
            "title": page_title,
            "summary": summary,
            "snippet": page_snippet,
            "source_url": page_url,
            "source": "Wikipedia"
        }
        
        cache_manager.set("general_info", cache_key_data, result, ttl=settings.general_info_cache_ttl)
        logger.info(f"Successfully fetched and cached general info for {location}")
        return json.dumps(result)
        
    except requests.RequestException as e:
        logger.error(f"Wikipedia API error for {location}: {e}")
        return json.dumps({"error": f"Wikipedia API error: {str(e)}"})
    except Exception as e:
        logger.error(f"Unexpected error fetching general info for {location}: {e}")
        return json.dumps({"error": f"Unexpected error: {str(e)}"})

@tool
def generate_map(location: str, zoom: int = 13) -> str:
    """
    Generate a map URL for a location.
    
    Args:
        location: City name or address
        zoom: Map zoom level (1-20, default: 13)
        
    Returns:
        JSON string with map information including coordinates and URLs
    """
    cache_key_data = {"location": location, "zoom": zoom}
    cached = cache_manager.get("map", cache_key_data)
    if cached:
        logger.info(f"Returning cached map for {location}")
        return json.dumps(cached)
    
    try:
        logger.info(f"Generating map for {location}")
        geo_location = geolocator.geocode(location)
        if not geo_location:
            error_result = {"error": f"Could not find coordinates for {location}"}
            return json.dumps(error_result)
        
        lat, lon = geo_location.latitude, geo_location.longitude
        
        google_maps_url = f"https://www.google.com/maps/@{lat},{lon},{zoom}z"
        google_maps_search = f"https://www.google.com/maps/search/?api=1&query={lat},{lon}"
        google_maps_embed = f"https://www.google.com/maps/embed/v1/place?key={settings.google_maps_api_key}&q={lat},{lon}&zoom={zoom}"
        openstreetmap_url = f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom={zoom}"
        
        result = {
            "location": location,
            "coordinates": {
                "latitude": lat,
                "longitude": lon
            },
            "zoom": zoom,
            "maps": {
                "google_maps": google_maps_url,
                "google_maps_search": google_maps_search,
                "google_maps_embed": google_maps_embed,
                "openstreetmap": openstreetmap_url
            }
        }
        
        cache_manager.set("map", cache_key_data, result, ttl=settings.map_cache_ttl)
        logger.info(f"Successfully generated and cached map for {location}")
        return json.dumps(result)
        
    except (GeocoderTimedOut, GeocoderServiceError) as e:
        logger.error(f"Geocoding error for {location}: {e}")
        return json.dumps({"error": f"Geocoding service error: {str(e)}"})
    except Exception as e:
        logger.error(f"Unexpected error generating map for {location}: {e}")
        return json.dumps({"error": f"Unexpected error: {str(e)}"})

IMPLEMENTING SPECIALIZED AGENTS

Now we build the specialized agents. Create a file named agents.py:

import logging
from typing import List, Dict, Any, Optional
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from tools import get_weather_forecast, search_places, get_general_info, generate_map

logger = logging.getLogger(__name__)

class WeatherAgent:
    """Agent responsible for weather information retrieval."""
    
    def __init__(self, llm: BaseChatModel):
        """Initialize the weather agent."""
        self.llm = llm
        self.tools = [get_weather_forecast]
        
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are a weather information specialist. 
            Your job is to retrieve accurate weather information for locations.
            Use the available tools to get current weather and forecasts.
            Present the information in a clear, user-friendly format.
            Include current conditions and the 7-day forecast.
            Highlight important weather patterns or warnings."""),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad")
        ])
        
        agent = create_tool_calling_agent(self.llm, self.tools, self.prompt)
        self.executor = AgentExecutor(
            agent=agent,
            tools=self.tools,
            verbose=True,
            max_iterations=5,
            handle_parsing_errors=True,
            return_intermediate_steps=False
        )
    
    def get_weather(self, location: str) -> str:
        """Get weather information for a location."""
        try:
            logger.info(f"WeatherAgent processing request for {location}")
            result = self.executor.invoke({
                "input": f"Get the current weather and 7-day forecast for {location}. Present it in a clear, organized format."
            })
            return result.get("output", "Could not retrieve weather information")
        except Exception as e:
            logger.error(f"WeatherAgent error for {location}: {e}")
            return f"Error getting weather information: {str(e)}"


class InformationAgent:
    """Agent responsible for finding attractions, hotels, restaurants, and cafes."""
    
    def __init__(self, llm: BaseChatModel):
        """Initialize the information agent."""
        self.llm = llm
        self.tools = [search_places]
        
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are a local information specialist.
            Your job is to find attractions, hotels, restaurants, and cafes near a location.
            Use the search_places tool multiple times to gather comprehensive information.
            Search for each category separately: attractions, hotels, restaurants, and cafes.
            Present the results in an organized, easy-to-read format.
            Include ratings, addresses, and other relevant details.
            Highlight top-rated options and provide variety in recommendations."""),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad")
        ])
        
        agent = create_tool_calling_agent(self.llm, self.tools, self.prompt)
        self.executor = AgentExecutor(
            agent=agent,
            tools=self.tools,
            verbose=True,
            max_iterations=10,
            handle_parsing_errors=True,
            return_intermediate_steps=False
        )
    
    def search_location(self, location: str, radius_km: int = 20) -> str:
        """Search for places near a location."""
        try:
            logger.info(f"InformationAgent processing request for {location}")
            result = self.executor.invoke({
                "input": f"Find attractions, hotels, restaurants, and cafes within {radius_km}km of {location}. Search each category separately and present organized results."
            })
            return result.get("output", "Could not retrieve location information")
        except Exception as e:
            logger.error(f"InformationAgent error for {location}: {e}")
            return f"Error searching for places: {str(e)}"


class GeneralInfoAgent:
    """Agent responsible for general information and statistics."""
    
    def __init__(self, llm: BaseChatModel):
        """Initialize the general information agent."""
        self.llm = llm
        self.tools = [get_general_info]
        
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are a general information specialist.
            Your job is to provide comprehensive background information about locations.
            This includes population, languages spoken, currency, important historical events,
            public transportation, culture, and other relevant statistics.
            Use the available tools to gather this information.
            Present it in a well-organized, informative format.
            Focus on practical information that travelers would find useful."""),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad")
        ])
        
        agent = create_tool_calling_agent(self.llm, self.tools, self.prompt)
        self.executor = AgentExecutor(
            agent=agent,
            tools=self.tools,
            verbose=True,
            max_iterations=5,
            handle_parsing_errors=True,
            return_intermediate_steps=False
        )
    
    def get_info(self, location: str) -> str:
        """Get general information about a location."""
        try:
            logger.info(f"GeneralInfoAgent processing request for {location}")
            result = self.executor.invoke({
                "input": f"Get comprehensive general information about {location} including population, languages, currency, history, culture, and transportation. Focus on practical travel information."
            })
            return result.get("output", "Could not retrieve general information")
        except Exception as e:
            logger.error(f"GeneralInfoAgent error for {location}: {e}")
            return f"Error getting general information: {str(e)}"


class MapAgent:
    """Agent responsible for map generation."""
    
    def __init__(self, llm: BaseChatModel):
        """Initialize the map agent."""
        self.llm = llm
        self.tools = [generate_map]
        
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are a mapping specialist.
            Your job is to generate map information for locations.
            Use the available tools to create map URLs and coordinate information.
            Provide clear instructions on how to access and use the maps.
            Include both Google Maps and OpenStreetMap options."""),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad")
        ])
        
        agent = create_tool_calling_agent(self.llm, self.tools, self.prompt)
        self.executor = AgentExecutor(
            agent=agent,
            tools=self.tools,
            verbose=True,
            max_iterations=3,
            handle_parsing_errors=True,
            return_intermediate_steps=False
        )
    
    def get_map(self, location: str, zoom: int = 13) -> str:
        """Get map information for a location."""
        try:
            logger.info(f"MapAgent processing request for {location}")
            result = self.executor.invoke({
                "input": f"Generate map information for {location} with zoom level {zoom}. Provide clear access instructions."
            })
            return result.get("output", "Could not generate map information")
        except Exception as e:
            logger.error(f"MapAgent error for {location}: {e}")
            return f"Error generating map: {str(e)}"


class CollectorAgent:
    """Agent responsible for collecting and formatting information from other agents."""
    
    def __init__(self, llm: BaseChatModel):
        """Initialize the collector agent."""
        self.llm = llm
        
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are a professional travel report writer.
            Your job is to take information from various sources and create a comprehensive,
            well-formatted travel guide.
            
            Structure the report as follows:
            1. Title and Introduction - Brief engaging overview of the destination
            2. Overview - General information (population, language, currency, culture)
            3. Weather - Current conditions and forecast with travel recommendations
            4. Top Attractions - Must-see sights and activities
            5. Accommodation - Hotel recommendations with ratings
            6. Dining - Restaurant and cafe recommendations
            7. Getting Around - Transportation and map information
            8. Travel Tips - Practical advice and important information
            
            Use clear headings and organize information logically.
            Make it informative, engaging, and practical for travelers.
            Highlight key information and provide actionable recommendations.
            If any information is missing or contains errors, note it professionally."""),
            ("human", "{input}")
        ])
    
    def create_report(self, location: str, data: Dict[str, str]) -> str:
        """Create a formatted travel report from collected data."""
        try:
            logger.info(f"CollectorAgent creating report for {location}")
            
            input_text = f"""Create a comprehensive travel guide for {location}.

Use the following information gathered from various sources:

GENERAL INFORMATION:
{data.get('general_info', 'Not available')}

WEATHER INFORMATION:
{data.get('weather', 'Not available')}

PLACES (Attractions, Hotels, Restaurants, Cafes):
{data.get('places', 'Not available')}

MAP INFORMATION:
{data.get('map', 'Not available')}

Create a well-structured, engaging travel guide that synthesizes all this information.
Make it practical and useful for someone planning to visit {location}."""
            
            messages = self.prompt.format_messages(input=input_text)
            response = self.llm.invoke(messages)
            logger.info(f"CollectorAgent successfully created report for {location}")
            return response.content
            
        except Exception as e:
            logger.error(f"CollectorAgent error for {location}: {e}")
            return f"Error creating travel report: {str(e)}"


class TravelAgent:
    """Main travel agent that coordinates specialized agents."""
    
    def __init__(self, 
                 llm: BaseChatModel,
                 weather_agent: WeatherAgent,
                 info_agent: InformationAgent,
                 general_agent: GeneralInfoAgent,
                 map_agent: MapAgent,
                 collector_agent: CollectorAgent):
        """Initialize the travel agent coordinator."""
        self.llm = llm
        self.weather_agent = weather_agent
        self.info_agent = info_agent
        self.general_agent = general_agent
        self.map_agent = map_agent
        self.collector_agent = collector_agent
        self.conversation_history: List[Any] = []
        
        self.system_prompt = """You are a helpful travel assistant.
        Your job is to help users plan their trips by providing comprehensive travel information.
        
        When a user asks about a destination:
        1. First, clarify the exact location if needed (city, country, specific area)
        2. Ask about any specific preferences (budget, interests, travel dates) if relevant
        3. Coordinate with specialized agents to gather information
        4. Present a comprehensive travel guide
        
        Be friendly, helpful, and thorough. Ask clarifying questions when needed."""
    
    def _needs_clarification(self, user_input: str) -> Optional[str]:
        """Determine if user input needs clarification."""
        try:
            messages = [
                SystemMessage(content="""Analyze the user's travel request.
                Determine if you need clarification about:
                - The specific location (is it clear which city/country?)
                - The purpose or context of the trip
                - Any specific requirements or preferences
                
                If clarification is needed, respond with a specific, friendly question.
                If the request is clear enough to proceed, respond with exactly "CLEAR".
                Do not add any explanation, just "CLEAR"."""),
                HumanMessage(content=f"User request: {user_input}")
            ]
            
            response = self.llm.invoke(messages)
            clarification = response.content.strip()
            
            if clarification == "CLEAR" or "CLEAR" in clarification.upper():
                return None
            return clarification
        except Exception as e:
            logger.error(f"Error in _needs_clarification: {e}")
            return None
    
    def _extract_location(self, conversation: List[Any]) -> Optional[str]:
        """Extract the destination location from conversation."""
        try:
            conversation_text = "\n".join([
                f"{'User' if isinstance(msg, HumanMessage) else 'Assistant'}: {msg.content}"
                for msg in conversation
            ])
            
            messages = [
                SystemMessage(content="""Extract the destination location from this conversation.
                Return only the location name (city and/or country if mentioned).
                If no clear location is mentioned, return exactly "UNKNOWN".
                Do not add any explanation, just the location name or "UNKNOWN"."""),
                HumanMessage(content=conversation_text)
            ]
            
            response = self.llm.invoke(messages)
            location = response.content.strip()
            
            if location == "UNKNOWN" or "UNKNOWN" in location.upper():
                return None
            return location
        except Exception as e:
            logger.error(f"Error in _extract_location: {e}")
            return None
    
    def process_request(self, user_input: str) -> str:
        """Process a user request."""
        self.conversation_history.append(HumanMessage(content=user_input))
        
        clarification = self._needs_clarification(user_input)
        if clarification:
            logger.info("Requesting clarification from user")
            self.conversation_history.append(AIMessage(content=clarification))
            return clarification
        
        location = self._extract_location(self.conversation_history)
        if not location:
            response = "I'd be happy to help you with travel information! Which destination are you interested in learning about?"
            logger.info("Could not extract location, requesting specification")
            self.conversation_history.append(AIMessage(content=response))
            return response
        
        try:
            logger.info(f"Processing comprehensive travel request for {location}")
            print(f"\n{'='*70}")
            print(f"Gathering comprehensive travel information for {location}")
            print(f"{'='*70}\n")
            
            print("Step 1/4: Fetching general information...")
            general_info = self.general_agent.get_info(location)
            print("  ✓ General information retrieved\n")
            
            print("Step 2/4: Getting weather forecast...")
            weather_info = self.weather_agent.get_weather(location)
            print("  ✓ Weather forecast retrieved\n")
            
            print("Step 3/4: Searching for attractions, hotels, and restaurants...")
            places_info = self.info_agent.search_location(location)
            print("  ✓ Places information retrieved\n")
            
            print("Step 4/4: Generating map information...")
            map_info = self.map_agent.get_map(location)
            print("  ✓ Map information retrieved\n")
            
            print("Compiling comprehensive travel guide...")
            data = {
                'general_info': general_info,
                'weather': weather_info,
                'places': places_info,
                'map': map_info
            }
            
            report = self.collector_agent.create_report(location, data)
            print("  ✓ Travel guide compiled successfully\n")
            print(f"{'='*70}\n")
            
            self.conversation_history.append(AIMessage(content=report))
            logger.info(f"Successfully processed request for {location}")
            return report
            
        except Exception as e:
            error_msg = f"I encountered an error while gathering information about {location}: {str(e)}\nPlease try again or ask about a different destination."
            logger.error(f"Error processing request for {location}: {e}")
            self.conversation_history.append(AIMessage(content=error_msg))
            return error_msg
    
    def reset_conversation(self):
        """Reset conversation history."""
        self.conversation_history = []
        logger.info("Conversation history reset")

CREATING THE USER INTERFACE

Now create the main application file named main.py:

import sys
import logging
from llm_factory import llm_factory
from agents import WeatherAgent, InformationAgent, GeneralInfoAgent, MapAgent, CollectorAgent, TravelAgent
from cache import cache_manager
from config import settings

logging.basicConfig(
    level=getattr(logging, settings.log_level),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('travel_assistant.log'),
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger(__name__)

def print_banner():
    """Print application banner."""
    banner = """
╔══════════════════════════════════════════════════════════════════════╗
║                                                                      ║
║              AGENTIC TRAVEL ASSISTANT                                ║
║              Powered by LangChain                                    ║
║                                                                      ║
╚══════════════════════════════════════════════════════════════════════╝
    """
    print(banner)

def print_system_info():
    """Print system configuration information."""
    print(f"\nSystem Configuration:")
    print(f"  LLM Provider: {settings.llm_provider}")
    print(f"  LLM Model: {settings.llm_model}")
    print(f"  Temperature: {settings.llm_temperature}")
    print(f"  Cache Status: {'Enabled' if cache_manager.health_check() else 'Disabled'}")
    if cache_manager.health_check():
        stats = cache_manager.get_stats()
        print(f"  Cache Keys: {stats.get('total_keys', 0)}")
        print(f"  Cache Memory: {stats.get('used_memory', 'N/A')}")
    print()

def initialize_agents():
    """Initialize all agents."""
    try:
        logger.info("Initializing LLM and agents...")
        print("Initializing AI agents...")
        
        llm = llm_factory.create_llm()
        print("  ✓ Language model initialized")
        
        weather_agent = WeatherAgent(llm)
        print("  ✓ Weather agent ready")
        
        info_agent = InformationAgent(llm)
        print("  ✓ Information agent ready")
        
        general_agent = GeneralInfoAgent(llm)
        print("  ✓ General information agent ready")
        
        map_agent = MapAgent(llm)
        print("  ✓ Map agent ready")
        
        collector_agent = CollectorAgent(llm)
        print("  ✓ Collector agent ready")
        
        travel_agent = TravelAgent(
            llm=llm,
            weather_agent=weather_agent,
            info_agent=info_agent,
            general_agent=general_agent,
            map_agent=map_agent,
            collector_agent=collector_agent
        )
        print("  ✓ Travel coordinator ready")
        
        logger.info("All agents initialized successfully")
        return travel_agent
        
    except Exception as e:
        logger.error(f"Failed to initialize agents: {e}")
        print(f"\nError initializing agents: {e}")
        print("Please check your configuration and API keys.")
        sys.exit(1)

def print_help():
    """Print help information."""
    help_text = """
Available Commands:
  - Type your travel question or destination name
  - 'help' - Show this help message
  - 'reset' - Start a new conversation
  - 'stats' - Show cache statistics
  - 'clear' - Clear all cached data
  - 'quit' or 'exit' - Exit the application

Example Questions:
  - "Tell me about Paris"
  - "I want to visit Tokyo"
  - "What's the weather like in Barcelona?"
  - "Find hotels in Rome"
    """
    print(help_text)

def main():
    """Main entry point for the travel assistant."""
    print_banner()
    
    if not cache_manager.health_check():
        logger.warning("Redis is not available. Caching will be disabled.")
        print("⚠ WARNING: Redis is not available. The application will work but caching is disabled.")
        print("  For better performance, please ensure Redis is running on localhost:6379\n")
    
    print_system_info()
    
    travel_agent = initialize_agents()
    
    print("\n" + "="*70)
    print("\nWelcome to the Agentic Travel Assistant!")
    print("I can provide comprehensive travel information for any destination.")
    print("\nType 'help' for available commands or just ask about a destination.")
    print("="*70 + "\n")
    
    while True:
        try:
            user_input = input("\nšŸŒ You: ").strip()
            
            if not user_input:
                continue
            
            if user_input.lower() in ['quit', 'exit', 'q']:
                print("\n✈️  Thank you for using the Agentic Travel Assistant.")
                print("Safe travels and happy adventures!")
                logger.info("Application terminated by user")
                break
            
            if user_input.lower() == 'help':
                print_help()
                continue
            
            if user_input.lower() == 'reset':
                travel_agent.reset_conversation()
                print("\n✓ Conversation reset. You can start a new query.\n")
                continue
            
            if user_input.lower() == 'stats':
                if cache_manager.health_check():
                    stats = cache_manager.get_stats()
                    print(f"\nCache Statistics:")
                    print(f"  Status: {stats.get('status', 'unknown')}")
                    print(f"  Total Keys: {stats.get('total_keys', 0)}")
                    print(f"  Memory Used: {stats.get('used_memory', 'N/A')}")
                    print(f"  Connected Clients: {stats.get('connected_clients', 0)}")
                else:
                    print("\nCache is not available.")
                continue
            
            if user_input.lower() == 'clear':
                if cache_manager.health_check():
                    cache_manager.clear_all()
                    print("\n✓ All cached data cleared.")
                else:
                    print("\nCache is not available.")
                continue
            
            print("\nšŸ¤– Assistant: ", end="", flush=True)
            response = travel_agent.process_request(user_input)
            print(response)
            print("\n" + "-"*70)
            
        except KeyboardInterrupt:
            print("\n\n✈️  Goodbye! Safe travels!")
            logger.info("Application interrupted by user")
            break
        except Exception as e:
            logger.error(f"Unexpected error in main loop: {e}")
            print(f"\n❌ An unexpected error occurred: {str(e)}")
            print("Please try again or type 'quit' to exit.\n")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logger.critical(f"Critical error: {e}")
        print(f"\n❌ Critical error: {e}")
        sys.exit(1)

ENVIRONMENT CONFIGURATION

Finally, create an .env.example file as a template:

# LLM Provider Configuration
LLM_PROVIDER=openai
LLM_MODEL=gpt-4-turbo-preview
LLM_TEMPERATURE=0.7
LLM_MAX_TOKENS=4096

# API Keys
OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
GOOGLE_API_KEY=your_google_api_key_here
GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here
WEATHER_API_KEY=your_weather_api_key_here

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=

# Cache TTL Settings (in seconds)
CACHE_TTL=3600
WEATHER_CACHE_TTL=3600
PLACES_CACHE_TTL=86400
GENERAL_INFO_CACHE_TTL=604800
MAP_CACHE_TTL=2592000

# Request Configuration
REQUEST_TIMEOUT=30
MAX_RETRIES=3

# Logging
LOG_LEVEL=INFO

RUNNING THE APPLICATION

To run the complete application:

  1. Ensure Redis is running:

    redis-cli ping
    
  2. Copy the example environment file and add your API keys:

    cp .env.example .env
    
  3. Run the application:

    python main.py
    

Try asking questions like "Tell me about Barcelona" or "I want to visit Tokyo" and watch as the multi-agent system collaborates to provide comprehensive travel information.

CONCLUSION

Congratulations! You have built a sophisticated multi-agent AI system using LangChain. This travel assistant demonstrates the power of agentic AI through specialized agents working in harmony, intelligent caching for performance optimization, support for multiple LLM providers, robust error handling and logging, and a production-ready architecture.

The system you have created is extensible and maintainable. You can easily add new agents for additional functionality. The modular design ensures that changes to one agent do not affect others.

This tutorial has covered the fundamentals of building agentic AI systems, from understanding the core concepts to implementing a complete production-ready application. You now have the knowledge and tools to create your own multi-agent systems for any domain.