A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix ai_travel_planning_agent - add env comments, rewrite em dashes, add docstring, fix retry/cleanup bug, switch to GA model, add demo
Tiioluwani47e6aaa821f8
diff --git a/ai_agents/ai_travel_planning_agent/.env.example b/ai_agents/ai_travel_planning_agent/.env.exampleindex f811add..8e67145 100644--- a/ai_agents/ai_travel_planning_agent/.env.example+++ b/ai_agents/ai_travel_planning_agent/.env.example@@ -1,2 +1,7 @@+# Google AI Studio API key used to authenticate Gemini requests for all agents.+# Get one at https://aistudio.google.com/app/apikeyGOOGLE_API_KEY=your_google_api_key_here++# Tavily API key used for real-time web search by the flight, hotel, and itinerary agents.+# Get one at https://app.tavily.comTAVILY_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.mdindex 9db5761..f709ec5 100644--- a/ai_agents/ai_travel_planning_agent/README.md+++ b/ai_agents/ai_travel_planning_agent/README.md@@ -1,10 +1,15 @@+<a id="top"></a># 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.+## Demo+++## 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.+The AI Travel Planning Agent uses a root Google ADK agent to coordinate three specialist sub-agents: a Flight Agent, a Hotel Agent, and an 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@@ -12,14 +17,14 @@ The AI Travel Planning Agent uses a root Google ADK agent to coordinate three sp- 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+- Multi-turn conversation, so you can 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`) |+| LLM | Gemini 3.5 Flash (`gemini-3.5-flash`) || Web search | Tavily Search API || Location data | geopy + Nominatim (OpenStreetMap) || UI | Streamlit |@@ -112,5 +117,9 @@ ai-travel-planning-agent/├── tools.py # Tavily search and Nominatim location tools├── requirements.txt # Python dependencies├── .env.example # Environment variable template-└── .env # Your local API keys (git-ignored)+├── .env # Your local API keys (git-ignored)+└── assets/+ └── demo.png # Demo screenshot```++[Back to top](#top)diff --git a/ai_agents/ai_travel_planning_agent/agents.py b/ai_agents/ai_travel_planning_agent/agents.pyindex 65c5281..a1d6ca3 100644--- a/ai_agents/ai_travel_planning_agent/agents.py+++ b/ai_agents/ai_travel_planning_agent/agents.py@@ -2,7 +2,7 @@ from google.adk.agents import LlmAgentfrom google.adk.tools.agent_tool import AgentToolfrom tools import tavily_search, find_nearby_places-MODEL = "gemini-3-flash-preview"+MODEL = "gemini-3.5-flash"# ---------------------------------------------------------------------------# Specialist sub-agentsdiff --git a/ai_agents/ai_travel_planning_agent/app.py b/ai_agents/ai_travel_planning_agent/app.pyindex d61d6c5..f858565 100644--- a/ai_agents/ai_travel_planning_agent/app.py+++ b/ai_agents/ai_travel_planning_agent/app.py@@ -1,11 +1,22 @@+"""Streamlit chat app that coordinates flight, hotel, and itinerary agents into one travel plan."""import osimport asyncio+import loggingimport uuid# Load .env before any ADK/Google imports so API keys are availablefrom dotenv import load_dotenvload_dotenv()+# ADK logs the full traceback for every transient model error (even ones it+# or our own retry logic recovers from). We surface failures via the UI+# instead, so quiet this logger to keep the terminal readable.+logging.getLogger("google_adk").setLevel(logging.CRITICAL)++_TRANSIENT_ERROR_MARKERS = ("503", "UNAVAILABLE", "high demand")+_QUOTA_ERROR_MARKERS = ("429", "RESOURCE_EXHAUSTED")+_QUOTA_RETRY_DELAY_SECONDS = 8+import nest_asyncionest_asyncio.apply() # Allow asyncio.run() inside Streamlit's existing event loop@@ -13,6 +24,7 @@ import streamlit as stfrom google.adk.runners import Runnerfrom google.adk.sessions import InMemorySessionServicefrom google.genai import types+from google.genai.errors import ServerErrorfrom agents import root_agent@@ -96,23 +108,76 @@ if "adk_runner" not in st.session_state:# Agent runner helper# ---------------------------------------------------------------------------+def _is_transient_error(message: str) -> bool:+ """Check whether an error message looks like a temporary model-overload error."""+ return any(marker in message for marker in _TRANSIENT_ERROR_MARKERS)+++def _is_quota_error(message: str) -> bool:+ """Check whether an error message looks like a 429 quota/rate-limit error."""+ return any(marker in message for marker in _QUOTA_ERROR_MARKERS)++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(+ agen = 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+ )+ try:+ async for event in agen:+ # Some failures surface as an error event on the stream rather than+ # a raised exception, so check for that before looking for the final response.+ if getattr(event, "error_code", None):+ raise RuntimeError(event.error_message or event.error_code)+ 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+ finally:+ # Close the generator here, in the same task/context it was opened in,+ # so a retry doesn't start a new one while this one is still mid-teardown+ # (that's what was producing the GeneratorExit / OpenTelemetry cleanup errors).+ await agen.aclose()return final_text+async def _stream_response_with_retry(+ runner: Runner,+ session_id: str,+ user_id: str,+ content: types.Content,+ max_attempts: int = 2,+) -> str:+ """Call _stream_response, retrying on transient model errors.++ 503/UNAVAILABLE overload errors use the existing short exponential backoff.+ 429/RESOURCE_EXHAUSTED quota errors get exactly one retry after a longer delay,+ since retrying quota errors quickly just makes the exhaustion worse.+ """+ quota_retried = False+ for attempt in range(1, max_attempts + 1):+ try:+ return await _stream_response(runner, session_id, user_id, content)+ except (ServerError, RuntimeError) as e:+ message = str(e)+ if _is_quota_error(message):+ if attempt == max_attempts or quota_retried:+ raise+ quota_retried = True+ await asyncio.sleep(_QUOTA_RETRY_DELAY_SECONDS)+ elif _is_transient_error(message):+ if attempt == max_attempts:+ raise+ await asyncio.sleep(2 ** attempt)+ else:+ raise++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(@@ -138,7 +203,7 @@ async def _run_agent_async(runner: Runner, session_id: str, user_id: str, messag)try:- final_text = await _stream_response(runner, session_id, user_id, content)+ final_text = await _stream_response_with_retry(runner, session_id, user_id, content)except Exception as e:if "Session not found" in str(e):new_session_id = str(uuid.uuid4())@@ -148,7 +213,11 @@ async def _run_agent_async(runner: Runner, session_id: str, user_id: str, messagsession_id=new_session_id,)st.session_state.session_id = new_session_id- final_text = await _stream_response(runner, new_session_id, user_id, content)+ final_text = await _stream_response_with_retry(runner, new_session_id, user_id, content)+ elif isinstance(e, (ServerError, RuntimeError)) and _is_quota_error(str(e)):+ return "The AI model's quota is temporarily exhausted. Please wait a bit before trying again."+ elif isinstance(e, (ServerError, RuntimeError)) and _is_transient_error(str(e)):+ return "The AI model is temporarily overloaded. Please try again in a moment."else:raisediff --git a/ai_agents/ai_travel_planning_agent/assets/demo.png b/ai_agents/ai_travel_planning_agent/assets/demo.pngnew file mode 100644index 0000000..d302a3eBinary files /dev/null and b/ai_agents/ai_travel_planning_agent/assets/demo.png differ