AI ordering agent project · Chapter 2 of 12

Tools

By the end of this chapter you can describe a tool to a chat model with a JSON schema, say what the schema tells the model and what it does not enforce, and write the Python behind DabbaDrop's tools: small functions that call the ordering 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
  • Python
  • 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_slots and nothing happened, because there was no Python behind it. Two of the pilot week's 19 wrong orders were exactly the kind a tool prevents: a member got the 1 pm slot instead of 12:30, and a Jain member got a dish with onion. Both came from someone reading words and guessing an id.

Kunal's rule: the agent never guesses an id. Slot 80 and dish 25 come from DabbaDrop's own API, through a tool, as the member. And the tools that change things (an order, a payment) go through the same API, so its rules hold whatever the model writes: a slot is never overfilled, a dish from another kitchen is refused.

The lesson

Tour of the codebase

New or changed since chapter 1:

agent/llm.py, agent/reply.py   given: chapter 1's tasks
agent/context.py               given: ToolContext, what a tool may use (api, user_id, ...)
agent/tools/registry.py        given: TOOLS (from specs.py), FUNCTIONS (name to Python), WRITES
agent/tools/wallet.py          given: pay_order, playing DabbaPay, the wallet's provider
agent/routes.py                changed: POST /agent/tools/{name} runs one tool by hand, as you
agent/tools/specs.py           yours: FIND_DISH, PLACE_ORDER, LIST_MY_ORDERS, PAY_ORDER (Task 1)
agent/tools/dabba.py           yours: find_dish, find_slots (Task 2), place_order, list_my_orders (Task 3)

FUNCTIONS["find_dish"] is lambda ctx, a: dabba.find_dish(ctx.api, **a): the model's arguments, a dict, become your function's keyword arguments. pay_order is given: nobody runs DabbaPay in the lab, so wallet.py signs the payment webhook itself and sends it to the API.

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 Python, and your Python never sees the model.

Here is a made-up tool built with the given tool(...) helper:

FIND_CHUTNEYS = tool(
    "find_chutneys",
    "Find the chutneys a zone's kitchen can add to a dabba, with each chutney's chutney_id and price.",
    {
        "zone": ZONE,
        "chutney_name": {"type": ["string", "null"], "description": "Words of the chutney's name"},
        "kind": {"type": "string", "enum": ["sweet", "spicy"], "description": "Only chutneys of this kind"},
    },
    ["zone"],
)
  • type says what the value is: "string", "integer", "object". A list of two types, ["string", "null"], says the argument may be left empty.
  • enum lists the only values allowed. ZONE is a string with the six zones as its enum.
  • minimum and maximum bound a number.
  • required lists the arguments that must be given.
  • additionalProperties: false says no other arguments.
  • A tool with no arguments still has {} and [].

An enum with no empty choice forces a choice. Asked "Which chutneys can I add in Bandra?", where the member named no kind:

Which chutneys can I add in Bandra? -> [('find_chutneys', '{"zone":"Bandra","kind":"spicy"}')]

It picked one of the two allowed words. That is why the tasks' optional enums include None.

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 DabbaDrop's system message, real first steps (each request sent with chat and read with read_reply):

What is on the menu in Dadar?
  -> find_dish({"zone":"Dadar"})  [620 prompt tokens]
Show my orders
  -> list_my_orders({})  [614 prompt tokens]
Which Jain dishes can I get in Thane?
  -> find_dish({"zone":"Thane","diet":"jain"})  [621 prompt tokens]
Book 2 Jain Thali for Tuesday lunch at 12:30 in Thane
  -> find_slots({"zone":"Thane","date":"2026-11-03","time":"12:30"})  [628 prompt tokens]

For the booking, the model wants place_order, which needs a slot_id and a dish_id. Tara gave neither, so it asks for a lookup first: a tool whose name says what it finds. Each lookup's rows carry the key the next tool's argument is named for. Rename find_dish to find_dishes and the lab model no longer connects it to dish_id; it asks Tara instead:

Book 2 Jain Thali for Tuesday lunch at 12:30 in Thane
  -> 'Happy to help. Could you tell me dish id?'  [628 prompt tokens]

Leave place_order's required list empty and it calls it at once with the one thing it knows:

