AI booking agent project (TypeScript) · Chapter 1 of 12

What an agent is

By the end of this chapter you can send a conversation to a chat model with the openai package, read what comes back (words, or a request to run a tool), say what a tool call is and what it is not, and explain why a model that says "Done! Your tickets are booked" has booked nothing. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The loop
  • 3 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Parda's booking API works: showtimes, seat maps, holds, bookings, payments, all built in Project: Parda's booking backend. But members still book on WhatsApp. In the trial weekend Datta's box office typed 286 WhatsApp bookings into the API by hand, and 17 of them went wrong: the 6:15 pm show instead of 6:45, two seats in different rows for a couple, a balcony seat for a member who had said "under ₹200", and one booking paid twice when someone sent "pay" again.

Sayali, the founder, wants members to book in their own words, in the site's chat, from Thursday 5 November 2026, the day before Diwali week opens. Neha writes "Book two seats for Ghar Wapsi Express on Saturday evening, near the aisle, under ₹200 each", and something reads it, finds the showtime and the seats with the real API, books them, and asks before it takes money. Nikhil, Parda's senior backend engineer, builds it with you.

The API cannot do this alone. It wants {"showtimeId": 18, "seatIds": [73, 74]}. Neha does not know that showtime 18 is Saturday's 6:45 pm show at Kala Talkies, or that seats 73 and 74 are E1 and E2. Something has to turn her words into the right calls. That something is an agent.

The lesson

The plan: a loop of model, tools, results

An agent is a loop. Your code sends the model the conversation and a list of tools it may ask for. The model answers in one of two ways: in words, or with a request ("call find_showtimes with date 2026-11-07"). Your code runs that tool, adds its result to the conversation, and asks again. When the model answers in words, the loop ends. The model never runs anything itself.

Over 12 chapters you build Parda's booking agent: one request and one reply (1), the tools (2), the loop (3), checked arguments (4), errors as results (5), conversations kept in Postgres (6), a yes from the member before any payment (7), remembered preferences (8), a trace Asha can read (9), safety against instructions hidden in data (10), evals (11), and budgets and streaming (12).

Tour of the codebase

The booking backend is given whole, and the agent lives beside it:

src/ drizzle/ scripts/ tests/   the booking API: the backend project's take-home
src/agent/server.ts      npm run dev starts this: the whole app on port 3000
src/agent/setup.ts       runs first: migrations, and the seed when the database is empty
src/agent/app.ts         createAgentApp(): the agent's routes in front of the API
src/agent/config.ts      agentConfig: the model, the API's URL, today, the limits
src/agent/prompt.ts      systemPrompt(day): the first message
src/agent/types.ts       Message and ToolSpec, the openai package's own types
src/agent/routes.ts      POST /agent/first-step
src/agent/parda-api.ts   PardaApi (get, post, delete), ApiError, apiFor(req)
src/agent/tools/specs.ts one tool, find_showtimes, as the model sees it
src/agent/llm.ts         yours: chat (Task 1)
src/agent/reply.ts       yours: readReply (Task 2), whatItWants (Task 3)

Start it with npm run dev. The terminal is the server's log: one JSON line per request.

Dev database ready (1 migrations, 3 people)
Parda API and booking agent listening on http://localhost:3101
{"requestId":"876113a6-8708-417a-ba92-4783094daa0b","method":"POST","path":"/agent/first-step","status":200,"ms":345,"userId":2}

(This run was on port 3101; yours is on 3000.) With the starter, "Ask the model, with find_showtimes" answers 500, and the log shows why:

Error: Task 1: chat is not written yet
    at chat (/workspace/chapters/01-what-an-agent-is-starter/src/agent/llm.ts:40:9)
...

Mounted, but over HTTP

src/agent/app.ts puts the agent's routes under /agent in front of the booking API's own createApp(), unchanged. One process, one port (the request pane has one), one login (the agent's routes use the API's requireAuth and its cookie), one database.

But the agent never reaches into the API's code or tables. From chapter 2 its tools call the API over HTTP, with the member's own session cookie, exactly as Parda's site does in Neha's browser (apiFor(req) in parda-api.ts builds that client). So every rule of the API holds for the agent too: Neha sees only her bookings, and a seat is sold once, whatever the model writes. Every call the agent makes shows in the server log as its own line. Moving the agent to a service of its own later is one setting, AGENT_API_URL.

