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!