KatInterview

Build a Flight Booking Chat Agent with LLM Tool Calling

System DesignModel answer
MediumModel answerSystem DesignLLMtool-callingREST API

Last updated

Extend a Python starter script into a terminal chat agent that uses LLM function calling to search flights, register a passenger, and confirm a booking via a three-endpoint REST API.

Flight Booking Chat Agent

You are given two files: api.md, which documents a flight booking REST API, and agent_starter.py, a partial Python script with the conversation loop already scaffolded. Your task is to complete the script so that a user can describe a trip in plain English, browse available flights, and walk away with a confirmed booking — all through a terminal chat.

The project runs locally. Load credentials from environment variables; never hard-code them. Three variables are provided: OPENAI_API_KEY, OPENAI_BASE_URL, and FLIGHT_API_KEY.


The Flight API

All three endpoints accept POST requests with JSON bodies and require these headers:

{"X-API-Key": "<FLIGHT_API_KEY>", "Content-Type": "application/json"}

Register a passenger — POST /api/save_passenger_information

Request:

{
  "first_name": "Jane",
  "last_name": "Smith",
  "email": "[email protected]",
  "phone": "15559876543",
  "date_of_birth": "1988-03-22"
}

Response — store the passenger_id:

{
  "success": true,
  "passenger_id": "550e8400-e29b-41d4-a716-446655440001",
  "message": "Passenger information saved successfully"
}

Search flights — POST /api/search_flight

Request:

{"origin": "JFK", "destination": "LAX", "departure_date": "2025-11-15", "passengers": 1}

Response — store the flight_id of whichever flight the user picks:

{
  "success": true,
  "flights": [
    {
      "flight_id": "FLABCD1234",
      "flight_number": "AA123",
      "airline": "American Airlines",
      "departure_time": "2025-11-15T08:00:00",
      "arrival_time": "2025-11-15T11:30:00",
      "price": 299.99,
      "available": true
    }
  ],
  "total_results": 20
}

Book a flight — POST /api/book_flight

Uses the IDs returned by the two previous calls:

{
  "passenger_id": "550e8400-e29b-41d4-a716-446655440001",
  "flight_id": "FLABCD1234",
  "seat_preference": "window"
}

Response — surface the confirmation_code to the user:

{
  "success": true,
  "booking_id": "660e8400-e29b-41d4-a716-446655440001",
  "confirmation_code": "A7B3C9",
  "booking_details": {"pricing": {"total_price": 344.99}}
}

The Starter Script

#!/usr/bin/env python3
"""Flight Booking Agent Starter Template"""
import os
import json
import requests
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
FLIGHT_API_KEY = os.getenv("FLIGHT_API_KEY", "")
API_BASE_URL = "<flight API base URL provided in the round>"

client = OpenAI(api_key=OPENAI_API_KEY)

SYSTEM_PROMPT = "You are a helpful flight booking assistant."

WELCOME_MESSAGE = """Welcome to the Flight Booking Agent!
I can help you book flights. Just tell me where you'd like to go.
Type 'quit' to exit."""

# Replace the placeholder tool with the real ones
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name or zip code"},
                    "units": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
                "additionalProperties": False,
            },
        },
    }
]

def execute_function(function_name: str, arguments: dict) -> dict:
    """Execute API calls based on function name"""
    return {"error": "Not implemented"}

def run_agent():
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    print(f"\n{WELCOME_MESSAGE}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in ["quit", "exit"]:
            break
        if not user_input:
            continue

        messages.append({"role": "user", "content": user_input})

        response = client.chat.completions.create(
            model="gpt-4.1",
            messages=messages,
            tools=TOOLS if TOOLS else None,
        )
        assistant_message = response.choices[0].message

        if assistant_message.tool_calls:
            messages.append(assistant_message)
            for tool_call in assistant_message.tool_calls:
                result = execute_function(
                    tool_call.function.name,
                    json.loads(tool_call.function.arguments),
                )
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "name": tool_call.function.name,
                    "content": json.dumps(result),
                })

            response = client.chat.completions.create(
                model="gpt-4.1",
                messages=messages,
            )
            assistant_message = response.choices[0].message

        messages.append(assistant_message)
        print(f"\nAgent: {assistant_message.content}\n")

if __name__ == "__main__":
    run_agent()

What to build

Turn the starter into a working agent. A complete session looks like this:

  1. User describes a trip in plain language ("I want to fly from New York to LA on November 15th for one person").
  2. Agent searches for flights and presents the options clearly.
  3. User picks a flight.
  4. Agent collects the passenger's name, email, phone, and date of birth.
  5. Agent asks for a seat preference.
  6. Agent explicitly confirms the booking details with the user before charging anything.
  7. Agent completes the booking and reads back the confirmation code and total price.

Constraints

  • Python only; all secrets come from environment variables.
  • The three flight endpoints are the only external calls for booking logic. Do not invent additional endpoints.
  • Use the OpenAI-compatible endpoint and tool/function calling — do not implement intent detection by hand.
  • The tool loop within a single user turn must have a finite upper bound on iterations.

Questions worth thinking through before you start

  • At what point in the conversation should the agent call book_flight, and what explicit signal should it require from the user first?
  • The search endpoint accepts a passenger count, but booking takes a single passenger_id. What does that mean for multi-passenger trips?
  • What happens if the LLM hallucinates a flight_id that was never returned by the search call?
  • How should the agent handle an HTTP error or a "success": false response body?
  • If a user says "next Friday" instead of "2025-11-21", whose job is it to resolve that?

Hints

Hint 1

Define three tool schemas that mirror the API fields exactly — the LLM will only pass arguments it can infer from the schema descriptions, so be specific about formats like IATA codes and ISO 8601 dates.

Hint 2

Track state (passenger_id, flight_id, confirmation_code) in a small Python dict rather than trusting the LLM to remember them across turns; validate that IDs in booking calls actually came from prior API responses.

Hint 3

Wrap the tool-calling loop in a for/while with a hard cap (e.g., 10 iterations) and require the agent to echo back flight details and price before you call book_flight — never let the model trigger a booking without an explicit user confirmation step.