AI Engineering NotesRohit’s interview study guide
Chapter 04

Structured Output and Tool Calling

How to get data your code can trust out of a model, and how to let a model call your functions: JSON schemas and zod, validation and repair, the tool loop written by hand and with the SDK's runner, parallel calls, errors, server tools, and what replaced forced tool choice.

How these examples run. Every example ran on Node 26 with the real @anthropic-ai/sdk 1.17.0 and zod 4.6.7, and the Result under each one is what it printed. There is no API key in the examples, so each one starts with a block headed // Scripted replies: a stand-in for fetch that answers with replies in the exact shape the Messages API returns (ids, content blocks, stop_reason, usage). The model's words and tool choices inside those replies were written for the example; no model produced them. Everything below that block is the code you would ship. To run an example for real, delete the block and create the client with new Anthropic() and ANTHROPIC_API_KEY set. Real replies from current models can also carry thinking blocks next to the text and tool calls; the code here always picks blocks by type and sends response.content back unchanged, so it handles them without changes.

10 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Why applications need structured output

Added

A chat window is read by a person, and a person can read anything: a sentence, a bulleted list, a table, an apology followed by the answer. Your code can't. The moment a model's reply feeds an if statement, a database insert or a React component, it has to arrive in a shape your program knows in advance: these fields, these types, these allowed values. That is what "structured output" means: the model's answer is data that follows a schema, and not prose that a human has to interpret.

The mental model: treat the model like an external service whose response body you don't control. You would never write JSON.parse(body).user.address.city against a third-party API without a contract and a validator. A model is a third-party API whose "response format" is whatever text was most likely given your prompt. Left alone, it answers the same question with "Refund: yes", with a paragraph, or with JSON wrapped in a Markdown code fence, depending on small changes in the input. Structured output replaces "most likely text" with a contract.

There are three levels of contract, and it helps to name them, because interviewers ask what guarantees each one gives:

LevelHowWhat you can rely on
Ask nicely"Reply with JSON only" in the promptNothing. Usually works; fails on a long tail of inputs
Schema-constrainedoutput_config.format with a JSON schemaThe reply always parses and always matches the schema (unless the reply was cut off or refused)
Schema + your validationConstrained output, then your own checksThe shape and your business rules (totals add up, ids exist, dates are in the future)

The example below shows why the first level isn't enough. It takes three replies to the same question, "should this customer get a refund?", and runs the parser a developer typically writes first. The three replies were written for the example, in styles that models really do produce: a bare sentence, JSON in a code fence with a comment before it, and a hedged answer.

fragile-parse.mjsPlayground ↗
// Three replies to the same prompt: "Should order 1042 be refunded? Answer yes or no and give the amount."
// (Written for the example, in three styles a model can produce.)
const replies = [
  "Yes. The order qualifies for a full refund of $49.99.",
  "Here is the result:\n```json\n{\"refund\": true, \"amount\": 49.99}\n```",
  "I can't say yes or no with certainty, but the policy suggests no refund, since 45 days have passed (limit: 30).",
];

// Attempt 1: look for the word "yes".
const byKeyword = (text) => /\byes\b/i.test(text);
// Attempt 2: the prompt said "reply in JSON", so parse it.
const byJson = (text) => {
  try { return JSON.parse(text).refund; } catch (err) { return `throws ${err.name}`; }
};
// Attempt 3: pull the first number out as the amount.
const amount = (text) => Number(text.match(/\d+(\.\d+)?/)?.[0]);

replies.forEach((text, i) => {
  console.log(`reply ${i + 1}: keyword=${byKeyword(text)}  json=${byJson(text)}  amount=${amount(text)}`);
});
Result
reply 1: keyword=true  json=throws SyntaxError  amount=49.99
reply 2: keyword=false  json=throws SyntaxError  amount=49.99
reply 3: keyword=true  json=throws SyntaxError  amount=45
What’s happening
  1. The three strings stand in for three replies to one prompt. Nothing about them is unusual: a direct sentence, JSON wrapped in a Markdown code fence with a line of introduction, and a careful answer that explains itself.
  2. byKeyword looks for the word "yes". Reply 1 gives true (correct). Reply 2 means yes but never says the word, so it gives false. Reply 3 says "I can't say yes or no", so it gives true for an answer that means no. One parser, two wrong results out of three.
  3. byJson calls JSON.parse on the whole reply. It throws a SyntaxError on all three: replies 1 and 3 aren't JSON at all, and reply 2 contains JSON but starts with Here is the result: and a code fence. "Reply in JSON" in a prompt is a request, and the model's most likely text often includes a polite sentence around the data.
  4. amount grabs the first number. Replies 1 and 2 happen to give 49.99. Reply 3 gives 45, which is the number of days in the explanation, not an amount of money. The parser has no idea which number means what.
  5. No single attempt gets all three replies right, and each failure is silent: the code returns a wrong boolean or a wrong number and carries on. In production that's a refund issued for the wrong amount, with nothing in the logs.
  6. The fix isn't a cleverer regular expression. It's to stop parsing prose: make the model fill in { refund: boolean, amount: number } under a schema the API enforces, which is the next topic.
AdvancedWhere structured output shows up

Where structured output shows up in a real product:

  • Extraction: turning an email, a PDF or a support ticket into a row ({ category, priority, order_id }).
  • Classification and routing: an enum your code switches on ("billing" | "technical" | "sales").
  • UI generation: a list of typed blocks the front end renders as components, never raw HTML from the model.
  • Tool calls: the model asks your code to run a function, and the arguments are structured output with a schema. The second half of this chapter is about that.
  • Model-to-model hand-offs in a pipeline or an agent: one step's output is the next step's input, so it has to be parseable every time, not 98% of the time.
It parsed. Is it right?

A developer strips the sentence before the JSON and parses what's left. What does this print?

JavaScript
const reply = 'Sure! Here is the JSON:\n{"refund": true, "amount": "49.99"}';
const data = JSON.parse(reply.slice(reply.indexOf("{")));
console.log(data.amount + 10, data.amount > 100, data.refund === "true");
Show answer

49.9910 false false. The JSON parsed, and two of the three results are still wrong.

What’s happening
  1. reply.indexOf("{") finds the start of the object, so JSON.parse succeeds: no exception, which is what makes this bug quiet.
  2. data.amount is the string "49.99": the model put quotes round the number. "49.99" + 10 is string concatenation, so the first value is 49.9910. A refund of "49.9910" euros would go to the payment system.
  3. data.amount > 100 compares a string with a number; JavaScript converts "49.99" to 49.99, so this one happens to be right (false). Code that's right by accident is the hardest kind to notice.
  4. data.refund is the boolean true, and true === "true" is false. Code written for a model that sometimes says "true" in quotes now refuses a refund the model approved.
  5. "It's valid JSON" only says the brackets balance. Types and allowed values need a schema: with output_config.format, amount is always a number and refund always a boolean, and a zod check on your side catches the rest.

#Structured outputs with a JSON schema

Added

Structured outputs is the API feature that turns "please return JSON" into a guarantee. You send a JSON schema in output_config.format, and the model's reply is a single text block whose content is JSON that matches that schema: every required field present, every enum value one of yours, no extra keys.

How can an API guarantee what a model writes? Recall from Next-token prediction and the generation loop that a model produces a probability for every possible next token and a sampler picks one. Constrained decoding adds a filter between those two steps: the schema is compiled into a grammar, and at each step every token that would break the grammar is removed before picking. If the schema says the next thing must be one of "billing", "shipping" or "other", tokens that start anything else simply can't be chosen. Anthropic's documentation describes it in those words: structured outputs "guarantee schema-compliant responses through constrained decoding", using "constrained sampling with compiled grammar artifacts" (platform.claude.com, Structured outputs, read December 2026). The mental model is a form with locked fields: the model still decides what to write in each box, but it can't write outside the boxes, skip a required one, or add its own.

In TypeScript you don't write the JSON schema by hand. You write a zod schema (which you probably already use to validate request bodies), and the SDK's zodOutputFormat helper converts it. client.messages.parse() then sends the request, parses the reply and validates it against the same zod schema, so parsed_output is fully typed.

extract-ticket.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";

// Scripted replies (see "How these examples run")
const script = [{
  id: "msg_01Kq2vXb7RtYw3NfD8sLmP4c", type: "message", role: "assistant", model: "claude-opus-5-5",
  content: [{ type: "text", text: '{"category":"shipping","priority":"high","order_id":"A-10422","summary":"Parcel marked delivered but not received; customer wants it before a trip on Friday.","needs_human":false}' }],
  stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 412, output_tokens: 58 },
}];
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const Ticket = z.object({
  category: z.enum(["billing", "shipping", "technical", "other"]),
  priority: z.enum(["low", "normal", "high"]),
  order_id: z.string().nullable().describe("The order id exactly as written, or null if the email has none"),
  summary: z.string().describe("One sentence, no personal data"),
  needs_human: z.boolean(),
});

const email = `Hi, order A-10422 says "delivered" since Monday but nothing arrived.
I'm travelling on Friday and really need it before then. Can you check? Thanks, Priya`;

const format = zodOutputFormat(Ticket);
console.log("format sent:", format.type);
for (const [key, value] of Object.entries(format.schema.properties)) console.log(`  ${key}: ${JSON.stringify(value)}`);
console.log("  required:", format.schema.required.join(", "), "| additionalProperties:", format.schema.additionalProperties);

const message = await client.messages.parse({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  system: "You triage support emails for an online shop. Fill in the ticket fields from the email.",
  messages: [{ role: "user", content: `<email>\n${email}\n</email>` }],
  output_config: { format },
});

const ticket = message.parsed_output;
console.log("stop_reason:", message.stop_reason);
console.log("raw text:", message.content[0].text.slice(0, 44) + "…");
console.log("parsed:", ticket);
if (ticket.priority === "high") console.log(`-> page the ${ticket.category} queue about ${ticket.order_id}`);
Result
format sent: json_schema
  category: {"enum":["billing","shipping","technical","other"]}
  priority: {"enum":["low","normal","high"]}
  order_id: {"anyOf":[{"$ref":"#/$defs/__schema0"},{"type":"null"}],"description":"The order id exactly as written, or null if the email has none"}
  summary: {"type":"string","description":"One sentence, no personal data"}
  needs_human: {"type":"boolean"}
  required: category, priority, order_id, summary, needs_human | additionalProperties: false
