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

Tools

By the end of this chapter you can describe a tool to a chat model with a zod object turned into a JSON schema, say what that schema tells the model and what it does not enforce, and write the TypeScript behind Parda's tools: small functions that call the booking API as the member and return small, plain rows with the ids the next tool needs. 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

In chapter 1 the model asked for find_showtimes and nothing happened, because there was no code behind it. Two of the trial weekend's 17 wrong bookings were exactly the kind a tool prevents: a member got the 6:15 pm show instead of 6:45, and a member who said "under ₹200" got a ₹240 balcony seat. Both came from someone reading words and guessing.

Nikhil's rule: the agent never guesses an id or a seat. Showtime 18 comes from Parda's own API, through a tool, as the member. The seats are chosen by code from the real seat map, not by the model. And the tools that change things (a booking, a payment) go through the same API, so its rules hold whatever the model writes: a seat is sold once, and Neha sees only her own bookings.

The lesson

Tour of the codebase

New or changed since chapter 1:

src/agent/llm.ts, reply.ts   given: chapter 1's tasks
src/agent/context.ts         given: ToolContext, what a tool may use (api, userId, ...)
src/agent/tools/registry.ts  given: TOOLS (from specs.ts), FUNCTIONS (name to code), WRITES
src/agent/tools/seats.ts     given: pickSeats, choosing seats from a seat map
src/agent/tools/wallet.ts    given: payBooking, playing the wallet's payment provider
src/agent/routes.ts          changed: POST /agent/tools/:name runs one tool by hand, as you
src/agent/tools/specs.ts     yours: the four other descriptions, and TOOLS (Task 1)
src/agent/tools/parda.ts     yours: findShows, findShowtimes (Task 2), bookSeats, listMyBookings (Task 3)

FUNCTIONS.find_shows is (ctx, a) => parda.findShows(ctx.api, a): the arguments the model wrote, parsed into an object, become your function's second parameter. pay_booking is given: nobody runs the payment provider in the lab, so wallet.ts signs the payment webhook itself and sends it to the API. parda.ts also gives you helpers: showtimeNames, bookingRow, priceList and partOfDay.

A tool has two halves

The model sees a description: a name, a sentence, and the arguments as a JSON schema, a small JSON document that describes other JSON. Your code holds the function. The registry joins them by name. The model never sees your code, and your code never sees the model.

In this project each tool's arguments are a zod object, and the given tool(name, description, args) turns it into the JSON schema with z.toJSONSchema. Here is a made-up tool:

const FindReviewsArgs = z.object({
  title: z.string().describe("Words of the show's title"),
  stars: z.number().int().min(1).max(5).optional().describe('Only reviews with this many stars'),
  language: z.enum(['Marathi', 'Hindi', 'English']).optional().describe('Only reviews in this language'),
});

const FIND_REVIEWS = tool(
  'find_reviews',
  "Find what members wrote about a show, with each review's review_id and stars.",
  FindReviewsArgs,
);

Its parameters, as the model is sent them:

{
  "type": "object",
  "properties": {
    "title": {
      "type": "string",
      "description": "Words of the show's title"
    },
    "stars": {
      "description": "Only reviews with this many stars",
      "type": "integer",
      "minimum": 1,
      "maximum": 5
    },
    "language": {
      "description": "Only reviews in this language",
      "type": "string",
      "enum": ["Marathi", "Hindi", "English"]
    }
  },
  "required": ["title"],
  "additionalProperties": false
}

Each zod method writes one word of the schema:

  • z.string(), z.number().int(): the type, "string" or "integer". z.number() alone would be "number", which allows 2.5.
  • .min(1).max(5): minimum and maximum. Without them, .int() writes the largest safe integers, {"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991}.
  • z.enum([...]): enum, the only values allowed.
  • .describe('...'): the argument's description, for the model to read.
  • An argument without .optional() goes in required: it must be given.
  • additionalProperties: false: no other arguments. A tool with no arguments is z.object({}): properties {}, nothing required.
Optional, not nullable

zod has two ways to say "may be missing", and they write different schemas:

.optional()  {"max_price":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991}}
.nullable()  {"max_price":{"anyOf":[{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},{"type":"null"}]}}

.optional() keeps a plain type and leaves the key out of required. .nullable() makes an anyOf, "one of these two", and models (labd among them) then often write the number as text. Asked "Book 2 seats for showtime 21 under ₹200" with a nullable max_price:

book_seats({"showtime_id":21,"count":2,"max_price":"200"})

With .optional(), the same message gives "max_price":200. Chapter 4 refuses "200" for a number, so optional it is.

The name and the description choose the tool

