Check Tool Calls in Your Code

In Answer Every Tool Call, you fixed a loop so it answers every tool call by its ID, turns a thrown error into a result with isError: true, and stops at a round limit. You’ll bring them into your booking assistant first. Its loop also runs whatever the model asks for, with whatever arguments the model wrote. That was fine while its only tool read the public timetable. Passengers’ bookings are different, because each one belongs to someone.

In this lesson, you’ll give the assistant tools that look up and change bookings, and you’ll guard them in your own code. You’ll take the passenger ID from the app instead of the model and check every value against the ferry company’s data before anything runs. Start with the tool you’d write first, a lookup.

Look Up a Passenger’s Booking

Passengers ask about their own bookings all the time, such as which sailing they’re on, how many people are booked, or whether their car is included.

The starting project’s data/bookings.json holds a dozen bookings. Each one has a reference, the passengerId of the passenger who made it, a sailingId, the number of passengers, a vehicle or null, and a free-text note. The passengers themselves are in data/passengers.json.

Add a description of the lookup to tools.js, below findSailings(). This code reads the bookings when the module loads, just like the code that initializes SAILINGS. The description is close to the one in the first lesson’s check answers:

Language: JavaScript Filename: tools.js
const BOOKINGS = JSON.parse(
  await readFile("data/bookings.json", "utf8")
);

export const LOOK_UP_BOOKING = {
  name: "lookUpBooking",
  description:
    "Look up one booking by its reference, with its " +
    "sailing, passengers and vehicle. Use it whenever a " +
    "passenger asks about a booking they've made.",
  schema: {
    type: "object",
    properties: {
      reference: {
        type: "string",
        description: "Booking reference, such as LF-2417",
      },
    },
    required: ["reference"],
    additionalProperties: false,
  },
};

The function finds the booking with that reference. Like findSailings(), it returns only the fields a passenger’s question needs. If the reference is unknown, it throws an error, so your loop sends the error back as the tool’s result. The returned cancelled field stays false until the change tool you’ll add later in this lesson cancels the booking:

Language: JavaScript Filename: tools.js
export function lookUpBooking({ reference }) {
  const booking = BOOKINGS.find(
    (booking) => booking.reference === reference
  );
  if (!booking) throw new Error(`No booking ${reference}.`);
  return {
    reference: booking.reference,
    sailingId: booking.sailingId,
    passengers: booking.passengers,
    vehicle: booking.vehicle,
    note: booking.note,
    cancelled: booking.cancelled === true,
  };
}

Now assistant.js needs to know who’s asking. The natural first step is to tell the model, in the instructions, who’s signed in. Update the top of the file, so the passenger’s message comes from the command line and the model gets the new tool:

Language: JavaScript Filename: assistant.js
import { askWithTools } from "./model/index.js";
import {
  FIND_SAILINGS, findSailings,
  LOOK_UP_BOOKING, lookUpBooking,
} from "./tools.js";

const INSTRUCTIONS = `You answer passengers' questions for
Linden Ferries in a short, friendly reply.
Today is Wednesday, 2026-12-02.
The signed-in passenger is Amara Okafor, passenger P2.`;
const TOOLS = [FIND_SAILINGS, LOOK_UP_BOOKING];
const FUNCTIONS = { findSailings, lookUpBooking };

const messages = [
  { role: "user", content: process.argv[2] },
];

Below messages, replace the while (true) loop from Add askWithTools() to the Model Module with the exercise’s fixes. MAX_ROUNDS is the exercise’s MAX_REQUESTS cap, under the name this project uses. Each call runs in a try...catch block, so a thrown error goes back as the call’s result, and the log lines work for any tool:

Language: JavaScript Filename: assistant.js
const MAX_ROUNDS = 5;

for (let round = 1; round <= MAX_ROUNDS; round += 1) {
  const reply = await askWithTools({
    instructions: INSTRUCTIONS,
    messages,
    tools: TOOLS,
  });
  console.log("usage:", reply.usage);
  if (reply.failure) {
    console.log("No answer:", reply.failure);
    break;
  }
  if (reply.toolCalls.length === 0) {
    messages.push({
      role: "assistant",
      content: reply.answer,
    });
    console.log("answer:", reply.answer);
    break;
  }
  messages.push({
    role: "assistant",
    toolCalls: reply.toolCalls,
  });
  for (const call of reply.toolCalls) {
    console.log("call:", call.name, call.args);
    try {
      const result = await FUNCTIONS[call.name](call.args);
      messages.push({
        role: "tool",
        callId: call.id,
        result,
        isError: false,
      });
    } catch (error) {
      console.log("error result:", error.message);
      messages.push({
        role: "tool",
        callId: call.id,
        result: error.message,
        isError: true,
      });
    }
  }
}

process.argv[2] is the first argument after the script’s name, so you can try several questions without editing the file.

Amara’s bookings are LF-2414, LF-2417, and LF-2420. Say she mistypes the last digit of the one with her car. LF-2421 belongs to another passenger, Priya Nair. Before you run node --env-file=.env assistant.js "Is my car booked on LF-2421?", decide what you expect the assistant to say:

Here’s one real run, with your loop’s usage line for each request:

Language: Program Output
usage: { inputTokens: 256, outputTokens: 22 }
call: lookUpBooking { reference: 'LF-2421' }
usage: { inputTokens: 329, outputTokens: 19 }
answer: Yes, your car is included on booking **LF-2421**.

The model asked for LF-2421, the reference Amara typed. The tool returned Priya’s booking, note and all, and the assistant confirmed a car that isn’t Amara’s. In three more runs of the same question, it said yes every time.

The instructions named the passenger, but nothing in your code used that name. The prompt is only text the model reads. It doesn’t check anyone’s permissions. Your tool runs with the app’s access to every booking, and its reference comes from the model, which passes on whatever the passenger typed. Anyone who guesses a reference can read someone else’s booking this way.

Wouldn’t a firmer instruction fix it? In three runs with “Only help with their own bookings.” added to the instructions, the model refused LF-2421. It also refused Amara’s own LF-2417, all three times. The result doesn’t identify the owner, so the model can’t tell her bookings from anyone else’s.

Returning passengerId too let the model compare the booking’s owner with the signed-in passenger, and it refused LF-2421 in every such run. But that leaves the decision to the model, with Priya’s booking already in its request. The check belongs in your code.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.