Add askWithTools() to the Model Module

In the last video, you watched a passenger’s question about Saturday’s sailings go round the tool-calling loop. The model asked for two lookups in one reply, the results went back by their IDs, and the next reply was the answer. The history in that video used a shape of your own, with toolCalls on the model’s turn and a tool entry for each result.

In this lesson, you’ll give your model/ module a fourth function, askWithTools(), that uses that shape for either provider. Then you’ll write the booking assistant’s loop against it, so the assistant’s code never names a provider. Start with what the function promises the code that calls it.

Give the Module One Shape for Tool Calls

Each provider sends tool calls and takes results in its own format, and your features shouldn’t depend on which provider you use. So askWithTools() takes four main options, and only tools is new:

  • instructions and role: As in every function of the module.
  • messages: The history, with { role, content } entries for the passenger’s messages and the final answers, and two more kinds of entry from the video. { role: "assistant", toolCalls } records a reply’s requests, and { role: "tool", callId, result, isError } records one result.
  • tools: An array of descriptions like FIND_SAILINGS in tools.js, each with a name, a description, and a schema.

It returns an object with four properties, the same for both providers:

  • toolCalls: An array of { id, name, args }, with args already an object. It’s empty when the reply asks for nothing.
  • answer: The reply’s text when it’s a finished answer, or null.
  • failure: null, or "cut off", "refused", or "unfinished: " plus the provider’s reason, as askForJson() names them.
  • usage: The token counts, so you can still price every call.

You need failure because a reply cut off at the output limit may hold no calls, or a call whose arguments stopped halfway. If the loop took a reply without calls as the answer, a cut-off sentence would reach the passenger as if it were complete. So the module treats a reply as the answer only when it finishes normally.

Open model/index.js and add askWithTools() below streamAnswer(). It picks the model the way the other functions do and sends the request through sendWithRetries(), so it gets the retries and the module’s timeout. Like streamAnswer(), it takes an optional signal. One question can now cost several paid requests, and a passenger who leaves should be able to stop them all. It has no input shortcut, because a tool conversation always has a history:

Language: JavaScript Filename: model/index.js
export async function askWithTools({
  instructions,
  messages,
  tools,
  role = "capable",
  signal,
}) {
  const { adapter, model } = pickModel(role);
  const reply = await sendWithRetries(adapter, {
    model,
    instructions,
    messages,
    tools,
    maxOutputTokens: settings.maxOutputTokens,
    roleSettings: adapter.ROLE_SETTINGS[role],
    signal,
  });

The rest of the function sorts the reply into one of three results. It checks for a failure first, then for tool calls, and only then returns the text as the answer:

Language: JavaScript Filename: model/index.js
  const { toolCalls, usage } = reply;
  const failure = replyFailure(reply, adapter);
  if (failure) {
    return { toolCalls: [], answer: null, failure, usage };
  }
  if (toolCalls.length > 0) {
    return { toolCalls, answer: null, failure: null, usage };
  }
  return { toolCalls, answer: reply.text, failure: null, usage };
}

function replyFailure(reply, adapter) {
  if (reply.stopReason === adapter.CUT_OFF) return "cut off";
  if (reply.refused) return "refused";
  if (!reply.finished) return `unfinished: ${reply.stopReason}`;
  return null;
}

The checks in replyFailure() are the ones askForJson() makes, in the same order, and they use the finished and refused properties your provider files already report. On a failure, askWithTools() returns no tool calls at all, even if the reply holds some, so the loop can never run a call with unfinished arguments.

For the signal to work, sendWithRetries() needs two changes. First, replace the line at the top of each attempt that creates the timeout signal with these lines, which combine the caller’s signal with the timeout, as streamAnswer() does:

Language: JavaScript Filename: model/index.js
    const timeout = AbortSignal.timeout(settings.timeoutMs);
    const signal = request.signal
      ? AbortSignal.any([request.signal, timeout])
      : timeout;

Second, replace the await wait(seconds); between attempts with the sleep() that streamAnswer() already imported:

Language: JavaScript Filename: model/index.js
        await sleep(seconds * 1000, undefined, {
          signal: request.signal,
        });

