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:
Ensure Redis is running:
redis-cli pingCopy the example environment file and add your API keys:
cp .env.example .envRun 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.
No comments:
Post a Comment