stop_reason: end_turn
raw text: {"category":"shipping","priority":"high","or…
parsed: {
  category: 'shipping',
  priority: 'high',
  order_id: 'A-10422',
  summary: 'Parcel marked delivered but not received; customer wants it before a trip on Friday.',
  needs_human: false
}
-> page the shipping queue about A-10422
What’s happening
  1. Ticket is an ordinary zod schema: two enums, a nullable string, a string and a boolean. .describe() attaches a description to a field; .nullable() on order_id gives the model a legal way to say "the email didn't include one".
  2. zodOutputFormat(Ticket) converts it into the object the API wants. The printed lines show what was actually sent: type is json_schema, each enum became {"enum":[…]}, the nullable string became an anyOf of a string and null, the descriptions travelled with their fields, every field is in required and additionalProperties is false. Those last two are what "no missing fields, no extra keys" means in schema terms.
  3. client.messages.parse() sends a normal Messages request with that object under output_config.format. The email goes in the user message inside <email> tags so the model can tell the data from the instructions.
  4. The reply (scripted here) comes back with stop_reason: "end_turn" and one text block. The raw text is a JSON string, as the raw text: line shows: structured output doesn't add a new block type, it constrains what the text block may contain.
  5. parse() then runs JSON.parse on that text and validates the result with the zod schema, and puts the typed object on message.parsed_output. In TypeScript its type is inferred from the schema, so ticket.priority is "low" | "normal" | "high", not string.
  6. The last line is the point of the whole exercise: if (ticket.priority === "high") is plain code branching on a model's judgement, with no parsing and no "what if it said High priority!" case. The model decided the category and priority; the schema decided the vocabulary.
AdvancedWhat a schema can and can't say

The grammar compiler supports a subset of JSON Schema. From Anthropic's documentation (December 2026):

SupportedNot supported
object, array, string, integer, number, boolean, nullRecursive schemas
enum, const, anyOf, allOf, $ref / $defsoneOf (use anyOf), not
String formats: date-time, time, date, duration, email, hostname, uri, ipv4, ipv6, uuidNumber limits: minimum, maximum, multipleOf
required, and additionalProperties: false (which every object must have)String limits: minLength, maxLength
Array minItems of 0 or 1Other array limits

So the grammar can force "an integer", but not "an integer from 0 to 120". The SDK deals with that for you, and the next example shows exactly how: it strips the unsupported keywords out of the schema it sends, writes them into the field's description so the model still reads them, and enforces them on your side when it validates the reply.

schema-limits.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";

// Scripted replies (see "How these examples run")
const reply = (text, stop_reason = "end_turn") => ({
  id: "msg_01Vh6TqZc2LpWd9BnE5rXy7a", type: "message", role: "assistant", model: "claude-opus-5-5",
  content: [{ type: "text", text }], stop_reason, stop_sequence: null, usage: { input_tokens: 96, output_tokens: 21 },
});
const script = [
  reply('{"name":"Asha Rao","age":34,"email":null}'),
  reply('{"name":"Asha Rao","age":340,"email":null}'), // matches the grammar (an integer), breaks the zod rule
  reply('{"name":"Asha Rao","ag', "max_tokens"), // cut off mid-object
];
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const Person = z.object({
  name: z.string().min(1),
  age: z.number().int().min(0).max(120),
  email: z.string().email().nullable(),
});
const format = zodOutputFormat(Person);
console.log("age as sent:", JSON.stringify(format.schema.properties.age));
console.log("name as sent:", JSON.stringify(format.schema.properties.name));

for (const label of ["valid", "age out of range", "cut off"]) {
  try {
    const message = await client.messages.parse({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      messages: [{ role: "user", content: "Extract the person from: Asha Rao, 34." }],
      output_config: { format },
    });
    console.log(`${label}: parsed`, JSON.stringify(message.parsed_output));
  } catch (err) {
    const detail = err.message.match(/"message": "([^"]+)"/)?.[1] ?? err.message.split(": ").slice(2).join(": ");
    console.log(`${label}: ${err.constructor.name}: ${detail}`);
  }
}
Result
age as sent: {"type":"integer","description":"{minimum: 0, maximum: 120}"}
name as sent: {"type":"string","description":"{minLength: 1}"}
valid: parsed {"name":"Asha Rao","age":34,"email":null}
age out of range: AnthropicError: Too big: expected number to be <=120
cut off: AnthropicError: Failed to parse structured output as JSON: Unterminated string in JSON at position 22 (line 1 column 23)
What’s happening
  1. Person uses three rules the grammar can't express: min(1) on a string, min(0).max(120) on an integer, and an email format on a nullable string.
  2. The first two printed lines show what the SDK does about it. age is sent as {"type":"integer","description":"{minimum: 0, maximum: 120}"}: the limits are removed as constraints and written into the description, so the grammar only forces "an integer" while the model can still read the intended range. name gets the same treatment for minLength.
  3. Reply 1 is age: 34. It parses, passes zod, and parsed_output is the object.
  4. Reply 2 is age: 340. For the grammar that's a fine integer, so the API would return it. The SDK then validates against the original zod schema, the max(120) rule fails, and parse() throws an AnthropicError whose message carries zod's issue: Too big: expected number to be <=120. Constraints the server can't enforce are enforced on your side, loudly.
  5. Reply 3 has stop_reason: "max_tokens" and the text stops at {"name":"Asha Rao","ag. parse() throws again, this time from JSON.parse: Unterminated string in JSON at position 22. A token limit beats a grammar: the output is valid so far, and incomplete.
  6. So "guaranteed" has a precise meaning: the shape is guaranteed for a reply that finished normally. Ranges, lengths and patterns are checked by your validator, and truncation and refusals are checked by reading stop_reason.
AdvancedLatency, cost and schema design notes

Practical notes

  • The first request with a new schema is slower. The grammar has to be compiled; Anthropic caches compiled grammars for 24 hours from last use. Changing the structure of the schema compiles a new one; changing only a description doesn't.
  • It costs a few input tokens. The API adds a short system prompt describing the format, billed like any other input. And changing output_config.format between turns invalidates the prompt cache for that conversation (see Prompt caching), so keep one schema per conversation.
  • Not with citations. A request that turns on document citations and sets output_config.format is rejected with a 400: citations need to interleave citation blocks with text, which the grammar doesn't allow.
  • Descriptions are prompt text. .describe("The order id exactly as written, or null…") ends up in the schema the model reads. It is the cheapest place to say what a field means, what format it takes and when to use null.
  • Make "I don't know" representable. If a field can be missing from the source, make it .nullable(). A schema that requires a string forces the model to put something there, and the most likely something is an invented value. This is the single most common cause of hallucinated fields in extraction.
  • Field order is generation order. The model writes the object from the first key to the last. Put a field that benefits from reasoning (a short reasoning or evidence string) before the verdict it supports, so the verdict is written with that text already in context. On current Claude models the model also thinks before answering (see Reasoning models and thinking), so this matters less than it once did, but it never hurts.
  • Other providers have the same feature under other names. OpenAI calls its version Structured Outputs, and the AI SDK wraps each provider's version behind one call that takes a zod schema (see Provider-neutral code with the AI SDK). The idea, a schema compiled into a constraint on decoding, is the same; check each provider's supported-schema list, because the subsets differ.
What does the API actually enforce?

This schema goes through zodOutputFormat. For each of the four fields, is its rule enforced by the API's grammar, or only by your own code after the reply arrives? The lines below are what the helper really sends (run with SDK 1.17.0 and zod 4.6.7).

JavaScript
const Review = z.object({
  verdict: z.enum(["approve", "reject"]),
  score: z.number().min(0).max(1),
  tags: z.array(z.string()).max(3),
  note: z.string().optional(),
});
const { schema } = zodOutputFormat(Review);
// verdict {"enum":["approve","reject"]}
// score   {"type":"number","description":"{minimum: 0, maximum: 1}"}
// tags    {"type":"array","items":{…},"description":"{maxItems: 3}"}
// note    {"type":"string"}
// required: verdict, score, tags
Show answer

Grammar: verdict is one of two values, score is a number, tags is an array of strings, and verdict, score and tags are present. Your code only: the range of score and the length of tags.

What’s happening
  1. verdict is sent as an enum. The grammar can only produce "approve" or "reject": fully enforced by the API.
  2. score is sent as {"type":"number"} with the limits moved into the description. The grammar guarantees a number; 1.7 is a valid number. The 0-to-1 rule is checked by zod when messages.parse() validates the reply, and a violation throws.
  3. tags is the same story: an array of strings is guaranteed, maxItems: 3 became a description. Five tags would pass the API and fail zod.
  4. note is optional, so it isn't in required: the model may leave it out, and your code must handle undefined. (Use .nullable() if you'd rather always get the key.)
  5. The rule to remember: types, enums and required keys are the API's job; ranges, lengths and business rules are yours. The SDK tells the model about the second kind through descriptions and enforces them on your side.

#Validating and repairing model output

Added

Constrained output answers "is it the right shape?". It can't answer "is it right?". An invoice whose line items don't add up to its total, a meeting that ends before it starts, a customer_id that doesn't exist in your database: all of these are perfectly valid JSON matching a perfectly reasonable schema. And some setups have no constraint at all: an open-weight model served without grammar support, a provider or gateway that ignores the schema, or a reply that was cut off. So every production pipeline has a second line of defence: validate in your code, and decide what happens when validation fails.

The mental model is the one you already use for user input: parse, don't trust. A model's reply gets exactly the treatment of a form submission. Run it through a zod schema that includes your business rules, and you either hold a typed value you can rely on, or a list of precise issues. What's new compared with a form is what you can do with those issues: you can hand them back to the model and ask it to fix its own answer. That is a repair loop, and it works well because a validation error is a very specific instruction: "total: expected 118.00, the line items sum to 108.00" is much easier to act on than the original task.

The loop has three rules. Send the model its previous answer and the exact errors, not just "try again". Cap the attempts (one or two repairs; if a second repair fails, a third almost never succeeds, and you're paying for every try). And have a fallback for when the cap is reached: a queue for human review, a default, or an error to the caller, but never an unvalidated value passed downstream.

repair-loop.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";

// Scripted replies (see "How these examples run")
const reply = (n, obj) => ({
  id: `msg_01Rp${n}aLw8XcVe2TgYk6ZsQ4nB`, type: "message", role: "assistant", model: "claude-opus-5-5",
  content: [{ type: "text", text: JSON.stringify(obj) }],
  stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 300 + 90 * n, output_tokens: 74 },
});
const lines = [{ description: "Standing desk", quantity: 1, unit_price: 400 }, { description: "Monitor arm", quantity: 2, unit_price: 45 }];
const script = [
  reply(1, { invoice_number: "INV-2291", currency: "EUR", lines, total: 445, due_date: "2026-11-30" }), // total misses one arm
  reply(2, { invoice_number: "INV-2291", currency: "EUR", lines, total: 490, due_date: "2026-12-30" }),
];
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

// The shape: what the grammar can enforce.
const Invoice = z.object({
  invoice_number: z.string(),
  currency: z.enum(["EUR", "USD", "GBP"]),
  lines: z.array(z.object({ description: z.string(), quantity: z.number().int(), unit_price: z.number() })),
  total: z.number(),
  due_date: z.iso.date(),
});
// The business rules: what only your code knows.
const TODAY = "2026-12-06"; // fixed so the example prints the same every day
const CheckedInvoice = Invoice.superRefine((inv, ctx) => {
  const sum = inv.lines.reduce((s, l) => s + l.quantity * l.unit_price, 0);
  if (sum !== inv.total) ctx.addIssue({ code: "custom", path: ["total"], message: `total is ${inv.total} but the lines sum to ${sum}` });
  if (inv.due_date < TODAY) ctx.addIssue({ code: "custom", path: ["due_date"], message: `due_date ${inv.due_date} is before today (${TODAY})` });
});

