A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Travel Planner Agent using Orq.ai, LangChain and OpenWeatherMap
Tiioluwani78e13c208dd4
diff --git a/ai_agents/travel_planner_agent/.env.example b/ai_agents/travel_planner_agent/.env.examplenew file mode 100644index 0000000..e5a7978--- /dev/null+++ b/ai_agents/travel_planner_agent/.env.example@@ -0,0 +1,8 @@+# Orq.ai — LLM routing (deepseek-v4-flash)+ORQ_API_KEY=your_orq_api_key_here++# OpenWeatherMap — current weather and forecast+OPENWEATHER_API_KEY=your_openweather_api_key_here++# ExchangeRate-API — currency conversion+EXCHANGERATE_API_KEY=your_exchangerate_api_key_herediff --git a/ai_agents/travel_planner_agent/README.md b/ai_agents/travel_planner_agent/README.mdnew file mode 100644index 0000000..d7defb0--- /dev/null+++ b/ai_agents/travel_planner_agent/README.md@@ -0,0 +1,153 @@+# Travel Planner Agent++**Your AI co-pilot for end-to-end trip planning — from weather and budget to packing lists and day-by-day itineraries.**++## Overview++Travel Planner Agent is a conversational travel assistant that helps you plan trips through natural language. Describe where you want to go, when, your budget, and what you enjoy — the agent gathers any missing details, researches your destination with live tools, and returns a structured travel plan you can use right away.++Built with LangChain and Streamlit, it combines real-time weather, currency conversion, web research, and smart packing recommendations into a single chat experience.++## Demo++++## Features++- **Conversational trip planning** — describe trips in plain English; the agent asks follow-up questions when details are missing+- **Live weather data** — current conditions and a 5-day forecast for any destination via OpenWeatherMap+- **Budget and currency tools** — convert amounts between currencies and estimate trip costs via ExchangeRate-API+- **Destination research** — attractions, food, culture, and travel tips sourced from DuckDuckGo web search+- **Smart packing lists** — recommendations tailored to forecast, climate, and trip length+- **Structured travel plans** — overview, weather, budget, highlights, packing, and a suggested day-by-day itinerary+- **Session-based chat history** — multi-turn conversations with context preserved in the Streamlit UI++## Tech Stack++| Layer | Technology |+|-------|------------|+| Agent Orchestration | [LangChain](https://www.langchain.com/) + [LangGraph](https://www.langchain.com/langgraph) (`create_agent` tool-calling loop) |+| LLM | [OpenAI SDK](https://github.com/openai/openai-python) → [Orq.ai](https://orq.ai) router (`deepseek-v4-flash`) |+| Weather | [OpenWeatherMap API](https://openweathermap.org/api) |+| Currency | [ExchangeRate-API](https://www.exchangerate-api.com/) |+| Web Search | [DuckDuckGo Search](https://pypi.org/project/duckduckgo-search/) |+| UI | [Streamlit](https://streamlit.io/) chat interface |++## Prerequisites++- **Python 3.10 or higher**+- API keys for:+ - [Orq.ai](https://orq.ai) — LLM routing+ - [OpenWeatherMap](https://openweathermap.org/api) — weather and forecast data+ - [ExchangeRate-API](https://www.exchangerate-api.com/) — currency conversion++## Installation++### 1. Clone the repository++```bash+git clone git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/travel_planner_agent+```++### 2. Create a virtual environment++```bash+python -m venv .venv+```++### 3. Activate the virtual environment++**macOS / Linux**++```bash+source .venv/bin/activate+```++**Windows (PowerShell)**++```powershell+.\.venv\Scripts\Activate.ps1+```++**Windows (Command Prompt)**++```cmd+.venv\Scripts\activate.bat+```++### 4. Install dependencies++```bash+pip install -r requirements.txt+```++### 5. Configure environment variables++```bash+cp .env.example .env+```++Open `.env` and add your API keys. See the [Environment Variables](#environment-variables) section below for details.++## Environment Variables++| Variable | Description | Where to Get It |+|----------|-------------|-----------------|+| `ORQ_API_KEY` | Authenticates requests to the Orq.ai LLM router (`deepseek-v4-flash`) | [Orq.ai Dashboard](https://orq.ai) → API Keys |+| `OPENWEATHER_API_KEY` | Fetches current weather and 5-day forecasts for destinations | [OpenWeatherMap](https://home.openweathermap.org/api_keys) → API keys |+| `EXCHANGERATE_API_KEY` | Converts currencies and returns live exchange rates | [ExchangeRate-API](https://www.exchangerate-api.com/) → Get Free Key |++## Usage++### Run the app++With your virtual environment activated:++```bash+streamlit run app.py+```++Streamlit opens the app in your browser (typically at `http://localhost:8501`). Use the chat input at the bottom of the page to describe your trip.++### Example user inputs++| Scenario | Example prompt |+|----------|----------------|+| Full trip plan | *Plan a 7-day trip to Tokyo in April. My budget is $3,000 USD. I love food, temples, and street photography.* |+| Weather check | *What's the weather like in Barcelona? I'm visiting for 5 days in June.* |+| Currency conversion | *Convert 2,500 USD to EUR and THB for a two-week trip across Europe and Thailand.* |+| Packing help | *I'm going to Iceland for 8 days in February. What should I pack based on the weather?* |++### What the agent returns++Once it has enough context, the agent calls its tools and delivers a structured plan with:++1. **Trip Overview** — destination, dates, duration, and traveler preferences+2. **Weather** — current conditions and a forecast summary from OpenWeatherMap+3. **Budget & Currency** — cost estimates and currency conversions from ExchangeRate-API+4. **Destination Highlights** — attractions, dining, culture, and travel tips from web research+5. **Packing List** — clothing and essentials based on weather and trip length+6. **Suggested Itinerary** — a day-by-day outline aligned with your interests and schedule++The agent uses tools for all factual data (weather, rates, research) rather than guessing. If details are missing, it will ask clarifying questions before building the full plan.++Use **Clear conversation** in the sidebar to start a new trip from scratch.++## Project Structure++```+travel-planner-agent/+├── app.py # Streamlit UI and chat interface+├── agent.py # LangChain agent and tools+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+├── .gitignore+├── README.md+└── assets/+ └── demo.gif # Application demo+```++## License++MITdiff --git a/ai_agents/travel_planner_agent/agent.py b/ai_agents/travel_planner_agent/agent.pynew file mode 100644index 0000000..f1909e2--- /dev/null+++ b/ai_agents/travel_planner_agent/agent.py@@ -0,0 +1,309 @@+"""LangChain travel planner agent with weather, currency, research, and packing tools."""++import os+from typing import Optional++import requests+from dotenv import load_dotenv+from duckduckgo_search import DDGS+from langchain.agents import create_agent+from langchain_core.messages import AIMessage+from langchain_core.tools import tool+from langchain_openai import ChatOpenAI++load_dotenv()++SYSTEM_PROMPT = """You are Travel Planner Agent, an expert travel planning assistant.++Help users plan trips end to end. When they describe a trip, gather missing details (destination, dates, budget, interests, home currency) through natural conversation, then use your tools to research and build a comprehensive plan.++Always use tools for factual data — never invent weather, exchange rates, or attraction details.++When you have enough information, return a structured travel plan with these sections:+1. **Trip Overview** — destination, dates, duration, traveler context+2. **Weather** — current conditions and forecast summary (from weather tool)+3. **Budget & Currency** — estimated costs and conversions (from currency tool)+4. **Destination Highlights** — attractions, food, culture, tips (from research tool)+5. **Packing List** — tailored recommendations (from packing tool; pass weather summary)+6. **Suggested Itinerary** — day-by-day outline based on interests and duration++Be friendly, concise, and practical. Ask clarifying questions when key details are missing."""+++def _require_key(name: str) -> str:+ value = os.getenv(name)+ if not value:+ raise ValueError(f"Missing environment variable: {name}")+ return value+++@tool+def get_weather(destination: str) -> str:+ """Fetch current weather and a 5-day forecast for a destination city or location.++ Args:+ destination: City name (e.g. 'Tokyo', 'Paris, France').+ """+ api_key = _require_key("OPENWEATHER_API_KEY")+ base = "https://api.openweathermap.org/data/2.5"++ try:+ current_resp = requests.get(+ f"{base}/weather",+ params={"q": destination, "appid": api_key, "units": "metric"},+ timeout=15,+ )+ current_resp.raise_for_status()+ current = current_resp.json()++ forecast_resp = requests.get(+ f"{base}/forecast",+ params={"q": destination, "appid": api_key, "units": "metric"},+ timeout=15,+ )+ forecast_resp.raise_for_status()+ forecast = forecast_resp.json()+ except requests.RequestException as exc:+ return f"Weather lookup failed for '{destination}': {exc}"++ main = current.get("main", {})+ weather = (current.get("weather") or [{}])[0]+ wind = current.get("wind", {})++ lines = [+ f"Weather for {current.get('name', destination)}, {current.get('sys', {}).get('country', '')}",+ "",+ "Current:",+ f" {weather.get('main', 'N/A')} — {weather.get('description', 'N/A')}",+ f" Temperature: {main.get('temp', 'N/A')}°C (feels like {main.get('feels_like', 'N/A')}°C)",+ f" Humidity: {main.get('humidity', 'N/A')}%",+ f" Wind: {wind.get('speed', 'N/A')} m/s",+ "",+ "5-day forecast (3-hour intervals, sample):",+ ]++ seen_days: set[str] = set()+ for entry in forecast.get("list", [])[:16]:+ dt_txt = entry.get("dt_txt", "")+ day = dt_txt.split(" ")[0] if dt_txt else ""+ if day in seen_days:+ continue+ seen_days.add(day)+ w = (entry.get("weather") or [{}])[0]+ m = entry.get("main", {})+ lines.append(+ f" {day}: {w.get('main', 'N/A')} — "+ f"{m.get('temp_min', 'N/A')}°C to {m.get('temp_max', 'N/A')}°C, "+ f"{w.get('description', '')}"+ )+ if len(seen_days) >= 5:+ break++ return "\n".join(lines)+++@tool+def convert_currency(+ amount: float,+ from_currency: str,+ to_currency: str,+) -> str:+ """Convert an amount between currencies and show the exchange rate.++ Args:+ amount: Amount to convert (e.g. 1500).+ from_currency: Source currency code (e.g. 'USD').+ to_currency: Target currency code (e.g. 'JPY').+ """+ api_key = _require_key("EXCHANGERATE_API_KEY")+ from_code = from_currency.strip().upper()+ to_code = to_currency.strip().upper()+ url = f"https://v6.exchangerate-api.com/v6/{api_key}/pair/{from_code}/{to_code}/{amount}"++ try:+ resp = requests.get(url, timeout=15)+ resp.raise_for_status()+ data = resp.json()+ except requests.RequestException as exc:+ return f"Currency conversion failed: {exc}"++ if data.get("result") != "success":+ return f"Currency API error: {data.get('error-type', 'unknown')}"++ conversion = data.get("conversion_result", amount)+ rate = data.get("conversion_rate", "N/A")++ return (+ f"{amount:,.2f} {from_code} = {conversion:,.2f} {to_code}\n"+ f"Exchange rate: 1 {from_code} = {rate} {to_code}"+ )+++@tool+def research_destination(query: str) -> str:+ """Search the web for destination highlights, attractions, food, and travel tips.++ Args:+ query: Search query (e.g. 'best things to do in Kyoto Japan 2025').+ """+ try:+ with DDGS() as ddgs:+ results = list(ddgs.text(query, max_results=6))+ except Exception as exc:+ return f"Web research failed: {exc}"++ if not results:+ return f"No results found for: {query}"++ lines = [f"Research results for: {query}", ""]+ for i, hit in enumerate(results, 1):+ title = hit.get("title", "Untitled")+ body = hit.get("body", "")+ href = hit.get("href", "")+ lines.append(f"{i}. **{title}**")+ if body:+ lines.append(f" {body[:300]}{'...' if len(body) > 300 else ''}")+ if href:+ lines.append(f" Source: {href}")+ lines.append("")++ return "\n".join(lines)+++@tool+def get_packing_recommendations(+ destination: str,+ trip_days: int,+ weather_summary: str,+) -> str:+ """Generate a packing list based on weather data and trip duration.++ Args:+ destination: Trip destination.+ trip_days: Number of days for the trip.+ weather_summary: Weather text from get_weather (temperatures and conditions).+ """+ summary_lower = weather_summary.lower()+ hot = any(k in summary_lower for k in ("hot", "warm", "clear", "sunny")) or _temp_hint(+ summary_lower, above=24+ )+ cold = any(k in summary_lower for k in ("cold", "snow", "freez", "ice")) or _temp_hint(+ summary_lower, below=10+ )+ rain = any(k in summary_lower for k in ("rain", "drizzle", "storm", "shower", "thunder"))++ essentials = [+ "Passport / ID and travel documents",+ "Phone, charger, and travel adapter",+ "Wallet, cards, and some local cash",+ "Medications and basic first-aid kit",+ "Reusable water bottle",+ ]++ clothing: list[str] = ["Comfortable walking shoes", "Underwear and socks"]+ if hot:+ clothing += [+ "Light breathable shirts and shorts/skirts",+ "Sun hat and sunglasses",+ "Sunscreen (SPF 30+)",+ "Swimwear (if applicable)",+ ]+ elif cold:+ clothing += [+ "Thermal base layers",+ "Warm jacket or coat",+ "Gloves, scarf, and beanie",+ "Closed waterproof boots",+ ]+ else:+ clothing += [+ "Layered tops (t-shirts + light sweater)",+ "Jeans or comfortable pants",+ "Light jacket for evenings",+ ]++ if rain:+ clothing += ["Compact umbrella", "Waterproof jacket", "Quick-dry clothing"]++ extras = []+ if trip_days > 5:+ extras.append("Laundry soap sheets or plan for laundry mid-trip")+ if trip_days > 10:+ extras.append("Extra outfit rotation — pack for 7–10 days and wash")++ lines = [+ f"Packing list for {destination} ({trip_days} days)",+ "",+ "**Essentials**",+ *[f"- {item}" for item in essentials],+ "",+ "**Clothing & weather gear**",+ *[f"- {item}" for item in clothing],+ ]+ if extras:+ lines += ["", "**Trip-length tips**", *[f"- {item}" for item in extras]]++ lines += [+ "",+ "**Toiletries**",+ "- Toothbrush, toothpaste, deodorant",+ "- Skincare and any personal care items",+ "",+ f"_Based on weather context: {weather_summary[:200]}..._"+ if len(weather_summary) > 200+ else f"_Based on weather context provided._",+ ]++ return "\n".join(lines)+++def _temp_hint(text: str, above: Optional[float] = None, below: Optional[float] = None) -> bool:+ import re++ temps = [float(t) for t in re.findall(r"(-?\d+(?:\.\d+)?)\s*°C", text)]+ if not temps:+ return False+ avg = sum(temps) / len(temps)+ if above is not None and avg >= above:+ return True+ if below is not None and avg <= below:+ return True+ return False+++def create_travel_agent():+ """Build and return the LangChain tool-calling agent graph."""+ api_key = os.getenv("ORQ_API_KEY")+ if not api_key:+ raise ValueError("Missing environment variable: ORQ_API_KEY")++ llm = ChatOpenAI(+ model="deepseek-v4-flash",+ base_url="https://api.orq.ai/v3/router",+ api_key=api_key,+ temperature=0.4,+ )++ tools = [+ get_weather,+ convert_currency,+ research_destination,+ get_packing_recommendations,+ ]++ return create_agent(+ model=llm,+ tools=tools,+ system_prompt=SYSTEM_PROMPT,+ )+++def extract_agent_reply(result: dict) -> str:+ """Return the latest AI message content from an agent invoke result."""+ for message in reversed(result.get("messages", [])):+ if isinstance(message, AIMessage) and message.content:+ content = message.content+ if isinstance(content, str):+ return content+ return str(content)+ return "Sorry, I could not generate a response."diff --git a/ai_agents/travel_planner_agent/app.py b/ai_agents/travel_planner_agent/app.pynew file mode 100644index 0000000..017286b--- /dev/null+++ b/ai_agents/travel_planner_agent/app.py@@ -0,0 +1,107 @@+"""Travel Planner Agent — Streamlit chat interface."""++import os++import streamlit as st+from dotenv import load_dotenv+from langchain_core.messages import AIMessage, HumanMessage++from agent import create_travel_agent, extract_agent_reply++load_dotenv()++st.set_page_config(+ page_title="Travel Planner Agent",+ page_icon="✈️",+ layout="wide",+ initial_sidebar_state="expanded",+)+++def _check_env() -> list[str]:+ required = ["ORQ_API_KEY", "OPENWEATHER_API_KEY", "EXCHANGERATE_API_KEY"]+ return [key for key in required if not os.getenv(key)]+++def _init_session() -> None:+ if "messages" not in st.session_state:+ st.session_state.messages = []+ if "agent" not in st.session_state:+ missing = _check_env()+ if missing:+ st.session_state.agent = None+ st.session_state.env_error = (+ f"Missing API keys: {', '.join(missing)}. "+ "Copy `.env.example` to `.env` and add your keys."+ )+ else:+ try:+ st.session_state.agent = create_travel_agent()+ st.session_state.env_error = None+ except Exception as exc:+ st.session_state.agent = None+ st.session_state.env_error = str(exc)+++def _build_messages() -> list:+ messages = []+ for msg in st.session_state.messages:+ if msg["role"] == "user":+ messages.append(HumanMessage(content=msg["content"]))+ else:+ messages.append(AIMessage(content=msg["content"]))+ return messages+++def main() -> None:+ _init_session()++ with st.sidebar:+ st.title("✈️ Travel Planner")+ st.markdown(+ "Plan your trip through conversation — weather, budget, "+ "highlights, and packing in one place."+ )+ if st.button("Clear conversation", use_container_width=True):+ st.session_state.messages = []+ st.rerun()++ st.title("Travel Planner Agent")+ st.caption("Describe your trip in natural language — I'll research and build your plan.")++ if st.session_state.get("env_error"):+ st.error(st.session_state.env_error)++ for msg in st.session_state.messages:+ with st.chat_message(msg["role"]):+ st.markdown(msg["content"])++ if prompt := st.chat_input("Where would you like to go?"):+ if not st.session_state.agent:+ st.error(+ st.session_state.get("env_error")+ or "Agent not initialized. Check your environment variables."+ )+ return++ st.session_state.messages.append({"role": "user", "content": prompt})+ with st.chat_message("user"):+ st.markdown(prompt)++ with st.chat_message("assistant"):+ with st.spinner("Researching your trip..."):+ try:+ result = st.session_state.agent.invoke(+ {"messages": _build_messages()}+ )+ answer = extract_agent_reply(result)+ except Exception as exc:+ answer = f"Something went wrong: {exc}"++ st.markdown(answer)++ st.session_state.messages.append({"role": "assistant", "content": answer})+++if __name__ == "__main__":+ main()diff --git a/ai_agents/travel_planner_agent/assets/demo.gif b/ai_agents/travel_planner_agent/assets/demo.gifnew file mode 100644index 0000000..ddfe851Binary files /dev/null and b/ai_agents/travel_planner_agent/assets/demo.gif differdiff --git a/ai_agents/travel_planner_agent/requirements.txt b/ai_agents/travel_planner_agent/requirements.txtnew file mode 100644index 0000000..e7ba214--- /dev/null+++ b/ai_agents/travel_planner_agent/requirements.txt@@ -0,0 +1,9 @@+streamlit>=1.32.0+langchain>=0.3.0+langgraph>=0.2.0+langchain-openai>=0.2.0+langchain-core>=0.3.0+openai>=1.30.0+python-dotenv>=1.0.0+requests>=2.31.0+duckduckgo-search>=6.2.0