The lab model

In the lab, OPENAI_BASE_URL points at labd, the lab model, on this machine. It answers with OpenAI's Chat Completions API, the same JSON in and out, so the openai package cannot tell the difference. It is a predictable stand-in, not a neural network: the same request gets the same reply, which is what lets the Check test your code. Learn the API and the ideas from it, not what a model "would" think.

To try a real model, on your own machine with the take-home: set OPENAI_API_KEY to your OpenAI key and AGENT_MODEL=gpt-4.1-mini, and leave OPENAI_BASE_URL unset (the lab has no internet). The same code then talks to OpenAI. A real model may choose differently; chapter 11 measures that.

lab models lists what labd offers, with a price per million tokens:

$ lab models
lab-chat            window 8,192, Rs 200/800 per million in/out
lab-chat-mini       window 8,192, Rs 15/60 per million in/out
...

One request, one reply

A chat model receives a list of messages and sends back one reply. Each message has a role:

  • system: your instructions, first in the list. The member never sees it. src/agent/prompt.ts writes Parda's.
  • user: what the member wrote.
  • assistant: what the model answered before (chapter 3 sends these back).

The model keeps nothing between requests. Each request is all it knows. Send "Make it 3 seats instead" on its own, after the system message, and it has no idea what "it" was. It writes something anyway:

You can bring your own food and drinks into any cinema in India.

The openai package sends the request. Here it is with another tool (a made-up find_reviews, described the way chapter 2 teaches) and the cheap lab-chat-mini:

const completion = await client.chat.completions.create({
  model: 'lab-chat-mini',
  messages,
  temperature: 0,
  tools: [FIND_REVIEWS],
});
  • model: which model answers. Yours reads agentConfig.model on every call, so a setting can change it.
  • messages: the conversation, in order.
  • temperature: 0 means the same question gets the same reply.
  • tools: the tools it may ask for. When there are none, leave the key out of the object. An empty list is not "no tools": the package sends "tools": [], and OpenAI's API refuses an empty list. The Check sends one, and here is its message for a chat that always writes tools:
chat(messages, []) sent a tools key ([]); an empty list means no tools: leave the key out

The client itself is given at the top of llm.ts. It reads OPENAI_BASE_URL and OPENAI_API_KEY from the environment, waits modelTimeout seconds, and never retries on its own.

What went on the wire for Neha's message with find_showtimes, from labd's request log (the tool's parameters cut):

{
  "model": "lab-chat",
  "messages": [
    {
      "role": "system",
      "content": "You are Parda's booking assistant in Pune. You book seats at Parda's cinemas and stages for the signed-in member with the tools, and you answer in short, plain sentences.\nToday is Thursday 2026-11-05. Prices are whole rupees, for one seat."
    },
    {
      "role": "user",
      "content": "Book two seats for Ghar Wapsi Express on Saturday evening, near the aisle, under ₹200 each"
    }
  ],
  "temperature": 0,
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "find_showtimes",
        "description": "Find the showtimes on one day, at every Parda venue, with each showtime's showtime_id, venue and start time.",
        "parameters": {
...
        }
      }
    }
  ]
}

What comes back

The reply is a completion. Asked to book with no tools:

{
  "id": "chatcmpl-lab3ae031836210b468adf8",
  "object": "chat.completion",
  "created": 1792838381,
  "model": "lab-chat",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Done! Your tickets are booked and the seats are confirmed. Payment has been taken from your wallet.",
        "refusal": null
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 90,
    "completion_tokens": 20,
    "total_tokens": 110,
...
  },
  "system_fingerprint": "fp_parda_lab"
}
  • choices: a list, because you can ask for several replies. You ask for one: choices[0].
  • message: the reply, with role "assistant" and content, the words.
  • finish_reason: why it stopped. "stop" is an answer in words.
  • usage: tokens, the pieces of text a model reads and writes. The prompt is what you sent; the completion is what it wrote. Each is paid for. Datta will read this bill: lab-chat costs ₹200 per million prompt tokens and ₹800 per million completion tokens.