The whole list of tools goes with every request, and the model chooses by name and description. With the five tools of the finished chapter and Parda's system message, real first steps (each sent with chapter 1's chat and read with readReply):

What is on on Saturday evening?
  -> find_showtimes({"date":"2026-11-07","part_of_day":"evening"})  [647 prompt tokens]
Show my bookings
  -> list_my_bookings({})  [643 prompt tokens]
Which comedy shows are on?
  -> find_shows({"kind":"comedy"})  [646 prompt tokens]
Book 2 seats for showtime 21
  -> book_seats({"showtime_id":21,"count":2})  [649 prompt tokens]
Book two seats for Ghar Wapsi Express on Saturday evening, near the aisle, under ₹200 each
  -> find_showtimes({"date":"2026-11-07","title":"Ghar Wapsi Express","part_of_day":"evening"})  [662 prompt tokens]

For Neha's booking, the model wants book_seats, which needs a showtime_id. She gave none, so it asks for a lookup first: a tool whose name says what it finds. find_showtimes finds showtime_ids, and its rows carry the key the next tool's argument is named for. Offer only book_seats and the lab model asks Neha instead:

  -> "Happy to help. Could you tell me which showtime?"  [286 prompt tokens]

Rename find_showtimes to search_timings, same description, and it no longer connects the lookup to showtime_id. Same question:

  -> "Happy to help. Could you tell me which showtime?"  [662 prompt tokens]

Make every book_seats argument optional (no required list) and it calls book_seats at once with what it knows, beside a lookup, two calls in one reply:

  -> book_seats({"count":2,"max_price":200,"seating":"aisle"}), find_shows({"title":"Ghar Wapsi Express"})  [653 prompt tokens]

A real model reads names, descriptions and required too. Name a lookup for what it finds, and say in its description which ids it returns.

Descriptions cost tokens, on every request: Neha's message with Parda's system message is 90 prompt tokens with no tools, 213 with find_showtimes alone, and 662 with the five.

What a schema does not enforce

The schema is a description. Nothing in this chapter checks a call against it. POST /agent/tools/:name runs a tool with whatever JSON you send, as the model's calls will be run. Send {"showtime":21,"count":2} (the wrong key) to book_seats:

{"error":{"code":"validation_failed","message":"Some fields are not right"}}
[422]

The server log says where it went:

{"requestId":"cc26ec95-44fb-49ca-a6b9-dcf9ff16030a","method":"GET","path":"/showtimes/undefined/seats","status":422,"ms":0}

And {"showtime_id":21,"count":0}, a count the schema says is at least 1, crashes inside the seat picker:

{"error":{"code":"internal","message":"Something went wrong on our side"}}
[500]
TypeError: Cannot read properties of undefined (reading 'label')
    at numberOf (/workspace/chapters/02-tools-solution/src/agent/tools/seats.ts:10:43)
...

Chapter 4 checks the arguments before a tool runs.

Tools call the API as the member

A tool receives api, a PardaApi (src/agent/parda-api.ts): api.get(path, query), api.post(path, body), api.delete(path). Each returns the answer's JSON, or throws ApiError with the API's own status, code and message. api.get leaves out query keys whose value is undefined, so you can pass every filter and only the given ones reach the API. Its requests carry the member's session cookie, so the API sees Neha.

Here is the API's own answer to a show search, GET /shows?q=puneri&limit=50:

{"items":[{"id":18,"title":"Puneri Patya","kind":"comedy","language":"Marathi","minutes":70,"certificate":"UA 13+"}],"page":1,"limit":50,"total":1,"pages":1}

A tool hands the model a smaller row: only what it needs, with the id under the key the next tool's argument is named for (show_id, not id), and the title last, as name (chapter 10 says why). The paging fields go: every field is tokens on every later request.

Times come back in UTC

A showtime's start comes back as ISO text in UTC:

{"items":[{"id":1,"startsAt":"2026-11-06T06:15:00.000Z","prices":{"Front":110,"Middle":170,"Balcony":220},"show":{"id":2,"title":"Pune 52","language":"Marathi"},"venue":{"id":2,"name":"Nilambari Cinema","area":"Kothrud"},"screen":{"id":2,"name":"Screen 1"}}],"page":1,"limit":1,"total":11,"pages":11}

06:15 UTC is 11:45 am in Pune. Members and the model speak Pune's clock, so turn the text into a Date and let the given helpers read it:

const startsAt = new Date('2026-11-06T16:00:00.000Z');
console.log(puneTime(startsAt), partOfDay(startsAt));
console.log(priceList({ Back: 250, Stalls: 350 }));
Fri 6 Nov, 9:30 pm night
Back ₹250, Stalls ₹350