The wait listens to the caller’s signal, not the combined one, so a stop during a retry’s wait ends it at once, but the attempt’s timeout can’t cut it short.

The signal.throwIfAborted() inside the catch block of sendWithRetries() now throws a caller’s abort instead of retrying it, so one signal stops every round of a loop. No script in this lesson passes a signal yet, and nothing else depends on it for now.

The reply has no toolCalls property yet, though. The provider files have to read the tool calls.

Translate the Shape in Each Provider File

Each provider file now has three jobs to add. It wraps your tool descriptions in its provider’s format, reads the tool calls out of a response, and turns your history into the provider’s own messages. That last job is the translation the video’s history needed, and it’s where the two providers differ most.

One rule from both providers’ documentation shapes the code. When the model asks for tools, the next request has to carry the reply back as it came, including the model’s reasoning, which your toolCalls entry doesn’t hold. So each file keeps the reply’s own items in a WeakMap, keyed by the toolCalls array it returned.

A WeakMap works like a Map whose keys are objects, except that once nothing else holds a key, the entry can go too, so old replies don’t pile up. Your loop puts that same array into the history, so the file can look it up when it translates the history. A copy of the array would be a different key, so the file throws an error when it finds no entry.

Open the version for your provider and type along in that file only. The other provider’s file comes finished in the course’s code download, with the same interface, so switching MODEL_PROVIDER later still works:

In model/openai.js, send() reads two more fields from the request, messages and tools. When there’s a history, it becomes the request’s input, and the tools go into the body’s tools array:

