Build a Flight Booking Chat Agent with LLM Tool Calling
System DesignModel answerLast 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:
- User describes a trip in plain language ("I want to fly from New York to LA on November 15th for one person").
- Agent searches for flights and presents the options clearly.
- User picks a flight.
- Agent collects the passenger's name, email, phone, and date of birth.
- Agent asks for a seat preference.
- Agent explicitly confirms the booking details with the user before charging anything.
- 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_idthat was never returned by the search call? - How should the agent handle an HTTP error or a
"success": falseresponse 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The agent has three layers to get right: tool schemas that give the LLM enough context to call the API correctly, a dispatch layer that authenticates and handles errors, and a conversation loop that manages state, enforces confirmation before booking, and caps the number of tool calls per turn.
1. Tool schemas
Replace the placeholder get_weather tool with three schemas. The descriptions do a lot of work — the model infers when to call each tool and how to populate arguments from them.
Key points per tool:
search_flights:originanddestinationare IATA airport codes (3-letter, uppercase). The system prompt should instruct the model to resolve city names to codes before calling.departure_dateisYYYY-MM-DD; the model should also resolve relative dates like "next Friday" to an absolute date using its knowledge of today's date (or ask the user to confirm).save_passenger: All five fields are required. Describedate_of_birthasYYYY-MM-DDexplicitly — without that, the model may produce a localized format.book_flight: Markpassenger_idandflight_idas required. Keepseat_preferenceoptional with an enum (window,aisle,middle) so the model doesn't hallucinate values.
TOOLS = [
{
"type": "function",
"function": {
"name": "search_flights",
"description": "Search available flights. origin and destination must be 3-letter IATA airport codes (e.g. JFK, LAX). departure_date must be YYYY-MM-DD.",
"parameters": {
"type": "object",
"properties": {
"origin": {"type": "string", "description": "Departure airport IATA code"},
"destination": {"type": "string", "description": "Arrival airport IATA code"},
"departure_date": {"type": "string", "description": "Date in YYYY-MM-DD format"},
"passengers": {"type": "integer", "description": "Number of passengers", "default": 1},
},
"required": ["origin", "destination", "departure_date"],
"additionalProperties": False,
},
},
},
{
"type": "function",
"function": {
"name": "save_passenger",
"description": "Register a passenger and get a passenger_id for booking.",
"parameters": {
"type": "object",
"properties": {
"first_name": {"type": "string"},
"last_name": {"type": "string"},
"email": {"type": "string"},
"phone": {"type": "string", "description": "Digits only, e.g. 15551234567"},
"date_of_birth": {"type": "string", "description": "YYYY-MM-DD"},
},
"required": ["first_name", "last_name", "email", "phone", "date_of_birth"],
"additionalProperties": False,
},
},
},
{
"type": "function",
"function": {
"name": "book_flight",
"description": "Book a flight. Only call this after the user has explicitly confirmed they want to proceed. Requires a passenger_id from save_passenger and a flight_id from search_flights.",
"parameters": {
"type": "object",
"properties": {
"passenger_id": {"type": "string"},
"flight_id": {"type": "string"},
"seat_preference": {"type": "string", "enum": ["window", "aisle", "middle"]},
},
"required": ["passenger_id", "flight_id"],
"additionalProperties": False,
},
},
},
]
2. State tracking and ID validation
The model can hallucinate IDs. Keep a small state dict and reject any booking call whose IDs don't match what the API actually returned:
state = {
"passenger_id": None,
"valid_flight_ids": set(),
"booking_confirmed": False,
}
In execute_function, update state["passenger_id"] when save_passenger succeeds, and add every flight_id from a search response to state["valid_flight_ids"]. Before calling book_flight, check both:
if args["flight_id"] not in state["valid_flight_ids"]:
return {"error": "flight_id was not returned by a prior search. Ask the user to search again."}
if args["passenger_id"] != state["passenger_id"]:
return {"error": "passenger_id does not match the registered passenger."}
This turns a silent data-integrity bug into an error message the model can relay to the user.
3. The dispatch layer
HEADERS = {"X-API-Key": FLIGHT_API_KEY, "Content-Type": "application/json"}
def call_api(path: str, body: dict) -> dict:
try:
r = requests.post(f"{API_BASE_URL}{path}", json=body, headers=HEADERS, timeout=10)
r.raise_for_status()
return r.json()
except requests.exceptions.Timeout:
return {"error": "Request timed out. Please try again."}
except requests.exceptions.HTTPError as e:
return {"error": f"HTTP {e.response.status_code}: {e.response.text}"}
except Exception as e:
return {"error": str(e)}
def execute_function(name: str, args: dict) -> dict:
if name == "search_flights":
result = call_api("/api/search_flight", args)
if result.get("success"):
for f in result.get("flights", []):
state["valid_flight_ids"].add(f["flight_id"])
return result
if name == "save_passenger":
result = call_api("/api/save_passenger_information", args)
if result.get("success"):
state["passenger_id"] = result["passenger_id"]
return result
if name == "book_flight":
if args.get("flight_id") not in state["valid_flight_ids"]:
return {"error": "Unknown flight_id. Please search for flights first."}
if args.get("passenger_id") != state["passenger_id"]:
return {"error": "passenger_id mismatch. Register the passenger first."}
if state["booking_confirmed"]:
return {"error": "A booking has already been made this session."}
result = call_api("/api/book_flight", args)
if result.get("success"):
state["booking_confirmed"] = True
return result
return {"error": f"Unknown function: {name}"}
4. The conversation loop
Two additions beyond the starter: a step cap per turn (prevents runaway tool chains), and a confirmation guard baked into the system prompt.
SYSTEM_PROMPT = """You are a flight booking assistant.
- Resolve city names to IATA codes and relative dates to YYYY-MM-DD before calling any tool.
- After searching, show flights in a numbered list with airline, times, and price.
- Collect all passenger details before calling save_passenger.
- Before calling book_flight, summarize the flight, total price, and passenger name,
then ask the user to confirm with yes/no. Only proceed on an explicit yes.
- After booking, read back the confirmation code and total price.
"""
The loop itself gains a step counter:
MAX_TOOL_STEPS = 10
# inside the while True loop, replace the tool-call block:
step = 0
while assistant_message.tool_calls and step < MAX_TOOL_STEPS:
step += 1
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, tools=TOOLS
)
assistant_message = response.choices[0].message
Common mistakes
- Letting the model trigger booking without confirmation. Mentioning it in the system prompt is necessary but not sufficient — the ID-validation guard in
execute_functionis the hard backstop. - Not capping the tool loop. A misbehaving model or a persistent API error can produce an infinite retry cycle.
- Missing the
toolrole message. Everytool_callin the assistant message must be paired with arole: toolreply before the next LLM call, or the API returns a validation error. - Assuming
total_resultsequalslen(flights). The API paginates; surface only the returned batch and let the user ask for more. - Multi-passenger bookings. The booking endpoint takes a single
passenger_id. For groups, you'd need onesave_passenger+ onebook_flightcall per traveler — clarify this constraint with the user upfront rather than silently booking only one seat.