async function extractInvoice(text, maxRepairs = 2) {
  const messages = [{ role: "user", content: `Extract the invoice.\n<invoice>\n${text}\n</invoice>` }];
  for (let attempt = 0; attempt <= maxRepairs; attempt++) {
    const message = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      messages,
      output_config: { format: zodOutputFormat(Invoice) },
    });
    if (message.stop_reason !== "end_turn") return { ok: false, reason: `stopped with ${message.stop_reason}` };
    const raw = message.content.find((b) => b.type === "text").text;
    const checked = CheckedInvoice.safeParse(JSON.parse(raw));
    if (checked.success) return { ok: true, invoice: checked.data, attempts: attempt + 1 };

    const problems = checked.error.issues.map((i) => `- ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
    console.log(`attempt ${attempt + 1} failed validation:\n${problems}`);
    messages.push({ role: "assistant", content: message.content });
    messages.push({ role: "user", content: `That answer failed validation:\n${problems}\nRe-read the invoice and return the corrected JSON.` });
  }
  return { ok: false, reason: `still invalid after ${maxRepairs} repairs` };
}

const result = await extractInvoice("INV-2291 … 1 × Standing desk €400, 2 × Monitor arm €45 … Total €490 … due 30 December 2026");
console.log(result.ok ? `ok after ${result.attempts} attempts: total ${result.invoice.total}, due ${result.invoice.due_date}` : `gave up: ${result.reason}`);
Result
attempt 1 failed validation:
- total: total is 445 but the lines sum to 490
- due_date: due_date 2026-11-30 is before today (2026-12-06)
ok after 2 attempts: total 490, due 2026-12-30
What’s happening
  1. There are two schemas on purpose. Invoice is the shape, and it's what goes to the API as the output format. CheckedInvoice adds the rules only your code can know, with superRefine: the lines must sum to the total, and the due date can't be in the past (TODAY is a fixed string so the example prints the same every day; z.iso.date() strings compare correctly as text).
  2. Attempt 1: messages.create returns a reply with stop_reason: "end_turn", so the JSON is complete. The code checks the stop reason before parsing; a max_tokens or refusal reply returns a typed failure straight away and is never fed to JSON.parse.
  3. CheckedInvoice.safeParse doesn't throw; it returns { success: false, error }. The scripted first answer has total: 445 (it counted one monitor arm, not two) and a due date in November, so there are two issues, each with a path and a message. They're printed as the two lines under attempt 1 failed validation.
  4. The repair turn pushes two messages: the assistant's failed answer exactly as it came back (message.content), then a user message with the issue list and a short instruction. The model's next request therefore contains the invoice text, its own wrong answer and precisely what was wrong with it.
  5. Attempt 2 returns total: 490 and due_date: "2026-12-30". Both rules pass, and the function returns { ok: true, invoice, attempts: 2 }.
  6. If the second and third answers had also failed, the loop would end and return { ok: false, reason: "still invalid after 2 repairs" }. The caller always gets a validated invoice or an explicit failure; there is no path on which unchecked model output leaves this function.
AdvancedWhen the model isn't constrained at all

With an open-weight model behind a server that has no grammar support, or any API where you only "asked nicely", the failures come one step earlier: the text isn't JSON yet. The usual offenders are a Markdown code fence around the object, a sentence before or after it, and a cut-off reply. A small tolerant extractor in front of the validator handles the first two; it must refuse the third.

lenient-json.mjsPlayground ↗
import { z } from "zod";

const Verdict = z.object({ refund: z.boolean(), amount: z.number().nonnegative() });

// Find the JSON object in a reply that may have a code fence or prose around it.
function extractJson(text) {
  const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
  const candidate = fenced ? fenced[1] : text;
  const start = candidate.indexOf("{");
  const end = candidate.lastIndexOf("}");
  if (start === -1 || end <= start) throw new Error("no JSON object found");
  return JSON.parse(candidate.slice(start, end + 1));
}

const replies = {
  clean: '{"refund": true, "amount": 49.99}',
  fenced: 'Here is the result:\n```json\n{"refund": true, "amount": 49.99}\n```\nLet me know if you need anything else.',
  prose: 'Sure! {"refund": false, "amount": 0} is my assessment.',
  truncated: '{"refund": true, "amo',
  "wrong type": '{"refund": "yes", "amount": "49.99"}',
};

for (const [name, text] of Object.entries(replies)) {
  try {
    const parsed = Verdict.safeParse(extractJson(text));
    console.log(`${name}: ${parsed.success ? "ok " + JSON.stringify(parsed.data) : "invalid: " + parsed.error.issues.map((i) => `${i.path[0]}: ${i.message}`).join("; ")}`);
  } catch (err) {
    console.log(`${name}: rejected (${err.message})`);
  }
}
Result
clean: ok {"refund":true,"amount":49.99}
fenced: ok {"refund":true,"amount":49.99}
prose: ok {"refund":false,"amount":0}
truncated: rejected (no JSON object found)
wrong type: invalid: refund: Invalid input: expected boolean, received string; amount: Invalid input: expected number, received string
What’s happening
  1. extractJson handles the two harmless wrappers. If there's a fenced block, it takes what's inside; then it slices from the first { to the last } and parses that.
  2. clean, fenced and prose all come out as valid objects. The fenced reply had a sentence before and after it; the prose reply had text on both sides of the object. Both would have crashed a bare JSON.parse.
  3. truncated is {"refund": true, "amo: there's an opening brace and no closing one, so the function throws no JSON object found. That's the right behaviour. Libraries that "repair" truncated JSON by closing the brackets will happily hand you {"refund": true} with the amount missing; a tolerant parser must never invent the end of an answer.
  4. wrong type parses as JSON, and then zod rejects it: refund is the string "yes" and amount is the string "49.99". The extractor fixes packaging; the schema still decides what's acceptable.
  5. This is the fallback stack for unconstrained models: extract, validate, and (from the previous example) repair. With output_config.format on a model that supports it, the first step disappears, which is one less thing to get wrong.
AdvancedDeciding what a failure means
  • Repair or retry? A retry resends the same request and hopes; it only helps when the failure was random (a truncation you fix by raising max_tokens, a transient error). A repair adds the failed answer and the errors to the conversation; it helps when the model made a mistake it can see once it's pointed out. Use the right one: retrying a deterministic mistake just pays for the same mistake twice.
  • Don't coerce silently. It's tempting to write z.coerce.number() so "49.99" becomes 49.99. That's fine for a string-typed number; it's dangerous for anything where the model's confusion is the signal (a "yes" where a boolean was expected often means the model misread the task). Coerce formats, never meanings.
  • Know what each attempt costs. A repair turn resends the whole conversation plus the failed answer, so the second attempt costs more input tokens than the first. Budget for it: if 3% of calls need one repair, the pipeline costs about 3% more, which is cheap; if 40% need one, the prompt or the schema is wrong, and you should fix that and not lean on the loop.
  • Log every failure with the raw text. Validation failures are free eval cases (see Building an eval set): each one is a real input your prompt handles badly.
  • Give up loudly. After the cap, return a typed failure ({ ok: false, reason }) the caller must handle. A pipeline that falls back to "best effort" unvalidated data has no validation.
Which failures can a repair turn fix?

For each failure, would you (a) repair by sending the error back, (b) retry with a changed request, or (c) do neither: the reply has stop_reason: "max_tokens"; the total doesn't match the line items; the reply has stop_reason: "refusal"; a required customer_id was filled with an id that isn't in your database.

Show answer

Retry with a higher max_tokens; repair; neither; repair, but only if the model can find out which ids are valid.

What’s happening
  1. max_tokens: the model didn't make a mistake, it ran out of room. Sending the half-written JSON back as an "error" teaches it nothing. Resend the same request with a larger max_tokens (or ask for less output).
  2. Totals that don't add up: a mistake the model can see once you state it precisely, so a repair turn with the exact numbers (total is 445 but the lines sum to 490) is the right tool. This is the case the example ran.
  3. Refusal: the model declined on policy grounds; repeating or "repairing" won't change that, and pushing harder is the wrong instinct. Return a typed failure and route the item to a person or a different process (see Stop reasons and refusals).
  4. An id that doesn't exist: telling the model "that id is invalid" only helps if it has a way to get a valid one. If the valid ids (or a lookup tool) are in the conversation, repair. If not, the model can only guess again, so make the field nullable and resolve the id in code.
  5. The pattern: a repair turn works when the error message contains enough information to do better. If it doesn't, change what the model can see or what it's asked to produce.

#How tool calling works

Added

A model can only produce text. It can't look up an order, read the clock, query your database or send an email. Tool calling (also called function calling) is the convention that gets around this: you describe functions the model may ask for, and when it wants one, it stops and replies with a structured request, "call get_order with { "order_id": "A-10422" }", in place of an answer. Your code runs the function, sends the result back, and the model continues with that result in its context.

The single most important sentence in this chapter: the model never executes anything. It writes a request; your process decides whether and how to run it. That's why tool calling is safe to reason about (every side effect goes through code you wrote) and why it's a loop (each request-and-result is one more round trip to the API).

The mental model is a colleague on the phone who has no computer. You tell them at the start which lookups you can do for them. They ask, "can you check order A-10422?"; you look it up and read out the result; they think and either ask for something else or give the customer the answer. They choose what to ask for; you do the work and can always say no.

Your code Model (API) 1. request tools + user message 2. stop_reason: "tool_use" tool_use { id, name, input } 3. run the function validate, execute, catch 4. request: history + result tool_result { tool_use_id, content } 5. stop_reason: "end_turn" text: the answer Steps 2 to 4 repeat while the model keeps asking for tools.
One tool call is two API requests. The model writes the request for a call; your code runs it and sends the result back with the whole history.

Four pieces of data make up the protocol. All four appear in the example below.

PieceWhereWhat it is
Tool definitiontools in the requestname, description, and input_schema (a JSON schema for the arguments)
tool_use blockThe model's reply (content)id, name and input: the model's request to call one tool
stop_reason: "tool_use"The model's reply"I've stopped because I'm waiting for tool results"
tool_result blockYour next user messagetool_use_id (matching the request's id) and content (the result, as text)
one-tool-call.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const reply = (id, content, stop_reason, usage) => ({
  id, type: "message", role: "assistant", model: "claude-opus-5-5", content, stop_reason, stop_sequence: null, usage,
});
const script = [
  reply("msg_01Hn4kTz8QwLb6VxPc2RmYe9Ad", [
    { type: "text", text: "I'll look that order up." },
    { type: "tool_use", id: "toolu_01B7xNq3MvKd5WpZt8LcGy2Rf", name: "get_order", input: { order_id: "A-10422" }, caller: { type: "direct" } },
  ], "tool_use", { input_tokens: 438, output_tokens: 52 }),
  reply("msg_01Jp9wRc3YtNf7ZqSd5VkXb2Ge", [
    { type: "text", text: "Order A-10422 shipped on 1 December with DHL and is due on 8 December." },
  ], "end_turn", { input_tokens: 531, output_tokens: 27 }),
];
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const tools = [{
  name: "get_order",
  description: "Look up one order by its id. Call this whenever the user asks about the status, contents or delivery of a specific order. Returns status, carrier and expected delivery date.",
  input_schema: {
    type: "object",
    properties: { order_id: { type: "string", description: "The order id, e.g. A-10422" } },
    required: ["order_id"],
    additionalProperties: false,
  },
}];
const orders = { "A-10422": { status: "shipped", carrier: "DHL", shipped: "2026-12-01", expected: "2026-12-08" } };
const getOrder = ({ order_id }) => orders[order_id] ?? { error: `No order with id ${order_id}` };

const messages = [{ role: "user", content: "Where is my order A-10422?" }];

// Request 1: the question plus the tool definitions.
const first = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
console.log("1st reply stop_reason:", first.stop_reason);
for (const block of first.content) console.log("  block:", block.type, block.type === "tool_use" ? `${block.name} ${JSON.stringify(block.input)}` : JSON.stringify(block.text));

// Run the tool the model asked for, in our own process.
const call = first.content.find((b) => b.type === "tool_use");
const result = getOrder(call.input);
console.log("ran get_order ->", JSON.stringify(result));

// Request 2: everything so far, plus the result, linked to the call by its id.
messages.push({ role: "assistant", content: first.content });
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: call.id, content: JSON.stringify(result) }] });
console.log("2nd request roles:", messages.map((m) => m.role).join(" -> "));

const second = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
console.log("2nd reply stop_reason:", second.stop_reason);
console.log("answer:", second.content.find((b) => b.type === "text").text);
console.log("input tokens:", first.usage.input_tokens, "+", second.usage.input_tokens);
Result
1st reply stop_reason: tool_use
  block: text "I'll look that order up."
  block: tool_use get_order {"order_id":"A-10422"}
ran get_order -> {"status":"shipped","carrier":"DHL","shipped":"2026-12-01","expected":"2026-12-08"}
2nd request roles: user -> assistant -> user
2nd reply stop_reason: end_turn
answer: Order A-10422 shipped on 1 December with DHL and is due on 8 December.
input tokens: 438 + 531
What’s happening
  1. The request carries tools: one definition with a name, a description that says when to call it, and an input_schema for the arguments. The orders object and getOrder function are ordinary application code; the model never sees them, only the definition.
  2. Request 1 sends the user's question. The reply has stop_reason: "tool_use" and two content blocks: a text block ("I'll look that order up.") and a tool_use block naming get_order with input {"order_id":"A-10422"}. The model pulled the id out of the question and put it where the schema said it goes. input arrives already parsed, as an object.
  3. The model has now stopped. Nothing has been looked up yet. first.content.find((b) => b.type === "tool_use") gets the request, and getOrder(call.input) runs in this process and returns the order record.
  4. The conversation is rebuilt for request 2: the original user message, then an assistant message whose content is first.content unchanged (both blocks, including the tool_use with its id), then a user message containing a tool_result block. tool_use_id: call.id is what ties the result to the request; the printed roles are user -> assistant -> user.
  5. Request 2 returns stop_reason: "end_turn" and a text block that uses the data: shipped on 1 December with DHL, due on 8 December. Those facts exist only in the tool result, which is the whole point: the answer is grounded in your data, not in what the model remembers.
  6. The last line shows the cost of the round trip: 438 input tokens for the first request and 531 for the second (scripted figures, but the direction is real). The second request is bigger because it resends everything, plus the model's tool request and the result. Tool calls are never free: each one is another full request.
AdvancedWhat the model actually sees

There is no special "tool channel" inside the model. The API turns your tools array into text placed at the very start of the prompt (the order is tools, then system prompt, then messages), and the model was trained to answer with a tool request when one fits. Three consequences follow, and all three come up in interviews:

  • Tool definitions are prompt. The description is the main thing the model uses to decide whether to call a tool, and every definition is billed as input tokens on every request. Thirty verbose tools are a long prompt before the user has said a word.
  • Tool results are context. A result is just more text in the conversation, and it stays there (and is billed again) on every later request. A tool that returns a 50 KB JSON blob makes every remaining step slower and more expensive, and buries the useful part.
  • Arguments are model output. input was written by a model, possibly after reading text an attacker controls (a web page, an email). Treat it like a request body from the internet: validate it, authorise it against the user's permissions, and never build SQL or shell commands from it by string concatenation. Excessive agency and tool permissions goes deeper.
The history that stores only text

To save space, a teammate stores each assistant turn as plain text: messages.push({ role: "assistant", content: textOf(response) }). Then they push the tool_result as usual. The first tool call in production fails. Why, and what's the smallest fix?

Show answer

The second request is rejected with a 400: the tool_result refers to a tool_use id that no longer exists in the conversation. Push response.content unchanged.

What’s happening
  1. The model's reply had two blocks: a text block and a tool_use block with an id such as toolu_01B7….
  2. Keeping only the text drops the tool_use block. The assistant message in the history is now just "I'll look that order up.".
  3. The next user message carries { type: "tool_result", tool_use_id: "toolu_01B7…" }. The API checks that every tool_result answers a tool_use in the previous assistant message, finds none, and rejects the request.
  4. The fix is messages.push({ role: "assistant", content: response.content }): the whole array, every block, exactly as received. That's also what keeps thinking blocks and server-tool results valid on later turns.
  5. If storage size is the worry, trim old tool results or compact old turns (Memory and context management); never store a lossy copy of the turn you're about to answer.

#Designing tools a model can use

Added

A tool definition is an API you design for a reader that is a model. That reader is fast and well read, but it has never seen your codebase, can't ask a colleague what acct_ref means, and decides whether to call your tool from three things only: the name, the description and the parameter schema. Anthropic's "Building effective agents" article (December 2024) calls this the agent-computer interface, and says to give it the care a human-computer interface gets: "put yourself in the model's shoes" and write the definition like a good docstring for a junior developer.

The same article has the most quoted tool-design story in the field. While building a coding agent for the SWE-bench benchmark, Anthropic's team "spent more time optimizing our tools than the overall prompt". The model kept making mistakes with a file tool that took relative paths once it had moved out of the root directory; they changed the tool to "always require absolute filepaths", and the model then used it flawlessly. That's the mental model for this topic: when a model misuses a tool, fix the tool first. Change the arguments so the mistake can't be made (the article borrows the manufacturing word poka-yoke, mistake-proofing), and only then reach for more prompt.

Here is the same tool written twice. The left version is what most first attempts look like; the right version is what the model needs.

JavaScript
// Before
const tool = {
  name: "search",
  description: "Searches orders.",
  input_schema: {
    type: "object",
    properties: {
      q: { type: "string" },
      f: { type: "string" },
      n: { type: "number" },
    },
  },
};
JavaScript
// After
const tool = {
  name: "search_orders",
  description:
    "Search this customer's orders. Call this when the user refers to an " +
    "order without giving its id (\"my last order\", \"the headphones\"). " +
    "Returns at most `limit` orders, newest first, each with id, date, " +
    "status and item names. If you already have an order id, call get_order.",
  strict: true,
  input_schema: {
    type: "object",
    properties: {
      query: { type: "string", description: "Words from the item name, e.g. \"headphones\". Use \"\" for all orders." },
      status: { enum: ["any", "open", "shipped", "delivered", "cancelled"], description: "Filter by status; \"any\" for no filter." },
      limit: { type: "integer", description: "How many orders to return, 1 to 20. Use 5 unless the user asks for more." },
    },
    required: ["query", "status", "limit"],
    additionalProperties: false,
  },
};
What’s happening
  1. Name. search says nothing: search what? With ten tools in the request, the model picks among names first. search_orders states the verb and the object, and pairs naturally with get_order.
  2. Description. "Searches orders." repeats the name. The rewrite answers the four questions the model actually has: what it does, when to call it (with example phrasings from users), what comes back, and when to use a different tool. Anthropic's guidance is to be prescriptive about when to call a tool, because that trigger sentence is what moves the "should I call this?" decision.
  3. Parameter names. q, f and n force a guess. query, status and limit don't. Each has a description with the format and an example, which is where you say things like "use an empty string for all orders".
  4. Enums over free strings. f: string invites "Shipped", "in transit" and "status=shipped". status as an enum makes every value a valid one, and "any" gives the model an explicit way to say "no filter" where it would otherwise have to guess between omitting the field, null and "".
  5. strict: true with additionalProperties: false and every property in required turns the schema from a hint into a guarantee: the arguments are produced with the same constrained decoding as structured outputs, so tool_use.input always validates against the schema. Without strict, the schema is guidance the model nearly always follows.
  6. Limits live in the description, because the grammar can't express "1 to 20" (the same subset as in Structured outputs with a JSON schema). Your handler still has to clamp the value: the description asks, your code enforces.
AdvancedDesigning tool results and errors

What a tool returns matters as much as what it takes

The result of a tool call is the next thing the model reads, so design it like a prompt. Three rules cover most of it.

Return what the model needs, not what the database has. A raw row with forty columns, internal ids and audit timestamps costs tokens on every later request and hides the two fields that matter. Return a trimmed object with human-meaningful names ("status": "shipped", not "st": 3).

Bound the size. Any tool that can return a list needs a limit and should say when there's more ("showing 5 of 37; narrow the query or raise the limit"). A single unbounded result can fill the context window on its own.

Make errors instructions. When a call fails, the error text is the model's only clue about what to do next. "Error: 400" teaches nothing. "No order with id A-1042. Order ids look like A-10422 (a letter, a dash and five digits). Ask the user to check the id, or call search_orders." tells the model how to recover. The model below shows the difference in code: a small dispatcher that validates every call with zod and turns each kind of failure into a result the model can act on.

tool-errors.mjsPlayground ↗
import { z } from "zod";

const orders = { "A-10422": { status: "shipped", items: ["Standing desk"] } };

// Each tool: a zod schema for its input and a handler. A handler throws a ToolFailure for expected problems.
class ToolFailure extends Error {}
const registry = {
  get_order: {
    input: z.object({ order_id: z.string().regex(/^[A-Z]-\d{5}$/, "must look like A-10422 (a letter, a dash, five digits)") }),
    run: ({ order_id }) => {
      const order = orders[order_id];
      if (!order) throw new ToolFailure(`No order with id ${order_id}. Ask the user to check the id, or call search_orders to find it.`);
      return order;
    },
  },
  refund_order: {
    input: z.object({ order_id: z.string(), amount: z.number().positive() }),
    run: () => { throw new TypeError("Cannot read properties of undefined (reading 'charge')"); }, // a real bug
  },
};

// Turns one tool_use block into one tool_result block. Never throws.
async function executeTool(toolUse) {
  const result = (content, is_error = false) => ({ type: "tool_result", tool_use_id: toolUse.id, content, ...(is_error && { is_error }) });
  const tool = registry[toolUse.name];
  if (!tool) return result(`Unknown tool "${toolUse.name}". Available tools: ${Object.keys(registry).join(", ")}.`, true);
  const parsed = tool.input.safeParse(toolUse.input);
  if (!parsed.success) {
    return result("Invalid input: " + parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; "), true);
  }
  try {
    return result(JSON.stringify(await tool.run(parsed.data)));
  } catch (err) {
    if (err instanceof ToolFailure) return result(err.message, true);
    console.error(`[log] ${toolUse.name} crashed: ${err.message}`); // the stack trace goes to your logs, not to the model
    return result(`${toolUse.name} failed because of an internal error. Don't retry; tell the user it couldn't be done right now.`, true);
  }
}

const calls = [
  { id: "toolu_01", name: "get_order", input: { order_id: "A-10422" } },
  { id: "toolu_02", name: "get_order", input: { order_id: "10422" } },
  { id: "toolu_03", name: "get_order", input: { order_id: "A-99999" } },
  { id: "toolu_04", name: "cancel_order", input: { order_id: "A-10422" } },
  { id: "toolu_05", name: "refund_order", input: { order_id: "A-10422", amount: 400 } },
];
for (const call of calls) {
  const r = await executeTool(call);
  console.log(`${call.name}(${JSON.stringify(call.input)})\n  ${r.is_error ? "is_error" : "ok"}: ${r.content}`);
}
Result
get_order({"order_id":"A-10422"})
  ok: {"status":"shipped","items":["Standing desk"]}
get_order({"order_id":"10422"})
  is_error: Invalid input: order_id must look like A-10422 (a letter, a dash, five digits)
get_order({"order_id":"A-99999"})
  is_error: No order with id A-99999. Ask the user to check the id, or call search_orders to find it.
cancel_order({"order_id":"A-10422"})
  is_error: Unknown tool "cancel_order". Available tools: get_order, refund_order.
refund_order({"order_id":"A-10422","amount":400})
  is_error: refund_order failed because of an internal error. Don't retry; tell the user it couldn't be done right now.
What’s happening
  1. registry pairs each tool with a zod schema and a handler. executeTool is the one function that stands between a model's request and your code, and it has a rule: it never throws. Whatever happens, it returns a tool_result block, because the loop must always send one back.
  2. Call 1 is valid: A-10422 matches the pattern, the order exists, and the result is the order as JSON with no is_error field.
  3. Call 2 sends order_id: "10422". safeParse fails on the regex, and the result is is_error with zod's message, which was written for this reader: must look like A-10422 (a letter, a dash, five digits). The model can fix that by itself on the next turn.
  4. Call 3 is well formed but the order doesn't exist. The handler throws a ToolFailure, an expected failure, whose message says what to do next: ask the user, or call search_orders. That text goes straight to the model.
  5. Call 4 names a tool that isn't registered (models occasionally invent a plausible name, especially when a tool was mentioned in the conversation but not offered). The result lists the tools that do exist.
  6. Call 5 hits a real bug: a TypeError from deep in the handler. That is not shown to the model: the dispatcher logs Cannot read properties of undefined (reading 'charge') to stderr for you, and tells the model only that it failed and not to retry. Leaking raw exceptions wastes tokens, can expose internals, and invites the model to "fix" its arguments for a bug that isn't its fault.
  7. Five calls, five results, and four different kinds of failure, each telling the model something different: fix the argument, try another route, use a real tool, or stop. That distinction is what "errors that help" means.
AdvancedFew big tools or many small ones?

Both extremes fail. Too many small tools (one per REST endpoint: get_user, get_user_orders, get_order_items, get_item_price…) force the model to chain five calls to answer one question; every hop is a request, and every hop can go wrong. It also bloats the prompt: each definition is input tokens on every request. One giant tool (run_query(sql) or do(action, params)) pushes all the design into free-form arguments, gives you nothing to validate or gate, and gives the model nothing to choose between.

The useful question is: what would a person doing this job want as one action? Tools shaped like tasks ("find this customer's recent orders with their status") beat tools shaped like tables. A few concrete rules:

  • Merge calls that always happen together. If every get_order is followed by get_shipment, return the shipment inside the order.
  • Split by risk. Reading and writing belong in different tools so you can gate the write (confirmation, permissions) without slowing the read. refund_order should never be a mode of manage_order.
  • Keep names and boundaries distinct. Two tools the model could plausibly confuse (search_orders and find_orders) will be confused. Say in each description when to use the other one.
  • Watch the count. There's no hard limit worth quoting, but accuracy in choosing the right tool drops as the list grows, and the definitions are billed on every request. When you have dozens of tools and each request needs a few, Anthropic's tool search tool lets the model load definitions on demand (mark the rest defer_loading: true), and for a general-purpose agent, one bash tool plus a handful of dedicated tools for anything you need to gate or render is often the better shape (see Why agents fail and how to make them reliable).
Pick the calendar tool

An assistant must book meetings. Three designs are proposed. Which do you ship? (a) One tool calendar(action, params) where action is a free string and params is any object. (b) Tools mirroring the REST API: list_calendars, get_calendar, list_events, get_event, create_event, patch_event, delete_event, list_attendees, add_attendee. (c) find_free_slots(attendees, duration_minutes, between), book_meeting(slot_id, title, attendees) and cancel_meeting(meeting_id).

Show answer

(c): three tools shaped like the tasks, with the write actions separate from the read.

What’s happening
  1. Design (a) gives the model nothing to choose between and gives you nothing to validate: action can be any string, params any shape. You can't use strict, can't gate "delete" separately from "list", and every mistake is found at run time.
  2. Design (b) is validatable, and it makes one job ("find a time for these four people") into a chain of six or more calls, each a model round trip and each a chance to go wrong. Nine definitions are also billed as input tokens on every request.
  3. Design (c) matches what a person would ask an assistant to do. find_free_slots does the joining across calendars in your code, which is exact and fast, and returns a short list of slots with ids.
  4. book_meeting takes a slot_id from that list, not free-form start and end times. That's mistake-proofing: the model can't book a slot that wasn't offered, or get a time zone wrong.
  5. Reading and writing are separate tools, so book_meeting and cancel_meeting can require confirmation while find_free_slots runs freely.

#Writing the tool loop yourself

Added

One tool call is two requests. A real task is usually several: look up the order, then check the policy, then issue the refund, each step chosen by the model after reading the previous result. The code that keeps going until the model is finished is the tool loop (also called the agent loop: an agent is this loop plus good tools, as What an agent is explains). It's about thirty lines, and writing it once by hand is the best way to understand every agent framework you'll meet later, because they all contain this loop.

The mental model is a while loop around the two steps you've already seen: call the model; if it asked for tools, run them, append the results and go round again; otherwise stop. The model decides whether to continue (by asking for a tool or not). Your loop decides whether it's allowed to continue: a step limit, a check on each stop reason, and control over what each tool may do.

The loop has to get five things right, and each has a line in the example:

  1. Append the assistant's reply with all its content blocks before the results.
  2. Answer every tool_use block, in one user message.
  3. Send a failed tool back as a result with is_error: true; never drop it and never throw out of the loop for a failure the model could recover from.
  4. Stop for the right reason: end_turn is done; max_tokens and refusal are not "keep going".
  5. Cap the number of steps. A model that keeps calling tools, or two tools that keep sending it back and forth, would otherwise run until your budget is gone.
tool-loop.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
let n = 0;
const reply = (content, stop_reason, usage) => ({
  id: `msg_01Lw${++n}eXb4TqNs8VdKc2ZpRy6Ah`, type: "message", role: "assistant", model: "claude-opus-5-5",
  content, stop_reason, stop_sequence: null, usage,
});
const use = (id, name, input) => ({ type: "tool_use", id: `toolu_01${id}`, name, input, caller: { type: "direct" } });
const scriptFor = () => [
  reply([{ type: "text", text: "Let me check that order." }, use("Aq3", "get_order", { order_id: "A-10422" })], "tool_use", { input_tokens: 720, output_tokens: 48 }),
  reply([use("Bt7", "get_refund_policy", { reason: "not_delivered" })], "tool_use", { input_tokens: 842, output_tokens: 31 }),
  reply([{ type: "text", text: "The parcel is 5 days late, which is past the 3-day threshold, so a refund applies." }, use("Cz9", "refund_order", { order_id: "A-10422", amount: 490 })], "tool_use", { input_tokens: 951, output_tokens: 64 }),
  reply([{ type: "text", text: "I've refunded €490 for order A-10422 (refund R-7731). It should reach your card in 3 to 5 working days." }], "end_turn", { input_tokens: 1034, output_tokens: 39 }),
];
let script = scriptFor();
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const tools = [
  { name: "get_order", description: "Look up one order by id: status, total and delivery dates. Call this first whenever the user mentions an order.",
    input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"], additionalProperties: false } },
  { name: "get_refund_policy", description: "Get the refund rule for a reason. Call this before refunding anything.",
    input_schema: { type: "object", properties: { reason: { enum: ["not_delivered", "damaged", "changed_mind"] } }, required: ["reason"], additionalProperties: false } },
  { name: "refund_order", description: "Refund an order. Only call this after get_order and get_refund_policy show the refund is allowed.",
    input_schema: { type: "object", properties: { order_id: { type: "string" }, amount: { type: "number" } }, required: ["order_id", "amount"], additionalProperties: false } },
];
const handlers = {
  get_order: ({ order_id }) => ({ order_id, status: "in_transit", total: 490, currency: "EUR", promised: "2026-12-01", today: "2026-12-06" }),
  get_refund_policy: ({ reason }) => ({ reason, rule: "Full refund if the parcel is more than 3 days past the promised date." }),
  refund_order: ({ order_id, amount }) => ({ refund_id: "R-7731", order_id, amount, status: "issued" }),
};

async function runTool(block) {
  try {
    const handler = handlers[block.name];
    if (!handler) throw new Error(`Unknown tool ${block.name}`);
    return { type: "tool_result", tool_use_id: block.id, content: JSON.stringify(await handler(block.input)) };
  } catch (err) {
    return { type: "tool_result", tool_use_id: block.id, content: err.message, is_error: true };
  }
}

async function runLoop(userText, { maxSteps = 6 } = {}) {
  const messages = [{ role: "user", content: userText }];
  const usage = { input: 0, output: 0 };
  for (let step = 1; step <= maxSteps; step++) {
    const response = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      system: "You are a support agent for an online shop. Use the tools to check facts before acting.",
      tools,
      messages,
    });
    usage.input += response.usage.input_tokens;
    usage.output += response.usage.output_tokens;
    const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
    const calls = response.content.filter((b) => b.type === "tool_use");
    console.log(`step ${step}: sent ${messages.length} messages -> ${response.stop_reason}${text ? ` | "${text}"` : ""}`);

    if (response.stop_reason === "end_turn") return { status: "done", text, steps: step, usage };
    if (response.stop_reason !== "tool_use") return { status: `stopped: ${response.stop_reason}`, steps: step, usage };

    messages.push({ role: "assistant", content: response.content }); // the whole reply, tool_use blocks included
    const results = [];
    for (const call of calls) {
      const result = await runTool(call);
      console.log(`        ${call.name}(${JSON.stringify(call.input)}) -> ${result.content}`);
      results.push(result);
    }
    messages.push({ role: "user", content: results }); // every result, in one message
  }
  return { status: "stopped: step limit", steps: maxSteps, usage };
}

const done = await runLoop("My order A-10422 still hasn't arrived. I'd like my money back.");
console.log(`=> ${done.status} in ${done.steps} steps, ${done.usage.input} input + ${done.usage.output} output tokens\n`);

script = scriptFor(); // the same scripted model, but a loop that allows only 2 steps
const capped = await runLoop("My order A-10422 still hasn't arrived. I'd like my money back.", { maxSteps: 2 });
console.log(`=> ${capped.status} after ${capped.steps} steps`);
Result
step 1: sent 1 messages -> tool_use | "Let me check that order."
        get_order({"order_id":"A-10422"}) -> {"order_id":"A-10422","status":"in_transit","total":490,"currency":"EUR","promised":"2026-12-01","today":"2026-12-06"}
step 2: sent 3 messages -> tool_use
        get_refund_policy({"reason":"not_delivered"}) -> {"reason":"not_delivered","rule":"Full refund if the parcel is more than 3 days past the promised date."}
step 3: sent 5 messages -> tool_use | "The parcel is 5 days late, which is past the 3-day threshold, so a refund applies."
        refund_order({"order_id":"A-10422","amount":490}) -> {"refund_id":"R-7731","order_id":"A-10422","amount":490,"status":"issued"}
step 4: sent 7 messages -> end_turn | "I've refunded €490 for order A-10422 (refund R-7731). It should reach your card in 3 to 5 working days."
=> done in 4 steps, 3547 input + 182 output tokens

step 1: sent 1 messages -> tool_use | "Let me check that order."
        get_order({"order_id":"A-10422"}) -> {"order_id":"A-10422","status":"in_transit","total":490,"currency":"EUR","promised":"2026-12-01","today":"2026-12-06"}
step 2: sent 3 messages -> tool_use
        get_refund_policy({"reason":"not_delivered"}) -> {"reason":"not_delivered","rule":"Full refund if the parcel is more than 3 days past the promised date."}
=> stopped: step limit after 2 steps
What’s happening
  1. runLoop starts with one user message. Step 1 sends it (sent 1 messages); the scripted model replies with stop_reason: "tool_use", a sentence of text and a request for get_order.
  2. The loop pushes the assistant reply whole (text block and tool_use block), runs get_order through runTool, and pushes one user message holding the result. The conversation is now 3 messages long, which is what step 2 reports.
  3. Step 2: with the order in context (promised 1 December, today 6 December, still in transit), the model asks for get_refund_policy with the reason it inferred, not_delivered. No text this time; a reply can be a tool call and nothing else.
  4. Step 3: the model now has the order and the rule ("more than 3 days past the promised date"). It states its reasoning and asks for refund_order with the amount it read from the first result, 490. Each decision was made from the previous tool result: that's what separates a loop from a script.
  5. Step 4: the refund result (R-7731) is in context, and the model answers the customer with stop_reason: "end_turn". The loop returns. Four requests were made, with 1, 3, 5 and 7 messages: the history grows by two messages per tool round, and every request resends all of it.
  6. The token line shows what that growth costs: 3,547 input tokens in total (720 + 842 + 951 + 1,034 in the scripted usage) against 182 output tokens. In tool loops, input tokens dominate, which is why prompt caching matters so much for agents.
  7. The second run uses the same scripted model with maxSteps: 2. After two tool rounds the for loop ends and the function returns stopped: step limit. The refund was never issued, and the caller knows the task is unfinished. Without the cap, a model that never stops asking would spend until something else broke.
AdvancedEvery stop reason in a loop

The other stop reasons

The loop above treats anything that isn't end_turn or tool_use as a reason to stop and report. Here is what each one means inside a tool loop, and what production code does about it.

stop_reasonMeaning in a loopWhat to do
end_turnThe model is finished and has answeredReturn the text
tool_useIt's waiting for resultsRun the tools, append, continue
max_tokensThe reply was cut off, possibly in the middle of a tool call's argumentsNever run tools from this reply. Retry the step with a higher max_tokens
pause_turnA server tool's own loop paused (see Server tools)Append the assistant content and send again, with no new user message
refusalThe model declinedStop, don't run any tools from this reply, surface a failure
stop_sequenceIt produced one of your stop stringsWhatever your protocol says; rare in tool loops
AdvancedWhat the hand-written loop still needs for production

The example is complete as a loop, and it's still missing what turns a loop into a service. Each of these has its own topic:

  • A budget, not just a step count: stop when accumulated tokens or cost pass a limit (The agent loop in code).
  • Timeouts and cancellation: an AbortSignal passed to both the model call and every tool, so a user closing the tab stops the work (Cancellation, timeouts and retries end to end).
  • Streaming: client.messages.stream() with finalMessage() in place of create(), so the user sees text as it's written and long turns don't hit HTTP timeouts (Streaming responses).
  • Prompt caching: the system prompt and tools are identical on every step, and each step resends the whole growing history, so a cache breakpoint saves most of the input cost of a long loop (Prompt caching).
  • A trace: every request, tool call, result and token count logged with one id, because "why did it refund twice?" can only be answered from the trajectory (Observability: tracing LLM calls).
  • Approval for risky tools: refund_order should not run just because a model asked (Human in the loop).
What does a ten-step loop cost?

A loop's first request is 700 input tokens. Each tool round adds 120 tokens to the history (the model's call and the result). No caching. How many input tokens are billed over ten requests? Predict, then check against the code.

JavaScript
let history = 700, total = 0;
for (let step = 1; step <= 10; step++) { total += history; history += 120; }
console.log(total, history);
Show answer

12400 1900: 12,400 input tokens billed, for a conversation that only ever grew to 1,900.

What’s happening
  1. Request 1 sends 700 tokens. Request 2 resends those 700 plus 120 new ones: 820. Request 3 sends 940, and so on up to 1,780 for request 10.
  2. The total is 700 + 820 + 940 + … + 1,780. Ten requests averaging 1,240 tokens: 12,400.
  3. The history after the loop is 1,900 tokens. You paid for 12,400, about six and a half times the final size, because everything is resent every time. Over n steps the bill grows roughly with n².
  4. Now imagine one tool returned 5,000 tokens at step 2 instead of 120. Those 5,000 tokens would be billed again on each of the eight later requests: 40,000 extra tokens from a single large result. That's why tool results should be trimmed.
  5. With prompt caching, the already-seen prefix of each request is read at a fraction of the input price, which removes most of the quadratic cost. Loops are where caching pays most.

#The SDK tool runner

Added

Having written the loop by hand, you know exactly what a helper would have to do: build the tools array from your functions, call the API, run what was asked for, catch errors and turn them into is_error results, append everything, and repeat until the model stops asking. The Anthropic SDK ships that helper as the tool runner (client.beta.messages.toolRunner, in beta in SDK 1.17.0). Anthropic's own guidance is to prefer it over a hand-written loop unless you need something it can't do.

The mental model: you write tools as functions with a zod schema, and the runner is the while loop. betaZodTool bundles a tool's name, description, input schema and run function into one object. The runner converts the zod schema to JSON Schema for the request, and before calling run it validates the model's arguments with the same zod schema, so run receives typed, checked input. If run throws, the model gets an error result and can react.

It isn't a black box. The runner is an async iterable: each turn of the loop yields the model's message before the tools for that message run, so you can log, inspect, change the next request, or break. Or you can just await it and get the final message.

tool-runner.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";

// Scripted replies (see "How these examples run")
let n = 0;
const reply = (content, stop_reason, usage) => ({
  id: `msg_01Mx${++n}fYc5UrPt9WeLd3AqSz7Bj`, type: "message", role: "assistant", model: "claude-opus-5-5",
  content, stop_reason, stop_sequence: null, usage,
});
const use = (id, name, input) => ({ type: "tool_use", id: `toolu_01${id}`, name, input, caller: { type: "direct" } });
const script = [
  reply([use("Dk2", "get_stock", { sku: "DESK-01" })], "tool_use", { input_tokens: 610, output_tokens: 29 }),
  reply([{ type: "text", text: "12 in stock. Reserving two." }, use("Em5", "reserve_stock", { sku: "DESK-01", quantity: "two" })], "tool_use", { input_tokens: 668, output_tokens: 41 }),
  reply([use("Fn8", "reserve_stock", { sku: "DESK-01", quantity: 2 })], "tool_use", { input_tokens: 760, output_tokens: 33 }),
  reply([{ type: "text", text: "Done: two DESK-01 desks are reserved for you (reservation RSV-204), and 10 remain in stock." }], "end_turn", { input_tokens: 822, output_tokens: 30 }),
];
const requests = [];
const fetch = async (url, init) => { requests.push(JSON.parse(init.body)); return Response.json(script.shift()); };
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const stock = { "DESK-01": 12 };
const getStock = betaZodTool({
  name: "get_stock",
  description: "Get how many units of a product are in stock. Call this before reserving.",
  inputSchema: z.object({ sku: z.string().describe("Product code, e.g. DESK-01") }),
  run: ({ sku }) => JSON.stringify({ sku, in_stock: stock[sku] ?? 0 }),
});
const reserveStock = betaZodTool({
  name: "reserve_stock",
  description: "Reserve units of a product for the current customer.",
  inputSchema: z.object({ sku: z.string(), quantity: z.number().int().positive() }),
  run: ({ sku, quantity }) => {
    if (quantity > stock[sku]) throw new Error(`Only ${stock[sku]} left of ${sku}`);
    stock[sku] -= quantity;
    return JSON.stringify({ reservation_id: "RSV-204", sku, quantity, remaining: stock[sku] });
  },
});

const runner = client.beta.messages.toolRunner({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  max_iterations: 8,
  thread: false, // send the full history every turn, like the hand-written loop
  tools: [getStock, reserveStock],
  messages: [{ role: "user", content: "Please reserve two DESK-01 desks for me." }],
});

let turn = 0;
for await (const message of runner) {
  const calls = message.content.filter((b) => b.type === "tool_use").map((b) => `${b.name}(${JSON.stringify(b.input)})`);
  console.log(`turn ${++turn}: ${message.stop_reason}${calls.length ? " " + calls.join(", ") : ""}`);
  const toolResponse = await runner.generateToolResponse(); // run this turn's tools now (cached, so they don't run twice)
  for (const r of toolResponse?.content ?? []) console.log(`   result${r.is_error ? " (is_error)" : ""}: ${String(r.content).replace(/\s+/g, " ").slice(0, 160)}`);
}
const final = await runner.done();
console.log("final:", final.content.find((b) => b.type === "text").text);
console.log("requests sent:", requests.length, "| messages in each:", requests.map((r) => r.messages.length).join(", "));
console.log("tool definition sent:", JSON.stringify(requests[0].tools[0]));
Result
turn 1: tool_use get_stock({"sku":"DESK-01"})
   result: {"sku":"DESK-01","in_stock":12}
turn 2: tool_use reserve_stock({"sku":"DESK-01","quantity":"two"})
   result (is_error): Error: [ { "expected": "number", "code": "invalid_type", "path": [ "quantity" ], "message": "Invalid input: expected number, received string" } ]
turn 3: tool_use reserve_stock({"sku":"DESK-01","quantity":2})
   result: {"reservation_id":"RSV-204","sku":"DESK-01","quantity":2,"remaining":10}
turn 4: end_turn
final: Done: two DESK-01 desks are reserved for you (reservation RSV-204), and 10 remain in stock.
requests sent: 4 | messages in each: 1, 3, 5, 7
tool definition sent: {"type":"custom","name":"get_stock","input_schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"sku":{"type":"string","description":"Product code, e.g. DESK-01"}},"required":["sku"],"additionalProperties":false},"description":"Get how many units of a product are in stock. Call this before reserving."}
What’s happening
  1. betaZodTool creates each tool from a zod inputSchema and a run function. The last printed line shows what the runner sent for get_stock: type: "custom", the name, the description, and an input_schema generated from the zod object (with additionalProperties: false and the .describe() text). You never wrote JSON Schema.
  2. client.beta.messages.toolRunner({...}) doesn't send anything yet. Iterating it with for await starts the loop; each iteration yields one assistant message.
  3. Turn 1: the model asks for get_stock. runner.generateToolResponse() runs the tool now and returns the user message the runner will send next, so the code can print the result: {"sku":"DESK-01","in_stock":12}. The runner caches it, so the tool doesn't run a second time when the loop continues.
  4. Turn 2: the scripted model asks for reserve_stock with quantity: "two", a string. The zod schema says z.number().int().positive(), so the runner doesn't call run at all. It sends back a result with is_error: true whose content is zod's issue list ("expected": "number", "path": ["quantity"], Invalid input: expected number, received string). The stock is untouched.
  5. Turn 3: reading that error, the model repeats the call with quantity: 2. Validation passes, run executes, stock goes 12 → 10, and the result includes the reservation id.
  6. Turn 4 has stop_reason: "end_turn" and no tool calls, so the iteration ends. runner.done() resolves to that final message.
  7. requests sent: 4 | messages in each: 1, 3, 5, 7 is the same growth as the hand-written loop, because thread: false asks the runner to send the full history each time. Everything the manual loop did (appending the assistant content, matching tool_use_ids, building the user message, looping) happened inside the runner.
AdvancedHooks: where you step in

Because each turn is yielded to your code, most "I need control" requirements don't need a hand-written loop. These are the runner's methods in SDK 1.17.0 (read from its type definitions):

You want toUse
Just get the answerawait runner or await runner.runUntilDone()
Bound the loopmax_iterations (counts API requests)
See or change results before the model doesawait runner.generateToolResponse() inside the loop: it runs the turn's tools once and returns the user message that will be sent
Change the next request (model, max_tokens, messages)runner.setMessagesParams((p) => ({ ...p, max_tokens: 32000 }))
Add a message mid-runrunner.pushMessages({ role: "user", content: "…" })
Cancelrunner.setRequestOptions({ signal }); a tool's run also receives context.signal
Approve a risky callCheck inside run and return a "declined" result, or break out of the loop when the yielded message contains the call
Stream each turnstream: true: each iteration yields a message stream instead of a message

An approval gate, the most common requirement, is a few lines inside run. Nothing is hidden: declining is just another tool result.

JavaScript
const refundOrder = betaZodTool({
  name: "refund_order",
  description: "Refund an order. Requires approval from a human agent.",
  inputSchema: z.object({ order_id: z.string(), amount: z.number().positive() }),
  run: async ({ order_id, amount }) => {
    const approved = await askHuman(`Refund €${amount} for ${order_id}?`); // your UI, Slack, a queue…
    if (!approved) return "The human agent declined this refund. Do not retry; explain to the customer that it needs manual review.";
    return JSON.stringify(await payments.refund(order_id, amount));
  },
});
What’s happening
  1. The model can ask for refund_order whenever it likes. Asking costs nothing, because nothing has happened yet.
  2. The runner validates the arguments against the zod schema and calls run, which waits for a person before touching the payments API. The loop is paused at this await for as long as the human takes.
  3. If the answer is no, run returns a normal string. The model reads it as the tool's result and tells the customer, following the instruction in the string. No exception, no special state.
  4. If the answer is yes, the refund happens and its result goes back. Either way the decision was made in your code, with the exact arguments on screen, which is what makes it an approval and not a hope.
AdvancedRunner caveats: beta, threads, errors

What to know before relying on it

  • It's beta, and it changes. In SDK 1.17.0 the runner by default runs over a message thread (another beta: the API keeps the conversation briefly, and each request sends only the new messages; the SDK adds the message-threads-2026-08-12 beta header itself). The example sets thread: false to send the full history each turn, which is what the hand-written loop does and what works with every feature. Read the release notes when you upgrade.
  • Tools run in your process, and a turn's calls run concurrently. When one reply asks for several tools, the runner starts them together (its source uses Promise.all), so two run functions can be in flight at once: don't share mutable state between them without care. A run that blocks the event loop blocks the whole runner, so keep handlers async.
  • Thrown errors become error results. Any exception from run is sent to the model as Error: <message> with is_error: true. That's convenient, and it means an internal message like a SQL error can reach the model (and, through it, the user). Catch what you expect and write the message deliberately, as in Designing tools a model can use.
  • Zod isn't required. betaTool from @anthropic-ai/sdk/helpers/beta/json-schema takes a hand-written JSON Schema; it doesn't validate arguments at run time, so validate inside run.
  • When to write the loop yourself: when you can't take a beta dependency, when your control flow doesn't fit "one turn at a time" (interleaving other work, custom scheduling of tool calls), or when you're on another provider's API. The loop from the previous topic is short enough that this is a real option, not a failure.
The model sends a string where a number belongs

A tool is defined with betaZodTool and inputSchema: z.object({ sku: z.string(), quantity: z.number().int().positive() }). The model calls it with { "sku": "DESK-01", "quantity": "two" }. What happens: (a) run is called with quantity: "two"; (b) the runner throws and your for await loop crashes; (c) something else?

Show answer

(c): run is never called. The runner sends the model a tool_result with is_error: true containing zod's issues, and the loop continues.

What’s happening
  1. Before calling run, the runner parses the model's arguments with the tool's zod schema. "two" fails z.number().
  2. Because validation failed, your run function doesn't execute. In the example on this page, the stock count stayed at 12 after this call.
  3. The failure is turned into an error result, not an exception. The run above printed it: Error: [ { "expected": "number", "code": "invalid_type", "path": [ "quantity" ], "message": "Invalid input: expected number, received string" } ].
  4. That result goes back to the model like any other tool result. On the next turn the scripted model called the tool again with quantity: 2, which passed.
  5. So with betaZodTool, the schema is a guard in front of your function. With betaTool (raw JSON Schema) there is no run-time validation: run receives whatever was parsed, and the check is yours to write.

#Parallel tool calls and tool errors

Added

Ask "what's the weather in Paris, Tokyo and Lima?" and a sensible assistant doesn't look up one city, wait, think, and then look up the next. It asks for all three at once. Models do the same: one reply can contain several tool_use blocks, and your code is expected to run them all and return all the results together. This is parallel tool use, it's on by default, and it's the cheapest speed-up in an agent: three lookups in one round trip, not three.

The mental model is an order of several dishes on one ticket. The kitchen (your code) cooks them at the same time and sends them out together on one tray. If one dish can't be made, the tray still goes out with the other dishes and a note about the missing one; you don't send the whole table home. That's the two rules of this topic: all results in one message, and a failure is a result, not an exception.

parallel-tools.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const reply = (id, content, stop_reason, usage) => ({ id, type: "message", role: "assistant", model: "claude-opus-5-5", content, stop_reason, stop_sequence: null, usage });
const use = (id, city) => ({ type: "tool_use", id, name: "get_weather", input: { city }, caller: { type: "direct" } });
const script = [
  reply("msg_01Nq7gZd6VsQu1XfMe4BrTa8Ck", [
    { type: "text", text: "I'll check all three cities." },
    use("toolu_01Gp1", "Paris"), use("toolu_01Hq2", "Tokyo"), use("toolu_01Jr3", "Atlantis"),
  ], "tool_use", { input_tokens: 512, output_tokens: 96 }),
  reply("msg_01Pr8hAe7WtRv2YgNf5CsUb9Dm", [
    { type: "text", text: "Paris is 8°C and rainy, Tokyo is 14°C and clear. I couldn't get weather for Atlantis: it isn't a city the service knows. Did you mean Atlanta?" },
  ], "end_turn", { input_tokens: 655, output_tokens: 44 }),
];
const sent = [];
const fetch = async (url, init) => { sent.push(JSON.parse(init.body)); return Response.json(script.shift()); };
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const tools = [{
  name: "get_weather",
  description: "Get the current weather for one city. To compare several cities, call this once per city in the same turn.",
  input_schema: { type: "object", properties: { city: { type: "string" } }, required: ["city"], additionalProperties: false },
}];
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const weather = { Paris: "8°C, rain", Tokyo: "14°C, clear" };
async function getWeather({ city }) {
  await sleep(300); // stands in for a network call
  if (!weather[city]) throw new Error(`Unknown city "${city}". Check the spelling or ask the user which city they mean.`);
  return weather[city];
}

const messages = [{ role: "user", content: "What's the weather in Paris, Tokyo and Atlantis right now?" }];
const first = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
const calls = first.content.filter((b) => b.type === "tool_use");
console.log(`reply 1: ${first.stop_reason} with ${calls.length} tool_use blocks: ${calls.map((c) => c.input.city).join(", ")}`);

// Run every call at once. Each promise settles to a tool_result; a failure becomes is_error, never a rejection.
const started = performance.now();
const results = await Promise.all(calls.map(async (call) => {
  try {
    return { type: "tool_result", tool_use_id: call.id, content: await getWeather(call.input) };
  } catch (err) {
    return { type: "tool_result", tool_use_id: call.id, content: err.message, is_error: true };
  }
}));
const elapsed = performance.now() - started;
console.log(`ran ${results.length} calls of 300 ms each; finished in under 700 ms: ${elapsed < 700}`);

messages.push({ role: "assistant", content: first.content });
messages.push({ role: "user", content: results }); // ONE user message with all three results
for (const r of results) console.log(`  ${r.tool_use_id}: ${r.is_error ? "is_error " : ""}${r.content}`);

const second = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
const last = sent[1].messages.at(-1);
console.log(`request 2: last message is role "${last.role}" with ${last.content.length} blocks (${last.content.map((b) => b.type).join(", ")})`);
console.log("answer:", second.content[0].text);
Result
reply 1: tool_use with 3 tool_use blocks: Paris, Tokyo, Atlantis
ran 3 calls of 300 ms each; finished in under 700 ms: true
  toolu_01Gp1: 8°C, rain
  toolu_01Hq2: 14°C, clear
  toolu_01Jr3: is_error Unknown city "Atlantis". Check the spelling or ask the user which city they mean.
request 2: last message is role "user" with 3 blocks (tool_result, tool_result, tool_result)
answer: Paris is 8°C and rainy, Tokyo is 14°C and clear. I couldn't get weather for Atlantis: it isn't a city the service knows. Did you mean Atlanta?
What’s happening
  1. The first reply has stop_reason: "tool_use" and three tool_use blocks, each with its own id and a different city. The tool description nudged this: "call this once per city in the same turn".
  2. calls.map(async …) starts all three lookups immediately; Promise.all waits for them together. Each lookup sleeps 300 ms to stand in for a network call. The printed check, finished in under 700 ms: true, shows they overlapped: one after another would take at least 900 ms.
  3. Each call is wrapped in its own try/catch, so a failure can't reject the Promise.all and lose the other two results. Paris and Tokyo return normal results. Atlantis throws inside getWeather, and the catch turns that into { …, is_error: true } with a message that suggests what to do.
  4. All three results go into one user message, in the same order as the calls, each carrying the tool_use_id of the call it answers. The line starting request 2: confirms what was actually sent: one user message with three tool_result blocks.
  5. The second reply uses the two successful results and handles the failure sensibly: it reports Paris and Tokyo, says Atlantis wasn't recognised, and asks whether the user meant Atlanta. The model could only do that because it was told what failed and why.
  6. If the code had thrown on the Atlantis error, the user would have got nothing for a question that was two-thirds answerable. If it had silently dropped the failed call, the API would have rejected the next request, because one tool_use id would have had no result.
AdvancedRules for running calls in parallel
  • One message, all results. Every tool_use id in the assistant message needs its tool_result in the next user message. Anthropic's documentation adds a subtle reason to keep them together: answering parallel calls in separate messages teaches the model, through the conversation history it sees, to stop making parallel calls.
  • Order doesn't matter; ids do. Results are matched by tool_use_id, so return them in whatever order is convenient. Promise.all keeps the original order anyway.
  • Not everything is safe to parallelise. Three reads are. A reserve_stock and a charge_card in the same reply are not obviously independent: if one fails, what happens to the other? Run read-only tools concurrently and side-effecting ones in sequence, or design the write tools to be idempotent (see the retry discussion in Cancellation, timeouts and retries end to end).
  • Bound each call. Promise.all waits for the slowest call. Give every tool a timeout (AbortSignal.timeout(ms)) and return a timeout as an is_error result ("timed out after 10 s; the service may be down, don't retry more than once").
  • Turning it off. tool_choice: { type: "auto", disable_parallel_tool_use: true } makes the model request at most one tool per reply. Use it when your tools must run strictly one at a time and the model has no way to know that.
AdvancedWhat makes a good error result

is_error: true tells the model the call failed; the content tells it what to do about it. The model reads errors exactly like it reads any other text, so write them for that reader:

FailurePoor resultUseful result
Bad argument400 Bad Requestorder_id must look like A-10422; you sent "10422".
Not foundnullNo order A-99999 for this customer. Call search_orders to list their orders.
Not allowedForbiddenThis user can't refund orders over €200. Offer to escalate to a human agent.
TransientECONNRESETThe shipping service didn't respond. Try once more; if it fails again, tell the user tracking is unavailable.
Your bugA stack traceInternal error; don't retry. (and the stack trace in your logs)

Two things never belong in an error result: secrets (connection strings, tokens, internal hostnames in stack traces) and an empty string. An empty or missing result leaves the model to guess, and its guess is often to tell the user it worked.

Two of three parallel calls succeeded. What do you send?

A reply asked for get_order, get_shipment and get_invoice in one turn. The first two succeeded; get_invoice threw a timeout. A teammate proposes: "send the two results now so the model can start, and send the invoice result when the retry finishes." What's wrong, and what should the next request contain?

Show answer

The next request must contain all three results in one user message: two normal results and one with is_error: true describing the timeout.

What’s happening
  1. The API requires every tool_use in an assistant message to be answered in the next user message. A request with two of three results is rejected with a 400, so "send two now" doesn't work at all.
  2. "Send the third later" has no place to go: after the model has replied to the results, the conversation has moved on, and a tool_result must directly follow the tool_use it answers.
  3. So decide before sending: either wait for the retry (bounded by a timeout), or send the failure. The failure is the better default: { type: "tool_result", tool_use_id: "<the invoice call>", content: "Timed out after 10 s. You can call get_invoice again once.", is_error: true }.
  4. The model then has the order, the shipment and a clear note about the invoice. It can answer with what it has, or ask for get_invoice again in its next reply, which your loop handles like any other call.
  5. The general rule: the tool loop is turn-based. Every turn must be complete before the next one starts, and partial failure is expressed inside the turn with is_error, never by leaving a result out.

#Server tools: web search, web fetch and code execution

Added

Every tool so far ran in your process: the model asked, your code did the work. Server tools are different: they're tools the provider runs for you. You add one line to tools, and when the model wants to search the web, read a URL or run some Python, Anthropic's servers do it and feed the result back to the model inside the same API request. You never see a stop_reason: "tool_use" for them and you never send a tool_result; the reply arrives with the search already done and the answer already written.

The mental model: a client tool is a function you lend the model; a server tool is a capability the model already has, which you switch on. The trade is the usual one for managed services. You get no code to write, no sandbox to secure and no search API contract to sign. You give up control: you can't change how the search works, what the sandbox contains, or where it runs.

Tooltype (December 2026)What runs on Anthropic's sideResult block in the reply
Web searchweb_search_20260209A search; results are filtered and returned with citationsweb_search_tool_result
Web fetchweb_fetch_20260209Fetches one URL (a page or PDF) that already appears in the conversationweb_fetch_tool_result
Code executioncode_execution_20260521Bash and file edits in a sandboxed container with Pythonbash_code_execution_tool_result, text_editor_code_execution_tool_result

The type strings carry a date because the tools are versioned; use the newest one your model supports (Anthropic's web search page already lists a web_search_20260318 with one more option; the SDK installed here, 1.17.0, has types up to the ones in the table).

The example declares web search and reads the reply. The reply is scripted in the shape Anthropic documents, so the search results in it were written for the example (a made-up router on example.com); the code that walks the blocks is what you'd run against the real API.

web-search.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const script = [{
  id: "msg_01Qs9jBf8XuSw3ZhPg6DtVc1En", type: "message", role: "assistant", model: "claude-opus-5-5",
  content: [
    { type: "text", text: "I'll search for the latest firmware release." },
    { type: "server_tool_use", id: "srvtoolu_01Kt4LmNp7QrSu2VwXy5Za8Bc", name: "web_search", input: { query: "Acme AX-200 router latest firmware version" }, caller: { type: "direct" } },
    { type: "web_search_tool_result", tool_use_id: "srvtoolu_01Kt4LmNp7QrSu2VwXy5Za8Bc", caller: { type: "direct" }, content: [
      { type: "web_search_result", url: "https://support.example.com/ax-200/firmware", title: "AX-200 firmware downloads", encrypted_content: "EqgfCioIARgBIiQ3YTAwMjY1Mi1mZjM5…", page_age: "November 28, 2026" },
      { type: "web_search_result", url: "https://forum.example.org/t/ax-200-update", title: "AX-200 update thread", encrypted_content: "ErQdCioIARgBIiQ4YjExMzc2My0wMDRh…", page_age: null },
    ] },
    { type: "text", text: "According to the vendor's download page, " },
    { type: "text", text: "the latest AX-200 firmware is version 3.2.1, released on 24 November 2026", citations: [
      { type: "web_search_result_location", url: "https://support.example.com/ax-200/firmware", title: "AX-200 firmware downloads", encrypted_index: "Eo8BCioIAhgBIiQyYjQ0OWJmZi1lNm…", cited_text: "Version 3.2.1 (24 November 2026): security fixes and improved mesh roaming." },
    ] },
    { type: "text", text: "." },
  ],
  stop_reason: "end_turn", stop_sequence: null,
  usage: { input_tokens: 5420, output_tokens: 212, server_tool_use: { web_search_requests: 1, web_fetch_requests: 0 } },
}];
const fetch = async () => Response.json(script.shift());
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  tools: [{ type: "web_search_20260209", name: "web_search", max_uses: 3, blocked_domains: ["reddit.com"] }],
  messages: [{ role: "user", content: "What is the latest firmware for the Acme AX-200 router?" }],
});

console.log("stop_reason:", response.stop_reason);
let answer = "";
let searched = false;
const sources = new Map();
for (const block of response.content) {
  if (block.type === "server_tool_use") console.log(`server ran ${block.name}: ${JSON.stringify(block.input)}`);
  if (block.type === "web_search_tool_result") {
    if (Array.isArray(block.content)) console.log(`  ${block.content.length} results: ${block.content.map((r) => new URL(r.url).hostname).join(", ")}`);
    else console.log(`  search failed: ${block.content.error_code}`); // an error is an object, not a list
    searched = true;
  }
  if (block.type === "text" && !searched) console.log(`model, before searching: "${block.text}"`);
  if (block.type === "text" && searched) {
    answer += block.text;
    for (const c of block.citations ?? []) {
      if (!sources.has(c.url)) sources.set(c.url, sources.size + 1);
      answer += ` [${sources.get(c.url)}]`;
    }
  }
}
console.log("answer:", answer);
for (const [url, i] of sources) console.log(`  [${i}] ${url}`);
console.log("searches billed:", response.usage.server_tool_use.web_search_requests);
Result
stop_reason: end_turn
model, before searching: "I'll search for the latest firmware release."
server ran web_search: {"query":"Acme AX-200 router latest firmware version"}
  2 results: support.example.com, forum.example.org
answer: According to the vendor's download page, the latest AX-200 firmware is version 3.2.1, released on 24 November 2026 [1].
  [1] https://support.example.com/ax-200/firmware
searches billed: 1
What’s happening
  1. The only tool-related code in the request is one object in tools: type: "web_search_20260209", the fixed name web_search, max_uses: 3 to cap the searches in this turn, and a blocked_domains list. There is no input_schema and no handler: the tool's interface is built into the model.
  2. One request goes out and one reply comes back with stop_reason: "end_turn". The search happened in between, on Anthropic's side. There was no tool_use stop and no second request from this code.
  3. The reply's content is a transcript of what happened, in order. A text block (the model saying it will search), then a server_tool_use block: like tool_use, but its id starts with srvtoolu_ and it's a record of a call that has already run. The code prints the query the model chose.
  4. Next is the web_search_tool_result block with the same id. On success its content is an array of web_search_result objects (url, title, page_age, and encrypted_content, which you can't read and must send back untouched if the conversation continues). The code prints the two hostnames. On failure content is a single error object, which is why the code checks Array.isArray first.
  5. Then come the answer's text blocks. The API splits the answer wherever a citation starts or ends: "According to the vendor's download page, " has no citations; the next block, the actual claim, carries a citations array with the url, title and cited_text it's based on. The code stitches the text together and appends a numbered marker for each cited URL, giving … released on 24 November 2026 [1].
  6. response.usage.server_tool_use.web_search_requests is 1: searches are counted, and billed, separately from tokens. The 5,420 input tokens in the scripted usage are realistic in spirit: search results are read by the model, so they are input tokens you pay for.
AdvancedThe server-side loop and pause_turn

When a request includes server tools, the API runs a tool loop of its own: sample, run the server tool, feed the result back, sample again. That loop has a limit (10 iterations by default, per Anthropic's tool use guide). If it's reached, the request returns with stop_reason: "pause_turn": the turn isn't finished, the server just handed control back. To continue, append the assistant content exactly as received and send the request again. Don't add a "please continue" user message: the API sees the trailing server_tool_use block and resumes.

JavaScript
let response = await client.messages.create({ model, max_tokens: 16000, tools, messages });
for (let resumes = 0; response.stop_reason === "pause_turn" && resumes < 5; resumes++) {
  messages.push({ role: "assistant", content: response.content }); // unchanged, encrypted fields included
  response = await client.messages.create({ model, max_tokens: 16000, tools, messages });
}
What’s happening
  1. The first request may come back finished (end_turn) or paused (pause_turn). Only the second case enters the loop.
  2. messages.push({ role: "assistant", content: response.content }) keeps everything the server did so far: its searches, their results and any text. The result blocks carry encrypted_content; they must go back unmodified or the API rejects the request.
  3. The second create call has no new user message. The conversation ends with an assistant message that ends in a server tool call, which is the signal to resume.
  4. resumes < 5 is your own cap, for the same reason as maxSteps in the hand-written loop: something must bound the work. The SDK's tool runner resumes paused turns for you (each resume counts toward max_iterations).

If a reply mixes server tools with your own client tools, you get stop_reason: "tool_use" as usual for the client ones; return their results and the API carries on, running any pending server tool in the next request.

AdvancedWeb fetch and code execution

Web fetch ({ type: "web_fetch_20260209", name: "web_fetch" }) retrieves the content of one URL. It only fetches URLs that already appear in the conversation (in a user message or in an earlier search result), which stops the model from being talked into requesting arbitrary addresses it invented. Options include max_uses, allowed_domains or blocked_domains (one or the other, never both), citations and max_content_tokens to cap how much of a long page enters the context. The result is a web_fetch_tool_result whose content is a web_fetch_result holding a document block.

Code execution ({ type: "code_execution_20260521", name: "code_execution" }) gives the model a sandboxed Linux container. From Anthropic's documentation (December 2026): 1 CPU, 5 GiB of RAM and 5 GiB of disk, Python 3.11 with the data-science libraries (pandas, numpy, matplotlib and so on) pre-installed, and no internet access. The model gets two sub-tools there: one runs shell commands and one creates and edits files. In the reply you see server_tool_use blocks and, for each command, a bash_code_execution_tool_result whose content has stdout, stderr and return_code. A container can be reused across requests (pass the container id from the previous response) to keep files and installed packages.

JavaScript
for (const block of response.content) {
  if (block.type === "bash_code_execution_tool_result" && block.content.type === "bash_code_execution_result") {
    const { return_code, stdout, stderr } = block.content;
    console.log(return_code === 0 ? stdout : `exit ${return_code}: ${stderr}`);
  }
}

Use code execution when the model needs to compute, not recall: arithmetic over a CSV, a chart, checking that code it wrote actually runs. A model doing long division in its head is guessing; a model running pandas is calculating.

AdvancedCost, control and when to bring your own
  • Price. Web search is billed per use on top of tokens: $10 per 1,000 searches on the Claude API (Anthropic's web search page, December 2026), and every result the model reads counts as input tokens, in that turn and in later ones. max_uses caps searches per turn. Code execution is free when used with web search or web fetch; on its own it's billed by container time ($0.05 per hour after 1,550 free hours a month per organisation; Anthropic's tool documentation, December 2026).
  • Citations are part of the contract. Web search text blocks carry citations, and Anthropic's web search page says that when you display API outputs directly to end users, citations to the original source must be included. The example builds numbered references for that reason.
  • Errors don't throw. A failed search is still HTTP 200: the web_search_tool_result block's content is an object like { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" } and not an array. The example branches on Array.isArray for exactly this.
  • Search results are untrusted input. A web page can contain text written to manipulate a model ("ignore your instructions and…"). A model with web search and a tool that can act (send email, change data) is the classic indirect prompt injection setup; see Prompt injection: direct and indirect. allowed_domains is a real mitigation, not a nicety.
  • Not everywhere. Server tools run on Anthropic's platform. On cloud platforms that host Claude models themselves, availability differs by tool (Anthropic's page lists only the basic web search version on some of them). If you're building against Bedrock or Vertex, check before designing around a server tool.
  • When to bring your own. Write a client tool for search when you need a specific index (your documents, your product catalogue: that's RAG), a specific search provider, auditable queries, or data that must not leave your network. Use the server tool when "search the public web and cite it" is exactly the requirement.
Spot the bug in the result reader

This line collects the URLs from every web search in a reply. It works in testing and throws in production. What does it throw, and when?

JavaScript
const urls = response.content
  .filter((b) => b.type === "web_search_tool_result")
  .flatMap((b) => b.content.map((r) => r.url));
Show answer

TypeError: b.content.map is not a function, on any reply where a search failed (for example after max_uses was reached).

What’s happening
  1. For a successful search, content is an array of web_search_result objects, so .map works. That's every reply you saw in testing.
  2. For a failed search the API still answers with HTTP 200, and the block's content is a single object: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" }.
  3. An object has no .map, so the callback throws a TypeError. Running the line against one successful and one failed block prints exactly TypeError: b.content.map is not a function.
  4. The fix is to branch on the shape first: Array.isArray(b.content) ? b.content.map((r) => r.url) : [], and to log the error_code in the other branch.
  5. The general lesson for server tools: errors arrive as data inside a successful response. Nothing is thrown by the SDK, so nothing reminds you to handle them.

#Controlling tool use

Added

Giving a model tools hands it a decision: answer directly, or call something first? Usually you want the model to make that call. Sometimes you don't: a first step that must always be a lookup, a turn that must be a plain answer with no side effects, a pipeline where exactly one tool makes sense. tool_choice is the request parameter for this, and it's an area where the API changed in a way that catches people who learned it a year ago.

The four values, and where each stands on current models (from Anthropic's tool use documentation, December 2026):

tool_choiceMeaningClaude Opus 5.5, Sonnet 5.5, Fable 5.2
{ type: "auto" }The model decides whether to call a tool. The defaultSupported
{ type: "none" }The model may not call tools this turnSupported
{ type: "any" }The model must call some toolRejected with a 400
{ type: "tool", name }The model must call this toolRejected with a 400

So on the newest models, forced tool choice is gone. Anthropic's documentation states the restriction and the replacements, not the reason; what it does say is that these models always think before they act (thinking can't be turned off on Opus 5.5 or Fable 5.2), and a forced call was an instruction about the very first thing the model outputs. Older models, including Claude Opus 5 and Sonnet 5, still accept any and tool. The mental model for the new world: you no longer command a tool call, you make it the obvious thing to do and then check that it happened.

The example shows the old habit failing and the replacement working.

tool-choice.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const reply = (id, content, stop_reason) => ({ id, type: "message", role: "assistant", model: "claude-opus-5-5", content, stop_reason, stop_sequence: null, usage: { input_tokens: 480, output_tokens: 40 } });
const script = [
  new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: 'tool_choice: type "tool" and "any" are not supported for this model.' }, request_id: "req_011CZx4VuQe7TbMw3RkHn9Dp" }), { status: 400, headers: { "content-type": "application/json", "request-id": "req_011CZx4VuQe7TbMw3RkHn9Dp" } }),
  Response.json(reply("msg_01Rt1kCg9YvTx4AiQh7EuWd2Fp", [{ type: "text", text: "Your order is probably on its way! Orders usually arrive within a week." }], "end_turn")),
  Response.json(reply("msg_01Su2mDh1ZwUy5BjRi8FvXe3Gq", [{ type: "tool_use", id: "toolu_01Lu6", name: "get_order", input: { order_id: "A-10422" }, caller: { type: "direct" } }], "tool_use")),
];
const fetch = async () => script.shift();
// End of scripted replies

const client = new Anthropic({ apiKey: "sk-ant-test", fetch });

const tools = [{
  name: "get_order",
  description: "Look up one order by id. Call this whenever the user asks about a specific order; never answer about an order from memory.",
  strict: true,
  input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"], additionalProperties: false },
}];
const base = { model: "claude-opus-5-5", max_tokens: 16000, tools };
const question = { role: "user", content: "Where is order A-10422?" };

// 1. The old way: force the call.
try {
  await client.messages.create({ ...base, messages: [question], tool_choice: { type: "tool", name: "get_order" } });
} catch (err) {
  if (!(err instanceof Anthropic.BadRequestError)) throw err;
  console.log(`forced: ${err.status} ${err.error.error.type}: ${err.error.error.message}`);
}

// 2. The new way: auto, a clear instruction, then check and re-prompt once.
async function callExpectingTool(name, messages, retries = 1) {
  for (let attempt = 0; ; attempt++) {
    const response = await client.messages.create({ ...base, messages, tool_choice: { type: "auto" } });
    const call = response.content.find((b) => b.type === "tool_use" && b.name === name);
    console.log(`auto, attempt ${attempt + 1}: ${response.stop_reason}${call ? ` -> ${call.name}(${JSON.stringify(call.input)})` : " (no tool call)"}`);
    if (call || attempt === retries) return { response, call };
    messages = [...messages, { role: "assistant", content: response.content },
      { role: "user", content: `Don't answer from memory. Call the ${name} tool for this order and answer from its result.` }];
  }
}
const { call } = await callExpectingTool("get_order", [question]);
console.log(call ? "proceeding with the tool call" : "no tool call after retry: fall back");
Result
forced: 400 invalid_request_error: tool_choice: type "tool" and "any" are not supported for this model.
auto, attempt 1: end_turn (no tool call)
auto, attempt 2: tool_use -> get_order({"order_id":"A-10422"})
proceeding with the tool call
What’s happening
  1. The tool is defined with strict: true and a description that states the rule: never answer about an order from memory.
  2. Attempt 1 uses the old habit, tool_choice: { type: "tool", name: "get_order" }. The API answers with HTTP 400 and the SDK throws Anthropic.BadRequestError. The printed message is the one Anthropic documents for these models: tool_choice: type "tool" and "any" are not supported for this model. A 400 is never retried by the SDK; the request is wrong, not unlucky.
  3. callExpectingTool is the replacement. It sends tool_choice: { type: "auto" } and then looks at what came back: is there a tool_use block for the tool it expected?
  4. On the first try the scripted model answers from memory ("probably on its way"), with stop_reason: "end_turn" and no tool call. This is the failure forced choice used to prevent. The code detects it, and builds a new message list: the model's answer, then a user message saying exactly what was wrong and what to do.
  5. On the second try the reply is stop_reason: "tool_use" with get_order({"order_id":"A-10422"}). Because of strict: true, those arguments are guaranteed to match the schema, the same guarantee forcing the tool gave.
  6. retries = 1 bounds the pattern: one corrective nudge, then the caller gets call: undefined and takes its fallback path. With a good description the first attempt nearly always calls the tool; the check exists for the times it doesn't.
