Implement a Conversational Flight Search and Booking Agent with Tool Calling
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Implement a conversational flight-reservation agent in Python (TOOLS and FlightAgent) that bridges a tool-calling language model and a three-endpoint JSON HTTP service.
In TOOLS, define three OpenAI-compatible function schemas ("type": "function", with "additionalProperties": False on each parameter object):
search_flights— requiresorigin(3-letter IATA airport string),destination(3-letter IATA airport string),departure_date(YYYY-MM-DDstring), andpassengers(integer>= 1).save_passenger— requires the five string fields inPASSENGER_FIELDS:first_name,last_name,email,phone, anddate_of_birth(YYYY-MM-DD).book_flight— requirespassenger_id(string) andflight_id(string), plus optionalseat_preference(string).
Backing HTTP Endpoints
When running live (FlightApi), every endpoint accepts POST JSON requests with an X-API-Key header (configured via OPENAI_API_KEY, OPENAI_BASE_URL, and FLIGHT_API_KEY environment variables). Inside FlightAgent, all network calls go through the injected post(path, body) callable:
POST /api/search_flight- Request payload:
{"origin": "BOS", "destination": "SEA", "departure_date": "2026-04-18", "passengers": 1} - Success payload:
{"success": true, "flights": [{"flight_id": "...", "flight_number": "...", "airline": "...", "departure_time": "...", "arrival_time": "...", "price": 219.5, "available": true}], "total_results": 12}
- Request payload:
POST /api/save_passenger_information- Request payload:
{"first_name": "...", "last_name": "...", "email": "...", "phone": "...", "date_of_birth": "YYYY-MM-DD"} - Success payload:
{"success": true, "passenger_id": "PAX-101", "message": "..."}
- Request payload:
POST /api/book_flight- Request payload:
{"passenger_id": "PAX-101", "flight_id": "FL20"}(include"seat_preference"only when a non-empty string is supplied) - Success payload:
{"success": true, "booking_id": "BK-901", "confirmation_code": "K9M4P2", "booking_details": {"pricing": {"total_price": 254.5}}}
- Request payload:
FlightAgent Behavior
FlightAgent(chat, post, confirm, max_rounds=6) receives three external callables — chat(messages, tools), post(path, body), and confirm(question) — and maintains session state across turns:
send(user_text): Appends{"role": "user", "content": user_text}toself.messages, then callsself.chat(self.messages, TOOLS)for at mostself.max_roundsiterations. Append every assistant dictionary returned byself.chattoself.messages. If the reply contains notool_calls, return its textcontent(or""ifNone). Otherwise, run each requested tool call in order and append{"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)}. Ifmax_roundscalls all request tools without producing a text reply, append a brief assistant apology message toself.messagesand return it.run_tool_call(call)&execute_function(name, arguments): Parsecall["function"]["arguments"]from JSON and dispatch tosearch_flights,save_passenger, orbook_flight. Never let an exception escaperun_tool_call: malformed JSON, non-object arguments, unknown tool names, invalid inputs, and transport errors must all return a dictionary containing"error".search_flights(args): Strip and uppercase airport codes; reject non-3-letter ASCII alphabetic codes, identicaloriginanddestination, invalid or non-YYYY-MM-DDcalendar dates, and invalid passenger counts (including booleans or integers< 1; default1). After posting to/api/search_flight, ifsuccessis falsey return the raw response; otherwise filter toavailableflights, sort ascending byprice, keep at mostMAX_FLIGHTS_SHOWN(5), record each kept flight inself.flights[flight_id], and return{"success": True, "total_results": <API total_results>, "available": <count of available flights>, "flights": <kept flights>}.save_passenger(args): Require non-empty stripped strings for all fivePASSENGER_FIELDS, validatedate_of_birthas a realYYYY-MM-DDdate, and verifyemailcontains non-empty text before and after"@". Post to/api/save_passenger_information; whensuccessandpassenger_idare returned, store the cleaned record inself.passengers[passenger_id]and return the response.book_flight(args):- Reject any
passenger_idnot stored inself.passengersorflight_idnot stored inself.flights(which excludes sold-out and unsearched flights) with{"error": ...}before prompting or making an HTTP call. - Prevent duplicate bookings per
(passenger_id, flight_id): if already confirmed inself.bookings, return{"success": True, "confirmation_code": <saved_code>, ...}without callingpost; if a prior attempt left the outcome unknown (None), return an error dictionary without callingpost. - Call
self.confirm(question)with a prompt naming the flight'sflight_numberand the traveler'sfirst_nameandlast_name. If declined, return{"success": False, "error": ...}without modifyingself.bookingsor callingpost. - Mark
self.bookings[(passenger_id, flight_id)] = Nonebefore callingself.post("/api/book_flight", body). Ifpostraises (for instance on a timeout), keepNonerecorded and return{"success": False, "error": ...}. If the response hassuccesstruthy, storeconfirmation_code; otherwise remove theNonemarker so future attempts are permitted.
- Reject any
Examples
Example 1
Input:
API flights for BOS -> SEA on 2026-04-18:
- FL10 (AS410, $285.00, available=True)
- FL20 (B618, $219.50, available=True)
- FL30 (UA77, $169.00, available=False)
Turn 1 user text:
"Fly from BOS to SEA on 2026-04-18 for 1 traveler"
Turn 2 user text:
"Book B618 with an aisle seat for Maya Lin, maya.lin@example.org, 12065550194, DOB 1993-08-22"
confirm(...) returns: True
Output:
Turn 1 return: "1. B618 $219.50 2. AS410 $285.00. Which flight would you like?"
Turn 2 return: "Reservation complete! Confirmation code: K9M4P2."
API calls made: ["/api/search_flight", "/api/save_passenger_information", "/api/book_flight"]
Walk-through: On Turn 1, search_flights filters out sold-out FL30, sorts the two open options cheapest-first (FL20 then FL10), and saves both IDs in self.flights. On Turn 2, the loop runs three model rounds inside a single send() call: Round 1 saves Maya's details (passenger_id = "PAX-101"), Round 2 verifies "PAX-101" and "FL20", gets True from confirm(), and posts /api/book_flight with "seat_preference": "aisle" to obtain "K9M4P2", and Round 3 returns the final confirmation text.
Example 2
Input:
Session already has passenger "PAX-101" and shown flights {"FL10", "FL20"} (sold-out "FL30" excluded).
1. run_tool_call: book_flight({"passenger_id": "PAX-101", "flight_id": "FL30"})
2. run_tool_call: book_flight({"passenger_id": "PAX-101", "flight_id": "FL10"}) -> post raises TimeoutError
3. run_tool_call: book_flight({"passenger_id": "PAX-101", "flight_id": "FL10"}) -> retried
Output:
Call 1: {"error": "..."} (0 API calls, 0 confirm prompts)
Call 2: {"success": False, "error": "..."} (1 API call to /api/book_flight)
Call 3: {"error": "..."} (still 1 API call total; retry blocked)
Walk-through: Call 1 fails Guard 1 because FL30 was unavailable and never stored in self.flights. Call 2 passes confirmation and marks ("PAX-101", "FL10") as None before post raises TimeoutError. Because the server may have completed the charge before timing out, Call 3 sees None in self.bookings and refuses to issue a second /api/book_flight request.
Constraints
- Use only the Python standard library inside
FlightAgentand its validation helpers (openaiandrequestsare imported lazily inside the live CLI adapters). - Every date (
departure_dateanddate_of_birth) must be a valid calendar date formatted strictly as10-characterYYYY-MM-DD(compact ISO strings such as"20260418"are invalid). passengersmust be an integer>= 1(boolvalues must be rejected).send()may invokeself.chatat mostmax_roundstimes per user message, passingTOOLSon every call, and must leaveself.messagesending with an"assistant"text message.
Step-by-step walkthrough
Understand how a tool-calling agent works (and clarify open rules)
A language model cannot open network sockets or call REST APIs on its own. Instead, tool calling works as a relay between two partners: the model reads the conversation and replies with either plain text for the user or a structured JSON request asking our Python program to run a named function; our Python program validates the inputs, calls the real flight API, and appends the JSON result back to the conversation so the model can decide its next step.
User terminal <--- plain text ---> FlightAgent (Python) <--- messages + TOOLS ---> LLM | v POST + X-API-Key Flight REST APIBefore writing code, state clear answers to the prompt's clarifying questions:
- Explicit confirmation before booking: Yes, enforced in Python code (
confirm(question)) right beforePOST /api/book_flight. Relying on a system prompt alone is unsafe because a model can skip instructions. - Multiple travelers:
search_flightsacceptspassengers >= 1, whereasbook_flightaccepts a singlepassenger_id, so a group trip saves each traveler separately and books them one by one. seat_preference: Optional string; include it in thebook_flightpayload only when provided.- Timeouts and retries: The API has no idempotency key, so
book_flightmust never auto-retry after a timeout or5xxerror. Instead, mark that(passenger_id, flight_id)pair as having an unknown outcome and block repeat attempts. - City names and relative dates: The model translates
"Boston"or"this Saturday"into 3-letter IATA codes ("BOS") andYYYY-MM-DDdates; we inject today's ISO date into the system prompt so relative dates resolve accurately. - Large search results: Filter out unavailable flights, sort by price, and return at most
MAX_FLIGHTS_SHOWN = 5flights alongsidetotal_resultsandavailablecounts so the user gets concise options and the chat history stays small.
To make the agent testable without live API keys,
FlightAgentaccepts its three external boundaries as callables:chat(messages, tools),post(path, body), andconfirm(question).- Explicit confirmation before booking: Yes, enforced in Python code (
Spot what the starter loop gets wrong
Suppose the user already searched flights and now sends one message containing everything needed to finish:
"Book B618 with an aisle seat for Maya Lin, maya.lin@example.org, 12065550194, DOB 1993-08-22."Finishing that turn requires two sequential tool calls (save_passengerto obtainpassenger_id, thenbook_flightusing that ID). Look at what a naive single-pass starter loop does instead:Naive single-pass trace: LLM call 1 (tools=TOOLS) -> tool_calls: [save_passenger(...)] Python runs save_passenger -> {"passenger_id": "PAX-101"} LLM call 2 (tools=None!) -> forced to reply in text without calling book_flight!Because a single
ifcheck instead of awhile/forloop — and omittingtools=TOOLSon the follow-up LLM call — drops tool access mid-turn, the model cannot chainsave_passengerintobook_flight. We also make three other clean improvements:- Define explicit schemas for
search_flights,save_passenger, andbook_flight. - Cap the inner loop with
max_rounds = 6so a confused model calling tools forever cannot hang the session or burn unlimited tokens. - Store plain Python
dictmessages inself.messagesinstead of SDK response objects so the history is easy to serialize, inspect, and assert on in tests.
- Define explicit schemas for
Define JSON-schema tools and session state
Each of the three REST endpoints becomes one function entry in
TOOLS. Setting"additionalProperties": Falseand documenting where IDs come from helps the model pass clean arguments:# Excerpt from TOOLS: the booking tool schema (search_flights and save_passenger follow the same pattern) BOOK_TOOL = { "type": "function", "function": { "name": "book_flight", "description": "Book one flight for one saved passenger. The user is asked to confirm first.", "parameters": { "type": "object", "properties": { "passenger_id": {"type": "string", "description": "passenger_id returned by save_passenger"}, "flight_id": {"type": "string", "description": "flight_id from a search_flights result"}, "seat_preference": {"type": "string", "description": "Optional, for example window or aisle"}, }, "required": ["passenger_id", "flight_id"], "additionalProperties": False, }, }, }Even with good descriptions, an LLM can still invent a plausible-looking ID like
"FL999"or try to book a sold-out flight.FlightAgent.__init__therefore keeps authoritative session state in three dictionaries:class FlightAgent: def __init__(self, chat, post, confirm, max_rounds: int = 6) -> None: self.chat = chat self.post = post self.confirm = confirm self.max_rounds = max_rounds today_str = date.today().isoformat() system_prompt = f"{SYSTEM_PROMPT}\nToday's date is {today_str}." # messages: ordered chat history of {"role": "system"|"user"|"assistant"|"tool", ...} dicts self.messages: List[Dict[str, Any]] = [{"role": "system", "content": system_prompt}] # flights: {flight_id: flight_dict} for available flights actually shown to the user self.flights: Dict[str, Dict[str, Any]] = {} # passengers: {passenger_id: passenger_dict} for travelers saved in this session self.passengers: Dict[str, Dict[str, Any]] = {} # bookings: {(passenger_id, flight_id): confirmation_code or None while request is in flight} self.bookings: Dict[Tuple[str, str], Optional[str]] = {}Build the multi-round conversation loop
When
send(user_text)runs, we append the user's message and enter a bounded loop of at mostself.max_roundsmodel calls:- Call
self.chat(self.messages, TOOLS)and immediately append the assistant's reply toself.messages. - If
replyhas notool_calls, the model is talking directly to the user — returnreply.get("content") or "". - Otherwise, execute every tool call in order and append one
{"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)}message per call before looping back to the model.
History after a 2-tool-call turn: [system] -> [user] -> [assistant: tool_calls=[c1, c2]] -> [tool: c1] -> [tool: c2] -> [assistant: text]Every
tool_call_idin an assistant message must be followed by a matchingrole="tool"message; otherwise the OpenAI-compatible API rejects the next request with a400error. And if allmax_roundsiterations ask for tools without producing final text, we append a short assistant apology after the last tool result so the history ends cleanly for the next user turn:def send(self, user_text: str) -> str: """Handle one user message: call the model, run its tools, repeat until it answers in text.""" self.messages.append({"role": "user", "content": user_text}) for _ in range(self.max_rounds): reply = self.chat(self.messages, TOOLS) self.messages.append(reply) tool_calls = reply.get("tool_calls") or [] if not tool_calls: return reply.get("content") or "" for call in tool_calls: result = self.run_tool_call(call) tool_message = { "role": "tool", "tool_call_id": call["id"], "content": json.dumps(result), } self.messages.append(tool_message) apology = "Sorry, I could not finish that. Could you rephrase it or tell me what to do next?" self.messages.append({"role": "assistant", "content": apology}) return apology- Call
Validate inputs and turn tool failures into error dicts
Because every
tool_call_idneeds a JSON answer,run_tool_callmust never raise an unhandled exception. Malformed JSON arguments, unknown tool names, invalid dates, and network failures are all caught and returned as{"error": ...}dictionaries so the model can read what went wrong and ask the user for a correction.We also validate airport codes,
YYYY-MM-DDdates, and passenger counts locally before touching the network. Notice two subtle Python traps handled by the helpers below:- In Python 3.11+,
date.fromisoformat()accepts compact strings like"20251115", so_iso_datecheckslen == 10and the two hyphens explicitly. - In Python,
boolis a subclass ofint(isinstance(True, int)isTrue), so_passenger_countrejects booleans first.
def _airport(value: Any) -> str: """Normalize and validate a 3-letter ASCII IATA airport code such as 'JFK'.""" if not isinstance(value, str): raise ValueError(f"expected a 3-letter airport code, got {value!r}") code = value.strip().upper() if len(code) != 3 or not code.isascii() or not code.isalpha(): raise ValueError(f"expected a 3-letter airport code, got {value!r}") return code def _iso_date(value: Any, field: str) -> str: """Validate that value is a real calendar date written strictly as YYYY-MM-DD.""" if not isinstance(value, str): raise ValueError(f"{field} must be a date as YYYY-MM-DD") cleaned = value.strip() if len(cleaned) != 10 or cleaned[4] != "-" or cleaned[7] != "-": raise ValueError(f"{field} must be a real date as YYYY-MM-DD, got {value!r}") try: return date.fromisoformat(cleaned).isoformat() except ValueError: raise ValueError(f"{field} must be a real date as YYYY-MM-DD, got {value!r}") def _passenger_count(value: Any) -> int: """Validate passenger count >= 1; reject bool because isinstance(True, int) is True in Python.""" if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"passengers must be a whole number of at least 1, got {value!r}") return value- In Python 3.11+,
Implement search, passenger save, and safe booking
Each endpoint method combines input validation, session memory, and safety checks:
search_flights: Upper-cases and validatesoriginanddestination, rejectsorigin == destination, calls/api/search_flight, filters toavailable == True, sorts by price ascending, keeps the topMAX_FLIGHTS_SHOWN = 5, and saves those 5 inself.flightsbyflight_id. Trimming 20 flights (~1,200 tokens) down to 5 (~300 tokens) saves ~900 tokens on every subsequent LLM call in the conversation.save_passenger: Strips and checks all fivePASSENGER_FIELDS, validatesdate_of_birthand basiclocal@domainemail shape, posts to/api/save_passenger_information, and recordsresult["passenger_id"]inself.passengers.book_flight: Runs four guards in strict order before sending/api/book_flight, and usesNoneinself.bookings[(passenger_id, flight_id)]as an in-flight lock:
State of self.bookings[(passenger_id, flight_id)]: not in bookings --(confirm == True)--> None (request in flight) | +-----------------------------+-----------------------------+ | | | API success=True API success=False Exception / timeout v v v "K9M4P2" (idempotent deleted from bookings stays None (future retries cached code on repeat) (safe to try again) blocked: outcome unknown!)Here is
book_flightshowing all four guards:def book_flight(self, args: Dict[str, Any]) -> Dict[str, Any]: passenger_id = args.get("passenger_id") flight_id = args.get("flight_id") if passenger_id not in self.passengers: return {"error": "Unknown passenger_id. Use the passenger_id returned by save_passenger."} if flight_id not in self.flights: return {"error": "Unknown flight_id. Use a flight_id from the search_flights result."} booking_key = (passenger_id, flight_id) if booking_key in self.bookings: saved_code = self.bookings[booking_key] if saved_code is None: return { "error": ( "An earlier attempt to book this passenger on this flight got no answer, " "so it may have gone through. Do not book again; ask the user to check " "their email or contact support." ) } return { "success": True, "confirmation_code": saved_code, "note": "Already booked in this session; no new booking was made.", } flight = self.flights[flight_id] passenger = self.passengers[passenger_id] question = ( f"Book {flight.get('flight_number')} ({flight.get('airline')}) departing " f"{flight.get('departure_time')} for {passenger['first_name']} {passenger['last_name']}, " f"price {flight.get('price')}?" ) if not self.confirm(question): return {"success": False, "error": "The user did not confirm the booking. Ask what to change."} body: Dict[str, Any] = {"passenger_id": passenger_id, "flight_id": flight_id} seat_pref = args.get("seat_preference") if isinstance(seat_pref, str) and seat_pref.strip(): body["seat_preference"] = seat_pref.strip() self.bookings[booking_key] = None try: result = self.post("/api/book_flight", body) except Exception as exc: return { "success": False, "error": ( f"The booking request failed ({exc}). It may or may not have gone through, " "so do not retry; ask the user to check their email or contact support." ), } if result.get("success"): self.bookings[booking_key] = result.get("confirmation_code", "") else: del self.bookings[booking_key] return resultTrace a full booking turn and wire the live adapters
Suppose Turn 1 searched BOS -> SEA on
2026-04-18and storedFL20(B618,$219.5) andFL10(AS410,$285.0) inself.flightswhile dropping sold-outFL30. Now on Turn 2 the user types:"Book B618 with an aisle seat for Maya Lin, maya.lin@example.org, 12065550194, DOB 1993-08-22":Round 1: chat(messages, TOOLS) -> tool_calls: [c2: save_passenger(Maya Lin, ...)] POST /api/save_passenger_information -> {"success": true, "passenger_id": "PAX-101"} self.passengers["PAX-101"] saved; tool message c2 appended Round 2: chat(messages, TOOLS) -> tool_calls: [c3: book_flight("PAX-101", "FL20", "aisle")] Guards: "PAX-101" in passengers? yes. "FL20" in flights? yes. ("PAX-101", "FL20") in bookings? no. confirm("Book B618 (Skyward Air) ... for Maya Lin, price 219.5?") -> True self.bookings[("PAX-101", "FL20")] = None POST /api/book_flight -> {"success": true, "confirmation_code": "K9M4P2"} self.bookings[("PAX-101", "FL20")] = "K9M4P2"; tool message c3 appended Round 3: chat(messages, TOOLS) -> content: "Reservation complete! Confirmation code: K9M4P2." No tool_calls -> send() returns the string to the terminalFinally,
OpenAIChatandFlightApiwrap the real libraries with lazy imports inside their methods so unit tests run cleanly in offline sandboxes withoutopenaiorrequestsinstalled. Notice howFlightApiseparates5xxresponses (raiseRuntimeErrorbecause the server may have committed the booking before crashing) from4xxresponses (return{"success": False, ...}because the request was rejected cleanly).Complete solution
from typing import Any, Dict, List, Optional, Tuple import json import os from datetime import date MODEL = "gpt-4.1" API_BASE_URL = "<flight API base URL provided in the round>" MAX_FLIGHTS_SHOWN = 5 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.""" SYSTEM_PROMPT = """You are a flight booking assistant in a terminal chat. 1. Get the origin, destination and date, then call search_flights. Use 3-letter IATA airport codes and YYYY-MM-DD dates. If a city has several airports, ask which one. 2. Show the flights from the tool result as a short numbered list (flight number, airline, departure and arrival time, price) and ask the user to pick one. 3. Get first name, last name, email, phone and date of birth, then call save_passenger. 4. Call book_flight with the passenger_id and flight_id that the tools returned. The app asks the user to confirm before the booking is made. 5. Tell the user the confirmation code. Use only flight_id and passenger_id values returned by a tool; never invent them. If a tool returns an error, explain it in one sentence and ask how to continue.""" PASSENGER_FIELDS = ("first_name", "last_name", "email", "phone", "date_of_birth") # TOOLS: JSON Schema definitions passed to the LLM on every turn so it knows # which Python functions exist and what exact argument shapes they accept. TOOLS: List[Dict[str, Any]] = [ { "type": "function", "function": { "name": "search_flights", "description": "Search flights on one date. Returns up to 5 available flights, cheapest first.", "parameters": { "type": "object", "properties": { "origin": {"type": "string", "description": "3-letter IATA code of the departure airport, e.g. BOS"}, "destination": {"type": "string", "description": "3-letter IATA code of the arrival airport, e.g. SEA"}, "departure_date": {"type": "string", "description": "Departure date as YYYY-MM-DD"}, "passengers": {"type": "integer", "minimum": 1, "description": "Number of travelers"}, }, "required": ["origin", "destination", "departure_date", "passengers"], # Reject invented extra keys so arguments match our Python handler. "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "save_passenger", "description": "Save one traveler's details. Returns the passenger_id needed by book_flight.", "parameters": { "type": "object", "properties": { "first_name": {"type": "string"}, "last_name": {"type": "string"}, "email": {"type": "string"}, "phone": {"type": "string", "description": "Digits only, with country code, e.g. 12065550194"}, "date_of_birth": {"type": "string", "description": "YYYY-MM-DD"}, }, "required": list(PASSENGER_FIELDS), "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "book_flight", "description": "Book one flight for one saved passenger. The user is asked to confirm first.", "parameters": { "type": "object", "properties": { "passenger_id": {"type": "string", "description": "passenger_id returned by save_passenger"}, "flight_id": {"type": "string", "description": "flight_id from a search_flights result"}, "seat_preference": {"type": "string", "description": "Optional, for example window or aisle"}, }, "required": ["passenger_id", "flight_id"], "additionalProperties": False, }, }, }, ] def _airport(value: Any) -> str: """Normalize and validate a 3-letter ASCII IATA airport code such as 'JFK'.""" if not isinstance(value, str): raise ValueError(f"expected a 3-letter airport code, got {value!r}") code = value.strip().upper() if len(code) != 3 or not code.isascii() or not code.isalpha(): raise ValueError(f"expected a 3-letter airport code, got {value!r}") return code def _iso_date(value: Any, field: str) -> str: """Validate that value is a real calendar date written strictly as YYYY-MM-DD.""" if not isinstance(value, str): raise ValueError(f"{field} must be a date as YYYY-MM-DD") cleaned = value.strip() # Check exact YYYY-MM-DD punctuation first because Python 3.11+ fromisoformat() # also accepts compact strings like '20251115' and week dates like '2025-W46-6'. if len(cleaned) != 10 or cleaned[4] != "-" or cleaned[7] != "-": raise ValueError(f"{field} must be a real date as YYYY-MM-DD, got {value!r}") try: return date.fromisoformat(cleaned).isoformat() except ValueError: raise ValueError(f"{field} must be a real date as YYYY-MM-DD, got {value!r}") def _passenger_count(value: Any) -> int: """Validate passenger count >= 1; reject bool because isinstance(True, int) is True in Python.""" if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"passengers must be a whole number of at least 1, got {value!r}") return value def _price(flight: Dict[str, Any]) -> float: """Sort key that places flights with missing prices at the end.""" return flight.get("price", float("inf")) class FlightAgent: """One chat session. The three outside dependencies are passed in so tests can use fakes: chat(messages, tools) -> the assistant message as a dict ("content", optional "tool_calls") post(path, body) -> the flight API's JSON answer as a dict; raises when no answer came back confirm(question) -> True when the user agrees """ def __init__(self, chat, post, confirm, max_rounds: int = 6) -> None: self.chat = chat self.post = post self.confirm = confirm self.max_rounds = max_rounds # Include today's date in the system prompt so relative phrases ("next Friday") resolve accurately. today_str = date.today().isoformat() system_prompt = f"{SYSTEM_PROMPT}\nToday's date is {today_str}." # messages: ordered chat history of {"role": "system"|"user"|"assistant"|"tool", ...} dicts self.messages: List[Dict[str, Any]] = [{"role": "system", "content": system_prompt}] # flights: {flight_id: flight_dict} for available flights actually shown to the user self.flights: Dict[str, Dict[str, Any]] = {} # passengers: {passenger_id: passenger_dict} for travelers saved in this session self.passengers: Dict[str, Dict[str, Any]] = {} # bookings: {(passenger_id, flight_id): confirmation_code or None while request is in flight} self.bookings: Dict[Tuple[str, str], Optional[str]] = {} def send(self, user_text: str) -> str: """Handle one user message: call the model, run its tools, repeat until it answers in text.""" self.messages.append({"role": "user", "content": user_text}) # Loop up to max_rounds so multi-step turns (e.g. save_passenger -> book_flight -> reply) # can complete inside one user turn without risking an infinite tool loop. for _ in range(self.max_rounds): reply = self.chat(self.messages, TOOLS) self.messages.append(reply) tool_calls = reply.get("tool_calls") or [] if not tool_calls: # No tool calls means the model produced its final plain-text answer for this turn. return reply.get("content") or "" # Every requested tool_call_id MUST receive a matching role="tool" message in order, # otherwise the next chat completions call will reject the conversation history. for call in tool_calls: result = self.run_tool_call(call) tool_message = { "role": "tool", "tool_call_id": call["id"], "content": json.dumps(result), } self.messages.append(tool_message) # If max_rounds expired while the model was still calling tools, close the turn with # an assistant text message so the history remains valid for the user's next message. apology = "Sorry, I could not finish that. Could you rephrase it or tell me what to do next?" self.messages.append({"role": "assistant", "content": apology}) return apology def run_tool_call(self, call: Dict[str, Any]) -> Dict[str, Any]: """Run one tool call. Never raises: every problem goes back to the model as {"error": ...}.""" func_spec = call.get("function") or {} name = func_spec.get("name", "") raw_arguments = func_spec.get("arguments") or "{}" # Phase 1: Parse the JSON string generated by the model into a Python dictionary. try: arguments = json.loads(raw_arguments) except (json.JSONDecodeError, TypeError): return {"error": "The arguments were not valid JSON. Call the tool again with a JSON object."} if not isinstance(arguments, dict): return {"error": "The arguments must be a JSON object."} # Phase 2: Dispatch to the tool handler and turn validation/network exceptions into data # so the model can apologize or ask the user to fix bad input instead of crashing the app. try: return self.execute_function(name, arguments) except Exception as exc: return {"error": f"{name} failed: {exc}"} def execute_function(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: """Dispatch a parsed tool call to the matching endpoint method.""" if name == "search_flights": return self.search_flights(arguments) if name == "save_passenger": return self.save_passenger(arguments) if name == "book_flight": return self.book_flight(arguments) return {"error": f"Unknown tool: {name}"} def search_flights(self, args: Dict[str, Any]) -> Dict[str, Any]: """Validate search inputs, query the API, and keep the cheapest available flights.""" origin = _airport(args.get("origin")) destination = _airport(args.get("destination")) if origin == destination: raise ValueError("origin and destination must be different airports") body = { "origin": origin, "destination": destination, "departure_date": _iso_date(args.get("departure_date"), "departure_date"), "passengers": _passenger_count(args.get("passengers", 1)), } result = self.post("/api/search_flight", body) if not result.get("success"): return result # Filter out sold-out flights and keep only the cheapest MAX_FLIGHTS_SHOWN options # so we do not bloat every future LLM call with dozens of irrelevant flights. available_flights = [] for flight in result.get("flights", []): if flight.get("available"): available_flights.append(flight) available_flights.sort(key=_price) shown_flights = available_flights[:MAX_FLIGHTS_SHOWN] # Record shown flight_ids so book_flight can reject hallucinated or unavailable flights. for flight in shown_flights: self.flights[flight["flight_id"]] = flight return { "success": True, "total_results": result.get("total_results", len(available_flights)), "available": len(available_flights), "flights": shown_flights, } def save_passenger(self, args: Dict[str, Any]) -> Dict[str, Any]: """Validate required traveler details, save them via the API, and store passenger_id.""" body: Dict[str, str] = {} for field in PASSENGER_FIELDS: value = args.get(field) if not isinstance(value, str) or not value.strip(): raise ValueError(f"{field} is required") body[field] = value.strip() body["date_of_birth"] = _iso_date(body["date_of_birth"], "date_of_birth") local_part, sep, domain_part = body["email"].partition("@") if not sep or not local_part or not domain_part: raise ValueError(f"email does not look valid: {body['email']!r}") result = self.post("/api/save_passenger_information", body) if result.get("success") and result.get("passenger_id"): self.passengers[result["passenger_id"]] = body return result def book_flight(self, args: Dict[str, Any]) -> Dict[str, Any]: """Verify IDs, guard against duplicate bookings, ask human confirmation, and book.""" passenger_id = args.get("passenger_id") flight_id = args.get("flight_id") # Guard 1: Reject hallucinated IDs or unavailable flights never shown in this session. if passenger_id not in self.passengers: return {"error": "Unknown passenger_id. Use the passenger_id returned by save_passenger."} if flight_id not in self.flights: return {"error": "Unknown flight_id. Use a flight_id from the search_flights result."} # Guard 2: Prevent double-booking the same (passenger_id, flight_id) pair. booking_key = (passenger_id, flight_id) if booking_key in self.bookings: saved_code = self.bookings[booking_key] if saved_code is None: # A previous request timed out or got a 5xx, so the server may have booked it. return { "error": ( "An earlier attempt to book this passenger on this flight got no answer, " "so it may have gone through. Do not book again; ask the user to check " "their email or contact support." ) } return { "success": True, "confirmation_code": saved_code, "note": "Already booked in this session; no new booking was made.", } # Guard 3: Ask the human user directly in code rather than trusting the LLM prompt alone. flight = self.flights[flight_id] passenger = self.passengers[passenger_id] question = ( f"Book {flight.get('flight_number')} ({flight.get('airline')}) departing " f"{flight.get('departure_time')} for {passenger['first_name']} {passenger['last_name']}, " f"price {flight.get('price')}?" ) if not self.confirm(question): return {"success": False, "error": "The user did not confirm the booking. Ask what to change."} body: Dict[str, Any] = {"passenger_id": passenger_id, "flight_id": flight_id} seat_pref = args.get("seat_preference") if isinstance(seat_pref, str) and seat_pref.strip(): body["seat_preference"] = seat_pref.strip() # Mark the pair as None ("outcome unknown") BEFORE sending the network request. # If self.post raises on a timeout, None stays in self.bookings to block blind retries. self.bookings[booking_key] = None try: result = self.post("/api/book_flight", body) except Exception as exc: return { "success": False, "error": ( f"The booking request failed ({exc}). It may or may not have gone through, " "so do not retry; ask the user to check their email or contact support." ), } if result.get("success"): self.bookings[booking_key] = result.get("confirmation_code", "") else: # The server explicitly answered that the booking did not happen, so allow future retries. del self.bookings[booking_key] return result # ----- Real connections, used only when this file is run as a script ----- class OpenAIChat: """chat(messages, tools) backed by the OpenAI-compatible endpoint.""" def __init__(self, model: str = MODEL) -> None: # Lazy import so offline unit tests run even if the openai package is not installed. from openai import OpenAI self.client = OpenAI( api_key=os.environ["OPENAI_API_KEY"], base_url=os.getenv("OPENAI_BASE_URL") or None, ) self.model = model def __call__(self, messages: List[Dict[str, Any]], tools: List[Dict[str, Any]]) -> Dict[str, Any]: response = self.client.chat.completions.create(model=self.model, messages=messages, tools=tools) message = response.choices[0].message # Convert SDK objects into plain JSON-serializable dicts for easy logging and testing. reply: Dict[str, Any] = {"role": "assistant", "content": message.content} if message.tool_calls: calls = [] for call in message.tool_calls: calls.append({ "id": call.id, "type": "function", "function": {"name": call.function.name, "arguments": call.function.arguments}, }) reply["tool_calls"] = calls return reply class FlightApi: """post(path, body) for the flight API.""" def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None: self.base_url = base_url.rstrip("/") self.headers = {"X-API-Key": api_key, "Content-Type": "application/json"} self.timeout = timeout def __call__(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]: # Lazy import so offline unit tests do not require requests. import requests response = requests.post( self.base_url + path, json=body, headers=self.headers, timeout=self.timeout, ) # 5xx means the server failed mid-flight (outcome unknown), so raise like a timeout. if response.status_code >= 500: raise RuntimeError(f"flight API answered {response.status_code}") # 4xx means the server rejected the request before booking, so return a clean failure dict. if response.status_code >= 400: return {"success": False, "status": response.status_code, "error": response.text[:500]} return response.json() def ask_terminal(question: str) -> bool: """Prompt the human operator in the terminal and accept only explicit yes answers.""" return input(f"{question} [y/N] ").strip().lower() in ("y", "yes") def run_agent() -> None: """Entry point for interactive terminal sessions.""" try: from dotenv import load_dotenv load_dotenv() except ImportError: pass agent = FlightAgent( OpenAIChat(), FlightApi(API_BASE_URL, os.environ["FLIGHT_API_KEY"]), ask_terminal, ) print(f"\n{WELCOME_MESSAGE}\n") while True: try: user_input = input("You: ").strip() except EOFError: break if user_input.lower() in ("quit", "exit"): break if not user_input: continue try: answer = agent.send(user_input) except Exception as exc: # Keep the interactive session alive if the LLM endpoint itself is temporarily unreachable. answer = f"Sorry, I could not reach the model: {exc}" print(f"\nAgent: {answer}\n") if __name__ == "__main__": run_agent()✅ Submit now — all tests should pass.
Intuition & how it works
Think of a travel desk clerk sitting between a customer and an airline computer terminal. The clerk — the large language model (LLM) — handles natural human phrasing ("Fly me from Boston to Seattle on April 18"), while the computer terminal — our Python FlightAgent — holds the API credentials, sends HTTP requests, and enforces strict safety rules like asking the customer to confirm before charging their card. They coordinate through tool calling (also called function calling): a protocol where the model outputs a structured JSON object naming a Python function and its arguments instead of plain text, waits for our code to run that function and return a JSON result, and repeats until it has a plain-text answer for the user. Each tool's expected inputs are described using JSON Schema, a standard dictionary format declaring argument names, types, and required fields.
Why does a naive single-pass loop fail in real conversations? Checking tool_calls only once per user message and forgetting to pass tools=TOOLS on the follow-up model call breaks any turn requiring two chained steps — such as saving traveler details to get a passenger_id and then calling book_flight with that ID — causing the turn to stall halfway or hallucinate a fake confirmation. Likewise, letting tool exceptions crash Python or trusting the system prompt alone to verify IDs, ask confirmation, or guard timeouts risks broken chat histories, invented flight IDs like "FL999", and duplicate charges.
Let's trace our two-turn sample session with 3 flights (FL10 at $285.00, FL20 at $219.50, and sold-out FL30 at $169.00):
Turn 1: User says "Fly from BOS to SEA on 2026-04-18 for 1 traveler"
Round 1: LLM requests search_flights(BOS, SEA, 2026-04-18, 1)
Code drops sold-out FL30, sorts by price -> [FL20 ($219.50), FL10 ($285.00)], saves both IDs
Round 2: LLM sees tool JSON -> replies "1. B618 $219.50 2. AS410 $285.00. Which flight would you like?"
Turn 2: User says "Book B618 with an aisle seat for Maya Lin, maya.lin@example.org, 12065550194, DOB 1993-08-22"
Round 1: LLM requests save_passenger(...) -> API returns "PAX-101"; code saves passengers["PAX-101"]
Round 2: LLM requests book_flight("PAX-101", "FL20", "aisle")
Code verifies "PAX-101" & "FL20" exist, prompts human [y/N] -> True, marks ("PAX-101","FL20")=None,
calls API -> stores confirmation_code "K9M4P2"
Round 3: LLM sees "K9M4P2" -> replies "Reservation complete! Confirmation code: K9M4P2."
Complexity
- Time per user message:
O(R * F log F)local CPU work plus at mostRmodel calls, whereR = max_rounds(6by default) andFis the number of flights returned by/api/search_flight. In each round we inspect the model's reply, and ifsearch_flightsruns we filter and sortFflights by price inO(F log F)time;save_passengerandbook_flightdoO(1)dictionary lookups and short string checks. - Token growth across
Tturns:O(T)per call andO(T^2)cumulative tokens unless history is trimmed, because every LLM call resends the entireself.messageslist inside the model's context window (the maximum number of input + output tokens the model can process in one request). For example, if each turn appends ~300 tokens, Turn 50 sends50 * 300 = 15,000tokens, and Turns 1 through 50 together transmit300 * (1 + 2 + ... + 50) = 382,500history tokens. - Space:
O(H + S), whereHis the total number of messages stored inself.messagesandSis the number of shown flights, saved passengers, and booking records kept inself.flights,self.passengers, andself.bookingsduring the session.
Edge cases
- Chained tool calls in one user turn (
save_passengerthenbook_flight): Thefor _ in range(self.max_rounds)loop passesTOOLSon every round so the model can use the newly returnedpassenger_idimmediately. - Parallel tool calls in one assistant message (e.g., comparing BOS -> SEA and BOS -> PDX): The inner
for call in tool_callsloop executes every call in order and appends a matchingrole="tool"message for eachtool_call_id. - Save and book emitted in the exact same assistant message: Because
passenger_iddid not exist when the model generated the batch,book_flightsafely rejects the guessed ID with{"error": ...}, and the model retries in the next round using the real ID fromsave_passenger. - Invalid JSON, unknown tool names, bad dates (
18/04/2026), or city names ("Boston"): Caught insiderun_tool_calland returned as{"error": ...}without hitting the flight API or crashing the terminal loop. - Invented or sold-out flight IDs (
"FL999"orFL30): Rejected by checkingflight_id in self.flightsbefore prompting the user or calling/api/book_flight. - User declines
[y/N]confirmation: Returns{"success": False, "error": ...}without modifyingself.bookingsor calling the API, so the user can pick another flight. - Booking network timeout or
5xxerror:self.bookings[(passenger_id, flight_id)]remainsNone, blocking any automatic or manual retry in the session because the charge may already have succeeded on the server. - Duplicate booking after a confirmed success: Returns the cached
confirmation_codeimmediately without making a secondPOST /api/book_flightcall. - Runaway tool loop: Cut off after
max_roundscalls with a synthetic assistant apology soself.messagesnever ends on an unanswered state.
Common mistakes
- Omitting
tools=TOOLSafter the first tool execution: Forces the model into text-only mode mid-turn so multi-step workflows stall or hallucinate results. - Skipping a
role="tool"reply when one of several parallel calls fails: OpenAI-compatible chat endpoints reject the entire next request if anytool_call_idlacks a matching tool message. - Letting
json.loadsorrequestsexceptions crash the process: Tool failures are normal conversational events and should become{"error": ...}payloads for the model. - Trusting the system prompt alone for confirmation or ID validation: Prompt instructions are advisory; irreversible side effects like charging money must be gated in deterministic Python code.
- Auto-retrying
POST /api/book_flighton timeout: Without server-side deduplication, retrying a timed-out booking request can buy two tickets. - Dumping dozens of raw flights into the tool result: Wastes thousands of tokens across the session and overwhelms the user in terminal chat.
- Forgetting today's date in the system prompt: Leaves the model guessing the year or weekday when the user says
"this Saturday".
Follow-up questions
- If a reservation request times out before a response arrives, how can you prevent duplicate ticket purchases on retry? A timeout leaves the outcome uncertain: the server may have committed the reservation right before the response dropped. Because this HTTP service provides no idempotency key — a unique client-generated token (such as a UUID in an
Idempotency-Keyheader) that lets the server deduplicate retries and return the original confirmation code — our agent storesNoneinself.bookings[(passenger_id, flight_id)]before callingpostand blocks subsequent attempts for that pair. In production, persist that pending marker to durable storage before issuing the network call so process restarts preserve the lock, and extend the backend with eitherIdempotency-Keysupport onPOST /api/book_flightor a status-lookup endpoint (GET /api/bookings?passenger_id=...) to reconcile in-doubt bookings. - How can you run deterministic automated tests on the agent offline without hitting live LLM or airline endpoints? Use dependency injection — passing external collaborators (
chat,post, andconfirm) intoFlightAgent.__init__instead of hard-coding SDK clients inside business methods. Unit tests supply aFakeModelthat pops scripted assistant dictionaries and records every(messages, tools)snapshot, aFakeApithat returns canned flights or raisesTimeoutError, and a stubconfirmcallable. That allows fast, deterministic offline tests for chained tool turns, parallel tool calls, malformed JSON/date inputs, human confirmation refusals, and timeout locks, complemented by a small separate live-eval suite for prompt adherence. - What changes are needed to reserve a single flight for two travelers together? Pass
passengers: 2tosearch_flightsso only flights with at least two open seats qualify, callsave_passengeronce per person to obtain[passenger_id_1, passenger_id_2], and expose a group-booking toolbook_flight(flight_id, passenger_ids, seat_preferences)that prompts the human once naming both travelers and the combined fare. BecausePOST /api/book_flightbooks onepassenger_idper request, the operation lacks atomicity (an all-or-nothing guarantee where either both seats are booked or neither is): if the first call succeeds and the second fails, return both the first traveler'sconfirmation_codeand the error on the second so the user can resolve the partial reservation with support rather than losing track of the confirmed ticket. - How can you bound message history memory and token usage during a long multi-turn chat session? Since
self.flights,self.passengers, andself.bookingsalready live in structured Python dictionaries, old chat messages can be dropped while retainingmessages[0](the system prompt, optionally refreshed with active passenger and flight IDs) plus the newestmax_messages - 1entries. Always advance the cut point forward to a"user"message boundary so you never split an"assistant"tool_callsmessage from its matching"tool"replies, which OpenAI-compatible servers reject:
python
def trim_history(messages, max_messages):
"""Keep messages[0] (system prompt) plus the newest turns starting cleanly at a user message."""
if len(messages) <= max_messages:
return messages
start = len(messages) - (max_messages - 1)
while start < len(messages) and messages[start]["role"] != "user":
start += 1
return [messages[0]] + messages[start:]
Follow-up questions
- If a reservation request times out before a response arrives, how can you prevent duplicate ticket purchases on retry?
- How can you run deterministic automated tests on the agent offline without hitting live LLM or airline endpoints?
- What changes are needed to reserve a single flight for two travelers together?
- How can you bound message history memory and token usage during a long multi-turn chat session?
Similar questions
- In-Memory Feature Flag Rule Evaluator
- Dynamic Task Router with Least-Loaded Tie Rotation
- Locate Files Across a Directory Hierarchy and Return Absolute Paths
- Remaining Grid Leaves After Wind Shifts
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents
- Greedy and Beam-Search Token Sequence Decoding
More Cresta interview questions
- Dynamic Task Router with Least-Loaded Tie Rotation Medium
- Remaining Grid Leaves After Wind Shifts Medium
- In-Memory Feature Flag Rule Evaluator Medium Pro
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents Medium Pro
- Longest Suffix-to-Prefix String Overlap Medium Pro
- Asynchronous Video Walkthrough of a Past AI System Medium Pro
- Locate Files Across a Directory Hierarchy and Return Absolute Paths Medium Pro
- Greedy and Beam-Search Token Sequence Decoding Medium Pro
- Taking a Validated Prototype to Production Easy Pro