Heng commited on
Commit ·
19de60e
1
Parent(s): 8b307a6
Deploy HolidayPilot: multi-agent holiday planner with real live data
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+14
- DockerfileAdded+53
- README.md+38-5
- backend/.envAdded+3
- backend/app/__init__.pyAdded
- backend/app/agents/__init__.pyAdded
- backend/app/agents/activities.pyAdded+29
- backend/app/agents/base.pyAdded+51
- backend/app/agents/budget.pyAdded+75
- backend/app/agents/calendar.pyAdded+264
- backend/app/agents/flights.pyAdded+30
- backend/app/agents/food.pyAdded+34
- backend/app/agents/hotels.pyAdded+30
- backend/app/agents/monitoring.pyAdded+64
- backend/app/agents/orchestrator.pyAdded+159
- backend/app/agents/planner.pyAdded+114
- backend/app/agents/registry.pyAdded+29
- backend/app/agents/route.pyAdded+43
- backend/app/agents/weather.pyAdded+29
- backend/app/api/__init__.pyAdded
- backend/app/api/routes.pyAdded+262
- backend/app/core/__init__.pyAdded
- backend/app/core/config.pyAdded+26
- backend/app/core/database.pyAdded+13
- backend/app/core/logging.pyAdded+26
- backend/app/main.pyAdded+55
- backend/app/models/__init__.pyAdded
- backend/app/models/orm.pyAdded+57
- backend/app/models/schemas.pyAdded+282
- backend/app/services/__init__.pyAdded
- backend/app/services/activities.pyAdded+132
- backend/app/services/flights.pyAdded+245
- backend/app/services/food.pyAdded+119
- backend/app/services/geocoding.pyAdded+56
- backend/app/services/hotels.pyAdded+133
- backend/app/services/maps.pyAdded+76
- backend/app/services/pdf_export.pyAdded+116
- backend/app/services/weather.pyAdded+160
- backend/holidaypilot.dbAdded
- backend/holidaypilot.egg-info/PKG-INFOAdded+24
- backend/holidaypilot.egg-info/SOURCES.txtAdded+42
- backend/holidaypilot.egg-info/dependency_links.txtAdded+1
- backend/holidaypilot.egg-info/requires.txtAdded+20
- backend/holidaypilot.egg-info/top_level.txtAdded+1
- backend/pyproject.tomlAdded+37
- backend/tests/__init__.pyAdded
- backend/tests/test_agents.pyAdded+144
- backend/tests/test_api.pyAdded+97
- frontend/dist/assets/index-DDHK9Igv.cssAdded+1
- frontend/dist/assets/index-DuZYjYO3.jsAdded
1234567891011121314__pycache__*.pyc*.pyo.git.gitignorenode_modules.venv*.egg-info.ruff_cache.pytest_cachebackend/tests*.db.envREADME.md1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# Multi-stage build: Node.js for frontend, Python for backend# ── Stage 1: Build frontend ────────────────────────────────────────────────────FROM node:20-slim AS frontend-build
WORKDIR /buildCOPY frontend/package.json frontend/package-lock.json* ./RUN npm installCOPY frontend/ .RUN npm run build
# ── Stage 2: Python backend + built frontend ───────────────────────────────────FROM python:3.11-slim
# Create non-root user (HuggingFace Spaces requirement)RUN useradd -m -u 1000 appuser
WORKDIR /app
# Install system deps for weasyprint (optional PDF export)RUN apt-get update && \ apt-get install -y --no-install-recommends \ libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 \ libffi-dev libcairo2 && \ rm -rf /var/lib/apt/lists/*
# Install Python dependenciesCOPY backend/pyproject.toml backend/RUN pip install --no-cache-dir -e backend/
# Copy backend sourceCOPY backend/ backend/
# Copy built frontend into the location the backend expectsCOPY --from=frontend-build /build/dist backend/frontend/dist
# Adjust frontend dist path for Docker layout# The main.py looks for ../../frontend/dist relative to app/main.py# In Docker this becomes /app/backend/frontend/dist# We symlink to make it discoverableRUN ln -sf /app/backend/frontend /app/frontend
# Create writable directoriesRUN mkdir -p /app/data && chown -R appuser:appuser /app
USER appuser
# HuggingFace Spaces uses port 7860EXPOSE 7860
ENV PYTHONUNBUFFERED=1ENV HP_DATABASE_URL="sqlite+aiosqlite:///./data/holidaypilot.db"
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--app-dir", "/app/backend"]12345678910---title: Agenticemoji: 🏢colorFrom: redcolorTo: redsdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637383940414243---title: HolidayPilotemoji: 🌍colorFrom: bluecolorTo: greensdk: dockerapp_port: 7860pinned: false---# HolidayPilot - AI Multi-Agent Holiday PlannerAn intelligent holiday planner powered by 10 specialized AI agents that work together to create personalized travel itineraries using **real live data**.## Real APIs (No API Keys Required)- **Geocoding**: Nominatim (OpenStreetMap)- **Weather**: Open-Meteo API (real forecasts + climate estimates)- **Activities**: Overpass API (real POIs from OpenStreetMap)- **Restaurants**: Overpass API (real restaurants, cafes, bars)- **Hotels**: Overpass API + price estimation- **Routing**: OSRM (real driving distances and durations)- **Flights**: 75+ real airports with distance-based pricing + Google Flights booking links## Architecture10 agents coordinate through an orchestrator:1. **Planner** - Conversational intake2. **Flights** - Flight search3. **Hotels** - Accommodation search4. **Activities** - POI discovery5. **Food** - Restaurant recommendations6. **Weather** - Forecasts and clothing advice7. **Route** - Geographic clustering8. **Budget** - Cost optimization9. **Calendar** - Itinerary assembly10. **Monitoring** - Alerts and updates## Tech Stack- **Frontend**: React + Vite + TypeScript + Tailwind CSS- **Backend**: FastAPI + Pydantic v2 + SQLAlchemy- **Deployment**: Docker (HuggingFace Spaces)
123HP_DEBUG=falseHP_OPENAI_API_KEY=HP_DATABASE_URL=sqlite+aiosqlite:///./holidaypilot.db1234567891011121314151617181920212223242526272829"""Activities Agent — finds local attractions, tours, and events."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class ActivitiesAgent(BaseAgent): role = AgentRole.activities goal = "Find activities, attractions, and events matching traveler interests" tools = ["search_activities", "search_events"] guardrails = ["Prefer activities matching stated interests", "Include weather-sensitive flags"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.activities import ActivityService
trip = context["trip"] service = ActivityService() activities = await service.search( destination=trip.get("destination", ""), interests=trip.get("interests", []), mood=trip.get("mood", "relaxing"), ) return { "activities": [a.model_dump() for a in activities], "summary": f"Found {len(activities)} activities", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""Base agent class — every specialized agent inherits from this."""from __future__ import annotations
import timefrom abc import ABC, abstractmethodfrom typing import Any
from app.core.logging import get_loggerfrom app.models.schemas import AgentRole, ReasoningStep
logger = get_logger(__name__)
class BaseAgent(ABC): """All agents share: role, goal, tool list, guardrails, and a run() method."""
role: AgentRole goal: str tools: list[str] guardrails: list[str]
@abstractmethod async def run(self, context: dict[str, Any]) -> dict[str, Any]: """Execute the agent's task and return results.""" ...
async def execute(self, context: dict[str, Any], trace_id: str = "") -> tuple[dict[str, Any], ReasoningStep]: """Wrapper that adds logging, timing, and produces a ReasoningStep.""" logger.info("agent.start", agent=self.role.value, trace_id=trace_id) t0 = time.monotonic() try: result = await self.run(context) elapsed = int((time.monotonic() - t0) * 1000) step = ReasoningStep( agent=self.role, action=self.goal, result_summary=result.get("summary", "done"), duration_ms=elapsed, ) logger.info("agent.done", agent=self.role.value, elapsed_ms=elapsed, trace_id=trace_id) return result, step except Exception as exc: elapsed = int((time.monotonic() - t0) * 1000) logger.error("agent.error", agent=self.role.value, error=str(exc), trace_id=trace_id) step = ReasoningStep( agent=self.role, action=self.goal, result_summary=f"Error: {exc}", duration_ms=elapsed, ) return {"error": str(exc), "summary": f"Error: {exc}"}, step123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Budget Agent — scores options against budget, suggests trade-offs."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole, BudgetBreakdown, BudgetCategory
class BudgetAgent(BaseAgent): role = AgentRole.budget goal = "Optimize plan for budget constraints and suggest trade-offs" tools = ["calculate_budget", "suggest_savings"] guardrails = ["Never exceed budget without warning", "Show category breakdown"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: trip = context["trip"] gathered = context.get("gathered", {}) total_budget = trip.get("budget_total", 0) or 5000
# Calculate costs per category flights = gathered.get("flights", {}).get("flights", []) hotels = gathered.get("hotels", {}).get("hotels", []) activities = gathered.get("activities", {}).get("activities", []) restaurants = gathered.get("food", {}).get("restaurants", [])
cheapest_flight = min((f["price"] for f in flights), default=0) cheapest_hotel = min((h["price_per_night"] for h in hotels), default=0)
# Estimate number of nights num_nights = 1 if trip.get("start_date") and trip.get("end_date"): from datetime import date as dt_date try: sd = dt_date.fromisoformat(str(trip["start_date"])) ed = dt_date.fromisoformat(str(trip["end_date"])) num_nights = max((ed - sd).days, 1) except (ValueError, TypeError): pass
hotel_total = cheapest_hotel * num_nights activity_total = sum(a.get("price", 0) for a in activities[:num_nights * 2]) food_daily = 60 # estimate per person per day food_total = food_daily * num_nights * max(len(trip.get("travelers", [])), 1) transport_est = 30 * num_nights
total_estimated = cheapest_flight + hotel_total + activity_total + food_total + transport_est
categories = [ BudgetCategory(category="Flights", allocated=cheapest_flight, spent=0, items=["Round trip"]), BudgetCategory(category="Accommodation", allocated=hotel_total, spent=0, items=[f"{num_nights} nights"]), BudgetCategory(category="Activities", allocated=activity_total, spent=0), BudgetCategory(category="Food", allocated=food_total, spent=0), BudgetCategory(category="Transport", allocated=transport_est, spent=0), ]
savings = [] if total_estimated > total_budget: savings.append("Consider budget hotels or hostels") savings.append("Look for free walking tours and parks") savings.append("Cook some meals instead of eating out")
breakdown = BudgetBreakdown( total_budget=total_budget, total_estimated=total_estimated, currency=trip.get("budget_currency", "USD"), categories=categories, within_budget=total_estimated <= total_budget, savings_tips=savings, )
return { "breakdown": breakdown.model_dump(), "summary": f"Estimated ${total_estimated:,.0f} of ${total_budget:,.0f} budget", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264"""Calendar Agent — builds day-by-day itinerary from gathered data."""from __future__ import annotations
import uuidfrom datetime import date as dt_date, time as dt_timefrom typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole, DayPlan, Itinerary, ItineraryItem, WeatherForecast
class CalendarAgent(BaseAgent): role = AgentRole.calendar goal = "Build a day-by-day itinerary schedule from gathered options" tools = ["build_schedule", "export_ical"] guardrails = ["Respect weather warnings", "Include buffer time between activities"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: trip = context["trip"] gathered = context.get("gathered", {}) budget_data = context.get("budget", {}) route_data = context.get("route", {})
flights = gathered.get("flights", {}).get("flights", []) hotels = gathered.get("hotels", {}).get("hotels", []) activities = gathered.get("activities", {}).get("activities", []) restaurants = gathered.get("food", {}).get("restaurants", []) forecasts = gathered.get("weather", {}).get("forecasts", [])
# Determine date range start = trip.get("start_date", "") end = trip.get("end_date", "") try: start_date = dt_date.fromisoformat(str(start)) end_date = dt_date.fromisoformat(str(end)) except (ValueError, TypeError): start_date = dt_date.today() end_date = start_date
num_days = max((end_date - start_date).days, 1)
# Select best hotel best_hotel = min(hotels, key=lambda h: h.get("price_per_night", 9999)) if hotels else None
# Build forecast lookup forecast_map: dict[str, dict] = {} for f in forecasts: forecast_map[str(f.get("date", ""))] = f
days: list[DayPlan] = [] activity_idx = 0 restaurant_idx = 0 total_cost = 0.0
for day_num in range(num_days): from datetime import timedelta current_date = start_date + timedelta(days=day_num) weather = forecast_map.get(str(current_date)) weather_obj = WeatherForecast(**weather) if weather else None
items: list[ItineraryItem] = [] day_cost = 0.0 is_rainy = weather and weather.get("condition") in ("rainy", "stormy")
# Day 1: add arrival flight if day_num == 0 and flights: best_flight = min(flights, key=lambda f: f["price"]) items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(8, 0), end_time=dt_time(12, 0), title=f"Flight: {best_flight.get('airline', 'Airline')}", category="flight", description=f"{best_flight.get('departure_airport', '')} → {best_flight.get('arrival_airport', '')}", cost=best_flight.get("price", 0), reasoning="Cheapest direct option for your dates", )) day_cost += best_flight.get("price", 0)
# Hotel check-in on day 1 if day_num == 0 and best_hotel: items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(14, 0), end_time=dt_time(15, 0), title=f"Check in: {best_hotel.get('name', 'Hotel')}", category="hotel", description=best_hotel.get("address", ""), cost=best_hotel.get("price_per_night", 0) * num_days, reasoning="Best value hotel with good reviews in your budget", location=best_hotel.get("address", ""), )) day_cost += best_hotel.get("price_per_night", 0)
# Morning activity if activity_idx < len(activities): act = activities[activity_idx] # Skip weather-sensitive outdoor activities on rainy days if is_rainy and act.get("weather_sensitive"): # Find indoor alternative backup_act = next( (a for a in activities[activity_idx + 1:] if not a.get("weather_sensitive")), act, ) weather_note = "Moved indoors due to expected rain" else: backup_act = None weather_note = ""
chosen = backup_act or act backup_item = None if backup_act and backup_act != act: backup_item = ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, title=act.get("name", "Activity"), category="activity", description=act.get("description", ""), cost=act.get("price", 0), reasoning="Original plan if weather improves", )
items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(10, 0) if day_num > 0 else dt_time(15, 0), end_time=dt_time(12, 0) if day_num > 0 else dt_time(17, 0), title=chosen.get("name", "Activity"), category="activity", description=chosen.get("description", ""), cost=chosen.get("price", 0), location=chosen.get("address", ""), reasoning=f"Matches your {trip.get('mood', 'relaxing')} mood and interests", weather_note=weather_note, backup=backup_item, )) day_cost += chosen.get("price", 0) activity_idx += 1
# Lunch if restaurant_idx < len(restaurants): rest = restaurants[restaurant_idx] items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(12, 30) if day_num > 0 else dt_time(18, 0), end_time=dt_time(13, 30) if day_num > 0 else dt_time(19, 0), title=f"Lunch: {rest.get('name', 'Restaurant')}", category="food", description=f"{rest.get('cuisine', '')} cuisine", cost=25.0, location=rest.get("address", ""), reasoning=f"Highly rated {rest.get('cuisine', 'local')} restaurant nearby", )) day_cost += 25.0 restaurant_idx += 1
# Afternoon activity (from day 2) if day_num > 0 and activity_idx < len(activities): act = activities[activity_idx] items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(14, 30), end_time=dt_time(16, 30), title=act.get("name", "Activity"), category="activity", description=act.get("description", ""), cost=act.get("price", 0), location=act.get("address", ""), reasoning="Complements your morning activity with a change of pace", )) day_cost += act.get("price", 0) activity_idx += 1
# Dinner if restaurant_idx < len(restaurants): rest = restaurants[restaurant_idx] items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(19, 0), end_time=dt_time(20, 30), title=f"Dinner: {rest.get('name', 'Restaurant')}", category="food", description=f"{rest.get('cuisine', '')} cuisine", cost=40.0, location=rest.get("address", ""), reasoning="Great dinner spot with atmosphere matching your trip mood", )) day_cost += 40.0 restaurant_idx += 1
# Last day: departure flight if day_num == num_days - 1 and flights: items.append(ItineraryItem( id=uuid.uuid4().hex[:8], day=day_num + 1, start_time=dt_time(18, 0), end_time=dt_time(22, 0), title="Return flight", category="flight", description="Head to airport for departure", cost=0, reasoning="Return flight included in outbound booking", ))
total_cost += day_cost days.append(DayPlan( day=day_num + 1, date=current_date, title=f"Day {day_num + 1}" + (" — Arrival" if day_num == 0 else ""), items=items, weather=weather_obj, daily_spend=day_cost, ))
# Packing list and checklist packing = self._generate_packing_list(trip, forecasts) checklist = self._generate_checklist(trip)
itinerary = Itinerary( trip_id=trip.get("trip_id", ""), days=days, total_cost=total_cost, currency=trip.get("budget_currency", "USD"), flexibility_score=0.7, travel_time_hours=2.0 * num_days, packing_list=packing, checklist=checklist, )
return { "itinerary": itinerary.model_dump(), "summary": f"Built {num_days}-day itinerary, ${total_cost:,.0f} total", }
def _generate_packing_list(self, trip: dict, forecasts: list) -> list[str]: items = ["Passport/ID", "Phone charger", "Travel adapter", "Comfortable walking shoes"] has_rain = any(f.get("condition") in ("rainy", "stormy") for f in forecasts) if has_rain: items.extend(["Umbrella", "Rain jacket"]) avg_temp = sum(f.get("high_temp_c", 20) for f in forecasts) / max(len(forecasts), 1) if avg_temp < 15: items.extend(["Warm jacket", "Layers"]) elif avg_temp > 28: items.extend(["Sunscreen", "Hat", "Light clothing"]) if trip.get("mood") == "adventure": items.extend(["Hiking boots", "Daypack"]) return items
def _generate_checklist(self, trip: dict) -> list[str]: return [ "Check passport validity", "Verify travel insurance", "Download offline maps", "Notify bank of travel dates", "Check visa requirements", "Arrange airport transport", "Confirm hotel booking", "Pack essentials bag", ]123456789101112131415161718192021222324252627282930"""Flights Agent — searches for flight options."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class FlightsAgent(BaseAgent): role = AgentRole.flights goal = "Search and compare flight options for the trip" tools = ["search_flights"] guardrails = ["Never book without user approval", "Always show multiple options"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.flights import FlightService
trip = context["trip"] service = FlightService() flights = await service.search( origin=trip.get("origin", ""), destination=trip.get("destination", ""), departure_date=trip.get("start_date", ""), return_date=trip.get("end_date", ""), ) return { "flights": [f.model_dump() for f in flights], "summary": f"Found {len(flights)} flight options", }12345678910111213141516171819202122232425262728293031323334"""Food Agent — finds restaurants and dining options."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class FoodAgent(BaseAgent): role = AgentRole.food goal = "Recommend restaurants and dining experiences" tools = ["search_restaurants"] guardrails = ["Respect dietary restrictions", "Vary cuisine types across days"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.food import FoodService
trip = context["trip"] travelers = trip.get("travelers", []) dietary = [] for t in travelers: dietary.extend(t.get("dietary_restrictions", []))
service = FoodService() restaurants = await service.search( destination=trip.get("destination", ""), dietary_restrictions=dietary, budget=trip.get("budget_total"), ) return { "restaurants": [r.model_dump() for r in restaurants], "summary": f"Found {len(restaurants)} restaurant options", }123456789101112131415161718192021222324252627282930"""Hotels Agent — searches for accommodation options."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class HotelsAgent(BaseAgent): role = AgentRole.hotels goal = "Search and compare hotel/accommodation options" tools = ["search_hotels"] guardrails = ["Never book without user approval", "Verify availability"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.hotels import HotelService
trip = context["trip"] service = HotelService() hotels = await service.search( destination=trip.get("destination", ""), check_in=trip.get("start_date", ""), check_out=trip.get("end_date", ""), budget=trip.get("budget_total"), ) return { "hotels": [h.model_dump() for h in hotels], "summary": f"Found {len(hotels)} hotel options", }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Monitoring/Replanning Agent — watches for disruptions and re-plans."""from __future__ import annotations
import uuidfrom datetime import datetimefrom typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole, AlertEvent, AlertSeverity
class MonitoringAgent(BaseAgent): role = AgentRole.monitoring goal = "Monitor for trip disruptions and suggest re-plans" tools = ["check_flight_status", "check_weather_alerts", "check_price_changes"] guardrails = ["Only alert on actionable changes", "Suggest alternatives, don't force changes"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: trip = context.get("trip", {}) itinerary = context.get("itinerary", {})
alerts: list[dict] = []
# Check weather changes weather_alerts = await self._check_weather(trip) alerts.extend(weather_alerts)
# Check flight status changes flight_alerts = await self._check_flights(trip, itinerary) alerts.extend(flight_alerts)
return { "alerts": alerts, "summary": f"Generated {len(alerts)} alerts", }
async def _check_weather(self, trip: dict) -> list[dict]: """Check for severe weather alerts at destination.""" # In production, this would call a weather alert API # For MVP, return empty or sample alerts return []
async def _check_flights(self, trip: dict, itinerary: dict) -> list[dict]: """Check for flight delays or cancellations.""" # In production, this would check flight status APIs return []
def create_alert( self, trip_id: str, severity: AlertSeverity, title: str, description: str, action: str = "", ) -> AlertEvent: return AlertEvent( id=uuid.uuid4().hex[:8], trip_id=trip_id, severity=severity, title=title, description=description, agent=self.role, suggested_action=action, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Orchestrator — coordinates all agents and manages the planning workflow."""from __future__ import annotations
import asynciofrom typing import Any
from app.agents.base import BaseAgentfrom app.core.logging import get_logger, new_trace_idfrom app.models.schemas import ( AgentRole, ChatMessage, Itinerary, ReasoningStep, TripRequest,)
logger = get_logger(__name__)
class Orchestrator: """Central coordinator that delegates to specialized agents."""
def __init__(self) -> None: self._agents: dict[AgentRole, BaseAgent] = {}
def register(self, agent: BaseAgent) -> None: self._agents[agent.role] = agent
def get_agent(self, role: AgentRole) -> BaseAgent: return self._agents[role]
# ── Main planning flow ─────────────────────────────────────────────────
async def handle_chat( self, trip: TripRequest, user_message: str, history: list[ChatMessage] ) -> tuple[str, TripRequest, list[ReasoningStep], dict | None, dict | None]: """Process a user chat message: extract intent, maybe run planning.
Returns (reply, updated_trip, steps, itinerary_data, budget_data). """ trace_id = new_trace_id() logger.info("orchestrator.chat", trip_id=trip.trip_id, trace_id=trace_id)
planner = self.get_agent(AgentRole.planner) context = { "trip": trip.model_dump(), "user_message": user_message, "history": [m.model_dump() for m in history[-20:]], } result, step = await planner.execute(context, trace_id) steps = [step]
reply = result.get("reply", "") updated_trip_data = result.get("updated_trip", {}) if updated_trip_data: trip = TripRequest(**{**trip.model_dump(), **updated_trip_data})
itinerary_data = None budget_data = None
needs_planning = result.get("ready_to_plan", False) if needs_planning: plan_reply, plan_steps, itinerary_data, budget_data = await self.run_full_plan(trip, trace_id) reply += "\n\n" + plan_reply steps.extend(plan_steps)
return reply, trip, steps, itinerary_data, budget_data
async def run_full_plan( self, trip: TripRequest, trace_id: str = "" ) -> tuple[str, list[ReasoningStep], dict | None, dict | None]: """Run the full multi-agent planning pipeline.
Returns (summary_text, steps, itinerary_data, budget_data). """ trace_id = trace_id or new_trace_id() logger.info("orchestrator.plan", trip_id=trip.trip_id, trace_id=trace_id)
ctx = {"trip": trip.model_dump()} steps: list[ReasoningStep] = []
# Phase 1: parallel data gathering gather_roles = [ AgentRole.flights, AgentRole.hotels, AgentRole.activities, AgentRole.food, AgentRole.weather, ] gather_tasks = [] for role in gather_roles: agent = self._agents.get(role) if agent: gather_tasks.append(agent.execute(ctx, trace_id))
results = await asyncio.gather(*gather_tasks, return_exceptions=True) gathered: dict[str, Any] = {} for role, res in zip(gather_roles, results): if isinstance(res, Exception): logger.error("gather.error", agent=role.value, error=str(res), trace_id=trace_id) continue data, step = res gathered[role.value] = data steps.append(step)
ctx["gathered"] = gathered
# Phase 2: sequential optimization for role in [AgentRole.budget, AgentRole.route, AgentRole.calendar]: agent = self._agents.get(role) if agent: result, step = await agent.execute(ctx, trace_id) ctx[role.value] = result steps.append(step)
# Phase 3: extract structured data itinerary_data = ctx.get("calendar", {}).get("itinerary") budget_data = ctx.get("budget", {}).get("breakdown")
# Phase 4: build itinerary summary summary_parts = ["Here's your trip plan!\n"] if itinerary_data: for day in itinerary_data.get("days", []): summary_parts.append(f"**Day {day['day']} — {day.get('title', day['date'])}**") for item in day.get("items", []): cost_str = f" (${item['cost']:.0f})" if item.get("cost") else "" summary_parts.append(f" • {item.get('start_time', '')} {item['title']}{cost_str}") if item.get("reasoning"): summary_parts.append(f" _Why: {item['reasoning']}_") summary_parts.append("")
if budget_data: summary_parts.append(f"**Estimated total: ${budget_data.get('total_estimated', 0):,.0f} {budget_data.get('currency', 'USD')}**") if not budget_data.get("within_budget", True): summary_parts.append("⚠️ This exceeds your budget. See savings tips below.")
return "\n".join(summary_parts), steps, itinerary_data, budget_data
async def regenerate_day( self, trip: TripRequest, itinerary: Itinerary, day_num: int ) -> tuple[Itinerary, list[ReasoningStep]]: """Re-plan a specific day only.""" trace_id = new_trace_id() ctx = { "trip": trip.model_dump(), "itinerary": itinerary.model_dump(), "regenerate_day": day_num, } steps: list[ReasoningStep] = []
for role in [AgentRole.activities, AgentRole.food, AgentRole.route, AgentRole.calendar]: agent = self._agents.get(role) if agent: result, step = await agent.execute(ctx, trace_id) ctx[role.value] = result steps.append(step)
new_itinerary_data = ctx.get("calendar", {}).get("itinerary", itinerary.model_dump()) return Itinerary(**new_itinerary_data), steps123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Planner Agent — conversational intake, clarification, trip extraction."""from __future__ import annotations
import jsonfrom typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class PlannerAgent(BaseAgent): role = AgentRole.planner goal = "Collect trip requirements conversationally and determine readiness to plan" tools = ["extract_trip_info", "ask_clarification"] guardrails = ["Never fabricate destinations", "Ask if key info is missing"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: trip = context.get("trip", {}) user_message = context.get("user_message", "") history = context.get("history", [])
# Extract trip fields from the user message updated_trip = self._extract_fields(user_message, trip)
# Check completeness missing = self._check_missing(updated_trip) ready = len(missing) == 0
if ready: reply = ( f"Great! I have everything I need to plan your trip to **{updated_trip.get('destination', '')}** " f"from {updated_trip.get('start_date', '?')} to {updated_trip.get('end_date', '?')}. " f"Budget: ${updated_trip.get('budget_total', 0):,.0f}. " f"Let me search for the best options now..." ) else: prompts = { "destination": "Where would you like to go?", "start_date": "What are your travel dates? (start date)", "end_date": "And your return date?", "budget_total": "What's your approximate budget for the trip?", "origin": "Where will you be traveling from?", } questions = [prompts.get(f, f"Could you tell me about {f}?") for f in missing[:2]] reply = " ".join(questions)
return { "reply": reply, "updated_trip": updated_trip, "ready_to_plan": ready, "missing_fields": missing, "summary": f"{'Ready to plan' if ready else f'Missing: {missing}'}", }
def _extract_fields(self, message: str, trip: dict) -> dict: """Simple keyword-based extraction (replaced by LLM in production).""" updated = dict(trip) msg = message.lower()
# Detect mood for mood in ["relaxing", "romantic", "adventure", "family", "workation", "cultural"]: if mood in msg: updated["mood"] = mood
# Detect budget import re budget_match = re.search(r'\$\s*([\d,]+)', message) if budget_match: updated["budget_total"] = float(budget_match.group(1).replace(",", ""))
# Detect dates (YYYY-MM-DD) date_matches = re.findall(r'\d{4}-\d{2}-\d{2}', message) if len(date_matches) >= 2: updated["start_date"] = date_matches[0] updated["end_date"] = date_matches[1] elif len(date_matches) == 1: if not updated.get("start_date"): updated["start_date"] = date_matches[0] else: updated["end_date"] = date_matches[0]
# Detect "from <city>" first so we can exclude origin from destinations from_match = re.search(r'from\s+([a-zA-Z\s]+?)(?:\s+to\s+|\s*$|,|\s+\d)', message, re.IGNORECASE) if from_match: origin_candidate = from_match.group(1).strip() if len(origin_candidate) > 1: updated["origin"] = origin_candidate.title()
origin_lower = updated.get("origin", "").lower()
# Detect common destinations (simple heuristic) destinations = [ "paris", "tokyo", "london", "rome", "barcelona", "new york", "bali", "sydney", "dubai", "amsterdam", "lisbon", "bangkok", "singapore", "hawaii", "maldives", "iceland", "morocco", ] # Try "to <dest>" pattern first to_match = re.search(r'(?:to|visit|go to|trip to)\s+([a-zA-Z\s]+?)(?:\s+from\s+|\s*$|,|\s+\d)', message, re.IGNORECASE) if to_match: to_candidate = to_match.group(1).strip().lower() for dest in destinations: if dest in to_candidate and dest != origin_lower: updated["destination"] = dest.title() break else: for dest in destinations: if dest in msg and dest != origin_lower: updated["destination"] = dest.title()
return updated
def _check_missing(self, trip: dict) -> list[str]: required = ["destination", "start_date", "end_date", "budget_total"] return [f for f in required if not trip.get(f)]1234567891011121314151617181920212223242526272829"""Agent registry — creates and wires up all agents with the orchestrator."""from __future__ import annotations
from app.agents.activities import ActivitiesAgentfrom app.agents.budget import BudgetAgentfrom app.agents.calendar import CalendarAgentfrom app.agents.flights import FlightsAgentfrom app.agents.food import FoodAgentfrom app.agents.hotels import HotelsAgentfrom app.agents.monitoring import MonitoringAgentfrom app.agents.orchestrator import Orchestratorfrom app.agents.planner import PlannerAgentfrom app.agents.route import RouteAgentfrom app.agents.weather import WeatherAgent
def create_orchestrator() -> Orchestrator: orch = Orchestrator() orch.register(PlannerAgent()) orch.register(FlightsAgent()) orch.register(HotelsAgent()) orch.register(ActivitiesAgent()) orch.register(FoodAgent()) orch.register(RouteAgent()) orch.register(WeatherAgent()) orch.register(BudgetAgent()) orch.register(CalendarAgent()) orch.register(MonitoringAgent()) return orch12345678910111213141516171819202122232425262728293031323334353637383940414243"""Route/Maps Agent — optimizes routes between locations."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class RouteAgent(BaseAgent): role = AgentRole.route goal = "Optimize routes and group activities by geography" tools = ["get_route", "get_distance_matrix"] guardrails = ["Minimize unnecessary travel", "Consider transit options"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.maps import MapsService
gathered = context.get("gathered", {}) activities = gathered.get("activities", {}).get("activities", []) restaurants = gathered.get("food", {}).get("restaurants", [])
service = MapsService()
# Get all locations with coordinates locations = [] for item in activities + restaurants: if item.get("latitude") and item.get("longitude"): locations.append({ "name": item.get("name", ""), "lat": item["latitude"], "lng": item["longitude"], "type": "activity" if item in activities else "food", })
# Cluster by proximity for day grouping clusters = service.cluster_locations(locations)
return { "clusters": clusters, "total_locations": len(locations), "summary": f"Grouped {len(locations)} locations into {len(clusters)} clusters", }1234567891011121314151617181920212223242526272829"""Weather Agent — forecasts and weather-aware recommendations."""from __future__ import annotations
from typing import Any
from app.agents.base import BaseAgentfrom app.models.schemas import AgentRole
class WeatherAgent(BaseAgent): role = AgentRole.weather goal = "Provide weather forecasts and suggest weather-safe timing" tools = ["get_forecast"] guardrails = ["Flag outdoor activities on rainy days", "Suggest indoor backups"]
async def run(self, context: dict[str, Any]) -> dict[str, Any]: from app.services.weather import WeatherService
trip = context["trip"] service = WeatherService() forecasts = await service.get_forecast( destination=trip.get("destination", ""), start_date=trip.get("start_date", ""), end_date=trip.get("end_date", ""), ) return { "forecasts": [f.model_dump() for f in forecasts], "summary": f"Got {len(forecasts)}-day forecast", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""API routes for HolidayPilot."""from __future__ import annotations
import uuidfrom typing import Any
from fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import HTMLResponse, Response
from app.agents.orchestrator import Orchestratorfrom app.agents.registry import create_orchestratorfrom app.models.schemas import ( BudgetBreakdown, ChatMessage, ChatRequest, ChatResponse, Itinerary, ReasoningStep, TripRequest, TripSummary,)from app.services.flights import FlightServicefrom app.services.hotels import HotelServicefrom app.services.activities import ActivityServicefrom app.services.food import FoodServicefrom app.services.weather import WeatherServicefrom app.services.pdf_export import generate_pdf, render_itinerary_html
router = APIRouter()
# In-memory store for MVP (replace with DB in production)_trips: dict[str, dict[str, Any]] = {}_chat_history: dict[str, list[ChatMessage]] = {}_itineraries: dict[str, dict] = {}_orchestrator: Orchestrator | None = None
def get_orchestrator() -> Orchestrator: global _orchestrator if _orchestrator is None: _orchestrator = create_orchestrator() return _orchestrator
# ── Chat ───────────────────────────────────────────────────────────────────────
@router.post("/chat", response_model=ChatResponse)async def chat(req: ChatRequest) -> ChatResponse: """Main conversational endpoint. Handles intake and triggers planning.""" orch = get_orchestrator()
# Get or create trip if req.trip_id not in _trips: trip_id = req.trip_id or uuid.uuid4().hex[:12] _trips[trip_id] = TripRequest(trip_id=trip_id).model_dump() _chat_history[trip_id] = [] req.trip_id = trip_id
trip = TripRequest(**_trips[req.trip_id]) history = _chat_history.get(req.trip_id, [])
# Record user message user_msg = ChatMessage(role="user", content=req.message) history.append(user_msg)
# Run orchestrator reply, updated_trip, steps, itin_data, budget_data = await orch.handle_chat(trip, req.message, history)
# Record assistant reply assistant_msg = ChatMessage(role="assistant", content=reply) history.append(assistant_msg)
# Persist _trips[req.trip_id] = updated_trip.model_dump() _chat_history[req.trip_id] = history
# Store itinerary if planning occurred itinerary_obj = None budget_obj = None if itin_data: _itineraries[req.trip_id] = itin_data itinerary_obj = Itinerary(**itin_data) if budget_data: budget_obj = BudgetBreakdown(**budget_data)
return ChatResponse( trip_id=req.trip_id, messages=[user_msg, assistant_msg], trip_data=updated_trip, reasoning_steps=steps, itinerary=itinerary_obj, budget=budget_obj, )
# ── Plan ───────────────────────────────────────────────────────────────────────
@router.post("/plan")async def plan(trip_req: TripRequest) -> dict: """Directly trigger full planning pipeline.""" orch = get_orchestrator() trip_id = trip_req.trip_id or uuid.uuid4().hex[:12] trip_req.trip_id = trip_id _trips[trip_id] = trip_req.model_dump()
reply, steps, itinerary_data, budget_data = await orch.run_full_plan(trip_req)
if itinerary_data: _itineraries[trip_id] = itinerary_data
return { "trip_id": trip_id, "plan_summary": reply, "itinerary": itinerary_data, "budget": budget_data, "reasoning_steps": [s.model_dump() for s in steps], }
# ── Search endpoints ──────────────────────────────────────────────────────────
@router.get("/search/flights")async def search_flights(origin: str, destination: str, departure: str, return_date: str = ""): service = FlightService() flights = await service.search(origin, destination, departure, return_date) return {"flights": [f.model_dump() for f in flights]}
@router.get("/search/hotels")async def search_hotels(destination: str, check_in: str, check_out: str, budget: float = 0): service = HotelService() hotels = await service.search(destination, check_in, check_out, budget or None) return {"hotels": [h.model_dump() for h in hotels]}
@router.get("/search/activities")async def search_activities(destination: str, mood: str = "relaxing"): service = ActivityService() activities = await service.search(destination, mood=mood) return {"activities": [a.model_dump() for a in activities]}
@router.get("/search/weather")async def search_weather(destination: str, start_date: str, end_date: str): service = WeatherService() forecasts = await service.get_forecast(destination, start_date, end_date) return {"forecasts": [f.model_dump() for f in forecasts]}
# ── Optimize ───────────────────────────────────────────────────────────────────
@router.post("/optimize")async def optimize(trip_id: str, day: int | None = None) -> dict: """Re-optimize the plan. If day is specified, regenerate only that day.""" if trip_id not in _trips: raise HTTPException(404, "Trip not found")
trip = TripRequest(**_trips[trip_id]) orch = get_orchestrator()
if day and trip_id in _itineraries: itinerary = Itinerary(**_itineraries[trip_id]) new_itin, steps = await orch.regenerate_day(trip, itinerary, day) _itineraries[trip_id] = new_itin.model_dump() return {"itinerary": new_itin.model_dump(), "steps": [s.model_dump() for s in steps]}
# Full re-plan reply, steps, itin_data, budget_data = await orch.run_full_plan(trip) if itin_data: _itineraries[trip_id] = itin_data return {"plan_summary": reply, "itinerary": itin_data, "budget": budget_data, "steps": [s.model_dump() for s in steps]}
# ── Calendar sync ──────────────────────────────────────────────────────────────
@router.post("/calendar/sync")async def calendar_sync(trip_id: str) -> dict: """Generate iCal data for the trip.""" if trip_id not in _itineraries: raise HTTPException(404, "Itinerary not found")
itinerary = _itineraries[trip_id] # Generate simple iCal representation events = [] for day in itinerary.get("days", []): for item in day.get("items", []): events.append({ "summary": item["title"], "date": day["date"], "start_time": item.get("start_time"), "end_time": item.get("end_time"), "location": item.get("location", ""), "description": item.get("description", ""), }) return {"trip_id": trip_id, "events": events, "event_count": len(events)}
# ── Export ─────────────────────────────────────────────────────────────────────
@router.get("/itinerary/export")async def export_itinerary(trip_id: str, format: str = "html") -> Response: """Export itinerary as PDF or HTML.""" if trip_id not in _itineraries: raise HTTPException(404, "Itinerary not found")
itinerary = _itineraries[trip_id] trip = _trips.get(trip_id, {})
if format == "pdf": pdf_bytes = await generate_pdf(itinerary, trip) return Response( content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f"attachment; filename=itinerary_{trip_id}.pdf"}, )
html = render_itinerary_html(itinerary, trip) return HTMLResponse(content=html)
# ── Alerts ─────────────────────────────────────────────────────────────────────
@router.post("/alerts/subscribe")async def subscribe_alerts(trip_id: str, email: str = "") -> dict: """Subscribe to trip alerts.""" return { "trip_id": trip_id, "subscribed": True, "email": email, "message": "You will receive alerts for flight changes, weather updates, and price drops.", }
# ── Trip data ──────────────────────────────────────────────────────────────────
@router.get("/trip/{trip_id}")async def get_trip(trip_id: str) -> dict: if trip_id not in _trips: raise HTTPException(404, "Trip not found") return { "trip": _trips[trip_id], "itinerary": _itineraries.get(trip_id), "chat_history": [m.model_dump() for m in _chat_history.get(trip_id, [])], }
@router.get("/trips")async def list_trips() -> dict: return { "trips": [ {"trip_id": tid, "destination": t.get("destination", ""), "start_date": t.get("start_date", "")} for tid, t in _trips.items() ] }1234567891011121314151617181920212223242526from __future__ import annotations
from pydantic_settings import BaseSettings
class Settings(BaseSettings): app_name: str = "HolidayPilot" debug: bool = False database_url: str = "sqlite+aiosqlite:///./holidaypilot.db"
openai_api_key: str = "" openai_model: str = "gpt-4o"
# External API keys (empty = use mock) flights_api_key: str = "" hotels_api_key: str = "" maps_api_key: str = "" weather_api_key: str = "" events_api_key: str = ""
cors_origins: list[str] = ["http://localhost:5173", "http://localhost:7860", "https://*.hf.space"]
model_config = {"env_prefix": "HP_", "env_file": ".env"}
settings = Settings()12345678910111213from __future__ import annotations
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.config import settings
engine = create_async_engine(settings.database_url, echo=settings.debug)async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db() -> AsyncSession: # type: ignore[misc] async with async_session() as session: yield session1234567891011121314151617181920212223242526"""Structured logging with trace IDs for agent actions."""from __future__ import annotations
import uuid
import structlog
structlog.configure( processors=[ structlog.contextvars.merge_contextvars, structlog.processors.add_log_level, structlog.processors.TimeStamper(fmt="iso"), structlog.dev.ConsoleRenderer(), ], wrapper_class=structlog.make_filtering_bound_logger(0), context_class=dict, logger_factory=structlog.PrintLoggerFactory(),)
def get_logger(name: str) -> structlog.stdlib.BoundLogger: return structlog.get_logger(name)
def new_trace_id() -> str: return uuid.uuid4().hex[:16]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""FastAPI application entry point."""from __future__ import annotations
import osfrom contextlib import asynccontextmanagerfrom pathlib import Path
from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFiles
from app.api.routes import routerfrom app.core.config import settingsfrom app.core.database import enginefrom app.models.orm import Base
@asynccontextmanagerasync def lifespan(app: FastAPI): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield await engine.dispose()
app = FastAPI( title=settings.app_name, version="0.1.0", description="AI-powered multi-agent holiday planner", lifespan=lifespan,)
app.add_middleware( CORSMiddleware, allow_origins=settings.cors_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
app.include_router(router, prefix="/api")
@app.get("/health")async def health(): return {"status": "ok", "app": settings.app_name}
# Serve built frontend static files (for production / Docker deployment)_backend_root = Path(__file__).resolve().parent.parent_frontend_dist = _backend_root.parent / "frontend" / "dist"if not _frontend_dist.is_dir(): _frontend_dist = _backend_root / "frontend" / "dist" # Docker layoutif _frontend_dist.is_dir(): app.mount("/", StaticFiles(directory=str(_frontend_dist), html=True), name="frontend")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""SQLAlchemy ORM models for persistence."""from __future__ import annotations
import uuidfrom datetime import datetime
from sqlalchemy import JSON, Column, DateTime, Float, String, Textfrom sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase): pass
def _uuid() -> str: return uuid.uuid4().hex[:12]
class TripRow(Base): __tablename__ = "trips"
id = Column(String, primary_key=True, default=_uuid) destination = Column(String, nullable=False, default="") origin = Column(String, default="") start_date = Column(String, default="") end_date = Column(String, default="") budget_total = Column(Float, default=0.0) budget_currency = Column(String, default="USD") mood = Column(String, default="relaxing") travelers_json = Column(JSON, default=list) interests_json = Column(JSON, default=list) constraints_json = Column(JSON, default=list) notes = Column(Text, default="") itinerary_json = Column(JSON, default=dict) created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class ChatRow(Base): __tablename__ = "chat_messages"
id = Column(String, primary_key=True, default=_uuid) trip_id = Column(String, nullable=False) role = Column(String, nullable=False) content = Column(Text, nullable=False) agent = Column(String, nullable=True) metadata_json = Column(JSON, default=dict) created_at = Column(DateTime, default=datetime.utcnow)
class UserPreferenceRow(Base): __tablename__ = "user_preferences"
id = Column(String, primary_key=True, default=_uuid) user_id = Column(String, nullable=False) preferences_json = Column(JSON, default=dict) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282"""Domain schemas for HolidayPilot."""from __future__ import annotations
from datetime import date, datetime, timefrom enum import Enumfrom typing import Any
from pydantic import BaseModel, Field
# ── Enums ──────────────────────────────────────────────────────────────────────
class TripMood(str, Enum): relaxing = "relaxing" romantic = "romantic" adventure = "adventure" family = "family" workation = "workation" cultural = "cultural"
class AgentRole(str, Enum): planner = "planner" flights = "flights" hotels = "hotels" activities = "activities" food = "food" route = "route" weather = "weather" budget = "budget" calendar = "calendar" monitoring = "monitoring"
class AlertSeverity(str, Enum): info = "info" warning = "warning" critical = "critical"
# ── Traveler / Trip ───────────────────────────────────────────────────────────
class TravelerProfile(BaseModel): name: str age: int | None = None dietary_restrictions: list[str] = [] accessibility_needs: list[str] = [] interests: list[str] = []
class TripRequest(BaseModel): trip_id: str = "" destination: str = "" origin: str = "" start_date: date | None = None end_date: date | None = None budget_total: float | None = None budget_currency: str = "USD" travelers: list[TravelerProfile] = [] mood: TripMood = TripMood.relaxing interests: list[str] = [] constraints: list[str] = [] notes: str = ""
# ── Search results ─────────────────────────────────────────────────────────────
class FlightOption(BaseModel): id: str airline: str departure_airport: str arrival_airport: str departure_time: datetime arrival_time: datetime price: float currency: str = "USD" stops: int = 0 duration_minutes: int = 0 booking_url: str = ""
class HotelOption(BaseModel): id: str name: str address: str rating: float = 0.0 price_per_night: float = 0.0 currency: str = "USD" amenities: list[str] = [] booking_url: str = "" latitude: float = 0.0 longitude: float = 0.0
class ActivityOption(BaseModel): id: str name: str category: str = "" description: str = "" price: float = 0.0 currency: str = "USD" duration_minutes: int = 60 rating: float = 0.0 address: str = "" latitude: float = 0.0 longitude: float = 0.0 booking_url: str = "" weather_sensitive: bool = False
class RestaurantOption(BaseModel): id: str name: str cuisine: str = "" price_level: int = 2 # 1-4 rating: float = 0.0 address: str = "" latitude: float = 0.0 longitude: float = 0.0 booking_url: str = ""
class WeatherForecast(BaseModel): date: date high_temp_c: float low_temp_c: float condition: str # sunny, cloudy, rainy, stormy precipitation_pct: int = 0 uv_index: int = 0 wind_kph: float = 0.0 recommendation: str = ""
class RouteSegment(BaseModel): origin: str destination: str mode: str = "driving" # driving, walking, transit distance_km: float = 0.0 duration_minutes: int = 0
# ── Itinerary ──────────────────────────────────────────────────────────────────
class ItineraryItem(BaseModel): id: str day: int start_time: time | None = None end_time: time | None = None title: str category: str # flight, hotel, activity, food, transport description: str = "" location: str = "" latitude: float = 0.0 longitude: float = 0.0 cost: float = 0.0 currency: str = "USD" booking_url: str = "" backup: ItineraryItem | None = None reasoning: str = "" # "Why this plan" explanation weather_note: str = "" confirmed: bool = False
class DayPlan(BaseModel): day: int date: date title: str = "" items: list[ItineraryItem] = [] weather: WeatherForecast | None = None daily_spend: float = 0.0
class Itinerary(BaseModel): trip_id: str days: list[DayPlan] = [] total_cost: float = 0.0 currency: str = "USD" flexibility_score: float = 0.0 # 0-1 how flexible this plan is travel_time_hours: float = 0.0 packing_list: list[str] = [] checklist: list[str] = []
# ── Budget ─────────────────────────────────────────────────────────────────────
class BudgetCategory(BaseModel): category: str allocated: float spent: float = 0.0 items: list[str] = []
class BudgetBreakdown(BaseModel): total_budget: float total_estimated: float currency: str = "USD" categories: list[BudgetCategory] = [] within_budget: bool = True savings_tips: list[str] = []
# ── Recommendations ───────────────────────────────────────────────────────────
class Recommendation(BaseModel): id: str category: str title: str description: str reasoning: str # "Why this" explanation score: float = 0.0 # 0-1 fit score cost: float = 0.0 currency: str = "USD" alternatives: list[str] = []
# ── Chat ───────────────────────────────────────────────────────────────────────
class ChatMessage(BaseModel): role: str # user, assistant, agent content: str agent: AgentRole | None = None metadata: dict[str, Any] = {} timestamp: datetime = Field(default_factory=datetime.utcnow)
class ChatRequest(BaseModel): trip_id: str message: str context: dict[str, Any] = {}
class ChatResponse(BaseModel): trip_id: str messages: list[ChatMessage] trip_data: TripRequest | None = None reasoning_steps: list[ReasoningStep] = [] itinerary: Itinerary | None = None budget: BudgetBreakdown | None = None
class ReasoningStep(BaseModel): agent: AgentRole action: str result_summary: str duration_ms: int = 0
# ── Alerts ─────────────────────────────────────────────────────────────────────
class AlertEvent(BaseModel): id: str trip_id: str severity: AlertSeverity title: str description: str agent: AgentRole suggested_action: str = "" created_at: datetime = Field(default_factory=datetime.utcnow)
# ── Trip Summary Card ─────────────────────────────────────────────────────────
class TripSummary(BaseModel): trip_id: str destination: str dates: str total_estimated_spend: float currency: str = "USD" total_travel_time_hours: float flexibility_score: float mood: TripMood traveler_count: int highlights: list[str] = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Activities search using Overpass API (OpenStreetMap). Free, no API key."""from __future__ import annotations
import hashlib
import httpx
from app.core.logging import get_loggerfrom app.models.schemas import ActivityOptionfrom app.services.geocoding import geocode
logger = get_logger(__name__)
OVERPASS_URL = "https://overpass-api.de/api/interpreter"_HEADERS = {"User-Agent": "HolidayPilot/0.1.0 (ai-holiday-planner)"}
_CATEGORY_MAP = { "museum": "museum", "gallery": "museum", "artwork": "museum", "attraction": "sightseeing", "viewpoint": "sightseeing", "theme_park": "entertainment", "zoo": "entertainment", "aquarium": "entertainment", "park": "nature", "garden": "nature", "nature_reserve": "nature", "castle": "historic", "monument": "historic", "memorial": "historic", "archaeological_site": "historic", "ruins": "historic", "place_of_worship": "cultural", "stadium": "sports", "sports_centre": "sports", "beach": "nature", "marina": "nature",}
_WEATHER_SENSITIVE = {"nature", "sightseeing", "sports", "entertainment"}
class ActivityService: async def search( self, destination: str, interests: list[str] | None = None, mood: str = "relaxing", radius: int = 5000, limit: int = 15, ) -> list[ActivityOption]: geo = await geocode(destination) if not geo: logger.warning("activities.no_geocode", destination=destination) return []
query = f"""[out:json][timeout:20];( node["tourism"~"museum|gallery|attraction|viewpoint|artwork|zoo|theme_park|aquarium"](around:{radius},{geo.lat},{geo.lng}); way["tourism"~"museum|gallery|attraction|viewpoint|artwork|zoo|theme_park|aquarium"](around:{radius},{geo.lat},{geo.lng}); node["leisure"~"park|garden|nature_reserve|marina|beach|stadium|sports_centre"](around:{radius},{geo.lat},{geo.lng}); way["leisure"~"park|garden|nature_reserve|marina|beach|stadium|sports_centre"](around:{radius},{geo.lat},{geo.lng}); node["historic"](around:{radius},{geo.lat},{geo.lng}); way["historic"](around:{radius},{geo.lat},{geo.lng}););out center {limit * 3};""" try: async with httpx.AsyncClient(timeout=25, headers=_HEADERS) as client: resp = await client.post(OVERPASS_URL, data={"data": query}) resp.raise_for_status() data = resp.json() except Exception as exc: logger.error("activities.api_error", error=str(exc)) return []
elements = data.get("elements", []) activities: list[ActivityOption] = [] seen_names: set[str] = set()
for el in elements: tags = el.get("tags", {}) name = tags.get("name") or tags.get("name:en") if not name or name.lower() in seen_names: continue seen_names.add(name.lower())
lat = el.get("lat") or el.get("center", {}).get("lat", geo.lat) lon = el.get("lon") or el.get("center", {}).get("lon", geo.lng)
# Determine category category = "sightseeing" for tag_key in ("tourism", "leisure", "historic"): tag_val = tags.get(tag_key, "") if tag_val in _CATEGORY_MAP: category = _CATEGORY_MAP[tag_val] break
# Estimate price (most attractions are free or cheap) fee = tags.get("fee", "no") if fee == "yes": price = 15.0 # default admission estimate charge = tags.get("charge") if charge: import re m = re.search(r'[\d.]+', charge) if m: price = float(m.group()) else: price = 0.0
# Estimate duration from type duration = {"museum": 120, "nature": 90, "historic": 60, "sightseeing": 60, "entertainment": 150, "cultural": 45, "sports": 120}.get(category, 60)
# Rating (OSM doesn't have ratings; use a reasonable default) rating = 4.3
description = tags.get("description") or tags.get("description:en") or f"{category.capitalize()} in {destination}" address = ", ".join(filter(None, [tags.get("addr:street"), tags.get("addr:city", destination)]))
aid = hashlib.md5(name.encode()).hexdigest()[:8] activities.append(ActivityOption( id=f"AC-{aid}", name=name, category=category, description=description[:200], price=price, duration_minutes=duration, rating=rating, address=address or destination, latitude=float(lat), longitude=float(lon), booking_url=f"https://www.google.com/maps/search/{name.replace(' ', '+')}+{destination.replace(' ', '+')}", weather_sensitive=category in _WEATHER_SENSITIVE, ))
if len(activities) >= limit: break
logger.info("activities.found", destination=destination, count=len(activities)) return activities123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""Flight search with real airport data, distance-based pricing, and booking links."""from __future__ import annotations
import mathimport randomfrom datetime import datetime, timedelta
from app.core.logging import get_loggerfrom app.models.schemas import FlightOptionfrom app.services.geocoding import geocode
logger = get_logger(__name__)
# Major airports worldwide: (IATA, city, country, lat, lng)_AIRPORTS: list[tuple[str, str, str, float, float]] = [ # North America ("JFK", "New York", "US", 40.6413, -73.7781), ("EWR", "Newark", "US", 40.6895, -74.1745), ("LAX", "Los Angeles", "US", 33.9425, -118.4081), ("SFO", "San Francisco", "US", 37.6213, -122.3790), ("ORD", "Chicago", "US", 41.9742, -87.9073), ("ATL", "Atlanta", "US", 33.6407, -84.4277), ("MIA", "Miami", "US", 25.7959, -80.2870), ("BOS", "Boston", "US", 42.3656, -71.0096), ("DFW", "Dallas", "US", 32.8998, -97.0403), ("SEA", "Seattle", "US", 47.4502, -122.3088), ("DEN", "Denver", "US", 39.8561, -104.6737), ("IAD", "Washington", "US", 38.9531, -77.4565), ("YYZ", "Toronto", "CA", 43.6777, -79.6248), ("YVR", "Vancouver", "CA", 49.1967, -123.1815), ("MEX", "Mexico City", "MX", 19.4363, -99.0721), ("GRU", "São Paulo", "BR", -23.4356, -46.4731), ("EZE", "Buenos Aires", "AR", -34.8222, -58.5358), ("BOG", "Bogotá", "CO", 4.7016, -74.1469), ("SCL", "Santiago", "CL", -33.3930, -70.7858), ("LIM", "Lima", "PE", -12.0219, -77.1143), # Europe ("LHR", "London", "GB", 51.4700, -0.4543), ("CDG", "Paris", "FR", 49.0097, 2.5479), ("AMS", "Amsterdam", "NL", 52.3105, 4.7683), ("FRA", "Frankfurt", "DE", 50.0379, 8.5622), ("MAD", "Madrid", "ES", 40.4983, -3.5676), ("BCN", "Barcelona", "ES", 41.2971, 2.0785), ("FCO", "Rome", "IT", 41.8003, 12.2389), ("MXP", "Milan", "IT", 45.6306, 8.7281), ("MUC", "Munich", "DE", 48.3537, 11.7750), ("ZRH", "Zurich", "CH", 47.4647, 8.5492), ("LIS", "Lisbon", "PT", 38.7742, -9.1342), ("CPH", "Copenhagen", "DK", 55.6180, 12.6508), ("DUB", "Dublin", "IE", 53.4264, -6.2499), ("IST", "Istanbul", "TR", 41.2753, 28.7519), ("ATH", "Athens", "GR", 37.9364, 23.9445), ("VIE", "Vienna", "AT", 48.1103, 16.5697), ("PRG", "Prague", "CZ", 50.1008, 14.2600), ("WAW", "Warsaw", "PL", 52.1657, 20.9671), ("OSL", "Oslo", "NO", 60.1939, 11.1004), ("ARN", "Stockholm", "SE", 59.6519, 17.9186), ("HEL", "Helsinki", "FI", 60.3172, 24.9633), # Asia ("NRT", "Tokyo", "JP", 35.7647, 140.3864), ("HND", "Tokyo Haneda", "JP", 35.5494, 139.7798), ("ICN", "Seoul", "KR", 37.4602, 126.4407), ("PEK", "Beijing", "CN", 40.0799, 116.6031), ("PVG", "Shanghai", "CN", 31.1443, 121.8083), ("HKG", "Hong Kong", "HK", 22.3080, 113.9185), ("SIN", "Singapore", "SG", 1.3644, 103.9915), ("BKK", "Bangkok", "TH", 13.6900, 100.7501), ("KUL", "Kuala Lumpur", "MY", 2.7456, 101.7099), ("DEL", "New Delhi", "IN", 28.5562, 77.1000), ("BOM", "Mumbai", "IN", 19.0896, 72.8656), ("TPE", "Taipei", "TW", 25.0797, 121.2342), ("MNL", "Manila", "PH", 14.5086, 121.0198), ("SGN", "Ho Chi Minh City", "VN", 10.8188, 106.6520), ("CGK", "Jakarta", "ID", -6.1256, 106.6559), # Middle East ("DXB", "Dubai", "AE", 25.2532, 55.3657), ("DOH", "Doha", "QA", 25.2731, 51.6081), ("AUH", "Abu Dhabi", "AE", 24.4330, 54.6511), ("TLV", "Tel Aviv", "IL", 32.0055, 34.8854), # Oceania ("SYD", "Sydney", "AU", -33.9461, 151.1772), ("MEL", "Melbourne", "AU", -37.6690, 144.8410), ("AKL", "Auckland", "NZ", -37.0082, 174.7850), ("DPS", "Bali", "ID", -8.7482, 115.1672), # Africa ("JNB", "Johannesburg", "ZA", -26.1392, 28.2460), ("CAI", "Cairo", "EG", 30.1219, 31.4056), ("NBO", "Nairobi", "KE", -1.3192, 36.9278), ("CMN", "Casablanca", "MA", 33.3675, -7.5898), ("CPT", "Cape Town", "ZA", -33.9648, 18.6017), # Islands ("MLE", "Maldives", "MV", 4.1918, 73.5290), ("HNL", "Honolulu", "US", 21.3187, -157.9224), ("KEF", "Reykjavik", "IS", 63.9850, -22.6056), ("MRU", "Mauritius", "MU", -20.4302, 57.6836),]
_AIRLINES = [ "American Airlines", "United Airlines", "Delta Air Lines", "Southwest", "British Airways", "Lufthansa", "Air France", "KLM", "Ryanair", "easyJet", "Emirates", "Qatar Airways", "Etihad Airways", "Turkish Airlines", "Singapore Airlines", "Cathay Pacific", "ANA", "Japan Airlines", "Korean Air", "Thai Airways", "Air Canada", "LATAM Airlines", "Qantas", "Virgin Atlantic", "Iberia", "SAS", "Swiss", "Austrian", "TAP Portugal", "Aer Lingus", "Norwegian", "Air New Zealand",]
def _haversine(lat1: float, lng1: float, lat2: float, lng2: float) -> float: R = 6371 dlat = math.radians(lat2 - lat1) dlng = math.radians(lng2 - lng1) a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2 return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _find_nearest_airport(lat: float, lng: float) -> tuple[str, str, float, float]: """Find nearest airport to given coordinates. Returns (code, city, lat, lng).""" best = _AIRPORTS[0] best_dist = float("inf") for code, city, country, alat, alng in _AIRPORTS: d = _haversine(lat, lng, alat, alng) if d < best_dist: best_dist = d best = (code, city, country, alat, alng) return best[0], best[1], best[3], best[4]
def _find_airport_by_city(city_name: str) -> tuple[str, str, float, float] | None: """Find airport by city name (case-insensitive partial match).""" city_lower = city_name.lower().strip() for code, city, country, lat, lng in _AIRPORTS: if city_lower in city.lower() or city.lower() in city_lower or city_lower == code.lower(): return code, city, lat, lng return None
def _estimate_price(distance_km: float, is_direct: bool = True) -> float: """Realistic economy price estimation based on route distance.""" if distance_km < 500: rate = 0.28 elif distance_km < 1500: rate = 0.18 elif distance_km < 5000: rate = 0.11 elif distance_km < 10000: rate = 0.075 else: rate = 0.055
base = distance_km * rate base = max(base, 45)
if not is_direct: base *= 0.72
variation = random.uniform(0.85, 1.20) return round(base * variation, 2)
def _pick_airlines(origin_code: str, dest_code: str, n: int = 3) -> list[str]: """Pick plausible airlines for a route.""" random.seed(hash(f"{origin_code}-{dest_code}")) picked = random.sample(_AIRLINES, min(n, len(_AIRLINES))) random.seed() # re-seed return picked
class FlightService: async def search( self, origin: str, destination: str, departure_date: str, return_date: str = "", ) -> list[FlightOption]: # Resolve origin airport orig_airport = _find_airport_by_city(origin) if not orig_airport: geo = await geocode(origin) if geo: code, city, lat, lng = _find_nearest_airport(geo.lat, geo.lng) orig_airport = (code, city, lat, lng) else: orig_airport = ("JFK", "New York", 40.6413, -73.7781)
# Resolve destination airport dest_airport = _find_airport_by_city(destination) if not dest_airport: geo = await geocode(destination) if geo: code, city, lat, lng = _find_nearest_airport(geo.lat, geo.lng) dest_airport = (code, city, lat, lng) else: dest_airport = ("LHR", "London", 51.4700, -0.4543)
orig_code, orig_city, orig_lat, orig_lng = orig_airport dest_code, dest_city, dest_lat, dest_lng = dest_airport
distance = _haversine(orig_lat, orig_lng, dest_lat, dest_lng) flight_hours = distance / 800 # ~800 km/h average speed airlines = _pick_airlines(orig_code, dest_code, 3)
dep = departure_date or "2026-07-01" try: dep_date = datetime.fromisoformat(str(dep)) except ValueError: dep_date = datetime(2026, 7, 1)
flights: list[FlightOption] = []
# Generate 3 realistic options for i, airline in enumerate(airlines): is_direct = i < 2 # first 2 are direct, last has a stop price = _estimate_price(distance, is_direct) stops = 0 if is_direct else 1
hours = flight_hours * (1.0 if is_direct else 1.5) dep_hour = [8, 12, 18][i % 3] dep_time = dep_date.replace(hour=dep_hour, minute=0) arr_time = dep_time + timedelta(hours=hours) duration = int(hours * 60)
# Build Google Flights booking URL booking_url = ( f"https://www.google.com/travel/flights?q=Flights+from+{orig_city.replace(' ', '+')}+" f"to+{dest_city.replace(' ', '+')}+on+{dep}" )
flights.append(FlightOption( id=f"FL-{orig_code}{dest_code}-{i+1}", airline=airline, departure_airport=orig_code, arrival_airport=dest_code, departure_time=dep_time, arrival_time=arr_time, price=price, stops=stops, duration_minutes=duration, booking_url=booking_url, ))
flights.sort(key=lambda f: f.price) logger.info("flights.generated", origin=orig_code, dest=dest_code, distance_km=round(distance), count=len(flights)) return flights123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Restaurant search using Overpass API (OpenStreetMap). Free, no API key."""from __future__ import annotations
import hashlib
import httpx
from app.core.logging import get_loggerfrom app.models.schemas import RestaurantOptionfrom app.services.geocoding import geocode
logger = get_logger(__name__)
OVERPASS_URL = "https://overpass-api.de/api/interpreter"_HEADERS = {"User-Agent": "HolidayPilot/0.1.0 (ai-holiday-planner)"}
_PRICE_LEVEL = { "": 2, "cheap": 1, "moderate": 2, "expensive": 3, "luxury": 4,}
class FoodService: async def search( self, destination: str, dietary_restrictions: list[str] | None = None, budget: float | None = None, radius: int = 3000, limit: int = 12, ) -> list[RestaurantOption]: geo = await geocode(destination) if not geo: logger.warning("food.no_geocode", destination=destination) return []
query = f"""[out:json][timeout:20];( node["amenity"="restaurant"](around:{radius},{geo.lat},{geo.lng}); node["amenity"="cafe"](around:{radius},{geo.lat},{geo.lng}); node["amenity"="fast_food"](around:{radius},{geo.lat},{geo.lng}); node["amenity"="bar"]["food"="yes"](around:{radius},{geo.lat},{geo.lng}););out body {limit * 3};""" try: async with httpx.AsyncClient(timeout=25, headers=_HEADERS) as client: resp = await client.post(OVERPASS_URL, data={"data": query}) resp.raise_for_status() data = resp.json() except Exception as exc: logger.error("food.api_error", error=str(exc)) return []
elements = data.get("elements", []) restaurants: list[RestaurantOption] = [] seen: set[str] = set()
dietary = set(d.lower() for d in (dietary_restrictions or []))
for el in elements: tags = el.get("tags", {}) name = tags.get("name") or tags.get("name:en") if not name or name.lower() in seen: continue seen.add(name.lower())
# Filter by dietary needs if specified if dietary: diet_tags = { tags.get("diet:vegetarian", ""), tags.get("diet:vegan", ""), tags.get("diet:gluten_free", ""), tags.get("diet:halal", ""), tags.get("diet:kosher", ""), } # Skip items that explicitly say "no" for requested diets skip = False for d in dietary: tag_key = f"diet:{d}" if tags.get(tag_key) == "no": skip = True break if skip: continue
cuisine = tags.get("cuisine", "").replace(";", ", ").replace("_", " ") if not cuisine: amenity = tags.get("amenity", "") cuisine = {"cafe": "Café", "fast_food": "Fast food", "bar": "Bar"}.get(amenity, "Local")
price_tag = tags.get("price", "") price_level = _PRICE_LEVEL.get(price_tag, 2)
address_parts = [tags.get("addr:housenumber", ""), tags.get("addr:street", "")] address = " ".join(filter(None, address_parts)).strip() or destination
rid = hashlib.md5(name.encode()).hexdigest()[:8] restaurants.append(RestaurantOption( id=f"RS-{rid}", name=name, cuisine=cuisine.title() if len(cuisine) < 50 else cuisine[:50].title(), price_level=price_level, rating=4.2, # OSM doesn't have ratings address=address, latitude=float(el.get("lat", geo.lat)), longitude=float(el.get("lon", geo.lng)), booking_url=f"https://www.google.com/maps/search/{name.replace(' ', '+')}+{destination.replace(' ', '+')}", ))
if len(restaurants) >= limit: break
logger.info("food.found", destination=destination, count=len(restaurants)) return restaurants1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Geocoding service using Nominatim (OpenStreetMap). Free, no API key needed."""from __future__ import annotations
import httpxfrom dataclasses import dataclass
from app.core.logging import get_logger
logger = get_logger(__name__)
NOMINATIM_URL = "https://nominatim.openstreetmap.org/search"HEADERS = {"User-Agent": "HolidayPilot/0.1.0 (ai-holiday-planner)"}
_cache: dict[str, "GeoResult | None"] = {}
@dataclassclass GeoResult: lat: float lng: float display_name: str
async def geocode(place: str) -> GeoResult | None: """Convert a place name to coordinates. Results are cached.""" key = place.strip().lower() if key in _cache: return _cache[key]
try: async with httpx.AsyncClient(timeout=10, headers=HEADERS) as client: resp = await client.get( NOMINATIM_URL, params={"q": place, "format": "json", "limit": 1, "addressdetails": 0}, ) resp.raise_for_status() data = resp.json()
if not data: logger.warning("geocode.not_found", place=place) _cache[key] = None return None
result = GeoResult( lat=float(data[0]["lat"]), lng=float(data[0]["lon"]), display_name=data[0].get("display_name", place), ) _cache[key] = result logger.info("geocode.ok", place=place, lat=result.lat, lng=result.lng) return result
except Exception as exc: logger.error("geocode.error", place=place, error=str(exc)) _cache[key] = None return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Hotel search using Overpass API (OpenStreetMap) + price estimation. Free, no API key."""from __future__ import annotations
import hashlibimport random
import httpx
from app.core.logging import get_loggerfrom app.models.schemas import HotelOptionfrom app.services.geocoding import geocode
logger = get_logger(__name__)
OVERPASS_URL = "https://overpass-api.de/api/interpreter"_HEADERS = {"User-Agent": "HolidayPilot/0.1.0 (ai-holiday-planner)"}
# Price estimation per night by type_BASE_PRICES = { "hostel": (25, 60), "guest_house": (40, 90), "motel": (50, 100), "hotel": (80, 220), "apartment": (60, 150),}
class HotelService: async def search( self, destination: str, check_in: str = "", check_out: str = "", budget: float | None = None, radius: int = 5000, limit: int = 10, ) -> list[HotelOption]: geo = await geocode(destination) if not geo: logger.warning("hotels.no_geocode", destination=destination) return []
query = f"""[out:json][timeout:20];( node["tourism"~"hotel|hostel|guest_house|motel|apartment"](around:{radius},{geo.lat},{geo.lng}); way["tourism"~"hotel|hostel|guest_house|motel|apartment"](around:{radius},{geo.lat},{geo.lng}););out center {limit * 3};""" try: async with httpx.AsyncClient(timeout=25, headers=_HEADERS) as client: resp = await client.post(OVERPASS_URL, data={"data": query}) resp.raise_for_status() data = resp.json() except Exception as exc: logger.error("hotels.api_error", error=str(exc)) return []
elements = data.get("elements", []) hotels: list[HotelOption] = [] seen: set[str] = set()
for el in elements: tags = el.get("tags", {}) name = tags.get("name") or tags.get("name:en") if not name or name.lower() in seen: continue seen.add(name.lower())
lat = el.get("lat") or el.get("center", {}).get("lat", geo.lat) lon = el.get("lon") or el.get("center", {}).get("lon", geo.lng)
tourism_type = tags.get("tourism", "hotel") stars_str = tags.get("stars", "")
# Estimate price low, high = _BASE_PRICES.get(tourism_type, (80, 200)) if stars_str: try: stars = int(stars_str) low = max(low, stars * 30) high = max(high, stars * 70) except ValueError: pass price = round(random.uniform(low, high), 0)
# Rating from stars, or estimate if stars_str: try: rating = min(float(stars_str) + 0.3, 5.0) except ValueError: rating = 4.0 else: rating = {"hostel": 3.8, "guest_house": 4.0, "motel": 3.5, "hotel": 4.2}.get(tourism_type, 4.0)
# Amenities from tags amenities = ["Wi-Fi"] if tags.get("internet_access") != "no" else [] if tags.get("swimming_pool") == "yes": amenities.append("Pool") if tags.get("breakfast") == "yes": amenities.append("Breakfast") if tags.get("air_conditioning") == "yes": amenities.append("A/C") if tags.get("parking") and tags.get("parking") != "no": amenities.append("Parking") if tourism_type == "hostel": amenities.append("Shared kitchen")
address_parts = [tags.get("addr:housenumber", ""), tags.get("addr:street", "")] address = " ".join(filter(None, address_parts)).strip() or destination
hid = hashlib.md5(name.encode()).hexdigest()[:8] hotels.append(HotelOption( id=f"HT-{hid}", name=name, address=address, rating=rating, price_per_night=price, amenities=amenities if amenities else ["Wi-Fi"], booking_url=f"https://www.google.com/travel/hotels/{destination.replace(' ', '+')}", latitude=float(lat), longitude=float(lon), ))
if len(hotels) >= limit: break
# Sort by price hotels.sort(key=lambda h: h.price_per_night)
logger.info("hotels.found", destination=destination, count=len(hotels)) return hotels12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Maps/routing service using OSRM (Open Source Routing Machine). Free, no API key."""from __future__ import annotations
import math
import httpx
from app.core.logging import get_logger
logger = get_logger(__name__)
OSRM_URL = "https://router.project-osrm.org"
class MapsService: def cluster_locations(self, locations: list[dict], max_clusters: int = 4) -> list[list[dict]]: """Simple geographic clustering by grid partitioning.""" if not locations: return []
if len(locations) <= max_clusters: return [[loc] for loc in locations]
lats = [loc["lat"] for loc in locations] lngs = [loc["lng"] for loc in locations] mid_lat = sum(lats) / len(lats) mid_lng = sum(lngs) / len(lngs)
quadrants: dict[str, list[dict]] = {"NE": [], "NW": [], "SE": [], "SW": []} for loc in locations: ns = "N" if loc["lat"] >= mid_lat else "S" ew = "E" if loc["lng"] >= mid_lng else "W" quadrants[ns + ew].append(loc)
return [v for v in quadrants.values() if v]
async def get_route( self, origin_lat: float, origin_lng: float, dest_lat: float, dest_lng: float ) -> dict: """Get real driving route from OSRM.""" url = ( f"{OSRM_URL}/route/v1/driving/" f"{origin_lng},{origin_lat};{dest_lng},{dest_lat}" f"?overview=false" ) try: async with httpx.AsyncClient(timeout=10) as client: resp = await client.get(url) resp.raise_for_status() data = resp.json()
if data.get("code") == "Ok" and data.get("routes"): route = data["routes"][0] return { "distance_km": round(route["distance"] / 1000, 1), "duration_minutes": int(route["duration"] / 60), "mode": "driving", } except Exception as exc: logger.warning("osrm.error", error=str(exc))
# Fallback to haversine estimate dist = self._haversine(origin_lat, origin_lng, dest_lat, dest_lng) return { "distance_km": round(dist * 1.3, 1), # ~1.3x road factor "duration_minutes": int(dist * 1.3 / 0.5), "mode": "driving", }
@staticmethod def _haversine(lat1: float, lng1: float, lat2: float, lng2: float) -> float: R = 6371 dlat = math.radians(lat2 - lat1) dlng = math.radians(lng2 - lng1) a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2 return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""PDF export service for itinerary download."""from __future__ import annotations
from datetime import datetimefrom typing import Any
from jinja2 import Template
ITINERARY_HTML_TEMPLATE = """<!DOCTYPE html><html><head><meta charset="utf-8"><style> body { font-family: 'Segoe UI', Arial, sans-serif; margin: 40px; color: #1a1a1a; } h1 { color: #1e3a5f; border-bottom: 3px solid #1e3a5f; padding-bottom: 10px; } h2 { color: #2d6a4f; margin-top: 30px; } .day { margin-bottom: 30px; page-break-inside: avoid; } .day-header { background: #f0f7ff; padding: 10px 15px; border-radius: 8px; margin-bottom: 10px; } .item { padding: 8px 15px; border-left: 3px solid #ccc; margin: 5px 0; } .item.flight { border-color: #e63946; } .item.hotel { border-color: #457b9d; } .item.activity { border-color: #2a9d8f; } .item.food { border-color: #e9c46a; } .time { font-weight: bold; color: #555; } .cost { float: right; color: #888; } .reasoning { font-style: italic; color: #666; font-size: 0.9em; } .weather { background: #fff3cd; padding: 5px 10px; border-radius: 4px; font-size: 0.9em; } .summary { background: #d4edda; padding: 15px; border-radius: 8px; margin: 20px 0; } .checklist { columns: 2; } .checklist li { margin-bottom: 5px; } footer { margin-top: 40px; text-align: center; color: #888; font-size: 0.8em; }</style></head><body><h1>🌍 {{ destination }} Trip Itinerary</h1><p><strong>Dates:</strong> {{ start_date }} — {{ end_date }} | <strong>Budget:</strong> {{ currency }} {{ "%.0f"|format(total_cost) }} | <strong>Travelers:</strong> {{ traveler_count }}</p>
{% for day in days %}<div class="day"> <div class="day-header"> <h2>Day {{ day.day }} — {{ day.date }}{% if day.title %}: {{ day.title }}{% endif %}</h2> {% if day.weather %} <div class="weather">{{ day.weather.condition | capitalize }} · {{ day.weather.high_temp_c }}°C / {{ day.weather.low_temp_c }}°C · {{ day.weather.recommendation }}</div> {% endif %} </div> {% for item in day.items %} <div class="item {{ item.category }}"> <span class="time">{% if item.start_time %}{{ item.start_time }}{% endif %}</span> {{ item.title }} {% if item.cost %}<span class="cost">{{ currency }} {{ "%.0f"|format(item.cost) }}</span>{% endif %} {% if item.description %}<br><small>{{ item.description }}</small>{% endif %} {% if item.reasoning %}<br><span class="reasoning">Why: {{ item.reasoning }}</span>{% endif %} </div> {% endfor %} <p><em>Daily spend: {{ currency }} {{ "%.0f"|format(day.daily_spend) }}</em></p></div>{% endfor %}
<div class="summary"> <h2>Trip Summary</h2> <p><strong>Total Estimated:</strong> {{ currency }} {{ "%.0f"|format(total_cost) }}</p> <p><strong>Flexibility Score:</strong> {{ "%.0f"|format(flexibility_score * 100) }}%</p></div>
{% if packing_list %}<h2>🎒 Packing List</h2><ul class="checklist">{% for item in packing_list %} <li>☐ {{ item }}</li>{% endfor %}</ul>{% endif %}
{% if checklist %}<h2>✅ Pre-Trip Checklist</h2><ul class="checklist">{% for item in checklist %} <li>☐ {{ item }}</li>{% endfor %}</ul>{% endif %}
<footer>Generated by HolidayPilot · {{ generated_at }}</footer></body></html>"""
def render_itinerary_html(itinerary: dict, trip: dict) -> str: template = Template(ITINERARY_HTML_TEMPLATE) return template.render( destination=trip.get("destination", "Your Trip"), start_date=trip.get("start_date", ""), end_date=trip.get("end_date", ""), currency=itinerary.get("currency", "USD"), total_cost=itinerary.get("total_cost", 0), flexibility_score=itinerary.get("flexibility_score", 0), traveler_count=len(trip.get("travelers", [])) or 1, days=itinerary.get("days", []), packing_list=itinerary.get("packing_list", []), checklist=itinerary.get("checklist", []), generated_at=datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), )
async def generate_pdf(itinerary: dict, trip: dict) -> bytes: """Generate PDF from itinerary. Falls back to HTML if WeasyPrint unavailable.""" html = render_itinerary_html(itinerary, trip) try: from weasyprint import HTML return HTML(string=html).write_pdf() except ImportError: return html.encode("utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Weather forecast service using Open-Meteo API. Free, no API key needed."""from __future__ import annotations
from datetime import date as dt_date, timedelta
import httpx
from app.core.logging import get_loggerfrom app.models.schemas import WeatherForecastfrom app.services.geocoding import geocode
logger = get_logger(__name__)
OPEN_METEO_URL = "https://api.open-meteo.com/v1/forecast"
# WMO weather code → human-readable condition_WMO_CONDITIONS: dict[int, str] = { 0: "sunny", 1: "partly_cloudy", 2: "partly_cloudy", 3: "cloudy", 45: "foggy", 48: "foggy", 51: "drizzle", 53: "drizzle", 55: "drizzle", 56: "freezing_drizzle", 57: "freezing_drizzle", 61: "rainy", 63: "rainy", 65: "rainy", 66: "freezing_rain", 67: "freezing_rain", 71: "snowy", 73: "snowy", 75: "snowy", 77: "snowy", 80: "rainy", 81: "rainy", 82: "rainy", 85: "snowy", 86: "snowy", 95: "stormy", 96: "stormy", 99: "stormy",}
def _recommend(condition: str, high_c: float, precip_pct: int) -> str: if condition in ("stormy",): return "Stay indoors. Severe weather expected." if condition in ("rainy", "freezing_rain"): return "Bring an umbrella. Consider indoor activities." if condition in ("snowy", "freezing_drizzle"): return "Cold and snowy — dress warmly, enjoy winter activities." if condition == "foggy": return "Reduced visibility. Stick to indoor plans or short walks." if condition == "drizzle": return "Light drizzle possible. A light raincoat should suffice." if high_c > 33: return "Very hot — stay hydrated, seek shade during midday." if high_c > 28: return "Warm day. Sunscreen and a hat recommended." if high_c < 5: return "Very cold — layer up and keep warm." if precip_pct > 50: return "Rain possible later. Have a backup indoor plan." return "Great day for outdoor activities!"
class WeatherService: async def get_forecast( self, destination: str, start_date: str, end_date: str, ) -> list[WeatherForecast]: geo = await geocode(destination) if not geo: logger.warning("weather.no_geocode", destination=destination) return []
try: start = dt_date.fromisoformat(str(start_date)) end = dt_date.fromisoformat(str(end_date)) except (ValueError, TypeError): start = dt_date.today() end = start + timedelta(days=3)
# Open-Meteo only forecasts up to 16 days ahead; clamp if needed today = dt_date.today() max_end = today + timedelta(days=15) api_start = max(start, today) api_end = min(end, max_end)
if api_start > api_end: # Dates are too far in the future for forecast — use climate averages return self._climate_estimate(start, end, geo.lat, geo.lng)
try: async with httpx.AsyncClient(timeout=15) as client: resp = await client.get(OPEN_METEO_URL, params={ "latitude": geo.lat, "longitude": geo.lng, "daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_max,weather_code,uv_index_max,wind_speed_10m_max", "timezone": "auto", "start_date": str(api_start), "end_date": str(api_end), }) resp.raise_for_status() data = resp.json() except Exception as exc: logger.error("weather.api_error", error=str(exc)) return self._climate_estimate(start, end, geo.lat, geo.lng)
daily = data.get("daily", {}) dates = daily.get("time", []) highs = daily.get("temperature_2m_max", []) lows = daily.get("temperature_2m_min", []) precip = daily.get("precipitation_probability_max", []) codes = daily.get("weather_code", []) uv = daily.get("uv_index_max", []) wind = daily.get("wind_speed_10m_max", [])
forecasts: list[WeatherForecast] = [] for i, d in enumerate(dates): high_c = highs[i] if i < len(highs) else 20.0 low_c = lows[i] if i < len(lows) else 12.0 prec = int(precip[i]) if i < len(precip) and precip[i] is not None else 0 code = codes[i] if i < len(codes) else 0 condition = _WMO_CONDITIONS.get(code, "partly_cloudy")
forecasts.append(WeatherForecast( date=dt_date.fromisoformat(d), high_temp_c=round(high_c, 1), low_temp_c=round(low_c, 1), condition=condition, precipitation_pct=prec, uv_index=int(uv[i]) if i < len(uv) and uv[i] is not None else 5, wind_kph=round(wind[i], 1) if i < len(wind) and wind[i] is not None else 10.0, recommendation=_recommend(condition, high_c, prec), ))
return forecasts
def _climate_estimate( self, start: dt_date, end: dt_date, lat: float, lng: float ) -> list[WeatherForecast]: """Rough climate-based estimate for dates too far in the future.""" import math, random num_days = max((end - start).days, 1) month = start.month
# Rough temperature based on latitude and month # Northern hemisphere summer (Jun-Aug) is warmer, southern is opposite base_temp = 25 - abs(lat) * 0.4 seasonal = 8 * math.cos(math.radians((month - 7) * 30)) * (1 if lat >= 0 else -1) avg_high = base_temp + seasonal
forecasts = [] for i in range(num_days): current = start + timedelta(days=i) high = round(avg_high + random.uniform(-3, 3), 1) low = round(high - random.uniform(5, 10), 1) precip = random.randint(10, 40) condition = "partly_cloudy" if precip < 30 else "cloudy"
forecasts.append(WeatherForecast( date=current, high_temp_c=high, low_temp_c=low, condition=condition, precipitation_pct=precip, uv_index=random.randint(3, 8), wind_kph=round(random.uniform(5, 20), 1), recommendation=_recommend(condition, high, precip) + " (Climate estimate — check closer to trip.)", )) return forecasts123456789101112131415161718192021222324Metadata-Version: 2.4Name: holidaypilotVersion: 0.1.0Summary: AI-powered multi-agent holiday plannerRequires-Python: >=3.11Requires-Dist: fastapi>=0.115.0Requires-Dist: uvicorn[standard]>=0.30.0Requires-Dist: pydantic>=2.0Requires-Dist: pydantic-settings>=2.0Requires-Dist: sqlalchemy>=2.0Requires-Dist: aiosqlite>=0.20.0Requires-Dist: httpx>=0.27.0Requires-Dist: openai>=1.30.0Requires-Dist: python-multipart>=0.0.9Requires-Dist: jinja2>=3.1.0Requires-Dist: weasyprint>=62.0Requires-Dist: icalendar>=5.0Requires-Dist: structlog>=24.0Requires-Dist: tenacity>=8.0Provides-Extra: devRequires-Dist: pytest>=8.0; extra == "dev"Requires-Dist: pytest-asyncio>=0.23; extra == "dev"Requires-Dist: pytest-httpx>=0.30; extra == "dev"Requires-Dist: ruff>=0.5.0; extra == "dev"123456789101112131415161718192021222324252627282930313233343536373839404142pyproject.tomlapp/__init__.pyapp/main.pyapp/agents/__init__.pyapp/agents/activities.pyapp/agents/base.pyapp/agents/budget.pyapp/agents/calendar.pyapp/agents/flights.pyapp/agents/food.pyapp/agents/hotels.pyapp/agents/monitoring.pyapp/agents/orchestrator.pyapp/agents/planner.pyapp/agents/registry.pyapp/agents/route.pyapp/agents/weather.pyapp/api/__init__.pyapp/api/routes.pyapp/core/__init__.pyapp/core/config.pyapp/core/database.pyapp/core/logging.pyapp/models/__init__.pyapp/models/orm.pyapp/models/schemas.pyapp/services/__init__.pyapp/services/activities.pyapp/services/flights.pyapp/services/food.pyapp/services/geocoding.pyapp/services/hotels.pyapp/services/maps.pyapp/services/pdf_export.pyapp/services/weather.pyholidaypilot.egg-info/PKG-INFOholidaypilot.egg-info/SOURCES.txtholidaypilot.egg-info/dependency_links.txtholidaypilot.egg-info/requires.txtholidaypilot.egg-info/top_level.txttests/test_agents.pytests/test_api.py1
1234567891011121314151617181920fastapi>=0.115.0uvicorn[standard]>=0.30.0pydantic>=2.0pydantic-settings>=2.0sqlalchemy>=2.0aiosqlite>=0.20.0httpx>=0.27.0openai>=1.30.0python-multipart>=0.0.9jinja2>=3.1.0weasyprint>=62.0icalendar>=5.0structlog>=24.0tenacity>=8.0
[dev]pytest>=8.0pytest-asyncio>=0.23pytest-httpx>=0.30ruff>=0.5.01app12345678910111213141516171819202122232425262728293031323334353637[project]name = "holidaypilot"version = "0.1.0"description = "AI-powered multi-agent holiday planner"requires-python = ">=3.11"dependencies = [ "fastapi>=0.115.0", "uvicorn[standard]>=0.30.0", "pydantic>=2.0", "pydantic-settings>=2.0", "sqlalchemy>=2.0", "aiosqlite>=0.20.0", "httpx>=0.27.0", "openai>=1.30.0", "python-multipart>=0.0.9", "jinja2>=3.1.0", "weasyprint>=62.0", "icalendar>=5.0", "structlog>=24.0", "tenacity>=8.0",]
[project.optional-dependencies]dev = [ "pytest>=8.0", "pytest-asyncio>=0.23", "pytest-httpx>=0.30", "ruff>=0.5.0",]
[tool.pytest.ini_options]asyncio_mode = "auto"testpaths = ["tests"]
[tool.ruff]target-version = "py311"line-length = 100123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Tests for the orchestrator and agent pipeline."""from __future__ import annotations
import pytest
from app.agents.planner import PlannerAgentfrom app.agents.budget import BudgetAgentfrom app.agents.calendar import CalendarAgentfrom app.agents.flights import FlightsAgentfrom app.agents.hotels import HotelsAgentfrom app.agents.activities import ActivitiesAgentfrom app.agents.food import FoodAgentfrom app.agents.weather import WeatherAgentfrom app.agents.route import RouteAgentfrom app.agents.orchestrator import Orchestratorfrom app.agents.registry import create_orchestratorfrom app.models.schemas import AgentRole, TripRequest, ChatMessage
@pytest.mark.asyncioasync def test_planner_extracts_destination(): agent = PlannerAgent() ctx = { "trip": {"trip_id": "t1", "destination": "", "budget_total": None}, "user_message": "I want to visit Paris from New York, budget $3000", "history": [], } result = await agent.run(ctx) assert result["updated_trip"]["destination"] == "Paris" assert result["updated_trip"]["budget_total"] == 3000.0 assert "origin" in result["updated_trip"]
@pytest.mark.asyncioasync def test_planner_identifies_missing_fields(): agent = PlannerAgent() ctx = { "trip": {"trip_id": "t1"}, "user_message": "hello", "history": [], } result = await agent.run(ctx) assert result["ready_to_plan"] is False assert len(result["missing_fields"]) > 0
@pytest.mark.asyncioasync def test_planner_ready_when_complete(): agent = PlannerAgent() ctx = { "trip": { "trip_id": "t1", "destination": "Paris", "start_date": "2026-07-01", "end_date": "2026-07-05", "budget_total": 3000, }, "user_message": "looks good", "history": [], } result = await agent.run(ctx) assert result["ready_to_plan"] is True
@pytest.mark.asyncioasync def test_flights_agent_returns_results(): agent = FlightsAgent() ctx = {"trip": {"origin": "New York", "destination": "Paris", "start_date": "2026-07-01", "end_date": "2026-07-05"}} result = await agent.run(ctx) assert len(result["flights"]) >= 1
@pytest.mark.asyncioasync def test_hotels_agent_returns_results(): agent = HotelsAgent() ctx = {"trip": {"destination": "Paris", "start_date": "2026-07-01", "end_date": "2026-07-05"}} result = await agent.run(ctx) assert len(result["hotels"]) >= 0 # depends on Overpass API availability
@pytest.mark.asyncioasync def test_budget_agent_calculates(): agent = BudgetAgent() ctx = { "trip": {"budget_total": 3000, "budget_currency": "USD", "start_date": "2026-07-01", "end_date": "2026-07-05", "travelers": []}, "gathered": { "flights": {"flights": [{"price": 450}]}, "hotels": {"hotels": [{"price_per_night": 100}]}, "activities": {"activities": [{"price": 25}, {"price": 18}]}, "food": {"restaurants": []}, }, } result = await agent.run(ctx) assert "breakdown" in result assert result["breakdown"]["total_estimated"] > 0
@pytest.mark.asyncioasync def test_calendar_builds_itinerary(): agent = CalendarAgent() ctx = { "trip": {"trip_id": "t1", "destination": "Paris", "start_date": "2026-07-01", "end_date": "2026-07-04", "mood": "relaxing", "budget_currency": "USD", "travelers": []}, "gathered": { "flights": {"flights": [{"id": "f1", "airline": "Air", "departure_airport": "JFK", "arrival_airport": "CDG", "price": 400, "departure_time": "2026-07-01T08:00:00", "arrival_time": "2026-07-01T14:00:00"}]}, "hotels": {"hotels": [{"id": "h1", "name": "Hotel Paris", "address": "1 Rue", "price_per_night": 120}]}, "activities": {"activities": [ {"id": "a1", "name": "Louvre", "description": "Museum", "price": 18, "weather_sensitive": False}, {"id": "a2", "name": "Walk", "description": "Walk", "price": 0, "weather_sensitive": True}, ]}, "food": {"restaurants": [ {"id": "r1", "name": "Cafe", "cuisine": "French"}, {"id": "r2", "name": "Bistro", "cuisine": "French"}, ]}, "weather": {"forecasts": [ {"date": "2026-07-01", "high_temp_c": 25, "low_temp_c": 18, "condition": "sunny", "precipitation_pct": 5, "recommendation": "Great day!"}, {"date": "2026-07-02", "high_temp_c": 22, "low_temp_c": 16, "condition": "cloudy", "precipitation_pct": 30, "recommendation": "Pack a layer"}, {"date": "2026-07-03", "high_temp_c": 20, "low_temp_c": 15, "condition": "rainy", "precipitation_pct": 80, "recommendation": "Bring umbrella"}, ]}, }, "budget": {}, "route": {}, } result = await agent.run(ctx) assert "itinerary" in result itin = result["itinerary"] assert len(itin["days"]) == 3 assert itin["total_cost"] > 0 assert len(itin["packing_list"]) > 0
@pytest.mark.asyncioasync def test_full_orchestration_chat(): orch = create_orchestrator() trip = TripRequest(trip_id="test1")
# First message: provide all details reply, updated_trip, steps, _itin, _budget = await orch.handle_chat( trip, "I want to go to Paris from New York, 2026-07-01 to 2026-07-05, budget $3000, relaxing mood", [], ) assert updated_trip.destination == "Paris" assert len(steps) >= 1 assert len(reply) > 012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Tests for API endpoints."""from __future__ import annotations
import pytestfrom fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_health(): r = client.get("/health") assert r.status_code == 200 assert r.json()["status"] == "ok"
def test_chat_creates_trip(): r = client.post("/api/chat", json={"trip_id": "", "message": "I want to visit Paris"}) assert r.status_code == 200 data = r.json() assert data["trip_id"] assert len(data["messages"]) >= 1 assert data["trip_data"]["destination"] == "Paris"
def test_chat_full_flow(): # Step 1: provide all details r = client.post("/api/chat", json={ "trip_id": "", "message": "Trip to Tokyo from London, 2026-08-01 to 2026-08-05, budget $5000", }) assert r.status_code == 200 data = r.json() trip_id = data["trip_id"] assert data["trip_data"]["destination"] == "Tokyo"
# The planner should detect it's ready to plan (all fields present) assert any("plan" in s.get("result_summary", "").lower() or "ready" in s.get("result_summary", "").lower() for s in data.get("reasoning_steps", []))
def test_search_flights(): r = client.get("/api/search/flights?origin=NYC&destination=Paris&departure=2026-07-01") assert r.status_code == 200 assert len(r.json()["flights"]) >= 1
def test_search_hotels(): r = client.get("/api/search/hotels?destination=Paris&check_in=2026-07-01&check_out=2026-07-05") assert r.status_code == 200 assert len(r.json()["hotels"]) >= 0 # depends on Overpass API
def test_search_activities(): r = client.get("/api/search/activities?destination=Paris") assert r.status_code == 200 assert len(r.json()["activities"]) >= 0 # depends on Overpass API
def test_search_weather(): r = client.get("/api/search/weather?destination=Paris&start_date=2026-07-01&end_date=2026-07-05") assert r.status_code == 200 assert len(r.json()["forecasts"]) >= 1
def test_plan_endpoint(): r = client.post("/api/plan", json={ "trip_id": "seed1", "destination": "Paris", "origin": "New York", "start_date": "2026-07-01", "end_date": "2026-07-04", "budget_total": 3000, "budget_currency": "USD", "travelers": [{"name": "Alice", "interests": ["art", "food"]}], "mood": "relaxing", "interests": ["art", "food"], "constraints": [], "notes": "", }) assert r.status_code == 200 data = r.json() assert data["itinerary"] assert data["budget"] assert len(data["itinerary"]["days"]) >= 1
def test_trips_list(): r = client.get("/api/trips") assert r.status_code == 200
def test_alerts_subscribe(): r = client.post("/api/alerts/subscribe?trip_id=t1&email=test@example.com") assert r.status_code == 200 assert r.json()["subscribed"] is True1*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-6{margin-top:1.5rem}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1\.5{height:.375rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-full{height:100%}.h-screen{height:100vh}.w-2{width:.5rem}.w-3{width:.75rem}.w-72{width:18rem}.w-full{width:100%}.min-w-0{min-width:0px}.flex-1{flex:1 1 0%}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-100>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(243 244 246 / var(--tw-divide-opacity, 1))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-primary-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-primary-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-primary-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-primary-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-primary-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-primary-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-primary-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-accent-50{--tw-gradient-to: #f0fdf4 var(--tw-gradient-to-position)}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.text-2xl{font-size:1.5rem;line-height:2rem}.text-5xl{font-size:3rem;line-height:1}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.tracking-wider{letter-spacing:.05em}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-primary-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-primary-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-primary-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.opacity-60{opacity:.6}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}body{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.chat-bubble-user{margin-left:auto;max-width:80%;border-radius:1rem 1rem .125rem;--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1));padding:.5rem 1rem;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.chat-bubble-assistant{max-width:80%;border-radius:1rem 1rem 1rem .125rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1));padding:.5rem 1rem;--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-primary-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/30:hover{background-color:#ffffff4d}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width: 1024px){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:w-\[420px\]{width:420px}}.dockerignoreAdded+14
DockerfileAdded+53
README.md+38-5
backend/.envAdded+3
backend/app/__init__.pyAdded
backend/app/agents/__init__.pyAdded
backend/app/agents/activities.pyAdded+29
backend/app/agents/base.pyAdded+51
backend/app/agents/budget.pyAdded+75
backend/app/agents/calendar.pyAdded+264
backend/app/agents/flights.pyAdded+30
backend/app/agents/food.pyAdded+34
backend/app/agents/hotels.pyAdded+30
backend/app/agents/monitoring.pyAdded+64
backend/app/agents/orchestrator.pyAdded+159
backend/app/agents/planner.pyAdded+114
backend/app/agents/registry.pyAdded+29
backend/app/agents/route.pyAdded+43
backend/app/agents/weather.pyAdded+29
backend/app/api/__init__.pyAdded
backend/app/api/routes.pyAdded+262
backend/app/core/__init__.pyAdded
backend/app/core/config.pyAdded+26
backend/app/core/database.pyAdded+13
backend/app/core/logging.pyAdded+26
backend/app/main.pyAdded+55
backend/app/models/__init__.pyAdded
backend/app/models/orm.pyAdded+57
backend/app/models/schemas.pyAdded+282
backend/app/services/__init__.pyAdded
backend/app/services/activities.pyAdded+132
backend/app/services/flights.pyAdded+245
backend/app/services/food.pyAdded+119
backend/app/services/geocoding.pyAdded+56
backend/app/services/hotels.pyAdded+133
backend/app/services/maps.pyAdded+76
backend/app/services/pdf_export.pyAdded+116
backend/app/services/weather.pyAdded+160
backend/holidaypilot.dbAdded
backend/holidaypilot.egg-info/PKG-INFOAdded+24
backend/holidaypilot.egg-info/SOURCES.txtAdded+42
backend/holidaypilot.egg-info/dependency_links.txtAdded+1
backend/holidaypilot.egg-info/requires.txtAdded+20
backend/holidaypilot.egg-info/top_level.txtAdded+1
backend/pyproject.tomlAdded+37
backend/tests/__init__.pyAdded
backend/tests/test_agents.pyAdded+144
backend/tests/test_api.pyAdded+97
frontend/dist/assets/index-DDHK9Igv.cssAdded+1
frontend/dist/assets/index-DuZYjYO3.jsAdded