AdvancedWhat replaces a forced tool call

The replacements, by what you were forcing the call for

Forced tool choice was used for three different jobs. Each has a better tool now.

"I only wanted JSON." The most common use of tool_choice: { type: "tool" } was never about tools: people defined a fake record_result tool and forced it, because the arguments came back as schema-shaped JSON. That job belongs to structured outputs: put the schema in output_config.format and read the JSON from the text block (see Structured outputs with a JSON schema). It's the direct replacement and it works on every current model.

"The first step is always this lookup." If it's always the first step, the model doesn't need to decide it: call the function yourself and put the result in the prompt. Fetch the order in your code and send "Here is the order: … The customer asks: …". You save a round trip and remove a decision that could go wrong. This is the workflow-versus-agent distinction from What an agent is: steps you can predict belong in code.

"The model should use tools here, not improvise." Keep auto, and steer: say in the system prompt and in the tool's description when the tool must be used ("never answer about an order from memory"), turn on strict: true so the arguments are guaranteed valid, and verify in code that a call came back, re-prompting once if it didn't, as the example does. auto never guarantees a call, so the check is part of the pattern, not an optional extra.

AdvancedThe parameters that still work everywhere
  • { type: "none" } makes a turn tool-free while keeping the tools array in the request. That matters for prompt caching: removing the tools would change the start of the prompt and invalidate the cache, while tool_choice leaves the cached prefix intact. Use it for a "summarise what you've done" final turn, or when a step limit is reached and you want a last answer and no more calls.
  • disable_parallel_tool_use: true goes with auto and limits each reply to at most one tool call.
  • max_uses on a server tool caps how often it runs in a turn.
  • The tool list itself is the strongest control. A model can't call a tool it wasn't given. Giving a read-only agent only read tools beats any instruction not to write.
