codespeech

Day 1 · · 2 min read

How tool calling actually works

The question

When a model “uses a tool”, who is actually doing the work? And what does the conversation look like on the wire?

The deep dive

Tool calling is a contract with three parts:

  1. You describe tools. Each one has a name, a description and a JSON Schema for its input.
  2. The model decides. If a tool would help, the reply stops with a structured tool_use block instead of plain text.
  3. You execute and reply. Your code runs the function and sends back a tool_result that references the call’s id. The model then continues.
Your code Model tools + messages tool_use runs the tool tool_result final answer codespeech.com
The model only asks. Your code does the running.

The model never touches your system. It only produces JSON that matches a schema you gave it. Everything risky happens in your code, which is also where you put validation and permissions.

An agent is this loop running until the model stops asking for tools.

Call the model Asked for a tool? yes Run the tools, send back tool_result repeat no Final answer codespeech.com
The whole agent: repeat until the model stops asking for tools.

The build

A minimal weather tool, with the loop written out by hand:

const tools = [{
  name: 'get_weather',
  description: 'Current weather for a city.',
  input_schema: {
    type: 'object',
    properties: { city: { type: 'string' } },
    required: ['city'],
  },
}];

let messages = [{ role: 'user', content: 'Do I need an umbrella in Leeds?' }];

while (true) {
  const res = await client.messages.create({ model, max_tokens: 1024, tools, messages });
  messages.push({ role: 'assistant', content: res.content });
  if (res.stop_reason !== 'tool_use') break;

  const results = await Promise.all(
    res.content
      .filter((b) => b.type === 'tool_use')
      .map(async (b) => ({
        type: 'tool_result',
        tool_use_id: b.id,
        content: JSON.stringify(await getWeather(b.input.city)),
      })),
  );
  messages.push({ role: 'user', content: results });
}

Gotchas

  • Descriptions are the prompt. A vague description gets vague tool choice. Say when not to use the tool, too.
  • Return errors as results. If a tool fails, send the error text back as the tool_result (marked as an error) so the model can recover, instead of throwing.
A tool fails throw an error loop stops send it back as tool_result model recovers codespeech.com
A failure the model can see is a failure it can handle.
  • Several calls can come in one turn. Handle every tool_use block, not just the first.
Model reply text tool_use id: a tool_use id: b Your reply tool_result id: a tool_result id: b codespeech.com
One tool_result for every tool_use, matched by id.

Was this useful?

Anonymous. Notes are read only by the author.

Related

Get each day's post by email

One short email per post. No spam, unsubscribe any time.

Buttondown will send you a confirmation email. Click the link in it to finish subscribing.