A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add AI Travel Planning Agent using Google ADK and Gemini
Tiioluwani5740be050701
diff --git a/ai_agents/ai_travel_planning_agent/.env.example b/ai_agents/ai_travel_planning_agent/.env.examplenew file mode 100644index 0000000..f811add--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/.env.example@@ -0,0 +1,2 @@+GOOGLE_API_KEY=your_google_api_key_here+TAVILY_API_KEY=your_tavily_api_key_herediff --git a/ai_agents/ai_travel_planning_agent/README.md b/ai_agents/ai_travel_planning_agent/README.mdnew file mode 100644index 0000000..9db5761--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/README.md@@ -0,0 +1,116 @@+# AI Travel Planning Agent++> Multi-agent travel planner that turns a single natural language request into a complete trip plan with flights, hotels, and a day-by-day itinerary.++## Overview++The AI Travel Planning Agent uses a root Google ADK agent to coordinate three specialist sub-agents — Flight Agent, Hotel Agent, and Itinerary Agent. Each sub-agent independently searches the web in real time, and the root agent combines their results into one cohesive travel plan. Users interact through a Streamlit chat interface and can ask follow-up questions within the same conversational session.++## Features++- Natural language trip planning in a conversational chat UI+- Parallel specialist agents for flights, hotels, and itineraries+- Real-time web search via Tavily on every query+- Nearby place discovery using OpenStreetMap/Nominatim (no extra API key)+- Multi-turn conversation — ask follow-ups after the initial plan++## Tech Stack++| Layer | Technology |+|---|---|+| Agent framework | Google ADK (`google-adk`) |+| LLM | Gemini 3 Flash (`gemini-3-flash-preview`) |+| Web search | Tavily Search API |+| Location data | geopy + Nominatim (OpenStreetMap) |+| UI | Streamlit |++## Prerequisites++- Python 3.10 or higher+- A [Google AI Studio](https://aistudio.google.com/app/apikey) API key+- A [Tavily](https://app.tavily.com) API key++## Installation++**1. Clone the repository**++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/ai_travel_planning_agent+```++**2. Create and activate a virtual environment**++macOS / Linux:+```bash+python -m venv venv+source venv/bin/activate+```++Windows:+```bash+python -m venv venv+venv\Scripts\activate+```++**3. Install dependencies**++```bash+pip install -r requirements.txt+```++**4. Configure environment variables**++```bash+cp .env.example .env+```++Open `.env` and fill in your API keys (see [Environment Variables](#environment-variables)).++## Usage++```bash+streamlit run app.py+```++Open the URL shown in your terminal (usually `http://localhost:8501`).++**Example request:**++> *Plan a 5-day trip to Paris in June, budget $2000, I love art and food*++**What you get back:**++- Suggested outbound and return flights with estimated prices+- Hotel recommendations near key attractions with nightly rates+- A day-by-day itinerary with activities, restaurants, and travel tips++After the plan is generated, you can refine it conversationally:++> *Can you swap the Day 3 museum visit for something outdoors?*++## Environment Variables++Create a `.env` file in the project root with the following keys:++| Variable | Description | Where to get it |+|---|---|---|+| `GOOGLE_API_KEY` | Authenticates requests to Gemini via Google AI Studio | [aistudio.google.com/app/apikey](https://aistudio.google.com/app/apikey) |+| `TAVILY_API_KEY` | Enables real-time web search through Tavily | [app.tavily.com](https://app.tavily.com) |++```env+GOOGLE_API_KEY=your_google_api_key_here+TAVILY_API_KEY=your_tavily_api_key_here+```++## Project Structure++```text+ai-travel-planning-agent/+├── app.py # Streamlit UI and ADK session management+├── agents.py # Root agent and three specialist sub-agents+├── tools.py # Tavily search and Nominatim location tools+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+└── .env # Your local API keys (git-ignored)+```diff --git a/ai_agents/ai_travel_planning_agent/agents.py b/ai_agents/ai_travel_planning_agent/agents.pynew file mode 100644index 0000000..65c5281--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/agents.py@@ -0,0 +1,161 @@+from google.adk.agents import LlmAgent+from google.adk.tools.agent_tool import AgentTool+from tools import tavily_search, find_nearby_places++MODEL = "gemini-3-flash-preview"++# ---------------------------------------------------------------------------+# Specialist sub-agents+# ---------------------------------------------------------------------------++flight_agent = LlmAgent(+ name="flight_agent",+ model=MODEL,+ description="Searches for flight options, prices, airlines, and booking tips.",+ instruction="""You are an expert flight search specialist. Given the traveler's origin,+destination, travel dates, and budget, search for comprehensive flight information.++Use tavily_search to find:+- Available flight routes and airlines serving the route+- Estimated price ranges (economy, premium economy, business class)+- Typical flight durations and layover options+- Best booking platforms and timing tips (how far in advance to book)+- Budget airlines vs full-service carriers on this route+- Any relevant travel alerts or entry requirements++Structure your response clearly with:+1. Direct flights (if available) with price ranges+2. Connecting flight options with price ranges+3. Top airlines for this route+4. Booking recommendations and money-saving tips+5. Estimated total flight budget++Be specific with numbers and airline names. Search for the most current information.""",+ tools=[tavily_search],+)++hotel_agent = LlmAgent(+ name="hotel_agent",+ model=MODEL,+ description="Finds accommodation options across all budgets including hotels, Airbnb, and hostels.",+ instruction="""You are an expert accommodation specialist. Given the destination, travel dates,+duration, and budget, search for the best accommodation options.++Use tavily_search to find:+- Hotels across budget ranges (budget, mid-range, luxury)+- Alternative accommodations (Airbnb, boutique hotels, hostels, serviced apartments)+- Best neighborhoods to stay in for the traveler's interests+- Proximity to main attractions and transport hubs+- Guest ratings, review highlights, and what guests love or dislike+- Current prices and availability insights++Structure your response clearly with:+1. Budget options (under $80/night) - 2-3 recommendations+2. Mid-range options ($80-200/night) - 2-3 recommendations+3. Luxury options ($200+/night) - 1-2 recommendations+4. Best neighborhoods to stay in with reasons+5. Estimated total accommodation budget for the trip+6. Booking tips and platforms to use++Include specific hotel/property names, approximate prices, and ratings.""",+ tools=[tavily_search],+)++itinerary_agent = LlmAgent(+ name="itinerary_agent",+ model=MODEL,+ description="Builds detailed day-by-day travel itineraries with activities, dining, and logistics.",+ instruction="""You are an expert travel itinerary planner. Given the destination, trip duration,+traveler interests, and budget, create a detailed and realistic day-by-day itinerary.++Use tavily_search to find:+- Top attractions, museums, landmarks matching the traveler's interests+- Hidden gems and local favorites beyond tourist traps+- Best restaurants, cafes, street food for each meal and budget level+- Local transportation options (metro, buses, taxis, walking distances)+- Opening hours, admission costs, and booking requirements+- Seasonal events or festivals happening during the travel dates++Use find_nearby_places to get geographic context and coordinates for the main destination+and key neighborhoods to understand the city layout and plan logical routing.++Structure your response as a detailed daily plan:+- Day X: [Theme for the day]+ - Morning (9am-12pm): Activities with estimated time and cost+ - Lunch: Restaurant recommendation with cuisine type and price range+ - Afternoon (1pm-6pm): Activities with estimated time and cost+ - Dinner: Restaurant recommendation with specialty dishes+ - Evening (optional): Nightlife, shows, or relaxation options+ - Transport tips for the day+ - Estimated daily spend++End with a summary of must-see highlights and practical tips for the destination.""",+ tools=[tavily_search, find_nearby_places],+)++# ---------------------------------------------------------------------------+# Root orchestrator agent+# ---------------------------------------------------------------------------++root_agent = LlmAgent(+ name="travel_planning_agent",+ model=MODEL,+ description="AI Travel Planning Agent that coordinates flight, hotel, and itinerary specialists.",+ instruction="""You are an expert AI Travel Planning Coordinator. You create comprehensive,+personalized travel plans by orchestrating three specialist agents.++When a user submits a travel request:+1. Call flight_agent with the full travel details to get flight options+2. Call hotel_agent with the destination, duration, and budget for accommodation options+3. Call itinerary_agent with destination, duration, and interests for the day-by-day plan+4. Combine all three responses into ONE beautifully formatted travel plan++Format the final combined travel plan exactly like this:++---++# 🌍 Your Complete Travel Plan: [Destination]+**Trip Duration:** [X days] | **Budget:** [Amount] | **Travel Style:** [Interests]++---++## ✈️ FLIGHTS+[Insert complete flight agent response here]++---++## 🏨 HOTELS & ACCOMMODATION+[Insert complete hotel agent response here]++---++## 📅 DAY-BY-DAY ITINERARY+[Insert complete itinerary agent response here]++---++## 💰 BUDGET SUMMARY+| Category | Estimated Cost |+|----------|---------------|+| Flights (round trip) | $X |+| Accommodation (X nights) | $X |+| Daily activities & food | $X |+| Local transport | $X |+| **Total Estimated** | **$X** |++## 💡 QUICK TRAVEL TIPS+- [3-5 practical tips specific to the destination]++---++For follow-up questions (e.g., "Can you suggest vegetarian restaurants?", "What if my budget is lower?",+"Tell me more about Day 3"), use the context from the full plan already created to give specific,+helpful answers. You can call specialist agents again for deeper research on specific topics.++Always be enthusiastic, specific, and organize information so it's easy to scan and use.""",+ tools=[+ AgentTool(agent=flight_agent),+ AgentTool(agent=hotel_agent),+ AgentTool(agent=itinerary_agent),+ ],+)diff --git a/ai_agents/ai_travel_planning_agent/app.py b/ai_agents/ai_travel_planning_agent/app.pynew file mode 100644index 0000000..d61d6c5--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/app.py@@ -0,0 +1,214 @@+import os+import asyncio+import uuid++# Load .env before any ADK/Google imports so API keys are available+from dotenv import load_dotenv+load_dotenv()++import nest_asyncio+nest_asyncio.apply() # Allow asyncio.run() inside Streamlit's existing event loop++import streamlit as st+from google.adk.runners import Runner+from google.adk.sessions import InMemorySessionService+from google.genai import types++from agents import root_agent++# ---------------------------------------------------------------------------+# Page config+# ---------------------------------------------------------------------------++st.set_page_config(+ page_title="AI Travel Planning Agent",+ page_icon="✈️",+ layout="wide",+ initial_sidebar_state="expanded",+)++# ---------------------------------------------------------------------------+# Sidebar+# ---------------------------------------------------------------------------++with st.sidebar:+ st.title("✈️ AI Travel Planner")+ st.markdown("---")+ st.markdown(+ "### How to use\n"+ "Type a natural language travel request in the chat below.\n\n"+ "**Example prompts:**\n"+ "- *Plan a 5-day trip to Paris in June, budget $2000, I love art and food*\n"+ "- *Weekend getaway to Tokyo, budget $1500, interested in anime and street food*\n"+ "- *10 days in Italy visiting Rome and Florence, $3000 budget, history lover*\n\n"+ "After the plan is generated, you can ask follow-up questions!"+ )+ st.markdown("---")+ st.markdown(+ "### Powered by\n"+ "- 🤖 Google ADK + Gemini\n"+ "- 🔍 Tavily Search API\n"+ "- 🗺️ OpenStreetMap / Nominatim\n"+ "- 🌐 Streamlit"+ )+ st.markdown("---")++ if st.button("🗑️ Clear Conversation", use_container_width=True):+ st.session_state.messages = []+ st.session_state.session_id = str(uuid.uuid4())+ st.rerun()++ # API key status indicators+ st.markdown("### API Status")+ google_ok = bool(os.getenv("GOOGLE_API_KEY"))+ tavily_ok = bool(os.getenv("TAVILY_API_KEY"))+ st.markdown(+ f"{'✅' if google_ok else '❌'} Google API Key\n\n"+ f"{'✅' if tavily_ok else '❌'} Tavily API Key"+ )+ if not google_ok or not tavily_ok:+ st.warning("Add missing API keys to your `.env` file.")++# ---------------------------------------------------------------------------+# Session state initialization+# ---------------------------------------------------------------------------++if "messages" not in st.session_state:+ st.session_state.messages = []++if "session_id" not in st.session_state:+ st.session_state.session_id = str(uuid.uuid4())++if "user_id" not in st.session_state:+ st.session_state.user_id = "streamlit_user"++if "adk_runner" not in st.session_state:+ session_service = InMemorySessionService()+ runner = Runner(+ agent=root_agent,+ app_name="ai-travel-planning-agent",+ session_service=session_service,+ )+ st.session_state.adk_runner = runner+ st.session_state.adk_session_service = session_service++# ---------------------------------------------------------------------------+# Agent runner helper+# ---------------------------------------------------------------------------++async def _stream_response(runner: Runner, session_id: str, user_id: str, content: types.Content) -> str:+ """Collect the final response text from a single runner.run_async() call."""+ final_text = ""+ async for event in runner.run_async(+ session_id=session_id,+ user_id=user_id,+ new_message=content,+ ):+ if event.is_final_response():+ if event.content and event.content.parts:+ final_text = "\n".join(+ part.text for part in event.content.parts if hasattr(part, "text")+ )+ break+ return final_text+++async def _run_agent_async(runner: Runner, session_id: str, user_id: str, message: str) -> str:+ """Run the ADK agent and collect the final response text."""+ content = types.Content(+ role="user",+ parts=[types.Part(text=message)],+ )++ session_service = st.session_state.adk_session_service+ app_name = "ai-travel-planning-agent"++ # Ensure the session exists in the session service+ try:+ await session_service.get_session(+ app_name=app_name,+ user_id=user_id,+ session_id=session_id,+ )+ except Exception:+ await session_service.create_session(+ app_name=app_name,+ user_id=user_id,+ session_id=session_id,+ )++ try:+ final_text = await _stream_response(runner, session_id, user_id, content)+ except Exception as e:+ if "Session not found" in str(e):+ new_session_id = str(uuid.uuid4())+ await session_service.create_session(+ app_name=app_name,+ user_id=user_id,+ session_id=new_session_id,+ )+ st.session_state.session_id = new_session_id+ final_text = await _stream_response(runner, new_session_id, user_id, content)+ else:+ raise++ return final_text or "I couldn't generate a response. Please try again."+++def get_travel_plan(message: str) -> str:+ """Synchronous wrapper for the async ADK runner."""+ runner: Runner = st.session_state.adk_runner+ session_id: str = st.session_state.session_id+ user_id: str = st.session_state.user_id++ try:+ loop = asyncio.get_event_loop()+ return loop.run_until_complete(+ _run_agent_async(runner, session_id, user_id, message)+ )+ except RuntimeError:+ return asyncio.run(+ _run_agent_async(runner, session_id, user_id, message)+ )++# ---------------------------------------------------------------------------+# Main chat UI+# ---------------------------------------------------------------------------++st.title("🌍 AI Travel Planning Agent")+st.caption(+ "Describe your ideal trip and I'll coordinate flight, hotel, and itinerary specialists to build your complete travel plan."+)++# Render existing conversation history+for msg in st.session_state.messages:+ with st.chat_message(msg["role"]):+ st.markdown(msg["content"])++# Welcome message on first load+if not st.session_state.messages:+ with st.chat_message("assistant"):+ welcome = (+ "👋 Welcome! I'm your AI Travel Planning Agent.\n\n"+ "Tell me about your dream trip and I'll coordinate three specialist agents "+ "(Flight Search, Hotel Finder, and Itinerary Planner) to build you a complete travel plan.\n\n"+ "**Try something like:**\n"+ "> *Plan a 5-day trip to Paris in June, budget $2000, I love art and food*"+ )+ st.markdown(welcome)++# Chat input+if prompt := st.chat_input("Describe your travel plans... (e.g. '5 days in Bali, June, $1500, beaches and culture')"):+ # Show user message+ st.session_state.messages.append({"role": "user", "content": prompt})+ with st.chat_message("user"):+ st.markdown(prompt)++ # Run agents and show response+ with st.chat_message("assistant"):+ with st.spinner("🔍 Coordinating Flight, Hotel & Itinerary agents — this may take 30-60 seconds..."):+ response = get_travel_plan(prompt)++ st.markdown(response)++ st.session_state.messages.append({"role": "assistant", "content": response})diff --git a/ai_agents/ai_travel_planning_agent/requirements.txt b/ai_agents/ai_travel_planning_agent/requirements.txtnew file mode 100644index 0000000..d74abfe--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/requirements.txt@@ -0,0 +1,7 @@+google-adk>=1.0.0+google-genai>=1.0.0+streamlit>=1.32.0+python-dotenv>=1.0.0+tavily-python>=0.3.0+geopy>=2.4.0+nest-asyncio>=1.6.0diff --git a/ai_agents/ai_travel_planning_agent/tools.py b/ai_agents/ai_travel_planning_agent/tools.pynew file mode 100644index 0000000..9251847--- /dev/null+++ b/ai_agents/ai_travel_planning_agent/tools.py@@ -0,0 +1,71 @@+import os+from tavily import TavilyClient+from geopy.geocoders import Nominatim+from geopy.exc import GeocoderTimedOut, GeocoderUnavailable+++def tavily_search(query: str) -> str:+ """Search the web for current travel information using Tavily.++ Args:+ query: The search query string for travel-related information.++ Returns:+ Formatted string of search results with titles, URLs, and content snippets.+ """+ api_key = os.getenv("TAVILY_API_KEY")+ if not api_key:+ return "Error: TAVILY_API_KEY not configured."+ try:+ client = TavilyClient(api_key=api_key)+ response = client.search(+ query=query,+ search_depth="advanced",+ max_results=5,+ include_answer=True,+ )+ parts = []+ if response.get("answer"):+ parts.append(f"Summary: {response['answer']}\n")+ for r in response.get("results", []):+ snippet = r.get("content", "")[:600].strip()+ parts.append(f"**{r['title']}**\nURL: {r['url']}\n{snippet}")+ return "\n\n---\n\n".join(parts) if parts else "No results found."+ except Exception as e:+ return f"Search error: {e}"+++def find_nearby_places(location: str, category: str = "tourist attractions") -> str:+ """Find geographic information and nearby places using OpenStreetMap/Nominatim.++ Args:+ location: City, landmark, or address to look up (e.g., "Paris, France").+ category: Type of places to mention (e.g., "museums", "restaurants", "parks").++ Returns:+ Geographic details including coordinates, full address, and context.+ """+ geolocator = Nominatim(user_agent="ai-travel-planning-agent/1.0", timeout=10)+ try:+ geo = geolocator.geocode(location, addressdetails=True)+ if not geo:+ return f"Could not find geographic data for: {location}"++ address = geo.raw.get("address", {})+ details = {+ "Location": location,+ "Full Address": geo.address,+ "Latitude": f"{geo.latitude:.5f}",+ "Longitude": f"{geo.longitude:.5f}",+ "Country": address.get("country", "N/A"),+ "State/Region": address.get("state", address.get("county", "N/A")),+ "Category Searched": category,+ }+ lines = [f"{k}: {v}" for k, v in details.items()]+ return "\n".join(lines)+ except GeocoderTimedOut:+ return f"Geocoding timed out for: {location}. Try a more specific location name."+ except GeocoderUnavailable:+ return "Nominatim service temporarily unavailable. Please retry."+ except Exception as e:+ return f"Location lookup error: {e}"