Language: JavaScript Filename: model/openai.js
export async function send(request) {
  const {
    model, instructions, input, maxOutputTokens, roleSettings,
    schema, messages, tools,
  } = request;
  const payload = {
    model,
    instructions,
    input: messages ? toInput(messages) : input,
    max_output_tokens: maxOutputTokens,
    ...roleSettings,
  };

Below the if (schema) block, which stays as it was, add the tools:

Language: JavaScript Filename: model/openai.js
  if (tools) {
    payload.tools = tools.map(toTool);
  }

toTool() builds the same tool entry that your tool-request.js sent by hand in the lesson Describe a Tool and Read the Request, with type: "function" and the schema in parameters:

Language: JavaScript Filename: model/openai.js
function toTool(tool) {
  return {
    type: "function",
    name: tool.name,
    description: tool.description,
    parameters: tool.schema,
    strict: true,
  };
}

Next, readReply() reports the tool calls. Add one line to the object it returns, after usage: toolCalls: readToolCalls(data),. Then add the map and readToolCalls() below readReply():

Language: JavaScript Filename: model/openai.js
// The output items of each reply that asked for tools
const REPLY_ITEMS = new WeakMap();

function readToolCalls(data) {
  // An unfinished reply's arguments can be unfinished JSON
  if (data.status !== "completed") return [];
  const toolCalls = data.output
    .filter((item) => item.type === "function_call")
    .map((item) => ({
      id: item.call_id,
      name: item.name,
      args: JSON.parse(item.arguments),
    }));
  REPLY_ITEMS.set(toolCalls, data.output);
  return toolCalls;
}

Each call’s ID is its call_id, the one the result must quote, and its arguments string becomes an object. The whole output array goes into the map, reasoning items included, because OpenAI’s function calling guide says those must go back with the tool outputs.

Last, toInput() turns your history into input items. A toolCalls entry becomes the reply’s own items again, and a tool entry becomes a function_call_output item with the same call_id:

Language: JavaScript Filename: model/openai.js
function toInput(messages) {
  return messages.flatMap((entry) => {
    if (entry.toolCalls) {
      const items = REPLY_ITEMS.get(entry.toolCalls);
      if (!items) {
        throw new Error("toolCalls must come from askWithTools()");
      }
      return items;
    }
    if (entry.role === "tool") {
      const output = entry.isError
        ? { error: entry.result }
        : entry.result;
      return [{
        type: "function_call_output",
        call_id: entry.callId,
        output: JSON.stringify(output),
      }];
    }
    return [{ role: entry.role, content: entry.content }];
  });
}

The result goes back as a JSON string, the form the guide suggests. A function_call_output item has no error flag, so a result with isError: true goes back wrapped as { error: ... }, and the model can read that it failed. Every other entry keeps its { role, content } shape. The .flatMap() call lets one entry become several items, as a reply with two calls does.

In model/anthropic.js, send() reads two more fields from the request, messages and tools. When there’s a history, it becomes the request’s messages, and the tools go into the body’s tools array:

Language: JavaScript Filename: model/anthropic.js
export async function send(request) {
  const {
    model, instructions, input, maxOutputTokens, roleSettings,
    schema, messages, tools,
  } = request;
  const payload = {
    model,
    system: instructions,
    messages: messages
      ? toMessages(messages)
      : [{ role: "user", content: input }],
    max_tokens: maxOutputTokens,
    ...roleSettings,
  };

Below the if (schema) block, which stays as it was, add the tools:

Language: JavaScript Filename: model/anthropic.js
  if (tools) {
    payload.tools = tools.map(toTool);
  }

toTool() builds the same tool entry that your tool-request.js sent by hand in the lesson Describe a Tool and Read the Request, with the schema in input_schema:

Language: JavaScript Filename: model/anthropic.js
function toTool(tool) {
  return {
    name: tool.name,
    description: tool.description,
    input_schema: tool.schema,
    strict: true,
  };
}

Next, readReply() reports the tool calls, and a reply that stops to ask for tools counts as finished. Its stop reason is "tool_use", not "end_turn". Update finished and add toolCalls in the object it returns:

Language: JavaScript Filename: model/anthropic.js
    finished: ["end_turn", "tool_use"].includes(data.stop_reason),
    toolCalls: readToolCalls(data),

Then add the map and readToolCalls() below readReply():

Language: JavaScript Filename: model/anthropic.js
// The content of each reply that asked for tools
const REPLY_CONTENT = new WeakMap();

function readToolCalls(data) {
  const toolCalls = data.content
    .filter((block) => block.type === "tool_use")
    .map((block) => ({
      id: block.id,
      name: block.name,
      args: block.input,
    }));
  REPLY_CONTENT.set(toolCalls, data.content);
  return toolCalls;
}

Each tool_use block already has its input as an object. The whole content array goes into the map because Anthropic’s documentation on handling tool calls says to send the response’s content back unchanged. Claude 5 models think by default, and the thinking documentation requires the thinking blocks of a tool use turn to go back complete and unmodified.

Last, toMessages() turns your history into messages. A toolCalls entry becomes an assistant message with the reply’s own content again. Each tool entry becomes a tool_result block with the call’s ID in tool_use_id:

Language: JavaScript Filename: model/anthropic.js
function toMessages(history) {
  const messages = [];
  for (const entry of history) {
    if (entry.role === "tool") {
      addResult(messages, {
        type: "tool_result",
        tool_use_id: entry.callId,
        content: JSON.stringify(entry.result),
        is_error: entry.isError,
      });
    } else if (entry.toolCalls) {
      const content = REPLY_CONTENT.get(entry.toolCalls);
      if (!content) {
        throw new Error("toolCalls must come from askWithTools()");
      }
      messages.push({ role: "assistant", content });
    } else {
      messages.push({ role: entry.role, content: entry.content });
    }
  }
  return messages;
}

The results of one reply’s calls must all go in one user message, right after the assistant’s message, so addResult() adds a result to the last message when that message already holds results:

Language: JavaScript Filename: model/anthropic.js
function addResult(messages, result) {
  const last = messages.at(-1);
  if (last.role === "user" && Array.isArray(last.content)) {
    last.content.push(result);
  } else {
    messages.push({ role: "user", content: [result] });
  }
}

A passenger’s message has a string as its content, so an array there means a message of results. is_error is Anthropic’s own flag for a failed call, so isError maps onto it directly.

This lesson’s runs went to OpenAI only, with no Anthropic key, so this file is written from Anthropic’s documentation and hasn’t been run against the API.

With either provider, the file reads calls as { id, name, args } and translates your two new kinds of history entry into its own format. Before you build a loop on it, check it with one call. Create try-tools.js, which asks one question with FIND_SAILINGS and prints the whole reply:

Language: JavaScript Filename: try-tools.js
import { askWithTools } from "./model/index.js";
import { FIND_SAILINGS } from "./tools.js";

const reply = await askWithTools({
  instructions: "You answer passengers' questions " +
    "for Linden Ferries. Today is 2026-12-02.",
  messages: [{
    role: "user",
    content: "Any sailings from Linden Harbor to " +
      "Gull Island on Saturday?",
  }],
  tools: [FIND_SAILINGS],
});
console.dir(reply, { depth: null });

console.dir() with depth: null prints the nested args object in full. Run node --env-file=.env try-tools.js. Here’s one real run:

Language: Program Output
{
  toolCalls: [
    {
      id: 'call_0246234df4804f1285150f5e4df66ef8',
      name: 'findSailings',
      args: { from: 'Linden Harbor', to: 'Gull Island', date: '2026-12-05' }
    }
  ],
  answer: null,
  failure: null,
  usage: { inputTokens: 169, outputTokens: 37 }
}

The reply asks for one call instead of answering, so answer is null. The call’s args is already an object, with “Saturday” turned into a date, and the call’s id, which looks different with each provider, is what the result will quote. If your reply has these four properties, your provider file works.

The button above opens the mentor with that question, if the WeakMap and the reasoning it carries still feel like a detour.

Write the Assistant’s Loop

The module now answers in one shape, so the assistant can run the loop from the video without knowing the provider. The assistant needs one more piece first: the function behind FIND_SAILINGS, which the model has been asking for since the first lesson.

Add the following code to tools.js, below FIND_SAILINGS. The module reads the ferry company’s sailings once, when it loads. The function keeps the ones that match the arguments and returns only the fields a passenger’s question needs, with each departure as a time:

Language: JavaScript Filename: tools.js
import { readFile } from "node:fs/promises";

const SAILINGS = JSON.parse(
  await readFile("data/sailings.json", "utf8")
);

export function findSailings({ from, to, date }) {
  return SAILINGS.filter(
    (sailing) =>
      sailing.from === from &&
      sailing.to === to &&
      sailing.departs.startsWith(date)
  ).map((sailing) => ({
    id: sailing.id,
    departs: sailing.departs.slice(11),
    seatsLeft: sailing.seatsLeft,
    vehicleSpacesLeft: sailing.vehicleSpacesLeft,
    status: sailing.status,
  }));
}

Move the import line to the top of the file, with any other imports. Each sailing’s departs value looks like "2026-12-05T08:00", so .startsWith(date) matches the day and .slice(11) keeps the time.

Now create assistant.js. Its first part sets up the instructions, the tools the model may ask for, the functions that answer them by name, and the history with the passenger’s question:

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

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

const messages = [{
  role: "user",
  content: "Is there room for my car on Saturday " +
    "morning's sailing from Linden Harbor to Gull " +
    "Island or Heron Island? Either is fine.",
}];

The starting project’s sailings are for one weekend, December 5 and 6, so the instructions fix today as the Wednesday before, and “Saturday” lands on the data. A real assistant would use the current date. FUNCTIONS maps each tool’s name to your function, so a call’s name picks the code to run.

The loop itself goes below. Each pass sends the whole history, then either stops or answers every call and goes round again:

Language: JavaScript Filename: assistant.js
while (true) {
  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;
  }

A failure ends the loop with no answer, and a reply with no calls is the answer, so it joins the history and the loop ends. The while loop has no other way out. Each break leaves it.

The rest of the loop handles a reply with calls. It adds the reply to the history first, so the model sees its own requests next time. Then it runs every call and adds each result with the call’s ID:

Language: JavaScript Filename: assistant.js
  messages.push({
    role: "assistant",
    toolCalls: reply.toolCalls,
  });
  for (const call of reply.toolCalls) {
    const result = await FUNCTIONS[call.name](call.args);
    console.log(call.name, call.args.to, "->", result.length);
    messages.push({
      role: "tool",
      callId: call.id,
      result,
      isError: false,
    });
  }
}

The for...of loop answers every call in the reply, not only the first, and the callId of each result is the id of the call it answers.

The await costs nothing with findSailings(), which returns its rows at once, but a lookup that calls an API or a database returns a promise, and without await the model would get the promise as {}. The log line prints the tool’s name, the destination it asked about, and how many sailings came back.

This loop is the core of the assistant, and it still trusts more than it should. It runs every call as the model asked it. Strict mode makes the arguments fit the schema, but it doesn’t make them right. Checking them before a tool runs comes later in this course.

The loop also assumes that findSailings() never throws and that the model stops asking after a round or two, so the loop has no cap on its rounds. Your next exercise addresses both assumptions, so run this version only with this question for now.

Run node --env-file=.env assistant.js, then open the version for your provider to compare your output:

Here’s one real run, with the long lines wrapped for display:

Language: Program Output
usage: { inputTokens: 193, outputTokens: 86 }
findSailings Gull Island -> 2
findSailings Heron Island -> 1
usage: { inputTokens: 393, outputTokens: 76 }
answer: Yes! The **9:15 a.m. ferry from Linden Harbor to Heron Island**
this Saturday, December 5, has **3 vehicle spaces left**.

The 8:00 a.m. Gull Island ferry is full for vehicles, but the 2:30 p.m.
sailing has 6 vehicle spaces left if afternoon works for you.

The model asked for two calls in the first reply, and both ran. The second request carried 393 input tokens, about twice as many as the first, because the calls and their results were part of it.

The answer matches the data. The 8:00 to Gull Island has no vehicle spaces, and the 9:15 to Heron Island has three. The asterisks are Markdown bold, which a chat window could render. At the gpt-6.2-sol model’s $2 per million input tokens and $10 per million output tokens, the two requests’ 586 input and 162 output tokens cost about 0.28 cents together.

No Anthropic output was recorded for this lesson. Your output has the same kinds of lines: a usage line for each request, a findSailings line for each call, and the answer line.

Anthropic’s documentation shows Claude calling several tools in one reply, so you may see both lookups in one round, or one per round. Each round adds a usage line. At the claude-sonnet-5-5 model’s $2 per million input tokens and $10 per million output tokens, a run of two or three requests this size costs well under a cent.

Your answer will be worded differently, and your token counts may differ a little. Whichever provider answered, the assistant’s code is the same.

The button above opens the mentor, if you’d like to trace the history round by round before the questions below.

Check Your Understanding

Answer these questions before you open the answers:

  1. A friend’s version of the loop leaves out the messages.push() call that adds the reply’s toolCalls entry, and pushes only the results. What happens on the second request, and why?
  2. The assistant gets a second tool, lookUpBooking, described in tools.js like FIND_SAILINGS. Which files change, and which stay as they are?
  3. With MAX_OUTPUT_TOKENS=20 in .env, the first request comes back with no tool calls and no text. What does askWithTools() return, and what does the loop do?
  1. The second request fails. The results quote call IDs that appear nowhere in the history, because the reply that made those calls never joined it. Each reply’s calls have to go into the history before their results.

    In a real run against OpenAI, the request came back with a 400 error: No tool call found for function call output with call_id call_.... Anthropic’s documentation requires every tool_result block to come right after the assistant message with its tool_use block, and names the error you’d get otherwise.

  2. Only tools.js and assistant.js change. You add the description and function to tools.js. In assistant.js, you add the description to TOOLS and the function to FUNCTIONS. Nothing in model/ changes, because each provider file’s toTool() wraps any description with a name, a description, and a schema in its provider’s format.

  3. askWithTools() returns failure: "cut off", with an empty toolCalls array and answer: null. In a real run, the first request stopped at 20 output tokens, and the loop printed No answer: cut off and exited. It didn’t treat the empty reply as the answer, because the module accepts only replies that finish normally.

Your booking assistant now answers every tool call by its ID and stops at a finished answer, through one function that works with either provider.

The next lesson, Exercise: Answer Every Tool Call, is a coding exercise that runs in your browser with a scripted stand-in model, so it needs no key. You edit the code, click Run Tests, and read the feedback to see what to change. The Contents tab explains how coding exercises work. In the exercise, you’ll get a teammate’s version of the assistant’s loop ready for a busy summer, with lookups that fail and a model that keeps asking.

Become a Member to join the conversation.