Port this request to Claude Opus 5.5

An existing extraction service sends this to an older model: one tool, save_contact, with a schema of name, email and company, and tool_choice: { type: "tool", name: "save_contact" }. It reads response.content[0].input as the result. What happens if you only change the model id to claude-opus-5-5, and what's the correct port?

Show answer

It fails with a 400 on every request. The correct port removes the tool and uses structured outputs.

What’s happening
  1. On Claude Opus 5.5 a forced tool_choice (any or tool) is rejected: tool_choice: type "tool" and "any" are not supported for this model. Nothing is generated; the service is simply down until it's fixed.
  2. Switching to tool_choice: { type: "auto" } makes the 400 go away and introduces a quieter bug: the model may now answer in text with no tool call, and response.content[0].input is undefined (and content[0] may be a thinking or text block anyway, since the code indexed by position, not by type).
  3. The tool was never a tool. Nothing is being "called"; the service wants an object with three fields. So delete tools and tool_choice and send output_config: { format: zodOutputFormat(Contact) } with a zod schema of name, email and company.
  4. Read the result with messages.parse() and parsed_output, or from the text block with JSON.parse after checking stop_reason, and handle max_tokens and refusal as in the earlier examples.
  5. The lesson for migrations in general: when a parameter is removed, ask what job it was doing. "Force this tool" was doing the job of "give me this JSON", and there's now a feature built for exactly that.

Written fresh for AI engineering interviews (there was no Google Doc for this one). Examples were run on Node 26 with @anthropic-ai/sdk 1.17.0, the AI SDK 7.1 and transformers.js 4.3; API facts were checked against Anthropic’s documentation in December 2026.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.