<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tamal on Medium]]></title>
        <description><![CDATA[Stories by Tamal on Medium]]></description>
        <link>https://medium.com/@tmlahmed?source=rss-fffe80c198ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sva_EouWXwIOUCXPAr9KLg.png</url>
            <title>Stories by Tamal on Medium</title>
            <link>https://medium.com/@tmlahmed?source=rss-fffe80c198ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:42:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tmlahmed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Drop the Dropdowns! Let’s Talk to Our Flight Search Like a Human (with OpenAI & Amadeus)]]></title>
            <link>https://medium.com/@tmlahmed/drop-the-dropdowns-lets-talk-to-our-flight-search-like-a-human-with-openai-amadeus-20af47d743cb?source=rss-fffe80c198ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/20af47d743cb</guid>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[amadeus]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[flight]]></category>
            <dc:creator><![CDATA[Tamal]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 11:14:41 GMT</pubDate>
            <atom:updated>2025-05-01T16:55:54.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hv78C29_ZxJn25YqG36hdQ.png" /></figure><p>Seriously, who actually <em>enjoys</em> searching for flights? Clicking dates, scrolling endless airport lists… it feels like filling out tax forms sometimes. I always find myself thinking, “Why can’t I just <em>tell</em> it what I want?”</p><p>Like, wouldn’t it be awesome to just type:</p><p><em>“Yo, find me the cheapest way to get from Singapore to Bangkok sometime in July for like 10 days. Non-stop preferred!”</em></p><p>Or maybe:</p><p><em>“Need flights from Dhaka to London, leaving August 5th, coming back August 12th. For 2 people.”</em></p><p>Well, guess what? We can actually build that! It takes a bit of wrangling, some clever AI prompting, and plugging into a travel data powerhouse, but it’s totally doable. In this post, I’ll walk you through a project that does exactly this, using Python, Flask, the brains of OpenAI, and the flight data muscle of Amadeus.</p><p>If you’re a data science enthusiast, a budding developer, or just tired of clunky flight search forms, you’ll dig this. We’re turning human chatter into API calls and getting real flight info back.</p><h3>The Dream: Chat Our Way to Our Next Journey</h3><p>The goal is simple: bridge the gap between how we <em>think</em> about travel plans and how computers <em>need</em> information. We want to replace rigid forms with a fluid, conversational experience.</p><p>Here’s the game plan:</p><ol><li><strong>User Chats:</strong> We type our request naturally into a web page.</li><li><strong>AI Deciphers:</strong> An OpenAI model (like GPT) reads our request and figures out the important bits: where we’re going, coming from, dates (even vague ones!), number of people, etc.</li><li><strong>API Grunt Work:</strong> Armed with structured info from the AI, our app talks to the Amadeus API — a massive system used by travel agencies — to find actual flights or the cheapest dates.</li><li><strong>Results Served:</strong> The findings are neatly packaged and shown back to us.</li></ol><p>Sounds cool, right? Let’s pop the hood and see the code that makes it happen.</p><h3>The Tech Stack: Our Building Blocks</h3><p>We’re keeping it relatively simple but powerful:</p><ul><li><strong>Python:</strong> The backbone of our project.</li><li><strong>Flask:</strong> A lightweight Python web framework to handle requests and serve the UI.</li><li><strong>OpenAI API:</strong> To understand the user’s natural language query.</li><li><strong>Amadeus Self-Service API:</strong> To get real-time flight availability and pricing data.</li><li><strong>HTML/CSS/JavaScript:</strong> For the simple frontend interface.</li></ul><h3>Getting Set Up: Config and Dependencies</h3><p>Every good project needs some configuration. We need a place to securely store our API keys and maybe set some defaults. That’s what config.py does, using python-dotenv to load secrets from a .env file.</p><p><em>config.py</em></p><pre># config.py<br>import os<br>from dotenv import load_dotenv<br><br># Load environment variables from .env file<br>dotenv_path = os.path.join(os.path.dirname(__file__), &#39;.env&#39;)<br>if os.path.exists(dotenv_path):<br>    load_dotenv(dotenv_path)<br>else:<br>    print(&quot;Warning: .env file not found.&quot;)<br><br>class Config:<br>    &quot;&quot;&quot;Application configuration class.&quot;&quot;&quot;<br>    # OpenAI Configuration<br>    OPENAI_API_KEY = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>    if not OPENAI_API_KEY:<br>        raise ValueError(&quot;Missing required environment variable: OPENAI_API_KEY&quot;)<br><br>    # Amadeus Configuration<br>    AMADEUS_CLIENT_ID = os.getenv(&#39;AMADEUS_CLIENT_ID&#39;)<br>    AMADEUS_CLIENT_SECRET = os.getenv(&#39;AMADEUS_CLIENT_SECRET&#39;)<br>    if not AMADEUS_CLIENT_ID or not AMADEUS_CLIENT_SECRET:<br>        raise ValueError(&quot;Missing required environment variables: AMADEUS_CLIENT_ID or AMADEUS_CLIENT_SECRET&quot;)<br><br>    # Flask Configuration (optional, defaults can be used)<br>    PORT = int(os.getenv(&#39;PORT&#39;, 5000))<br>    DEBUG = os.getenv(&#39;FLASK_DEBUG&#39;, &#39;0&#39;) == &#39;1&#39;<br>    ENV = os.getenv(&#39;FLASK_ENV&#39;, &#39;production&#39;)<br><br>    # Application specific settings<br>    DEFAULT_ORIGIN_CITY = &quot;Dhaka&quot; # Default if user doesn&#39;t specify<br>    REFERENCE_DATE_FOR_NLP = &quot;2025-04-20&quot; # Used by OpenAI to understand relative dates like &quot;next month&quot;<br><br># Instantiate the config<br>config = Config()</pre><p>And requirements.txt lists all the Python packages we need to install.</p><pre># requirements.txt<br>Flask[async]&gt;=2.3,&lt;3.0<br>python-dotenv&gt;=1.0.0<br>openai&gt;=1.10.0,&lt;2.0.0<br>amadeus<br>Flask-Cors&gt;=4.0.0,&lt;5.0.0</pre><h3>The Backend Heartbeat</h3><p>The app.py file sets up our Flask web server. It initializes the app, loads the config, enables Cross-Origin Resource Sharing, registers our API routes (like the chat endpoint), and defines basic routes for serving the main HTML page and handling errors. It’s the central hub connecting incoming web requests to our backend logic.</p><p><em>app.py</em></p><pre># app.py<br>import logging<br>from flask import Flask, jsonify, render_template, send_from_directory, request # Added request import<br>from flask_cors import CORS<br>from datetime import datetime<br><br>from config import config<br>from controllers.chat_controller import chat_api<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#39;)<br>logger = logging.getLogger(__name__)<br><br># Initialize Flask App<br>app = Flask(__name__,<br>            template_folder=&#39;templates&#39;,<br>            static_folder=&#39;static&#39;)<br><br># Load configuration from config object<br>app.config.from_object(config)<br>app.config[&#39;DEBUG&#39;] = config.DEBUG<br>app.config[&#39;ENV&#39;] = config.ENV<br><br># Enable CORS<br>CORS(app, resources={r&quot;/api/*&quot;: {&quot;origins&quot;: &quot;*&quot;}})<br><br># Register Blueprints (Controllers)<br>app.register_blueprint(chat_api, url_prefix=&#39;/api/chat&#39;) # Our main API logic<br><br># --- Static File and Template Routes ---<br><br>@app.route(&#39;/&#39;)<br>def index():<br>    &quot;&quot;&quot;Serves the main HTML page.&quot;&quot;&quot;<br>    try:<br>        return render_template(&#39;index.html&#39;)<br>    except Exception as e:<br>        logger.error(f&quot;Error rendering index.html: {e}&quot;, exc_info=True)<br>        return &quot;Error loading page.&quot;, 500<br><br><br># --- API Health Check ---<br><br>@app.route(&#39;/health&#39;)<br>def health_check():<br>    &quot;&quot;&quot;Provides a simple health check endpoint.&quot;&quot;&quot;<br>    return jsonify({&quot;status&quot;: &quot;ok&quot;, &quot;timestamp&quot;: datetime.utcnow().isoformat()}), 200<br><br># --- Error Handlers ---<br><br>@app.errorhandler(404)<br>def not_found_error(error):<br>    logger.warning(f&quot;404 Not Found: {request.path}&quot;)<br>    if request.path.startswith(&#39;/api/&#39;):<br>        return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;API endpoint not found&quot;}), 404<br>    return &quot;Oops! Page not found.&quot;, 404<br><br>@app.errorhandler(500)<br>def internal_error(error):<br>    logger.error(f&quot;500 Internal Server Error: {error}&quot;, exc_info=True)<br>    return jsonify({<br>        &quot;success&quot;: False,<br>        &quot;error&quot;: &quot;An internal server error occurred&quot;,<br>        &quot;details&quot;: str(error) if config.DEBUG else None<br>        }), 500<br><br>@app.errorhandler(Exception)<br>def unhandled_exception(error):<br>    logger.error(f&quot;Unhandled Exception: {error}&quot;, exc_info=True)<br>    error_message = &quot;An unexpected error occurred.&quot;<br>    if config.DEBUG:<br>        error_message = f&quot;{error_message} Details: {str(error)}&quot;<br>    return jsonify({&quot;success&quot;: False, &quot;error&quot;: error_message}), 500<br><br># --- Main Execution ---<br><br>if __name__ == &#39;__main__&#39;:<br>    logger.info(f&quot;Starting Flask server on port {config.PORT} in {config.ENV} mode (Debug: {config.DEBUG})&quot;)<br>    app.run(host=&#39;0.0.0.0&#39;, port=config.PORT, debug=config.DEBUG)</pre><h3>The AI Brain</h3><p>Okay, this is where the real NLP magic happens! This openai_provider.py module is responsible for talking to OpenAI. Its main job (parse_flight_query) is to take the user&#39;s raw text query and transform it into a structured JSON object that the rest of our application can understand.</p><p>The secret sauce here is the <strong>system prompt</strong>. It’s like giving instructions to the AI. We tell it its role, what specific pieces of information to look for (origin, destination, dates, etc.), and <em>how</em> to format the output (strictly JSON!). We even tell it how to handle tricky things like:</p><ul><li><strong>Relative Dates:</strong> Understanding “next month” or “August 15th” requires context. We provide a REFERENCE_DATE_FOR_NLP in our config and instruct the AI to calculate absolute dates based on that.</li><li><strong>Query Types:</strong> Is the user asking for flights on <em>specific dates</em> or looking for the <em>cheapest dates</em> in a window? The prompt asks the AI to figure this out and set a queryType flag. This is crucial because it determines which Amadeus API we&#39;ll call later.</li><li><strong>Default Origin:</strong> If the user doesn’t mention where they’re flying <em>from</em>, we tell the AI to use a default location specified in our config.</li><li><strong>Specific Formats:</strong> We demand specific formats for dates (YYYY-MM-DD), date ranges (YYYY-MM-DD/YYYY-MM-DD), and trip durations (P[n]D like &quot;P7D&quot; for 7 days). This consistency makes life <em>much</em> easier downstream.</li></ul><p>We also use OpenAI’s ability to return JSON directly (response_format={&quot;type&quot;: &quot;json_object&quot;}) which saves us parsing headaches. There&#39;s also some basic validation <em>after</em> getting the AI response, just in case it hallucinates or misses something.</p><p><em>openai_provider.py</em></p><pre># providers/openai_provider.py<br>import os<br>import json<br>import logging<br>from datetime import datetime, timedelta<br>from openai import AsyncOpenAI, OpenAIError<br>import re<br>import calendar<br><br>from config import config<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>class OpenAIProvider:<br>    &quot;&quot;&quot;<br>    Provides methods to interact with the OpenAI API for parsing<br>    flight queries and generating recommendations.<br>    &quot;&quot;&quot;<br>    def __init__(self):<br>        try:<br>            # Ensure you have OPENAI_API_KEY set in your environment/.env file<br>            self.client = AsyncOpenAI(api_key=config.OPENAI_API_KEY)<br>            logger.info(&quot;OpenAI client initialized successfully.&quot;)<br>        except Exception as e:<br>            logger.error(f&quot;Failed to initialize OpenAI client: {e}&quot;, exc_info=True)<br>            raise ConnectionError(&quot;Could not initialize OpenAI client. Check API key.&quot;) from e<br><br><br>    async def parse_flight_query(self, user_query: str) -&gt; dict | None:<br>        &quot;&quot;&quot;<br>        Uses OpenAI to parse a natural language query into structured flight parameters,<br>        differentiating between specific date searches and cheapest date searches.<br>        &quot;&quot;&quot;<br>        logger.info(f&quot;Parsing flight query: &#39;{user_query}&#39;&quot;)<br>        reference_date_str = config.REFERENCE_DATE_FOR_NLP<br>        default_origin = config.DEFAULT_ORIGIN_CITY<br><br>        # --- System Prompt ---<br>        # This is the core instruction set for the AI<br>        system_prompt = f&quot;&quot;&quot;<br>            You are a flight search assistant. Analyze the user query to determine if they want flights on specific dates OR if they are looking for the cheapest dates within a given timeframe (like &#39;next month&#39;, &#39;June&#39;, &#39;August 2025&#39;) or for a specific trip duration.<br><br>            **Extract the following information:**<br>            - **Origin**: Identify the origin city or airport **explicitly mentioned by the user**.<br>            - **Destination**: Identify the destination city or airport mentioned by the user.<br>            - **Number of adults**: Default to 1 if not specified.<br>            - **queryType**: Determine if it&#39;s &quot;specificDate&quot; or &quot;cheapestDate&quot;.<br>            - **Specific Date Fields (if queryType=&quot;specificDate&quot;):**<br>                - `departureDate`: The exact departure date (YYYY-MM-DD). Interpret relative dates (e.g., &quot;May 15th&quot;, &quot;next Tuesday&quot;) based on the reference date {reference_date_str}.<br>                - `returnDate`: The exact return date (YYYY-MM-DD) or null if one-way. Interpret relative dates based on the reference date {reference_date_str}.<br>            - **Cheapest Date Fields (if queryType=&quot;cheapestDate&quot;):**<br>                - `departureWindow`: Calculate the specific date range (start and end dates) based on the user&#39;s request (e.g., &#39;next month&#39;, &#39;June&#39;, &#39;Aug 2025&#39;) relative to the reference date {reference_date_str}. **Always format this as &quot;YYYY-MM-DD/YYYY-MM-DD&quot;**. For example, if the reference date is {reference_date_str} and the user asks for &#39;next month&#39;, calculate the first and last day of the next month and return the range like &quot;2025-05-01/2025-05-31&quot;. If they ask for &#39;June&#39;, calculate the range for the upcoming June, e.g., &quot;2025-06-01/2025-06-30&quot;. Handle year context correctly (e.g., &quot;December&quot; likely means the upcoming December).<br>                - `duration`: If the user specifies a trip duration (e.g., &quot;for 7 days&quot;, &quot;a week&quot;), format as ISO 8601 duration string &quot;P[n]D&quot;. Set to null if not specified or if one-way.<br>                - `oneWay`: boolean (true if the query implies one-way, false otherwise - default to false).<br>                - `nonStop`: boolean (true if the query explicitly asks for non-stop flights, false otherwise - default to false).<br><br>            **IMPORTANT RULES:**<br>            - **Origin Handling:** Extract the origin **directly mentioned** in the user query. **If and ONLY IF** the user query **does not explicitly mention any origin location**, then set the origin field in the JSON to &quot;{default_origin}&quot;. Do NOT default if an origin is mentioned by the user.<br>            - **Date Calculation:** Perform date calculations relative to {reference_date_str} when needed for specific dates or departure windows. Ensure dates are logical (e.g., return date is after departure date).<br>            - **Duration Format:** Always use &quot;P[n]D&quot; for duration (e.g., &quot;P7D&quot; for 7 days).<br>            - **Mandatory Fields:** Origin and Destination are mandatory. If you cannot determine them, indicate an error (though the JSON format should still be returned if possible, maybe with nulls or specific error flags if you were allowed to modify the schema).<br><br>            **RESPONSE FORMAT:** Respond **ONLY** with valid JSON matching ONE of these schemas based on queryType:<br><br>            Schema for **queryType=&quot;specificDate&quot;**:<br>            {{<br>                &quot;queryType&quot;: &quot;specificDate&quot;,<br>                &quot;origin&quot;: &quot;city name or airport code&quot;,<br>                &quot;destination&quot;: &quot;city name or airport code&quot;,<br>                &quot;departureDate&quot;: &quot;YYYY-MM-DD&quot;,<br>                &quot;returnDate&quot;: &quot;YYYY-MM-DD&quot; or null,<br>                &quot;adults&quot;: number<br>            }}<br><br>            Schema for **queryType=&quot;cheapestDate&quot;**:<br>            {{<br>                &quot;queryType&quot;: &quot;cheapestDate&quot;,<br>                &quot;origin&quot;: &quot;city name or airport code&quot;,<br>                &quot;destination&quot;: &quot;city name or airport code&quot;,<br>                &quot;departureWindow&quot;: &quot;YYYY-MM-DD/YYYY-MM-DD&quot;,<br>                &quot;duration&quot;: &quot;P[n]D&quot; or null,<br>                &quot;oneWay&quot;: boolean,<br>                &quot;nonStop&quot;: boolean,<br>                &quot;adults&quot;: number<br>            }}<br>            &quot;&quot;&quot;<br><br>        try:<br>            completion = await self.client.chat.completions.create(<br>                model=&quot;gpt-4o-mini&quot;, # Using a capable but potentially cheaper model<br>                messages=[<br>                    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query}<br>                ],<br>                temperature=0.1, # Low temperature for more deterministic, structured output<br>                max_tokens=350, # Enough for the JSON structures<br>                response_format={&quot;type&quot;: &quot;json_object&quot;} # Request JSON output directly<br>            )<br><br>            raw_response = completion.choices[0].message.content.strip()<br>            logger.debug(f&quot;LLM raw output: {raw_response}&quot;)<br><br>            parsed_data = json.loads(raw_response)<br><br>            # --- Post-processing &amp; Validation ---<br>            # Basic checks to ensure the AI didn&#39;t go completely off the rails<br>            if not parsed_data.get(&#39;queryType&#39;) or parsed_data[&#39;queryType&#39;] not in [&#39;specificDate&#39;, &#39;cheapestDate&#39;]:<br>                 logger.error(f&quot;LLM failed to determine a valid queryType. Response: {parsed_data}&quot;)<br>                 raise ValueError(&quot;AI failed to determine the type of search required.&quot;)<br><br>            if not parsed_data.get(&#39;origin&#39;) or not parsed_data.get(&#39;destination&#39;):<br>                 logger.error(f&quot;LLM failed to extract origin or destination. Response: {parsed_data}&quot;)<br>                 raise ValueError(&quot;AI response missing origin or destination.&quot;)<br><br>            # Ensure adults is a positive integer, default to 1 if missing/invalid<br>            adults = parsed_data.get(&#39;adults&#39;)<br>            if not isinstance(adults, int) or adults &lt; 1:<br>                 parsed_data[&#39;adults&#39;] = 1<br>                 logger.info(&quot;Adult count invalid or missing, defaulting to 1.&quot;)<br><br>            # Validate formats for the &#39;cheapestDate&#39; type<br>            if parsed_data.get(&#39;queryType&#39;) == &#39;cheapestDate&#39;:<br>                duration_str = parsed_data.get(&#39;duration&#39;)<br>                if duration_str and not re.match(r&#39;^P\d+D$&#39;, duration_str):<br>                    logger.warning(f&quot;LLM provided invalid duration format &#39;{duration_str}&#39;. Setting to null.&quot;)<br>                    parsed_data[&#39;duration&#39;] = None # Nullify invalid format<br><br>                window_str = parsed_data.get(&#39;departureWindow&#39;)<br>                if not window_str or not re.match(r&#39;^\d{4}-\d{2}-\d{2}/\d{4}-\d{2}-\d{2}$&#39;, window_str):<br>                     logger.error(f&quot;LLM provided invalid departureWindow format: &#39;{window_str}&#39;. Expected YYYY-MM-DD/YYYY-MM-DD.&quot;)<br>                     raise ValueError(&quot;Received invalid date window format from AI.&quot;)<br><br>            # Validate formats for the &#39;specificDate&#39; type<br>            if parsed_data.get(&#39;queryType&#39;) == &#39;specificDate&#39;:<br>                 dep_date_str = parsed_data.get(&#39;departureDate&#39;)<br>                 ret_date_str = parsed_data.get(&#39;returnDate&#39;)<br>                 if not dep_date_str or not re.match(r&#39;^\d{4}-\d{2}-\d{2}$&#39;, dep_date_str):<br>                      logger.error(f&quot;LLM provided invalid departureDate format: &#39;{dep_date_str}&#39;.&quot;)<br>                      raise ValueError(&quot;Received invalid departure date format from AI.&quot;)<br>                 if ret_date_str and not re.match(r&#39;^\d{4}-\d{2}-\d{2}$&#39;, ret_date_str):<br>                      logger.warning(f&quot;LLM provided invalid returnDate format &#39;{ret_date_str}&#39;. Setting to null.&quot;)<br>                      parsed_data[&#39;returnDate&#39;] = None # Nullify invalid format<br><br>            logger.info(f&quot;Successfully parsed flight query: {parsed_data}&quot;)<br>            return parsed_data<br><br>        except json.JSONDecodeError as json_err:<br>            # Handle cases where the LLM output isn&#39;t valid JSON<br>            logger.error(f&quot;Failed to parse JSON response from OpenAI: {json_err}&quot;, exc_info=True)<br>            logger.error(f&quot;Raw response causing error: {raw_response}&quot;)<br>            raise ValueError(&quot;Received invalid response structure from AI.&quot;) from json_err<br>        except OpenAIError as openai_err:<br>            # Handle errors from the OpenAI API itself (network issues, auth errors, etc.)<br>            logger.error(f&quot;OpenAI API error during query parsing: {openai_err}&quot;, exc_info=True)<br>            raise ConnectionError(f&quot;AI service request failed: {openai_err}&quot;) from openai_err<br>        except ValueError as val_err:<br>             # Catch our specific validation errors raised above<br>             logger.error(f&quot;Validation error after parsing: {val_err}&quot;)<br>             raise val_err # Re-raise to be caught by the controller<br>        except Exception as e:<br>            # Catch-all for unexpected errors<br>            logger.error(f&quot;An unexpected error occurred during query parsing: {e}&quot;, exc_info=True)<br>            raise RuntimeError(&quot;An unexpected error occurred while processing the query with AI.&quot;) from e<br><br><br># Instantiate the provider so it can be imported and used elsewhere<br>openai_provider = OpenAIProvider()</pre><h3>The Travel Agent</h3><p>With our structured query from OpenAI, we now need to get actual flight data. That’s the job of the AmadeusProvider. It wraps the official amadeus-python library to make interacting with the Amadeus APIs a bit cleaner for our specific needs.</p><p>Key Tasks:</p><ol><li><strong>Initialization:</strong> Connects to the Amadeus API using Client ID and Secret from our config. Note that we’re using the ‘test’ environment here, which provides realistic but not bookable data — perfect for development!.</li><li><strong>Get Airport Code:</strong> Takes a city name (like “Dhaka”) and uses the Amadeus Locations API to find the corresponding IATA code (like “DAC”). This is crucial because most flight search APIs require these codes. It has some logic to handle cases where a city might have multiple airports.</li><li><strong>Search Specific Flights:</strong> If OpenAI determined queryType=&quot;specificDate&quot;, this function calls the Amadeus Flight Offers Search API with the exact parameters (origin/destination IATA codes, dates, adults). It returns a list of flight offers. It also sorts the results by the number of stops, figuring fewer stops is generally better.</li><li><strong>Search Cheapest Dates:</strong> If OpenAI determined queryType=&quot;cheapestDate&quot;, this function calls the Amadeus Flight Dates API. This is neat because you give it a <em>range</em> of dates (like &quot;2025-07-01/2025-07-31&quot;) and it tells you the cheapest days to fly within that window for your route. It handles converting the date window format from OpenAI and also deals with trip duration and non-stop preferences.</li><li><strong>Error Handling:</strong> Amadeus API calls can fail (rate limits, invalid parameters, server issues). The provider includes try...except blocks to catch ResponseError from the Amadeus library and log useful information without crashing the whole app.</li></ol><p><em>amadeus_provider.py</em></p><pre># providers/amadeus_provider.py<br>import logging<br>from datetime import datetime<br>import re<br>import calendar<br>from amadeus import Client, ResponseError, Location<br><br>from config import config<br><br># Basic logging setup<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>class AmadeusProvider:<br>    &quot;&quot;&quot;<br>    Provides methods to interact with the Amadeus Self-Service APIs.<br>    Handles initialization, API calls, and basic error handling.<br>    &quot;&quot;&quot;<br>    def __init__(self):<br>        &quot;&quot;&quot;Initializes the Amadeus client using credentials from config.&quot;&quot;&quot;<br>        try:<br>            # Make sure hostname matches your credentials (test or production)<br>            self.amadeus = Client(<br>                client_id=config.AMADEUS_CLIENT_ID,<br>                client_secret=config.AMADEUS_CLIENT_SECRET,<br>                hostname=&#39;test&#39;, # Use &#39;test&#39; for development, &#39;production&#39; for live<br>            )<br>            logger.info(&quot;Amadeus client initialized successfully (Test Environment).&quot;)<br>        except Exception as e:<br>            logger.error(f&quot;Failed to initialize Amadeus client: {e}&quot;, exc_info=True)<br>            # This is a critical failure, so raise an error<br>            raise ConnectionError(&quot;Could not initialize Amadeus client. Check API credentials and hostname.&quot;) from e<br><br>    # --- Flight Search for Specific Dates ---<br>    def search_flights(self, origin: str, destination: str, departure_date: str,<br>                             return_date: str | None = None, adults: int = 1, max_results: int = 10) -&gt; list | None:<br>        &quot;&quot;&quot;<br>        Searches for flight offers for specific dates using the Amadeus API.<br>        Returns a list of flight offers or None if an error occurs.<br>        Sorts results by number of stops (ascending).<br>        &quot;&quot;&quot;<br>        logger.info(f&quot;Searching flights: {origin} -&gt; {destination}, Dep: {departure_date}, Ret: {return_date}, Adults: {adults}&quot;)<br>        params = {<br>            &#39;originLocationCode&#39;: origin,<br>            &#39;destinationLocationCode&#39;: destination,<br>            &#39;departureDate&#39;: departure_date,<br>            &#39;adults&#39;: adults,<br>            &#39;currencyCode&#39;: &#39;USD&#39;,<br>        }<br>        # Add returnDate only if it&#39;s a round trip<br>        if return_date:<br>            params[&#39;returnDate&#39;] = return_date<br><br>        try:<br>            # Make the API call<br>            response = self.amadeus.shopping.flight_offers_search.get(**params)<br>            flight_offers = response.data<br><br>            # Sort results: Fewer stops are generally preferred<br>            # This lambda function calculates total stops across all legs of a journey<br>            sorted_offers = sorted(<br>                flight_offers,<br>                key=lambda offer: sum(<br>                    max(0, len(itinerary.get(&#39;segments&#39;, [])) - 1) # Stops = segments - 1 per leg<br>                    for itinerary in offer.get(&#39;itineraries&#39;, [])<br>                )<br>            )<br><br>            logger.info(f&quot;Found and sorted {len(sorted_offers)} flight offers for specific dates.&quot;)<br>            return sorted_offers<br>        except ResponseError as error:<br>             # Handle specific Amadeus API errors (like bad request, auth error, not found)<br>             logger.error(f&quot;Amadeus API error during flight search: {error.code} - {error.description}&quot;, exc_info=True)<br>             # Log the request params that caused the error for debugging<br>             logger.debug(f&quot;Request params causing error: {params}&quot;)<br>             return None # Indicate failure<br>        except Exception as e:<br>            # Catch any other unexpected errors during the API call or sorting<br>            logger.error(f&quot;An unexpected error occurred during flight search: {e}&quot;, exc_info=True)<br>            return None<br><br>    # --- Airport Code Lookup ---<br>    def get_airport_code(self, city_name: str) -&gt; str | None:<br>        &quot;&quot;&quot;<br>        Gets the IATA code for the primary airport associated with a city name using Amadeus Locations API.<br>        Returns the IATA code (string) or None if not found or error.<br>        &quot;&quot;&quot;<br>        logger.info(f&quot;Fetching airport code for city: &#39;{city_name}&#39;&quot;)<br>        # Basic validation<br>        if not city_name or len(city_name) &lt; 3:<br>             logger.warning(&quot;Invalid city name provided for airport code lookup.&quot;)<br>             return None<br><br>        # Optimization: If input looks like an IATA code already, return it directly<br>        if len(city_name) == 3 and city_name.isalpha() and city_name.isupper():<br>             logger.info(f&quot;Input &#39;{city_name}&#39; looks like an IATA code, returning directly.&quot;)<br>             return city_name<br><br>        try:<br>            # Use the Locations API, specifically searching by city keyword<br>            response = self.amadeus.reference_data.locations.get(<br>                keyword=city_name,<br>                subType=Location.ANY # Search cities and airports<br>            )<br><br>            # We prioritize airport codes directly associated with the best matching city.<br>            if response.data:<br>                # Amadeus often returns multiple results, best match is usually first<br>                best_match = response.data[0]<br>                # Check if the best match is an Airport or City<br>                if best_match.get(&#39;subType&#39;) == &#39;AIRPORT&#39; and best_match.get(&#39;iataCode&#39;):<br>                     iata_code = best_match[&#39;iataCode&#39;]<br>                     logger.info(f&quot;Found direct airport match for &#39;{city_name}&#39;: {iata_code}&quot;)<br>                     return iata_code<br>                elif best_match.get(&#39;subType&#39;) == &#39;CITY&#39; and best_match.get(&#39;iataCode&#39;):<br>                     city_iata_code = best_match[&#39;iataCode&#39;]<br>                     # Add logic here if needed to find associated airports from relationships if present<br>                     logger.info(f&quot;Found city match for &#39;{city_name}&#39;: {city_iata_code}. Using this code.&quot;)<br>                     return city_iata_code<br>                else:<br>                     # Maybe we found something but it wasn&#39;t a city/airport with a code<br>                     logger.warning(f&quot;Found location for &#39;{city_name}&#39; but couldn&#39;t extract a usable IATA code from best match: {best_match}&quot;)<br>                     return None<br><br>            else:<br>                logger.warning(f&quot;No location found for city name: &#39;{city_name}&#39; via Amadeus API.&quot;)<br>                return None<br>        except ResponseError as error:<br>            logger.error(f&quot;Amadeus API error getting airport code for &#39;{city_name}&#39;: {error.code} - {error.description}&quot;, exc_info=True)<br>            return None<br>        except Exception as e:<br>            logger.error(f&quot;An unexpected error occurred getting airport code for &#39;{city_name}&#39;: {e}&quot;, exc_info=True)<br>            return None<br><br>    # --- Cheapest Date Search ---<br>    def search_cheapest_dates(self, origin: str, destination: str,<br>                                    departure_window: str, duration: str | None = None,<br>                                    one_way: bool = False, non_stop: bool = False) -&gt; list | None:<br>        &quot;&quot;&quot;<br>        Searches for the cheapest flight dates within a given window (YYYY-MM-DD/YYYY-MM-DD)<br>        using the Amadeus Flight Dates API.<br>        &quot;&quot;&quot;<br>        logger.info(f&quot;Searching cheapest dates: {origin} -&gt; {destination}, Window: {departure_window}, Duration: {duration}, OneWay: {one_way}, NonStop: {non_stop}&quot;)<br><br>        params = {<br>            &#39;origin&#39;: origin,<br>            &#39;destination&#39;: destination,<br>            &#39;departureDate&#39;: departure_window.replace(&#39;/&#39;, &#39;,&#39;) # API expects comma-separated range YYYY-MM-DD,YYYY-MM-DD<br>        }<br><br>        # --- Handle optional parameters ---<br>        # Duration (for round trips) - needs to be number of days as string<br>        if not one_way and duration:<br>            match = re.match(r&#39;^P(\d+)D$&#39;, duration) # Extract days from P[n]D format<br>            if match:<br>                duration_days_str = match.group(1)<br>                params[&#39;returnDate&#39;] = departure_window.replace(&#39;/&#39;, &#39;,&#39;) <br>                params[&#39;viewBy&#39;] = &#39;DATE&#39;<br>                logger.info(f&quot;Interpreting duration {duration} for round trip (logic may need API spec review).&quot;)<br>            else:<br>                logger.warning(f&quot;Could not parse duration &#39;{duration}&#39; for cheapest dates search.&quot;)<br><br>        # Non-stop preference<br>        if non_stop:<br>            params[&#39;nonStop&#39;] = &#39;true&#39;<br><br>        if one_way:<br>             # Remove returnDate if we added it based on duration logic earlier<br>             params.pop(&#39;returnDate&#39;, None)<br>             logger.info(&quot;Configuring search for one-way trip.&quot;)<br><br><br>        try:<br>            # Make the API call to Flight Dates Search<br>            response = self.amadeus.shopping.flight_dates.get(**params)<br>            cheapest_results = response.data<br>            logger.info(f&quot;Found {len(cheapest_results)} cheapest date results.&quot;)<br>            # These results typically show date pairs/single dates and the cheapest price found for that date(s).<br>            return cheapest_results<br>        except ResponseError as error:<br>            logger.error(f&quot;Amadeus API error during cheapest date search: {error.code} - {error.description}&quot;, exc_info=True)<br>            logger.debug(f&quot;Request params causing error: {params}&quot;)<br>            return None<br>        except Exception as e:<br>            logger.error(f&quot;An unexpected error occurred during cheapest date search: {e}&quot;, exc_info=True)<br>            return None<br><br># Instantiate the provider for use in other modules<br>amadeus_provider = AmadeusProvider()</pre><h3>The Conductor</h3><p>This chat_controller.py is the main engine for handling our flight queries on the backend, managing requests sent to /api/chat. When we ask for a flight, it first passes our query to the openai_provider to decipher our intent and extract key details like locations, dates, and the type of search (specific dates vs. cheapest). Next, it uses the amadeus_provider to convert city names into the required IATA airport codes.</p><p>Depending on whether the AI identified our request as needing specific dates or the cheapest options, the controller then calls the relevant Amadeus search function (search_flights or search_cheapest_dates). Once Amadeus returns the flight data, the flight_formatter steps in to simplify this information into a clean structure.</p><p>Finally, the controller sends this formatted data, along with details of how our query was understood, back to the frontend, making sure to handle potential errors gracefully along the way.</p><p><em>chat_controller.py</em></p><pre># controllers/chat_controller.py<br>import logging<br>from flask import Blueprint, request, jsonify<br><br># Import our custom providers and formatters<br>from providers.openai_provider import openai_provider<br>from providers.amadeus_provider import amadeus_provider<br>from models.flight_formatter import format_flight_data, format_cheapest_date_data # Import both formatters<br>from config import config<br><br>logger = logging.getLogger(__name__)<br><br>chat_api = Blueprint(&#39;chat_api&#39;, __name__)<br><br># Define the main endpoint for handling chat queries<br># Accessible at /api/chat/query (see app.py for prefix)<br>@chat_api.route(&#39;/query&#39;, methods=[&#39;POST&#39;])<br>async def process_chat_query():<br>    &quot;&quot;&quot;<br>    Handles natural language flight search queries.<br>    Orchestrates calls to OpenAI for parsing, Amadeus for data fetching,<br>    and formatters for response preparation.<br>    Differentiates between specific date and cheapest date searches.<br>    &quot;&quot;&quot;<br>    try:<br>        # 1. Get request data<br>        request_data = request.get_json()<br>        if not request_data or &#39;query&#39; not in request_data:<br>            logger.warning(&quot;Chat query request missing &#39;query&#39; field.&quot;)<br>            # Return a user-friendly error and standard HTTP status code<br>            return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Oops! You forgot to enter your search query.&quot;}), 400<br><br>        query = request_data[&#39;query&#39;]<br>        logger.info(f&quot;Received chat query: &#39;{query}&#39;&quot;)<br><br>        # 2. Parse the natural language query using OpenAI<br>        parsed_params = None<br>        try:<br>            parsed_params = await openai_provider.parse_flight_query(query)<br>            if not parsed_params:<br>                 logger.error(&quot;OpenAI parsing returned None unexpectedly.&quot;)<br>                 return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Failed to understand query after parsing.&quot;}), 500<br>            logger.info(f&quot;Parsed flight parameters: {parsed_params}&quot;)<br>        except (ValueError, ConnectionError, RuntimeError) as e:<br>             # Catch specific errors raised by the OpenAI provider<br>             logger.error(f&quot;Error parsing query with OpenAI: {e}&quot;, exc_info=True)<br>             # Return a user-friendly message based on the error type<br>             error_message = f&quot;Error processing query with AI: {e}&quot;<br>             if isinstance(e, ConnectionError):<br>                  error_message = &quot;Could not reach the AI service. Please try again later.&quot;<br>             elif isinstance(e, ValueError):<br>                   error_message = f&quot;There was an issue understanding your request: {e}&quot;<br>             return jsonify({&quot;success&quot;: False, &quot;error&quot;: error_message}), 500<br>        except Exception as e:<br>             logger.error(f&quot;Unexpected error during OpenAI parsing: {e}&quot;, exc_info=True)<br>             return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;An unexpected error occurred while understanding your query.&quot;}), 500<br><br>        # --- Processing starts after successful parsing ---<br><br>        query_type = parsed_params.get(&#39;queryType&#39;)<br>        origin_city = parsed_params.get(&#39;origin&#39;)<br>        destination_city = parsed_params.get(&#39;destination&#39;)<br><br>        # 3. Get IATA codes using Amadeus<br>        if not origin_city or not destination_city:<br>             logger.warning(&quot;Missing origin or destination after parsing by AI.&quot;)<br>             return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Couldn&#39;t figure out the origin or destination from your query. Please be more specific.&quot;}), 400<br><br>        origin_code = None<br>        destination_code = None<br>        try:<br>            # Call Amadeus provider to resolve city names/codes to IATA codes<br>            origin_code = amadeus_provider.get_airport_code(origin_city)<br>            destination_code = amadeus_provider.get_airport_code(destination_city)<br><br>            if not origin_code or not destination_code:<br>                missing = []<br>                if not origin_code: missing.append(f&quot;origin (&#39;{origin_city}&#39;)&quot;)<br>                if not destination_code: missing.append(f&quot;destination (&#39;{destination_city}&#39;)&quot;)<br>                error_msg = f&quot;Could not find airport code(s) for {&#39;, &#39;.join(missing)}.&quot;<br>                logger.warning(error_msg)<br>                user_error = f&quot;Sorry, I couldn&#39;t find airport codes for the locations: {origin_city if not origin_code else &#39;&#39;} {destination_city if not destination_code else &#39;&#39;}. Please check the spelling or try a nearby major airport.&quot;<br>                return jsonify({&quot;success&quot;: False, &quot;error&quot;: user_error}), 400<br><br>            logger.info(f&quot;Resolved IATA codes: Origin={origin_code}, Destination={destination_code}&quot;)<br><br>        except Exception as e:<br>             logger.error(f&quot;Error retrieving airport codes from Amadeus: {e}&quot;, exc_info=True)<br>             return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;An error occurred while looking up airport codes. Please try again.&quot;}), 500<br><br><br>        # --- 4. Branch logic based on Query Type ---<br>        results_payload = {}<br>        formatted_results = None<br><br>        if query_type == &#39;specificDate&#39;:<br>            logger.info(&quot;Handling &#39;specificDate&#39; query type.&quot;)<br>            # 4a. Search Specific Flights using Amadeus<br>            try:<br>                # Ensure required date fields are present<br>                if &#39;departureDate&#39; not in parsed_params:<br>                     raise KeyError(&#39;departureDate&#39;)<br><br>                flight_offers = amadeus_provider.search_flights(<br>                    origin=origin_code,<br>                    destination=destination_code,<br>                    departure_date=parsed_params[&#39;departureDate&#39;],<br>                    return_date=parsed_params.get(&#39;returnDate&#39;),<br>                    adults=parsed_params.get(&#39;adults&#39;, 1)<br>                )<br><br>                # Amadeus provider returns None on API error<br>                if flight_offers is None:<br>                    logger.error(&quot;Flight search failed (Amadeus provider returned None).&quot;)<br>                    # 503 Service Unavailable is appropriate if the downstream API failed<br>                    return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Failed to search for flights from the airline system. Please try again later.&quot;}), 503<br><br>                # Format Specific Flight Data<br>                formatted_results = format_flight_data(flight_offers)<br>                if not formatted_results and flight_offers is not None:<br>                     # It&#39;s possible the API returned offers, but they were invalid/empty after formatting<br>                     logger.info(&quot;No valid flight offers found matching the criteria after formatting.&quot;)<br>                elif not formatted_results:<br>                     logger.info(&quot;No flight offers found for the specified criteria.&quot;)<br><br>                # Prepare response payload for specificDate<br>                results_payload = {<br>                    &quot;flights&quot;: formatted_results if formatted_results else [], # Ensure it&#39;s always a list<br>                    &quot;recommendations&quot;: recommendations<br>                }<br><br>            except KeyError as e:<br>                 # This happens if the AI parsing missed a required field for this query type<br>                 logger.error(f&quot;Missing expected key in parsed_params for specificDate search: {e}&quot;, exc_info=False) # Log key only<br>                 return jsonify({&quot;success&quot;: False, &quot;error&quot;: f&quot;Sorry, I&#39;m missing some required information ({e}) for a specific date search. Please try rephrasing your query.&quot;}), 400<br>            except Exception as e:<br>                # Catch unexpected errors during the Amadeus call or formatting<br>                logger.error(f&quot;Unexpected error during specific flight search or formatting: {e}&quot;, exc_info=True)<br>                return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;An unexpected error occurred while searching for specific flights.&quot;}), 500<br><br><br>        elif query_type == &#39;cheapestDate&#39;:<br>            logger.info(&quot;Handling &#39;cheapestDate&#39; query type.&quot;)<br>            # Search Cheapest Dates using Amadeus<br>            try:<br>                if &#39;departureWindow&#39; not in parsed_params:<br>                     raise KeyError(&#39;departureWindow&#39;)<br><br>                cheapest_results_raw = amadeus_provider.search_cheapest_dates(<br>                    origin=origin_code,<br>                    destination=destination_code,<br>                    departure_window=parsed_params[&#39;departureWindow&#39;],<br>                    duration=parsed_params.get(&#39;duration&#39;),<br>                    one_way=parsed_params.get(&#39;oneWay&#39;, False),<br>                    non_stop=parsed_params.get(&#39;nonStop&#39;, False)<br>                )<br><br>                # Amadeus provider returns None on API error<br>                if cheapest_results_raw is None:<br>                    logger.error(&quot;Cheapest date search failed (Amadeus provider returned None).&quot;)<br>                    return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Failed to search for cheapest dates from the airline system. Please try again later.&quot;}), 503<br><br>                # Format Cheapest Date Data<br>                formatted_results = format_cheapest_date_data(cheapest_results_raw)<br>                if not formatted_results and cheapest_results_raw is not None:<br>                     logger.info(&quot;No cheapest dates found matching the criteria after formatting.&quot;)<br>                elif not formatted_results:<br>                     logger.info(&quot;No cheapest dates found for the specified criteria.&quot;)<br><br>                # Prepare response payload for cheapestDate<br>                results_payload = {<br>                    &quot;cheapestDates&quot;: formatted_results if formatted_results else []<br>                }<br><br>            except KeyError as e:<br>                 logger.error(f&quot;Missing expected key in parsed_params for cheapestDate search: {e}&quot;, exc_info=False)<br>                 return jsonify({&quot;success&quot;: False, &quot;error&quot;: f&quot;Sorry, I&#39;m missing some required information ({e}) for a cheapest date search. Please try rephrasing.&quot;}), 400<br>            except Exception as e:<br>                logger.error(f&quot;Unexpected error during cheapest date search or formatting: {e}&quot;, exc_info=True)<br>                return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;An unexpected error occurred while searching for the cheapest dates.&quot;}), 500<br><br>        else:<br>            logger.error(f&quot;Unknown queryType encountered after parsing: {query_type}&quot;)<br>            return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;Could not determine the type of search required after parsing.&quot;}), 400<br><br><br>        # Return successful response<br>        response_payload = {<br>            &quot;success&quot;: True,<br>            &quot;queryType&quot;: query_type,<br>            &quot;parsedQuery&quot;: parsed_params<br>        }<br>        return jsonify(response_payload), 200<br><br>    except Exception as e:<br>        logger.error(f&quot;Unhandled error in process_chat_query endpoint: {e}&quot;, exc_info=True)<br>        return jsonify({&quot;success&quot;: False, &quot;error&quot;: &quot;An internal server error occurred while processing your request.&quot;}), 500</pre><h3>Making Data Pretty</h3><p>API responses, especially from complex systems like Amadeus, can be <em>huge</em> and nested, containing way more information than our simple frontend needs. The flight_formatter.py module acts like a filter and simplifier.</p><p>It takes the raw list of flight offers or cheapest date results from Amadeus and transforms it into a cleaner, flatter structure.</p><ul><li><strong>format_flight_data:</strong> Pulls out key details for each flight offer: price, airlines, number of stops, and simplified segment info (departure/arrival airports &amp; times, carrier code, duration). It calculates the total number of stops for the journey.</li><li><strong>format_cheapest_date_data:</strong> Extracts the origin, destination, departure/return dates, total price, and a handy link (if provided by Amadeus) to view actual flight offers for that cheap date. It also sorts the results by price, cheapest first.</li></ul><p>This formatting step is crucial because it decouples the frontend from the raw complexity of the backend APIs. The frontend only needs to know how to handle the simple, formatted structure.</p><p><em>flight_formatter.py</em></p><pre># models/flight_formatter.py<br>import logging<br>from datetime import datetime<br>from typing import List, Dict, Any, Optional<br><br>logger = logging.getLogger(__name__)<br><br>def format_flight_data(flight_offers: Optional[List[Dict[str, Any]]]) -&gt; List[Dict[str, Any]]:<br>    &quot;&quot;&quot;<br>    Formats the raw flight offer data received from the Amadeus Flight Offers Search API<br>    into a simpler, more frontend-friendly structure.<br><br>    Extracts key information like price, airlines, stops, and segment details.<br>    Calculates total stops per offer.<br>    &quot;&quot;&quot;<br>    if not flight_offers:<br>        logger.info(&quot;No flight offers provided to format.&quot;)<br>        return []<br><br>    formatted_flights = []<br>    for offer_index, offer in enumerate(flight_offers):<br>        try:<br>            required_keys = [&#39;id&#39;, &#39;price&#39;, &#39;itineraries&#39;, &#39;validatingAirlineCodes&#39;]<br>            if not all(k in offer for k in required_keys):<br>                logger.warning(f&quot;Skipping flight offer index {offer_index} (ID: {offer.get(&#39;id&#39;, &#39;N/A&#39;)}) due to missing essential keys: {[k for k in required_keys if k not in offer]}&quot;)<br>                continue<br><br>            # --- Calculate Total Stops ---<br>            total_stops = 0<br>            for itinerary in offer.get(&#39;itineraries&#39;, []):<br>                segments_in_itinerary = itinerary.get(&#39;segments&#39;, [])<br>                # Ensure we don&#39;t count negative stops if segments list is empty<br>                total_stops += max(0, len(segments_in_itinerary) - 1)<br><br>            # --- Extract Key Information ---<br>            formatted = {<br>                &#39;id&#39;: offer[&#39;id&#39;],<br>                &#39;price&#39;: {<br>                    &#39;currency&#39;: offer[&#39;price&#39;].get(&#39;currency&#39;, &#39;N/A&#39;),<br>                    &#39;total&#39;: offer[&#39;price&#39;].get(&#39;total&#39;, &#39;N/A&#39;),<br>                    &#39;base&#39;: offer[&#39;price&#39;].get(&#39;base&#39;, &#39;N/A&#39;)<br>                },<br>                &#39;airlines&#39;: offer.get(&#39;validatingAirlineCodes&#39;, []),<br>                # Process itineraries and their segments<br>                &#39;segments&#39;: [<br>                    [<br>                        {<br>                            &#39;departure&#39;: {<br>                                &#39;airport&#39;: segment.get(&#39;departure&#39;, {}).get(&#39;iataCode&#39;, &#39;N/A&#39;),<br>                                &#39;time&#39;: segment.get(&#39;departure&#39;, {}).get(&#39;at&#39;, &#39;N/A&#39;)<br>                            },<br>                            &#39;arrival&#39;: {<br>                                &#39;airport&#39;: segment.get(&#39;arrival&#39;, {}).get(&#39;iataCode&#39;, &#39;N/A&#39;),<br>                                &#39;time&#39;: segment.get(&#39;arrival&#39;, {}).get(&#39;at&#39;, &#39;N/A&#39;)<br>                            },<br>                            &#39;carrierCode&#39;: segment.get(&#39;carrierCode&#39;, &#39;N/A&#39;),<br>                            &#39;flightNumber&#39;: segment.get(&#39;number&#39;, &#39;N/A&#39;),<br>                            &#39;duration&#39;: segment.get(&#39;duration&#39;, &#39;N/A&#39;)<br>                        }<br>                        for segment in itinerary.get(&#39;segments&#39;, [])<br>                    ]<br>                    for itinerary in offer.get(&#39;itineraries&#39;, [])<br>                ],<br>                &#39;numberOfStops&#39;: total_stops<br>            }<br>            formatted_flights.append(formatted)<br><br>        except (KeyError, TypeError, IndexError) as e:<br>            logger.error(f&quot;Error formatting flight offer index {offer_index} (ID: {offer.get(&#39;id&#39;, &#39;N/A&#39;)}): {e}&quot;, exc_info=True)<br>            continue<br>        except Exception as e:<br>             logger.error(f&quot;Unexpected error formatting flight offer index {offer_index} (ID: {offer.get(&#39;id&#39;, &#39;N/A&#39;)}): {e}&quot;, exc_info=True)<br>             continue<br><br><br>    logger.info(f&quot;Successfully formatted {len(formatted_flights)} out of {len(flight_offers)} flight offers.&quot;)<br>    return formatted_flights<br><br><br># --- Formatter for Cheapest Date Results ---<br>def format_cheapest_date_data(cheapest_results: Optional[List[Dict[str, Any]]]) -&gt; List[Dict[str, Any]]:<br>    &quot;&quot;&quot;<br>    Formats the raw cheapest date data from the Amadeus Flight Dates API<br>    into a simpler structure suitable for the frontend.<br><br>    Extracts origin, destination, dates, price, and potentially a link to view offers.<br>    Sorts results by price (ascending).<br>    &quot;&quot;&quot;<br>    if not cheapest_results:<br>        logger.info(&quot;No cheapest date results provided to format.&quot;)<br>        return []<br><br>    formatted_dates = []<br>    for result_index, result in enumerate(cheapest_results):<br>        try:<br>            # Basic validation for expected keys and type<br>            required_keys = [&#39;type&#39;, &#39;origin&#39;, &#39;destination&#39;, &#39;departureDate&#39;, &#39;price&#39;]<br>            if not all(k in result for k in required_keys) or result.get(&#39;type&#39;) != &#39;flight-date&#39;:<br>                logger.warning(f&quot;Skipping invalid cheapest date result index {result_index}: {result.get(&#39;type&#39;, &#39;N/A&#39;)}&quot;)<br>                continue<br><br>            # Extract relevant fields<br>            formatted = {<br>                &#39;origin&#39;: result[&#39;origin&#39;],<br>                &#39;destination&#39;: result[&#39;destination&#39;],<br>                &#39;departureDate&#39;: result[&#39;departureDate&#39;],<br>                &#39;returnDate&#39;: result.get(&#39;returnDate&#39;),<br>                &#39;price&#39;: {<br>                    &#39;total&#39;: result[&#39;price&#39;].get(&#39;total&#39;, &#39;N/A&#39;),<br>                    &#39;currency&#39;: result[&#39;price&#39;].get(&#39;currency&#39;, &#39;USD&#39;)<br>                },<br>                # Extract the link to view actual flight offers for this date if available<br>                &#39;viewFlightLink&#39;: result.get(&#39;links&#39;, {}).get(&#39;flightOffers&#39;)<br>            }<br>            formatted_dates.append(formatted)<br><br>        except (KeyError, TypeError, IndexError) as e:<br>            logger.error(f&quot;Error formatting cheapest date result index {result_index}: {e}&quot;, exc_info=True)<br>            continue<br>        except Exception as e:<br>             logger.error(f&quot;Unexpected error formatting cheapest date result index {result_index}: {e}&quot;, exc_info=True)<br>             continue<br><br>    logger.info(f&quot;Successfully formatted {len(formatted_dates)} out of {len(cheapest_results)} cheapest date results.&quot;)<br><br>    # Sort the results by price (cheapest first)<br>    def get_price_sort_key(item):<br>        price_str = item.get(&#39;price&#39;, {}).get(&#39;total&#39;, &#39;inf&#39;)<br>        try:<br>            return float(price_str)<br>        except (ValueError, TypeError):<br>            return float(&#39;inf&#39;) # Put items with invalid prices at the end<br><br>    formatted_dates.sort(key=get_price_sort_key)<br><br>    return formatted_dates<br><br><br># --- Helper Functions ---<br><br>def format_time_iso(iso_time_str: Optional[str]) -&gt; str:<br>    &quot;&quot;&quot; Helper to format ISO 8601 datetime string to HH:MM format. &quot;&quot;&quot;<br>    if not iso_time_str:<br>        return &quot;N/A&quot;<br>    try:<br>        dt_obj = datetime.fromisoformat(iso_time_str)<br>        return dt_obj.strftime(&quot;%H:%M&quot;)<br>    except (ValueError, TypeError):<br>        logger.warning(f&quot;Could not format time string: {iso_time_str}&quot;)<br>        return &quot;Invalid&quot;<br><br>def format_duration_iso(iso_duration_str: Optional[str]) -&gt; str:<br>     &quot;&quot;&quot; Helper to format ISO 8601 duration string (e.g., PT2H30M) to Xh Ym format. &quot;&quot;&quot;<br>     if not iso_duration_str or not iso_duration_str.startswith(&#39;PT&#39;):<br>         return iso_duration_str or &quot;N/A&quot;<br>     try:<br>         duration = iso_duration_str[2:]<br>         hours = &#39;0&#39;<br>         minutes = &#39;0&#39;<br>         if &#39;H&#39; in duration:<br>             parts = duration.split(&#39;H&#39;)<br>             hours = parts[0]<br>             if len(parts) &gt; 1 and &#39;M&#39; in parts[1]:<br>                 minutes = parts[1].replace(&#39;M&#39;, &#39;&#39;)<br>         elif &#39;M&#39; in duration:<br>             minutes = duration.replace(&#39;M&#39;, &#39;&#39;)<br><br>         # Basic validation to ensure extracted parts are digits<br>         if not hours.isdigit(): hours = &#39;0&#39;<br>         if not minutes.isdigit(): minutes = &#39;0&#39;<br><br>         return f&quot;{hours}h {minutes}m&quot;<br>     except Exception:<br>         logger.warning(f&quot;Could not format duration string: {iso_duration_str}&quot;)<br>         return iso_duration_str</pre><h3>The User Interface: HTML, CSS, &amp; JavaScript</h3><p>To let the users actually <em>use</em> this backend, we need a frontend. It’s a simple setup using standard web technologies:</p><ul><li><strong>app.js</strong>: This JavaScript connects the user interface to the backend. When we search, it grabs our query, shows a loading message, and sends the request to the Flask API using fetch. Upon receiving the backend&#39;s response, it hides the loading message and either displays the formatted flight results (or cheapest dates) and the AI&#39;s interpretation, or shows an error message if something went wrong.</li><li><strong>index.html</strong>: This file lays out the basic structure of the webpage. It includes the title, the text input field where we type our flight query, a search button, and different div containers ready to display results like what the AI understood, the flight cards or cheapest dates, loading messages, and any errors.</li><li><strong>style.css</strong>: This adds the bare minimum styling to make the page usable, defining basic layout for the form and result areas. We&#39;ve stripped out most of the fancy looks here to keep it simple.</li></ul><p><em>static/app.js</em></p><pre>// static/app.js<br><br>// Cache frequently accessed elements for performance<br>const searchForm = document.getElementById(&#39;searchForm&#39;);<br>const queryInput = document.getElementById(&#39;queryInput&#39;);<br>const resultsDiv = document.getElementById(&#39;results&#39;);<br>const loadingDiv = document.getElementById(&#39;loading&#39;);<br>const parsedQueryDiv = document.getElementById(&#39;parsedQuery&#39;);<br>const flightCardsDiv = document.getElementById(&#39;flightCards&#39;);<br>const cheapestDatesDiv = document.getElementById(&#39;cheapestDates&#39;);<br>const recommendationsDiv = document.getElementById(&#39;recommendations&#39;);<br>const resultsTitle = document.getElementById(&#39;resultsTitle&#39;);<br>const errorDisplayDiv = document.getElementById(&#39;errorDisplay&#39;);<br><br><br>// --- Event Listener ---<br>searchForm.addEventListener(&#39;submit&#39;, async (e) =&gt; {<br>    e.preventDefault();<br><br>    const query = queryInput.value.trim();<br>    if (!query) {<br>        displayError(&quot;Please enter a flight search query.&quot;);<br>        return;<br>    }<br><br>    resetUI();<br>    loadingDiv.style.display = &#39;block&#39;;<br><br>    try {<br>        console.log(&quot;Sending query:&quot;, query);<br><br>        // --- API Call ---<br>        const response = await fetch(&#39;/api/chat/query&#39;, {<br>            method: &#39;POST&#39;,<br>            headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>            body: JSON.stringify({ query })<br>        });<br><br>        console.log(&quot;Response status:&quot;, response.status);<br>        const data = await response.json();<br>        console.log(&quot;Received data:&quot;, data);<br><br>        // --- Handle Response ---<br>        loadingDiv.style.display = &#39;none&#39;;<br><br>        if (!response.ok || !data.success) {<br>            const errorMsg = data.error || `Request failed with status ${response.status}`;<br>            throw new Error(errorMsg);<br>        }<br><br>        // --- Populate Results ---<br>        resultsDiv.style.display = &#39;block&#39;;<br><br>        // Display Parsed Query (what the AI understood)<br>        if (data.parsedQuery) {<br>            parsedQueryDiv.innerHTML = createParsedQueryHtml(data.parsedQuery, data.queryType);<br>            parsedQueryDiv.style.display = &#39;block&#39;;<br>        }<br><br>        // Display Results Title<br>        resultsTitle.style.display = &#39;block&#39;;<br><br>        // --- Branch display based on queryType ---<br>        if (data.queryType === &#39;specificDate&#39;) {<br>            resultsTitle.textContent = &quot;✈️ Flight Offers Found&quot;;<br>            cheapestDatesDiv.style.display = &#39;none&#39;;<br><br>            // Display Flight Cards<br>            if (data.flights &amp;&amp; data.flights.length &gt; 0) {<br>                flightCardsDiv.innerHTML = &#39;&#39;;<br>                data.flights.forEach(flight =&gt; {<br>                    flightCardsDiv.innerHTML += createFlightCard(flight);<br>                });<br>                flightCardsDiv.style.display = &#39;block&#39;;<br>            } else {<br>                 flightCardsDiv.innerHTML = &#39;&lt;p&gt;😕 No exact flights found matching your criteria for these dates.&lt;/p&gt;&#39;;<br>                 flightCardsDiv.style.display = &#39;block&#39;;<br>            }<br><br>        } else if (data.queryType === &#39;cheapestDate&#39;) {<br>            resultsTitle.textContent = &quot;📅 Cheapest Dates Found&quot;;<br>            flightCardsDiv.style.display = &#39;none&#39;;<br><br>            // Display Cheapest Dates<br>            if (data.cheapestDates &amp;&amp; data.cheapestDates.length &gt; 0) {<br>                cheapestDatesDiv.innerHTML = &#39;&lt;p&gt;Here are the cheapest dates found based on your criteria:&lt;/p&gt;&#39;;<br>                data.cheapestDates.forEach(dateInfo =&gt; {<br>                    cheapestDatesDiv.innerHTML += createCheapestDateCard(dateInfo);<br>                });<br>                cheapestDatesDiv.style.display = &#39;block&#39;;<br>            } else {<br>                cheapestDatesDiv.innerHTML = &#39;&lt;p&gt;😕 Could not find any cheap dates matching your criteria in the specified window.&lt;/p&gt;&#39;;<br>                cheapestDatesDiv.style.display = &#39;block&#39;;<br>            }<br>        } else {<br>             console.error(&quot;Unknown queryType received:&quot;, data.queryType);<br>             displayError(&quot;An unexpected error occurred while processing the search type.&quot;);<br>        }<br><br>    } catch (error) {<br>        console.error(&#39;Error during fetch or processing:&#39;, error);<br>        loadingDiv.style.display = &#39;none&#39;;<br>        resultsTitle.style.display = &#39;none&#39;;<br>        displayError(`&lt;strong&gt;Error:&lt;/strong&gt; ${error.message}`);<br>    }<br>});<br><br><br><br>function resetUI() {<br>    loadingDiv.style.display = &#39;none&#39;;<br>    parsedQueryDiv.innerHTML = &#39;&#39;;<br>    parsedQueryDiv.style.display = &#39;none&#39;;<br>    flightCardsDiv.innerHTML = &#39;&#39;;<br>    flightCardsDiv.style.display = &#39;none&#39;;<br>    cheapestDatesDiv.innerHTML = &#39;&#39;;<br>    cheapestDatesDiv.style.display = &#39;none&#39;;<br>    recommendationsDiv.innerHTML = &#39;&#39;;<br>    recommendationsDiv.style.display = &#39;none&#39;;<br>    resultsTitle.textContent = &quot;Results&quot;;<br>    resultsTitle.style.display = &#39;none&#39;;<br>    errorDisplayDiv.innerHTML = &#39;&#39;;<br>    errorDisplayDiv.style.display = &#39;none&#39;;<br>    resultsDiv.style.display = &#39;none&#39;;<br>}<br><br>function displayError(message) {<br>     errorDisplayDiv.innerHTML = message;<br>     errorDisplayDiv.style.display = &#39;block&#39;;<br>     parsedQueryDiv.style.display = &#39;none&#39;;<br>     flightCardsDiv.style.display = &#39;none&#39;;<br>     cheapestDatesDiv.style.display = &#39;none&#39;;<br>     recommendationsDiv.style.display = &#39;none&#39;;<br>     resultsTitle.style.display = &#39;none&#39;;<br>}<br><br>// Creates HTML for displaying the parsed query parameters<br>function createParsedQueryHtml(parsedQuery, queryType) {<br>     let html = `<br>        &lt;div class=&quot;parsed-query&quot;&gt;<br>            &lt;h3&gt;✅ Understood Request (${queryType === &#39;specificDate&#39; ? &#39;Specific Dates&#39; : &#39;Cheapest Dates&#39;}):&lt;/h3&gt;<br>            &lt;p&gt;&lt;strong&gt;From:&lt;/strong&gt; ${parsedQuery.origin || &#39;N/A&#39;}&lt;/p&gt;<br>            &lt;p&gt;&lt;strong&gt;To:&lt;/strong&gt; ${parsedQuery.destination || &#39;N/A&#39;}&lt;/p&gt;<br>     `;<br><br>    if (queryType === &#39;specificDate&#39;) {<br>         html += `&lt;p&gt;&lt;strong&gt;Departure:&lt;/strong&gt; ${parsedQuery.departureDate || &#39;N/A&#39;}&lt;/p&gt;`;<br>         if (parsedQuery.returnDate) {<br>             html += `&lt;p&gt;&lt;strong&gt;Return:&lt;/strong&gt; ${parsedQuery.returnDate}&lt;/p&gt;`;<br>         } else {<br>              html += `&lt;p&gt;&lt;strong&gt;Trip Type:&lt;/strong&gt; One Way&lt;/p&gt;`;<br>         }<br>    } else if (queryType === &#39;cheapestDate&#39;) {<br>         html += `&lt;p&gt;&lt;strong&gt;Search Window:&lt;/strong&gt; ${parsedQuery.departureWindow?.replace(&#39;/&#39;, &#39; to &#39;) || &#39;N/A&#39;}&lt;/p&gt;`;<br>         if (parsedQuery.duration) {<br>             html += `&lt;p&gt;&lt;strong&gt;Travel Duration:&lt;/strong&gt; ${formatIsoDurationToFriendly(parsedQuery.duration)}&lt;/p&gt;`;<br>         }<br>         html += `&lt;p&gt;&lt;strong&gt;One Way:&lt;/strong&gt; ${parsedQuery.oneWay ? &#39;Yes&#39; : &#39;No&#39;}&lt;/p&gt;`;<br>         html += `&lt;p&gt;&lt;strong&gt;Non-Stop Only:&lt;/strong&gt; ${parsedQuery.nonStop ? &#39;Yes&#39; : &#39;No&#39;}&lt;/p&gt;`;<br>    }<br><br>    html += `&lt;p&gt;&lt;strong&gt;Adults:&lt;/strong&gt; ${parsedQuery.adults || &#39;1&#39;}&lt;/p&gt;`; // Default to 1 if missing<br><br>    html += `&lt;/div&gt;`;<br>    return html;<br>}<br><br><br>function createFlightCard(flight) {<br>    const priceInfo = flight.price || {};<br>    const currency = priceInfo.currency || &#39;USD&#39;;<br>    const total = priceInfo.total || &#39;N/A&#39;;<br><br>    const airlines = flight.airlines?.join(&#39;, &#39;) || &#39;N/A&#39;;<br><br>    return `<br>        &lt;div class=&quot;flight-card&quot;&gt;<br>            &lt;div class=&quot;card-header&quot;&gt;<br>                 &lt;span class=&quot;flight-id&quot;&gt;ID: ${flight.id || &#39;N/A&#39;}&lt;/span&gt;<br>                 &lt;span class=&quot;price&quot;&gt;${currency} ${total}&lt;/span&gt;<br>            &lt;/div&gt;<br>             &lt;div class=&quot;card-body&quot;&gt;<br>                &lt;p class=&quot;airlines&quot;&gt;&lt;strong&gt;Airlines:&lt;/strong&gt; ${airlines}&lt;/p&gt;<br>                &lt;p class=&quot;stops&quot;&gt;&lt;strong&gt;Total Stops (Round Trip):&lt;/strong&gt; ${flight.numberOfStops ?? &#39;N/A&#39;}&lt;/p&gt; {/* Clarify stops meaning */}<br><br>                ${/* Map through itineraries (outbound/inbound legs) */&#39;&#39;}<br>                ${flight.segments?.map((itinerarySegments, index) =&gt; `<br>                    &lt;div class=&quot;itinerary&quot;&gt;<br>                        &lt;h4&gt;${index === 0 ? &#39;Outbound&#39; : index === 1 ? &#39;Return&#39; : `Leg ${index + 1}`}&lt;/h4&gt;<br>                        ${/* Map through segments within each itinerary */&#39;&#39;}<br>                        ${itinerarySegments?.map(segment =&gt; `<br>                            &lt;div class=&quot;segment&quot;&gt;<br>                                &lt;div class=&quot;segment-detail&quot;&gt;<br>                                    &lt;span&gt;&lt;strong style=&quot;color: #3498db;&quot;&gt;✈️ ${segment.carrierCode || &#39;&#39;} ${segment.flightNumber || &#39;&#39;}&lt;/strong&gt;&lt;/span&gt;<br>                                    &lt;span class=&quot;separator&quot;&gt;|&lt;/span&gt;<br>                                    &lt;span&gt;&lt;strong&gt;From:&lt;/strong&gt; ${segment.departure?.airport || &#39;N/A&#39;} (${formatTime(segment.departure?.time)})&lt;/span&gt;<br>                                    &lt;span class=&quot;separator&quot;&gt;→&lt;/span&gt;<br>                                    &lt;span&gt;&lt;strong&gt;To:&lt;/strong&gt; ${segment.arrival?.airport || &#39;N/A&#39;} (${formatTime(segment.arrival?.time)})&lt;/span&gt;<br>                                    &lt;span class=&quot;separator&quot;&gt;|&lt;/span&gt;<br>                                    &lt;span&gt;&lt;strong&gt;🕒 Duration:&lt;/strong&gt; ${formatDuration(segment.duration)}&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        `).join(&#39;&#39;) || &#39;&lt;p&gt;Segment details unavailable.&lt;/p&gt;&#39;}<br>                    &lt;/div&gt;<br>                `).join(&#39;&#39;) || &#39;&lt;p&gt;Itinerary details unavailable.&lt;/p&gt;&#39;}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    `;<br>}<br><br>// Creates HTML for a single cheapest date card<br>function createCheapestDateCard(dateInfo) {<br>     const priceInfo = dateInfo.price || {};<br>     const currency = priceInfo.currency || &#39;USD&#39;;<br>     const total = priceInfo.total || &#39;N/A&#39;;<br><br>    return `<br>        &lt;div class=&quot;cheapest-date-card&quot;&gt;<br>             &lt;div class=&quot;date-info&quot;&gt;<br>                 &lt;span class=&quot;date&quot;&gt;🛫 ${dateInfo.departureDate || &#39;N/A&#39;}&lt;/span&gt;<br>                 ${/* Conditionally show return date or (One Way) */&#39;&#39;}<br>                 ${dateInfo.returnDate<br>                     ? `&lt;span class=&quot;date-separator&quot;&gt;→&lt;/span&gt; &lt;span class=&quot;date&quot;&gt;🛬 ${dateInfo.returnDate}&lt;/span&gt;`<br>                     : &#39;&lt;span class=&quot;date-oneway&quot;&gt;(One Way)&lt;/span&gt;&#39;<br>                 }<br>            &lt;/div&gt;<br>             &lt;div class=&quot;price-info&quot;&gt;<br>                &lt;span class=&quot;price&quot;&gt;${currency} ${total}&lt;/span&gt;<br>                ${/* Conditionally show View Flights link if available */&#39;&#39;}<br>                ${dateInfo.viewFlightLink<br>                    ? `&lt;a href=&quot;${dateInfo.viewFlightLink}&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot; class=&quot;details-link&quot;&gt;View Flights&lt;/a&gt;`<br>                    : &#39;&#39;<br>                }<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    `;<br>}<br><br><br>// Formats ISO time string (e.g., &quot;2025-08-15T10:30:00&quot;) to &quot;HH:MM&quot;<br>function formatTime(isoTime) {<br>    if (!isoTime) return &#39;N/A&#39;;<br>    try {<br>        const date = new Date(isoTime);<br>        const hours = date.getHours().toString().padStart(2, &#39;0&#39;);<br>        const minutes = date.getMinutes().toString().padStart(2, &#39;0&#39;);<br>        return `${hours}:${minutes}`;<br>    } catch (e) {<br>        console.warn(&quot;Failed to format time:&quot;, isoTime, e);<br>        return &#39;Invalid&#39;;<br>    }<br>}<br><br>// Formats ISO duration (e.g., &quot;PT2H30M&quot;) to &quot;Xh Ym&quot;<br>function formatDuration(isoDuration) {<br>    if (!isoDuration || !isoDuration.startsWith(&#39;PT&#39;)) return isoDuration || &#39;N/A&#39;;<br>    try {<br>        let duration = isoDuration.substring(2);<br>        let hours = &#39;0&#39;;<br>        let minutes = &#39;0&#39;;<br>        if (duration.includes(&#39;H&#39;)) {<br>            [hours, duration] = duration.split(&#39;H&#39;);<br>        }<br>        if (duration.includes(&#39;M&#39;)) {<br>            [minutes] = duration.split(&#39;M&#39;);<br>        }<br>        hours = hours.match(/^\d+$/) ? hours : &#39;0&#39;;<br>        minutes = minutes.match(/^\d+$/) ? minutes : &#39;0&#39;;<br><br>        return `${hours}h ${minutes}m`;<br>    } catch (e) {<br>        console.warn(&quot;Failed to format duration:&quot;, isoDuration, e);<br>        return isoDuration;<br>    }<br>}<br><br>// Formats ISO duration like &quot;P7D&quot; to &quot;7 days&quot;<br>function formatIsoDurationToFriendly(isoDuration) {<br>    if (!isoDuration || !isoDuration.startsWith(&#39;P&#39;) || !isoDuration.endsWith(&#39;D&#39;)) return isoDuration || &#39;N/A&#39;;<br>    try {<br>        const days = isoDuration.substring(1, isoDuration.length - 1);<br>        const daysNum = parseInt(days);<br>        if (isNaN(daysNum)) return isoDuration;<br>        return `${daysNum} day${daysNum !== 1 ? &#39;s&#39; : &#39;&#39;}`;<br>    } catch(e) {<br>         console.warn(&quot;Failed to format friendly duration:&quot;, isoDuration, e);<br>        return isoDuration;<br>    }<br>}</pre><p><em>templates/index.html</em></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Natural Language Flight Search&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;style.css&#39;) }}&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h1&gt;✈️ Natural Language Flight Search ✈️&lt;/h1&gt;<br>        &lt;p&gt;Ask for flights like you normally would! Try things like:&lt;/p&gt;<br>        &lt;ul&gt;<br>            &lt;li&gt;&lt;em&gt;&quot;Flights from Dhaka to Cox&#39;s Bazar next Friday returning Sunday&quot;&lt;/em&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;em&gt;&quot;Cheapest flights SIN to KUL next month for 7 days&quot;&lt;/em&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;em&gt;&quot;One way flight London to Paris July 10th&quot;&lt;/em&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;em&gt;&quot;Find non-stop flights from New York to Los Angeles in September&quot;&lt;/em&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br><br>        &lt;form id=&quot;searchForm&quot;&gt;<br>            &lt;input<br>                type=&quot;text&quot;<br>                id=&quot;queryInput&quot;<br>                placeholder=&quot;e.g., Cheapest flights from DAC to BKK next month for 1 week&quot;<br>                required<br>                aria-label=&quot;Flight search query&quot;<br>            &gt;<br>            &lt;button type=&quot;submit&quot;&gt;Search Flights&lt;/button&gt;<br>        &lt;/form&gt;<br><br>        &lt;div id=&quot;results&quot;&gt;<br>            &lt;div id=&quot;loading&quot; class=&quot;loading&quot; style=&quot;display: none;&quot;&gt;<br>                 &lt;p&gt;⏳ Searching the skies... Please wait.&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;parsedQuery&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;<br><br>            &lt;div id=&quot;recommendations&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;<br><br>             &lt;h2 id=&quot;resultsTitle&quot; style=&quot;display: none;&quot;&gt;Results&lt;/h2&gt;<br><br>            &lt;div id=&quot;flightCards&quot; style=&quot;display: none;&quot;&gt;<br>                 &lt;/div&gt;<br><br>             &lt;div id=&quot;cheapestDates&quot; style=&quot;display: none;&quot;&gt;<br>                 &lt;/div&gt;<br><br>             &lt;div id=&quot;errorDisplay&quot; class=&quot;error&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;script src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;app.js&#39;) }}&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><em>templates/style.css</em></p><pre>/* static/style.css */<br>body {<br>    font-family: sans-serif;<br>}<br><br>.container {<br>    max-width: 800px;<br>    margin: 10px auto;<br>}<br><br>#searchForm {<br>    display: flex;<br>    margin-bottom: 15px;<br>}<br><br>#queryInput {<br>    flex-grow: 1;<br>    margin-right: 5px;<br>}<br><br>.parsed-query, .recommendations, .flight-card, .cheapest-date-card, .loading, .error {<br>    border: 1px solid #eee;<br>    padding: 5px;<br>    margin-bottom: 10px;<br>}<br><br>.error {<br>    border-color: red;<br>    color: red;<br>}<br><br>#loading, #parsedQuery, #recommendations, #resultsTitle,<br>#flightCards, #cheapestDates, #errorDisplay {<br>    display: none;<br>}</pre><h3>Putting it All Together</h3><p>Let’s quickly trace a query like <strong>“Cheapest flights from Singapore to Kuala Lumpur next month for 5 days”</strong>.</p><p>We type this into the webpage. The frontend JavaScript (app.js) sends our query to the backend controller (chat_controller.py). The controller first asks OpenAI to parse the request, figuring out we want the cheapest dates for SIN to KUL in May for 5 days. It confirms the airport codes (SIN, KUL) with Amadeus, then asks Amadeus for the cheapest dates matching these criteria. Once Amadeus responds with potential dates and prices, the controller formats this data cleanly and sends the results back to the JavaScript, which then displays the list of cheapest date options on our screen. Simple as that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0QZkTaogQGscW4yMD9uMg.png" /></figure><h3>The Bumps in the Road (Challenges)</h3><p>It’s not all smooth flying:</p><ul><li><strong>Prompt Engineering:</strong> Getting the OpenAI prompt <em>just right</em> takes trial and error. The AI needs clear instructions to handle dates, defaults, and different query types reliably.</li><li><strong>API Quirks:</strong> Real-world APIs like Amadeus have specific requirements (IATA codes!), rate limits, sometimes complex responses, and occasional errors. Robust error handling is key.</li><li><strong>Ambiguity:</strong> Natural language is messy! “Next weekend” can mean different things. While the AI is good, sometimes it might misinterpret highly ambiguous queries.</li><li><strong>Cost:</strong> Calling OpenAI and Amadeus APIs isn’t free. For a real application, you’d need to manage usage and costs. (Though Amadeus has a generous free tier for testing).</li></ul><h3>Final Thoughts: Let’s Talk Tech in a Human Way!</h3><p>This project was a blast because it tackles a common annoyance using cool tech. It shows how we can leverage large language models not just for chatbots, but as powerful <strong>interpreters</strong> sitting between humans and complex systems. By translating natural language into structured API calls, we can create much more intuitive and powerful user experiences.</p><p>So, next time you’re fighting with a dropdown menu, remember: there might be a more conversational way just waiting to be built!</p><p>Thanks for following along with this exploration into natural language flight search! I hope seeing how these different technologies like AI and travel APIs can be combined inspires you to think about how you might tackle similar challenges or build your own creative applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20af47d743cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>