Hand the model the raw text and the Check says:

findShowtimes for Ghar Wapsi Express on Saturday evening gave [{"showtime_id":18,"starts_at":"2026-11-07T13:15:00.000Z","venue":"Kala Talkies","prices":"Front ₹120, Middle ₹180, Balcony ₹240","name":"Ghar Wapsi Express"}]; the task wants [{"showtime_id":18,"starts_at":"Sat 7 Nov, 6:45 pm","venue":"Kala Talkies","prices":"Front ₹120, Middle ₹180, Balcony ₹240","name":"Ghar Wapsi Express"}]

Seats are chosen in code

Neha says "near the aisle, under ₹200". The model passes that on as seating and max_price; it never names a seat. The given pickSeats reads the seat map (GET /showtimes/:id/seats) and chooses: count free seats side by side in one row, the dearest seat class under the price, rows from the front, then the row's centre, or an end of the row for 'aisle'. It returns the seats, or null when no row has them. The balcony seat for "under ₹200" cannot happen: a row over the price is never considered.

Two calls that must both happen

Booking through the API is two calls: hold the seats (POST /holds, the backend's chapter 8), then turn the hold into a pending booking (POST /bookings). With no hold, the booking is refused. Pranav, by hand, on showtime 21 (each request, then the API's answer and its status):

POST /bookings {"showtimeId":21}
{"error":{"code":"no_holds","message":"You hold no seats for this showtime: hold them first"}}
[409]
POST /holds {"showtimeId":21,"seatIds":[1,2]}
{"hold":{"showtimeId":21,"seats":["A1","A2"],"expiresAt":"2026-10-24T10:53:35.596Z"}}
[201]
POST /bookings {"showtimeId":22}
{"error":{"code":"no_holds","message":"You hold no seats for this showtime: hold them first"}}
[409]

The second booking was refused (the wrong showtime, by hand; for the agent it could be a hold that expired, or the API restarting between the calls). The hold is still there:

 showtime_id | seat_id | user_id |          expires_at           
-------------+---------+---------+-------------------------------
          21 |       1 |       3 | 2026-10-24 16:23:35.596+05:30
          21 |       2 |       3 | 2026-10-24 16:23:35.596+05:30
(2 rows)

For 10 minutes A1 and A2 count as taken, and nobody booked them. On a Diwali Saturday that is two seats another member could not buy. DELETE /holds/21 lets them go:

{"released":2}
[200]

A tool that makes the first call must undo it when the second is refused, then throw the same error, so its caller still sees why.

Your turn

  • Task 1, specs.ts: FindShowsArgs, BookSeatsArgs, ListMyBookingsArgs and PayBookingArgs, the four tools, and all five in TOOLS in order. The trap: .nullable() for an optional argument.
  • Task 2, parda.ts, findShows and findShowtimes: one GET with the filters, small rows in the given key order; for showtimes, the shows found by title, the part of the day, and Pune's time. The trap: startsAt handed over as UTC text.
  • Task 3, parda.ts, bookSeats and listMyBookings: seat map, pickSeats, hold, booking; a refused booking lets go of the hold and throws again. Nikhil will ask: the model never sees Parda's database. How does it know which showtime_id to put in book_seats?

Run npm run dev and send the saved requests: Saturday evening's showtimes, comedy shows, "Book 2 aisle seats under ₹200 (by hand)", which answers

{"result":{"booking_id":2,"status":"pending","seats_booked":"E1, E2","total":400,"showtime_id":18,"name":"Ghar Wapsi Express, Sat 7 Nov, 6:45 pm"}}
[200]

then "List my bookings", and showtime 999 (404). Watch the log: the booking is the tool's own calls, then yours.

{"requestId":"35e5d173-4251-4c58-91d7-e10d3cdd9fa3","method":"GET","path":"/showtimes/18/seats","status":200,"ms":5}
{"requestId":"83039d12-b097-430b-b1a3-67af241fd89a","method":"POST","path":"/holds","status":201,"ms":5,"userId":2}
{"requestId":"2e91c688-5b93-4cb9-8866-2dd7ec940121","method":"POST","path":"/bookings","status":201,"ms":4,"userId":2}
{"requestId":"b73ee235-106a-47be-83aa-90a7d297ca8b","method":"GET","path":"/showtimes","status":200,"ms":2}
{"requestId":"358a552b-de95-4b11-90cc-273324d89340","method":"POST","path":"/agent/tools/book_seats","status":200,"ms":24,"userId":2}

