How I built a live Flights, Stays & eSIM interactive Travel Card inside ARPA.CHAT using Travelpayouts APIs, FastAPI, and React — including every caveat, rate limit, and fallback I hit along the way.
I've been building ARPA.CHAT solo since last year, out of a tiny office in Thessaloniki, Greece.
Every time I ship a new capability, somebody inevitably pops up and says: "Yeah, cool, but ChatGPT can do that too."
Honestly? That doesn't discourage me for a second, at least not as much at the early days of building, because think about what that sentence actually means: OpenAI, Google, and Anthropic can do it… and so can I. A solo guy from Thessaloniki. Not the biggest Greek tech companies—not Plaisio, not Intrasoft, not even OTE / Deutsche Telekom have their own AI ecosystem. We do.
And if you actually look closely at the timeline, we've been shipping interactive AI features 6 to 12 months before billion-dollar labs get around to them: interactive maps right inside chat, live flights & stays cards, playing full games of chess against your AI companion, zero-prompt customization with tactile faders and dropdowns, private chats, live full-duplex voice, and much more.
Today, I want to pull back the curtain on one of our favorite recent features: giving your AI agents the ability to handle live flights, stays, and eSIMs directly inside chat using an interactive Travel Card powered by Travelpayouts API, at least for the initial rollout.
The idea initially was to add integrations with food delivery apps, AirBnB, Spitogatos, TravelTech agencies, you name it. Yet paradoxically, none of them has consumer APIs, and even their closed APIs are vendor sided, eg. I can't show what food is available in Thessaloniki via Wolt, which would make our interactive chats dope af. So TravelPayouts was an intuitive starting point, just to:
- A. learn how to build and implement such features flawlessly on our Google Cloud ecosystem.
- B. have something tangible that actually works instead of overpromising revolutionizing travel by requiring users to do manual work, search, manage credentials or whatever.
- C. explore alt revenue streams from partner integrations.
If you're considering something similar for your AI app, this isn't a vague high-level fluff piece, but more of a practical, jargon-free, end-to-end guide for any developer or solo builder who wants to give their own AI agent (or local logical system) real travel search, live pricing, hotel suggestions, and monetized booking links—without getting burned by the subtle API quirks I had to learn the hard way.
The Core Idea: Never Let the LLM Hallucinate Prices or Links
Before writing a single line of code, here is the #1 architectural rule that makes this whole thing work:
The AI never fetches prices, never guesses flight numbers, and never invents booking URLs.
If you ask a raw LLM for a flight from Thessaloniki (SKG) to London (LON), it will happily hallucinate a $49 Ryanair flight that doesn't exist and a broken link.
Instead, we split the job cleanly into three layers:
- The AI Agent (Intent Parser + Curator): When the user asks about flights, hotels, or planning a trip, the AI answers naturally in prose AND emits a tiny, structured JSON block (
type: "travel") containing only the intent: origin, destination, dates, guest count, multi-city legs (if any), and 3 curated hotel names for that destination. - Your Backend Proxy (FastAPI / Python): Holds your secret Travelpayouts API token safely on the server, resolves city names/typos to IATA airport codes, queries live flight prices with a multi-stage fallback, and batches affiliate partner links.
- Your Frontend Card (React + TypeScript): Renders an interactive card directly inside the chat stream. Users can switch dates, toggle one-way vs. round-trip, type any city manually, switch between Flights and Stays, and click straight through to book—while caching results locally so switching tabs is instant.
The Stack We Used (and Why)
- Backend: Python + FastAPI +
httpx(async HTTP). Why? Travelpayouts requires a privateX-Access-Tokenheader. You can never expose that token in frontend JavaScript. A thin async FastAPI router proxies every call, handles batching, and caches responses in memory. - Frontend: React + TypeScript + Tailwind CSS. Why? Chat responses in our app are structured JSON content blocks. Adding a new
"travel"block type drops an interactive component straight into the conversation without breaking markdown rendering. - Travel Data & Monetization: Travelpayouts (Aviasales Flight Data API v3 + Places Autocomplete + IP Geo + Partner Links API).
Step 1: Setting Up Travelpayouts (and the Caveats Nobody Tells You)
Sign up at travelpayouts.com, create a Project, and grab three things from your dashboard:
- API Token (
X-Access-Token) — keep this strictly in your backend environment / Secret Manager. - Marker (
marker) — your affiliate ID. - TRS (
trs) — your specific Project ID.
Useful Official Docs & Endpoints
- Travelpayouts API Reference: travelpayouts.github.io/slate
- Flight Prices (Aviasales Data API v3):
https://api.travelpayouts.com/aviasales/v3/prices_for_dates - Airport & City Autocomplete (
places2):https://autocomplete.travelpayouts.com/places2 - User Origin Detection (
whereami):https://www.travelpayouts.com/whereami - Partner Links API (Affiliate Link Converter):
https://api.travelpayouts.com/links/v1/create
Crucial Caveat #1: Project Verification (index.html)
Before Travelpayouts approves your project and tracks clicks properly (especially for Travelpayouts Drive / link monetization), you need to verify your domain by dropping their verification <script> into your frontend index.html <head> (or using meta verification). Don't skip this—if your domain isn't verified and connected to the travel programs you want (Aviasales, Booking/Trip.com/Expedia, Airalo eSIMs, etc.), the Partner Links API will reject or skip your URLs.
Crucial Caveat #2: Only Convert URLs for Programs You Joined
When you call /links/v1/create, Travelpayouts only generates affiliate short-links for brands/programs your account is actually connected to. If you pass a random hotel website or a brand you didn't join, it fails. Always:
- Connect the programs you want inside your Travelpayouts dashboard (e.g., Aviasales, Trip.com, Airalo for eSIMs).
- Keep a small allow-list of your monetized domains on the backend, and gracefully fall back to the direct URL if conversion ever fails so a user never gets a dead button.
Step 2: Teaching Your AI Agent When to Emit a Travel Card
In your system prompt (where you define structured output blocks or tool calls), give the model a strict schema and a clear boundary so it only triggers the card when the user actually wants to search flights, stays, or plan a trip—not every time a city is mentioned in passing.
Here is a generic JSON block schema you can adapt to your own agent:
{ "type": "travel", "origin": "SKG", "destination": "London", "departureDate": "2026-12-10", "returnDate": "2026-12-14", "defaultTab": "flights", "guests": 2, "currency": "EUR", "legs": [ { "origin": "SKG", "destination": "LON", "departureDate": "2026-12-10", "oneWay": true }, { "origin": "LON", "destination": "ZRH", "departureDate": "2026-12-14", "oneWay": true } ], "recommendedStays": [ { "name": "The Hoxton, Shoreditch", "neighborhood": "Shoreditch", "priceTier": "€€", "perks": ["Boutique", "Near Tube", "Free Wi-Fi"] } ] } Notice how lightweight that is. The model outputs ~120 tokens, your streaming UI stays blazing fast, and the card immediately takes over to fetch live prices in the background.
Step 3: Building the Backend Proxy (and Solving the Hard Parts)
Here are the 4 biggest real-world problems we hit in production—and how to solve them cleanly in Python.
Challenge 1: Exact Dates Often Return Zero Cached Flights
Travelpayouts' prices_for_dates endpoint is backed by a massive cached flight-price index (which is why it's free and fast!). The downside? If a user searches an obscure route on an exact Tuesday, prices_for_dates might return [] (empty!).
The Fix: A 3-Stage Fallback Waterfall.
- Stage 1 (Exact): Search exact
departure_at(andreturn_atfor round-trip). - Stage 2 (Flexible Month): If empty, strip the day (
YYYY-MM-DD→YYYY-MM) to return the cheapest flights in that same month, and show a subtle"Flexible dates"badge on the UI. - Stage 3 (Cheapest Upcoming): If still empty, drop the dates completely so the user still sees real upcoming routes and prices instead of an ugly empty screen.
import httpx from typing import Optional, Dict, Any TP_TOKEN = "YOUR_TRAVELPAYOUTS_TOKEN" FLIGHTS_URL = "https://api.travelpayouts.com/aviasales/v3/prices_for_dates" async def fetch_flights_with_fallback( origin: str, destination: str, departure_date: Optional[str] = None, return_date: Optional[str] = None, currency: str = "eur", ) -> Dict[str, Any]: headers = {"X-Access-Token": TP_TOKEN} # Build 3-stage waterfall: exact -> flexible month -> cheapest upcoming attempts = [] if departure_date: exact = {"origin": origin, "destination": destination, "departure_at": departure_date, "currency": currency, "limit": 10} if return_date: exact["return_at"] = return_date attempts.append(("exact", exact)) flex = {"origin": origin, "destination": destination, "departure_at": departure_date[:7], "currency": currency, "limit": 10} if return_date: flex["return_at"] = return_date[:7] attempts.append(("flexible_month", flex)) attempts.append(("cheapest_upcoming", {"origin": origin, "destination": destination, "currency": currency, "limit": 10})) async with httpx.AsyncClient(timeout=8.0) as client: for mode, params in attempts: resp = await client.get(FLIGHTS_URL, params=params, headers=headers) if resp.status_code == 200: items = resp.json().get("data", []) if items: return {"matchType": mode, "flights": items} return {"matchType": "none", "flights": []} Challenge 2: Users Type "ny", "ldn", "mow", or Typos
Travelpayouts' places2 autocomplete API is great for full names ("Istanbul", "London"), but users naturally type shorthand like ny, la, hk, msc, or mow—which sometimes return weird small-town matches or nothing at all.
The Fix: Combine a small shorthand alias dictionary ("ny": "New York", "mow": "Moscow", "ldn": "London", "ist": "Istanbul") with a debounced frontend autocomplete dropdown backed by /places2 (types[]=city&types[]=airport). That way, any city on Earth resolves cleanly to its real IATA code.
Challenge 3: Partner Links API Caps You at 10 Links Per Request
If you try to convert 15 flight/hotel/eSIM links in one call to https://api.travelpayouts.com/links/v1/create, the API rejects the batch. And if you call it one link at a time in a loop, you'll hit rate limits and add seconds of latency.
The Fix: Chunk URLs into batches of <= 10, send them concurrently, and cache each converted URL in memory for 1 hour:
import time import httpx from typing import Dict, List, Tuple LINK_CACHE: Dict[str, Tuple[float, str]] = {} CACHE_TTL = 3600 async def convert_partner_links(urls: List[str], trs: int, marker: int, token: str) -> Dict[str, str]: now = time.time() result: Dict[str, str] = {} to_fetch: List[str] = [] for u in urls: cached = LINK_CACHE.get(u) if cached and (now - cached[0]) < CACHE_TTL: result[u] = cached[1] elif u not in to_fetch: to_fetch.append(u) # Batch in chunks of 10 (Travelpayouts API limit) async with httpx.AsyncClient(timeout=6.0) as client: for i in range(0, len(to_fetch), 10): batch = to_fetch[i : i + 10] payload = {"trs": trs, "marker": marker, "links": [{"url": u} for u in batch]} try: resp = await client.post( "https://api.travelpayouts.com/links/v1/create", json=payload, headers={"X-Access-Token": token, "Content-Type": "application/json"}, ) if resp.status_code == 200: for item in resp.json().get("result", {}).get("links", []): orig = item.get("url") partner = item.get("partner_url") or orig if orig: LINK_CACHE[orig] = (now, partner) result[orig] = partner except Exception: pass # Graceful fallback: never return a broken/empty link for u in urls: result.setdefault(u, u) return result Challenge 4: Stays (Hotels) When the User Manually Switches Cities
When the AI first renders the card, it includes 3 curated hotels for the destination. But what happens when the user manually types a brand-new city into the card's search box (say, switching from Istanbul to Moscow)? There are no AI-curated hotels for Moscow in that old JSON block!
The Fix:
- Build a
/travel/staysendpoint that generates pre-filled hotel search links (with check-in, check-out, and guest count) + category fallback cards ("Top Central Boutique Stays in Moscow", "Best Value Hotels in Moscow", "5-Star Luxury Stays in Moscow") whenever the user switches to a city not in the initial AI payload. - Hydrate real hotel/city photos with a multi-candidate retry fallback so cards always look sharp, never broken grey boxes.
Step 4: Making the Frontend Card Feel Native (Not Like a Clunky Widget)
A few small frontend details make a massive difference in how premium a Travel Card feels inside a chat app:
- In-Memory +
sessionStorageCaching: Switching between theFlightstab,Staystab, and multi-cityLegsshould be instantaneous. Cache API responses by(origin, destination, departureDate, returnDate, currency)with a short TTL insessionStorageso even refreshing the page doesn't cause jarring reloads or flickering photos—while keeping a manual Refresh button that bypasses cache when the user wants fresh live prices. - Independent Calendars for Flights vs. Stays: Don't couple flight dates and hotel check-in/out dates too tightly. Users often fly overnight or stay in two cities on one trip—give Stays its own clean check-in/out selector.
- Airline Logos with Monospace Fallback: Aviasales serves clean airline logos at
https://pics.avs.io/64/64/{AIRLINE_IATA}.png. Always add anonErrorfallback badge showing the 2-letter airline code (e.g.A3,LH,TK) so a missing logo never shows a broken image icon. - Auto-Collapse Older Cards: If a user plans 3 different trips in one long conversation, keep only the latest Travel Card expanded by default and collapse older ones into a sleek 1-line summary bar they can re-expand anytime.
- Contextual Follow-Up Pills: At the bottom of the card, drop 2–3 minimal pill buttons like "Best neighborhood to stay?", "3-day itinerary", or "Airport transfer tips" that feed right back into your AI companion.
Here is a simplified React + sessionStorage cache helper you can drop straight into your own frontend:
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes const memoryCache = new Map<string, { ts: number; data: any }>(); export function getCachedTravel<T>(key: string): T | null { const now = Date.now(); const mem = memoryCache.get(key); if (mem && now - mem.ts < CACHE_TTL_MS) return mem.data as T; try { const raw = sessionStorage.getItem(`travel_cache:${key}`); if (!raw) return null; const parsed = JSON.parse(raw); if (parsed && now - parsed.ts < CACHE_TTL_MS) { memoryCache.set(key, parsed); return parsed.data as T; } } catch { // Ignore private-mode storage errors } return null; } export function setCachedTravel(key: string, data: any): void { const entry = { ts: Date.now(), data }; memoryCache.set(key, entry); try { sessionStorage.setItem(`travel_cache:${key}`, JSON.stringify(entry)); } catch { // Ignore quota errors } } Bonus: The eSIM Strip
Since Travelpayouts also supports Airalo, we added a slim, non-intrusive eSIM strip at the bottom of the card ("Landing in Tokyo? Grab a local eSIM") using a pre-converted partner link. It's genuinely useful for travelers and takes 10 lines of UI code.
Putting It All Together
The beauty of this pattern is that it doesn't just apply to travel. Once your AI agent outputs clean, structured intent blocks and your backend acts as the deterministic execution layer (live APIs, caching, fallbacks, link monetization), your chat interface stops being a wall of text and turns into a real operating system.
You don't need a 50-person engineering team or a \$50M seed round to build this. You need clean boundaries between what the LLM is good at (understanding intent & curating) and what traditional code is good at (fetching live data, handling edge cases, and rendering fast UI).
If you want to try the Travel Card live, jump into arpa.chat and ask your companion to plan a weekend trip or find flights anywhere in the world.
Got questions about Travelpayouts quirks, FastAPI proxying, or structuring LLM UI cards? Drop them in the comments—happy to help fellow solo builders ship faster.