Book 2 Jain Thali for Tuesday lunch at 12:30 in Thane
  -> place_order({"quantity":2})  [620 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: the same booking message with DabbaDrop's system message is 628 prompt tokens with the five tools, 239 with find_slots alone and 97 with none.

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 call will be run:

$ curl -b advait.jar -X POST localhost:8000/agent/tools/place_order -d '{"slot_id":81,"dish":25,"quantity":1}'
{"error":{"code":"internal","message":"Something went wrong on our side"}}
[500]

The log ends with:

TypeError: place_order() got an unexpected keyword argument 'dish'

And "quantity": 0 reaches the API, whose own rules refuse it:

{"error":{"code":"validation_failed","message":"The request is not valid"}}
[422]

Chapter 4 checks the arguments before a tool runs.

Tools call the API as the member

A tool receives api, a DabbaApi (agent/dabba_api.py): api.get(path, params), api.post(path, body), api.delete(path). Each returns the answer's JSON, or raises ApiError with the API's own status, code and message. Its client carries the member's session cookie, so the API sees Tara.

Here is the API's answer to a menu search on Dadar Kitchen (kitchen 2, from GET /zones):

$ curl 'localhost:8000/dishes?kitchen_id=2&limit=50&q=bombil'
{"items":[{"id":20,"kitchen_id":2,"kitchen":"Dadar Kitchen","name":"Bombil Fry","category":"non-veg","price":240}],"page":1,"limit":50,"total":1,"pages":1}

A tool hands the model a smaller row: only what it needs, with the key named for the next tool's argument (dish_id, not id). Every field is tokens on every later request.

The server log shows the agent's own calls as their own lines. Running find_dish by hand as Tara:

{"id": "d20f70dd5187437ab292c186c9b5f1a2", "method": "GET", "path": "/zones", "status": 200, "ms": 2.7, "user_id": null}
{"id": "6b9e6ab2c4ef493e8e042ba950bb18a1", "method": "GET", "path": "/dishes", "status": 200, "ms": 3.7, "user_id": null}
{"id": "301dbf37c5874082aa457be24f74f0e5", "method": "POST", "path": "/agent/tools/find_dish", "status": 200, "ms": 36.4, "user_id": 2}

The inner calls finish first, so they log first. /zones and /dishes need no login, so their user_id is null; POST /holds and POST /orders will show Tara's 2. A zone that does not exist is the given zone_named's ApiError, and the route turns it into the API's shape:

{"error":{"code":"no_zone","message":"DabbaDrop does not deliver to Powai. It delivers to Andheri West, Goregaon, Malad, Dadar, Bandra, Thane."}}
[404]

A slot's time has an offset

GET /zones/{id}/slots?day=... gives every slot of the day, full or not:

{"zone":{"id":4,"name":"Dadar"},"day":"2026-11-02","slots":[{"id":46,"starts_at":"2026-11-02T12:00:00+05:30","ends_at":"2026-11-02T12:30:00+05:30","capacity":40,"status":"open","places_left":40},...

The model asks for "12:30"; the API says "2026-11-02T12:30:00+05:30". Comparing the two strings is never equal. Turn the text into a moment, then read its Mumbai clock time with the given clock:

t = datetime.fromisoformat("2026-11-02T13:00:00+05:30")
print(repr(t))
print(clock(t))
datetime.datetime(2026, 11, 2, 13, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))
13:00

Two calls that must both happen

Ordering through the API is two calls: hold a place in the slot (POST /holds, the backend's chapter 8), then turn the hold into an order (POST /orders). With no hold, the order is refused. Advait, by hand:

$ curl -b advait.jar -X POST localhost:8000/orders -d '{"slot_id":17,"items":[{"dish_id":1,"quantity":1}]}'
{"error":{"code":"no_hold","message":"Hold a place in this slot first"}}
[409]
$ curl -b advait.jar -X POST localhost:8000/holds -d '{"slot_id":17}'
{"hold":{"slot_id":17,"expires_at":"2026-10-24T11:02:33.119812+05:30","places_left":39}}
[201]
$ curl -b advait.jar -X POST localhost:8000/orders -d '{"slot_id":17,"items":[{"dish_id":25,"quantity":1}]}'
{"error":{"code":"bad_dishes","message":"Some of those dishes are not on this kitchen's menu today"}}
[422]

Dish 25 is Thane Kitchen's, and slot 17 is Goregaon's. The order was refused, but the hold is still there:

 slot_id | user_id |            expires_at            
---------+---------+----------------------------------
      17 |       3 | 2026-10-24 11:02:33.119812+05:30
(1 row)

For 10 minutes that place counts as taken, and nobody ordered it. A tool that makes the first call must undo it when the second is refused, then let the caller see the same error.

Your turn

  • Task 1, specs.py: the four descriptions, in FIND_SLOTS's style, and all five in TOOLS. The trap: a lookup named for the wrong thing, or required left out.
  • Task 2, dabba.py, find_dish and find_slots: optional query parameters only when given, small rows in the given key order, open slots with places left, and the clock time compared. The trap: comparing starts_at with "12:30" as text.
  • Task 3, dabba.py, place_order and list_my_orders: hold, then order; a refused order lets go of the hold and raises again. Kunal will ask: the model never sees DabbaDrop's database. How does it know which dish_id to put in place_order?

Run python -m agent and send the saved requests: find Jain dishes in Thane, Thane's Tuesday slots, book 2 Jain Thali at 12:30 by hand ({"result":{"order_id":2,"name":"2 x Jain Thali","status":"pending","total":550,"delivery_fee":30,"slot_id":80}}), list your orders, and Powai (404). Watch the log for the agent's own calls. In psql, select * from slot_holds; should be empty after the booking. Then press Check. A place_order that forgets the hold gets:

place_order was refused (bad_dishes), but Tara still holds a place in slot 80: let go of the hold (DELETE /holds/80) before you raise

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.py: describe the tools

    In agent/tools/specs.py, write FIND_DISH, PLACE_ORDER, LIST_MY_ORDERS and PAY_ORDER with the given tool(name, description, properties, required), in FIND_SLOTS's style, and list all five in TOOLS in this order: FIND_DISH, FIND_SLOTS, PLACE_ORDER, LIST_MY_ORDERS, PAY_ORDER.

    find_dish: zone (ZONE, required), dish_name (type ["string", "null"]), diet (type ["string", "null"], enum ["veg", "jain", "non-veg", None]). place_order: slot_id and dish_id (integers), quantity (integer, minimum 1, maximum 10), all three required. list_my_orders: no arguments. pay_order: order_id (integer, required). Each description is a plain sentence of yours saying what the tool does.

    The Check compares each tool's name, arguments, types and required list with this, wants a description of at least four words, then offers your TOOLS to the lab model with Tara's "Book 2 Jain Thali for Tuesday lunch at 12:30 in Thane" and wants its first step to be find_slots.

  2. Task 2

    dabba.py: the tools that look things up

    In agent/tools/dabba.py, write find_dish(api, zone, dish_name=None, diet=None): zone_named(api, zone) gives the zone's kitchen_id; GET /dishes with the params kitchen_id, limit 50, q = dish_name (only when given) and category = diet (only when given); return one dict per item of the answer's "items", with the keys in this order: dish_id (the item's id), price, category, name.

    Then find_slots(api, zone, date, time=None): GET /zones/{the zone's id}/slots with the param day = date; keep the slots whose status is open and whose places_left is 1 or more, and when time is given only the one whose clock(datetime.fromisoformat(starts_at)) equals it; return {"slot_id", "starts_at", "ends_at", "places_left"} for each.

    The Check calls them as Tara: Jain Thali in Thane (dish 25, ₹260), all 8 of Thane Kitchen's dishes, the three jain ones, Powai (zone_named's ApiError no_zone), Thane's slots on 2026-11-03 (79, 80, 81), the 12:30 one only (80), and again with slot 79 closed and slot 81 full (only 80). Then POST /agent/tools/find_dish as Tara.

  3. Task 3 · interview question

    Interview: dabba.py, the tools that change things

    In agent/tools/dabba.py, write place_order(api, slot_id, dish_id, quantity): POST /holds with {"slot_id"}, then POST /orders with {"slot_id", "items": [{"dish_id", "quantity"}]}; if that raises an ApiError, let go of the hold (DELETE /holds/{slot_id}) and raise the error again; return order_row(the answer's "order").

    Then list_my_orders(api): GET /orders/me, and order_row of each of its "orders", in the same order.

    The Check books 2 Jain Thali in slot 80 as Tara (₹520 and ₹30 delivery: total 550, and no hold left), tries Andheri Kitchen's Dal Tadka in the same slot (the API's ApiError bad_dishes, raised again, and no hold left for Tara), and lists Advait's orders (his one paid order) and Tara's (only hers).

    Kunal will ask: the model never sees DabbaDrop's database. How does it know which dish_id to put in place_order?

What you will learn

  • A tool's two halves: the description the model reads, and the function your code runs.
  • JSON schema for arguments: type, a type that may be null, enum, minimum and maximum, required, additionalProperties.
  • 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: DabbaApi, the member's cookie, and ApiError.
  • Two calls that must both happen, and undoing the first when the second is refused.

More in The loop

Build "Tools" yourself

DabbaDrop members want to order by chat. You build the agent that books their tiffins through DabbaDrop'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.