The inner calls finish first, so they log first. The seat map and the showtimes need no login, so they carry no userId; the hold and the booking are Neha's 2. In psql, select * from holds; should be empty after the booking. Then press Check. A bookSeats that forgets the hold gets:

when POST /bookings refused, bookSeats sent DELETE []; it should let go of the hold with DELETE /holds/18

What you build: 3 tasks

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

  1. Task 1

    specs.ts: describe the tools

    In src/agent/tools/specs.ts, write the zod objects FindShowsArgs, BookSeatsArgs, ListMyBookingsArgs and PayBookingArgs, then FIND_SHOWS, BOOK_SEATS, LIST_MY_BOOKINGS and PAY_BOOKING with the given tool(name, description, args), in FIND_SHOWTIMES's style, and list all five in TOOLS in this order: FIND_SHOWS, FIND_SHOWTIMES, BOOK_SEATS, LIST_MY_BOOKINGS, PAY_BOOKING.

    find_shows: title (a string), kind (z.enum(['film', 'play', 'comedy', 'music'])) and language (a string), all optional. book_seats: showtime_id (an integer), count (an integer, min 1, max 6), max_price (an integer, optional), seating (z.enum(['aisle', 'centre']), optional). list_my_bookings: no arguments. pay_booking: booking_id (an integer). Optional means .optional(), not .nullable(). Each description is a plain sentence of yours saying what the tool does.

    The Check reads the JSON schema of each tool (names, types, enums, limits, the required list), wants a description of at least four words, then offers your TOOLS to the lab model with Neha's "Book two seats for Ghar Wapsi Express on Saturday evening, near the aisle, under ₹200 each" and wants its first step to be find_showtimes.

  2. Task 2

    parda.ts: the tools that look things up

    In src/agent/tools/parda.ts, write findShows(api, { title, kind, language }): GET /shows with the query q = title, kind, language and limit 50; return one object per item of the answer's items, with the keys in this order: show_id (the item's id), kind, language, minutes, certificate, name (the title).

    Then findShowtimes(api, { date, title, part_of_day }): when title is given, GET /shows with q = title and limit 50 (none found: return []); GET /showtimes with date and limit 50; keep the items whose show is one of those found (all of them without a title) and, when part_of_day is given, whose partOfDay(new Date(startsAt)) equals it; return { showtime_id, starts_at: puneTime(new Date(startsAt)), venue: the venue's name, prices: priceList(prices), name: the show's title } for each.

    The Check calls them as Neha: the comedy shows, the shows with "ghar" in the title, the Marathi ones, Saturday's showtimes (all of them, the evening's, Ghar Wapsi Express's evening one, a title that does not exist) and the evening's again with showtime 19 cancelled. Then POST /agent/tools/find_showtimes as Neha.

  3. Task 3 · interview question

    Interview: parda.ts, the tools that change things

    In src/agent/tools/parda.ts, write bookSeats(api, { showtime_id, count, max_price, seating }): GET /showtimes/<showtime_id>/seats; seats = pickSeats(map, count, { maxPrice: max_price, seating }); null: throw new ApiError(409, 'no_seats', 'There are no <count> free seats side by side for showtime <showtime_id>'), with ' at ₹<max_price> or less' before ' for' when a price is given; POST /holds with { showtimeId, seatIds }; then POST /bookings with { showtimeId }, and if that throws an ApiError, let go of the hold (DELETE /holds/<showtime_id>) and throw the error again; return bookingRow(the answer's booking, await showtimeNames(api)).

    Then listMyBookings(api): GET /bookings/me, and bookingRow of each of its bookings, in the same order.

    The Check books 2 aisle seats under ₹200 in showtime 18 as Neha (E1 and E2, ₹360 and ₹40 fee: total 400, pending, no hold left), asks for 3 seats under ₹100 (no_seats, nothing held), makes POST /bookings refuse once (the same ApiError thrown again, DELETE /holds/18 sent, no hold left), and lists Pranav's bookings (his paid booking 1) and Neha's (only hers).

    Nikhil will ask: the model never sees Parda's database. How does it know which showtime_id to put in book_seats?

What you will learn

  • A tool's two halves: the description the model reads, and the function your code runs.
  • zod to JSON schema: z.object, .describe, .int, .min and .max, z.enum, .optional and why not .nullable, and the required list.
  • What chooses a tool: its name and its description, and what that costs in tokens.
  • What a schema does not do: it guides the model; nothing checks the call against it yet.
  • Tools as API calls: PardaApi, the member's cookie, ApiError, and small rows for the model.
  • Two calls that must both happen, and undoing the first when the second is refused.

More in The loop

Build "Tools" 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.