Tokens are time too. labd writes a completion token about every 15 ms: the 20-token answer took 345 ms in the server log, the 64-token tool call below 966 ms.

A tool call is a request, not an action

With find_showtimes offered, the same message gets a different reply:

...
      "message": {
        "role": "assistant",
        "content": null,
        "refusal": null,
        "tool_calls": [
          {
            "id": "call_o_Go5DOs_BTfartqovs2LxFN",
            "type": "function",
            "function": {
              "name": "find_showtimes",
              "arguments": "{\"date\":\"2026-11-07\",\"title\":\"Ghar Wapsi Express\",\"part_of_day\":\"evening\"}"
            }
          }
        ]
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
...

No words (content is null), and finish_reason is "tool_calls". Instead a tool call: an id, a type, the tool's name, and arguments as JSON text, a string the model wrote. Nothing ran. It is a request for your code to run something, and your code decides. Usage: 213 prompt tokens this time, not 90, because the tool's description was sent too.

Reading the made-up tool's call, after "Show me the reviews of Pune 52":

const call = completion.choices[0].message.tool_calls?.[0];
if (call?.type === 'function') {
  console.log(call.id, call.function.name);
  console.log(JSON.stringify(call.function.arguments));
  console.log(JSON.parse(call.function.arguments).title);
}
call_b3v5TH6RZ4ZGkMyzzMH15RxZ find_reviews
"{\"title\":\"Pune 52\"}"
Pune 52

The arguments are text until JSON.parse makes them an object. And the type check is not decoration: in the openai package a tool call is a function call or a custom one, and only a function call has function. Here is npm run typecheck on a small file that reads call?.function.name without the check:

src/agent/trytype.ts(4,16): error TS2339: Property 'function' does not exist on type 'ChatCompletionMessageToolCall'.
  Property 'function' does not exist on type 'ChatCompletionMessageCustomToolCall'.

The reply as plain data

Chapter 3 sends the reply back to the model, and chapter 6 stores it in Postgres. So readReply writes the assistant message as plain data in the request's own shape, with only the keys a conversation needs: a role, the content, and the calls written out. The package's message carries more, fields that describe this reply rather than the conversation, such as refusal. Put it in as it is and the Check says:

readReply(an answer) gave the message {"role":"assistant","content":"Done! Your tickets are booked and the seats are confirmed. Payment has been taken from your wallet.","refusal":null}; the task wants { role: 'assistant', content } and nothing else

The token counts live on the completion, not on its message.

Why the agent's today is Thursday 5 November

"Saturday" means nothing without today's date. The system message says it: Today is Thursday 2026-11-05. That date comes from today() in config.ts, which reads agentConfig.today, set from AGENT_TODAY. The lab fixes it to the day before Diwali week opens, so "Saturday" is 7 November, a day the seed has showtimes for. Leave it empty and the agent uses Pune's real date. Send no date at all (no system message) and labd counts from its own training date. Neha's Saturday becomes:

{"date":"2024-06-08","title":"Ghar Wapsi Express","part_of_day":"evening"}

A model only knows what is in the request.

The model said it booked

Here is the lesson of this chapter, through the finished route. "Ask the model, with no tools":

{"answer":"Done! Your tickets are booked and the seats are confirmed. Payment has been taken from your wallet."}
[200]

"Ask the model, with find_showtimes":

{"tool_calls":[{"name":"find_showtimes","arguments":{"date":"2026-11-07","title":"Ghar Wapsi Express","part_of_day":"evening"}}]}
[200]

"Did anything get booked?" (GET /bookings/me as Neha):

{"bookings":[]}
[200]

(Each body is followed by its status.) A model writes text. Text that says "booked" books nothing.

Your turn

  • Task 1, llm.ts, chat: one request with the given client: the model from agentConfig on every call, the messages unchanged, temperature 0, and tools only when the list has something in it. The trap: tools: [] sent as a key.
  • Task 2, reply.ts, readReply: the first choice's message as a Reply: the text (null for tool calls), a ToolCall per function call, the assistant message as plain data, and the token counts. The trap: putting the package's message in message.
  • Task 3, reply.ts, whatItWants: { answer } or { tool_calls } with the arguments parsed into an object. Nikhil will ask: with no tools, the model said "Done! Your tickets are booked". With find_showtimes, it asked for a call. Which of the two booked anything, and why?

Run npm run dev, then send the saved requests in order: "Is the app up?", "Ask the model, with no tools", "Ask the model, with find_showtimes", "Did anything get booked?" and "Ask without logging in" (401). Run lab requests 1 to see the last request labd received and its reply:

POST /v1/chat/completions  10:39:01  status 200
model: lab-chat
tools: find_showtimes
system    You are Parda's booking assistant in Pune. You book seats at Parda's cinemas and stages for the signed-in member with the tools, and you answer in short, plain sentences.
          Today is Thursday 2026-11-05. Prices are whole rupees, for one seat.
user      Book two seats for Ghar Wapsi Express on Saturday evening, near the aisle, under ₹200 each
reply     asks for find_showtimes({"date":"2026-11-07","title":"Ghar Wapsi Express","part_of_day":"evening"})
tokens: 213 in, 64 out

Then press Check. A whatItWants that leaves the arguments as text gets:

whatItWants(a tool call) gave {"tool_calls":[{"name":"find_showtimes","arguments":"{\"date\":\"2026-11-07\",\"title\":\"Ghar Wapsi Express\",\"part_of_day\":\"evening\"}"}]}; the task wants {"tool_calls":[{"name":"find_showtimes","arguments":{"date":"2026-11-07","title":"Ghar Wapsi Express","part_of_day":"evening"}}]}, the arguments parsed from JSON

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    llm.ts: one request to the model

    Write chat(messages, tools) in src/agent/llm.ts. It sends one Chat Completions request with the given client (client.chat.completions.create) and returns the completion it gets back, unchanged: model is agentConfig.model (lab-chat in the lab), messages is the list it was given, temperature is 0, and tools is the list only when it has at least one tool; otherwise leave the tools key out of the request.

    The Check sends a system message and Neha's message through your chat and reads what the lab model received: one request, lab-chat, the same messages, temperature 0, no tools key. Then it sends an empty tools list (still no tools key), the find_showtimes tool (sent as given) and, with the model setting changed to lab-chat-mini, wants lab-chat-mini.

  2. Task 2

    reply.ts: read the model's reply

    Write readReply(completion) in src/agent/reply.ts. It reads the first choice's message and returns a Reply: text is the message's content, or null when the model asked for tools; calls is { id, name, arguments } for each tool call of type 'function', in order, with arguments the JSON text as it came ([] for an answer); message is the plain object to add to the conversation, { role: 'assistant', content: the content }, plus tool_calls when there are calls: a list of { id, type: 'function', function: { name, arguments } }; usage is { prompt_tokens, completion_tokens } from completion.usage.

    The Check gets a real answer and a real find_showtimes call from the lab model and compares every field of your Reply with them.

  3. Task 3 · interview question

    Interview: reply.ts, what does the model want?

    Write whatItWants(reply) in src/agent/reply.ts. For an answer it returns { answer: the text }; for tool calls { tool_calls: [{ name, arguments: the arguments parsed from JSON }, ...] }, one per call, in order. It runs nothing; the given route POST /agent/first-step answers with it.

    The Check reads a real answer and a real find_showtimes call through your readReply and whatItWants, then sends POST /agent/first-step as Neha without tools and with them, and wants the bookings table to still hold only the seed's one booking.

    Nikhil will ask: with no tools, the model said "Done! Your tickets are booked". With find_showtimes, it asked for a call. Which of the two booked anything, and why?

What you will learn

  • What a chat model receives and sends back: a list of messages in, one reply out, and nothing remembered between requests.
  • The Chat Completions request: model, messages with their roles, temperature, tools.
  • The completion: choices, the message, finish_reason, usage (tokens, which are time and money).
  • A tool call: the model writes a tool's name and JSON arguments; your code decides whether to run it.
  • Why the agent's "today" is fixed, and how the same code talks to a real model.

More in The loop

Build "What an agent is" yourself

Parda members want to book by chat. You build the agent that finds the show, holds the seats through Parda's own API, and asks before it pays. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.