Objectives: LO-8.1, LO-8.2, LO-8.3
Prerequisites: Module 7, and the stop reasons from
Module 2
Time: about 6 hours: 2 for this reading, 2.5 for Lab 8, and 1.5 for the
practice; Self-test 2 follows, and takes about 2
more
So far, a model’s answer has been text that your code reads, such as a Label: billing line. This
module turns answers into data. A schema describes the record a response must hold, and code
checks every response against it. Then tools let the model ask your program to run a function,
such as a price lookup, and use the result. In Lab 8 you validate dispatch records, write three
tool definitions, and build the loop that runs tool calls, tested with a scripted stand-in.
From text to a record¶
A record, in this module, is a JSON object with named fields, such as a ticket’s queue and a
one-line summary. json.loads checks only JSON’s syntax: braces, quotes, and commas. It says
nothing about which fields the object has or what they hold.
A JSON Schema is a JSON object that describes which values are allowed. A validator, such
as the jsonschema package that the labs use, checks a value against a schema and reports the
first rule the value breaks. Five keywords cover most records:
typenames the JSON type:"object","string","integer","boolean", and so on.propertiesgives a schema for each named field.requiredlists the fields that must be present. The JSON Schema reference says a property is optional by default, so an empty object passes a schema that has norequiredlist."additionalProperties": falserejects any field thatpropertiesdoesn’t name.enumlists the only values a field may take.
Worked example: a schema for a work order¶
The menu in promptlab lists two services: flat, which costs $18 and takes 25 minutes, and
brakes, which costs $35 and takes 40. A work order names the service, the bench time, and
whether the customer approved the work:
WORK_ORDER = {
"type": "object",
"properties": {
"service": {"enum": ["flat", "brakes"]},
"minutes": {"type": "integer", "minimum": 1},
"approved": {"type": "boolean"},
},
"required": ["service", "minutes", "approved"],
"additionalProperties": False,
}The record {"service": "flat", "minutes": 25, "approved": true} is valid. Here is what
json.loads, then jsonschema.validate, make of five broken versions of it, with the messages
that jsonschema 4.26 gives:
| Change to the valid record | Fails at | Message |
|---|---|---|
Single quotes: {'service': 'flat', …} | Parsing | Expecting property name enclosed in double quotes |
"minutes": "25" | type | '25' is not of type 'integer' |
"service": "Flat" | enum | 'Flat' is not one of ['flat', 'brakes'] |
No approved field | required | 'approved' is a required property |
An extra "rush": true | additionalProperties | Additional properties are not allowed ('rush' was unexpected) |
Four of the five are valid JSON, so code that only calls json.loads would accept them. Exercise
L8.1 builds this kind of check for the lab’s dispatch records.
Three layers of checks¶
A record that passes its schema can still be wrong. Check every response in three layers, and keep their failures apart, as Module 3 kept format apart from meaning:
Syntax.
json.loadsreturns a Python value, or raisesjson.JSONDecodeError.Structure. The validator checks fields, types, and allowed values, or raises
jsonschema.ValidationError.Meaning. Your own code checks what a schema can’t express: business rules, facts from your data, and, in an evaluation, agreement with a labeled answer (Module 7).
Worked example: a valid record that is wrong¶
{"service": "brakes", "minutes": 25, "approved": true} passes WORK_ORDER. But the menu says a
brake job takes 40 minutes, so this record books the bench for too short a time. Only a check
against the menu catches it:
def check_work_order(record):
expected = MENU[record["service"]]["minutes"]
if record["minutes"] != expected:
raise ValueError(f"{record['service']} takes {expected} minutes, not {record['minutes']}")Dispatch records work the same way. {"queue": "repair," "summary": "Two identical card payments"} is a valid record that sends ticket T16, a billing question, to the repair queue. A
schema checks the shape of an answer; a labeled test case checks the answer. Lab 8’s
parse_record turns parse and schema errors into ValueError, so its caller has one kind of
error to handle.
Structured outputs¶
You can also ask the API to hold the model’s response to a schema. Anthropic’s
structured outputs guide
describes two features. With JSON outputs, the request sets output_config.format to
{"type": "json_schema", "schema": …}, and the response’s text holds JSON that follows the
schema. With strict tool use, a tool definition sets "strict": true, and the model’s input to
that tool follows the tool’s schema. The guide says both work by constrained decoding: the API
compiles the schema into a grammar that limits what the model can write.
The guarantee has limits, which the guide states, so keep validating locally:
Unsupported keywords. The guide lists
minimum,maximum,minLength, andmaxLengthamong the constraints structured outputs doesn’t support; sent as they are, they get a 400 error. Anthropic’s SDK helpers remove them before sending the request and add each to its field’s description. A helper that validates responses then checks them against your original schema, but the TypeScript helperjsonSchemaOutputFormat()doesn’t validate. Sent through a helper, Lab 8’s schema would tell the model about the 80-charactermaxLengthon a summary, but the API wouldn’t hold the model to it.Responses that stop early. A refusal (
stop_reason"refusal") or an answer cut off atmax_tokensmight not match the schema. Check the stop reason before you parse, as in Module 2.Capitalization in enums. The model might return an
enumvalue that differs from the schema only in case, with no error. The guide recommends comparing enum values without regard to case.
Worked example: a retry budget¶
When a response fails, the program can ask again, a fixed number of times. Say a work order allows two retries, so at most three requests:
Request 1 stops with
"max_tokens". The program doesn’t parse it, and retries with a largermax_tokens, as the guide advises for a cut-off structured response.Request 2 ends with
"end_turn", but givesbrakes25 minutes. It fails the menu check, so the program retries and says why: a brake job takes 40 minutes.Request 3 passes all three layers, and the program returns its record.
Had request 3 failed too, the program would raise an error holding the last response and its reason, so the caller can choose a fallback, such as a person’s queue. It must never return the invalid record. And each retry is one more request to pay for.
Tools: asking the program to act¶
A model can only write text. A tool lets it ask your program to do something it can’t do, such as read a price from the shop’s menu. Anthropic’s tool use overview says Claude decides when to call a tool from the user’s request and the tool’s description. Your application runs a client tool; a server tool, such as web search, runs on Anthropic’s computers. This course uses only client tools.
A request lists its tools in a tools field. Anthropic’s guide to
defining tools gives
each definition three parts:
name, which must match the regular expression^[a-zA-Z0-9_-]{1,128}$;description, in plain text: what the tool does, when to use it, and how it behaves;input_schema, a JSON Schema for the tool’s input.
The guide calls detailed descriptions the most important factor in how well tools work. It recommends at least three to four sentences for each description, and more for a complex tool: what the tool does, when to use it and when not to, what each parameter means, and what the tool doesn’t return.
Worked example: a receipt tool¶
Section H03 of the shop’s handbook says that a receipt copy needs an invoice reference, and that
electronic receipts go only through the shop register. A poor receipt tool is named receipt,
says only “Gets a receipt.”, and takes an optional ref string. A better one:
{
"name": "find_receipt",
"description": (
"Return the receipt for one completed sale, found by its invoice reference. "
"The result gives the sale's date, its items, and the amount paid in US dollars. "
"Use it when a customer asks for a copy of a receipt and has given an invoice "
"reference; if they haven't, ask for the reference instead of guessing one. "
"It doesn't send the receipt anywhere, because electronic receipts go only through "
"the shop register. An unknown reference returns an error result."
),
"input_schema": {
"type": "object",
"properties": {"invoice_ref": {"type": "string",
"description": "The reference, such as INV-1042"}},
"required": ["invoice_ref"],
"additionalProperties": False,
},
}The poor version leaves the model to guess what ref holds, whether the tool sends anything, and
what a wrong reference does. The better one answers each question, names its parameter for what it
holds, and requires it. Exercise L8.2 asks for descriptions like this for the lab’s three tools,
whose setup definitions have one sentence each.
A valid input can still be wrong¶
An input schema can say that service is a string, but not that it names a service the shop
offers. {"service": "chain"} passes find_service’s schema, and the menu has no chain, so the
lab’s run_tool answers with an error result. The program that runs the tools, called the
host, validates every input and decides whether each action is allowed, whatever the model
asked for. Module 11 builds its defenses on that rule.
What tools cost¶
The tool use overview says a request is billed for the tokens in its tools field, its tool_use
and tool_result blocks, and a tool-use system prompt that the API adds: 286 tokens on Claude Opus
5.5 when tool_choice is auto. Lab 8’s three definitions take about 690 characters as
json.dumps writes them, or about 277 tokens at Module 1’s 2.5 characters per token. So each
request carries about 563 extra input tokens: 563 × 4 / 1,000,000 ≈ 0.0023 dollars on Opus 5.5,
or about 22.50 dollars over 10,000 requests. Module 10 shows how caching a prompt’s stable
start, which can include the tools, cuts that repeated cost.
Steering which tool the model uses¶
The request’s tool_choice field has four settings: auto, the default, lets the model decide;
any requires some tool; tool requires one named tool; and none allows no tool. The guide to
defining tools says that Claude Opus 5.5 and Claude Sonnet 5.5 return a 400 error for any and
tool. On those models, use auto, and steer with descriptions and the system prompt. If a tool’s
input must match its schema exactly, add strict tool use; if the answer must be a fixed JSON shape,
use JSON outputs instead of a tool.
The tool-use loop¶
When the model decides to call tools, its response has stop_reason "tool_use" and one or more
tool_use blocks, each with an id, the tool’s name, and its input. Anthropic’s guide to
handling tool calls
gives the steps that Lab 8 implements:
Send the conversation with the
toolslist.If the stop reason is
"tool_use", run the tool that eachtool_useblock names, with itsinput.Add the response’s
content, unchanged, to the history as anassistantmessage.Add one
usermessage with onetool_resultblock for eachtool_useblock, even for a call that failed. Each result’stool_use_idis theidof the call it answers. The results come first in that message; any text goes after them.Send the history again with the same
tools, and repeat while the stop reason is"tool_use", up to a turn limit. On"end_turn", return the text. Handle every other stop reason as Module 2 did.
Worked example: two calls in one turn¶
A customer asks, “How much is a brake job, and how long does it take?” The first response, which is
illustrative, has two calls: b1 asks find_service about brakes, and b2 asks
estimate_minutes. (Real IDs look like toolu_01A09q90qw90lq917835lq9.) The program runs both
reads against the menu and sends a second request with these messages:
[
{"role": "user", "content": "How much is a brake job, and how long does it take?"},
{"role": "assistant", "content": [ # the first response's content, unchanged
{"type": "tool_use", "id": "b1", "name": "find_service",
"input": {"service": "brakes"}},
{"type": "tool_use", "id": "b2", "name": "estimate_minutes",
"input": {"service": "brakes"}},
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "b1", "content": '{"value": 35}'},
{"type": "tool_result", "tool_use_id": "b2", "content": '{"value": 40}'},
]},
]The second response ends with "end_turn" and text such as “A brake job costs $35 and takes
about 40 minutes.” The exchange took two requests. Had the program swapped the two tool_use_id
values, the price call’s result would say 40.
Anthropic’s guide to parallel tool use says to return all the results together in the next user message: sending each in its own message makes Claude less likely to call tools in parallel later. It leaves the order of running the calls to you, so independent reads can run at the same time, as in Module 9.
When a tool fails¶
A failed call still gets a result, with is_error set to true and content saying what went
wrong. The guide to handling tool calls says Claude might then call the tool again, so limit the
retries your loop allows, and write error messages that say what to try next. Exercise P8.3 asks
for the next message when one of two calls fails.
Testing the loop without a model¶
A ScriptedModel answers each request from a script and records every request it receives, so a
test can script a tool error or a rare stop reason and check what the code sent. It fakes only the
shape of the responses: whether a real model would choose find_service from your description
needs an evaluation against that model, as in Module 7. Exercises L8.3 and L8.4 test five cases:
two calls in a turn, a failed call, a cut-off answer or a refusal, a tool stop with no tool_use
blocks, and a loop that reaches its turn limit.
Common misconceptions¶
“If it parses, it’s a valid record.”
json.loadsaccepts{"queue": "repairs"}, which names a queue that doesn’t exist and has no summary. Only the schema’senumandrequiredcatch it.“Structured outputs make my own validation unnecessary.” They don’t cover refusals or cut-off responses, don’t guarantee an enum value’s case, and don’t support
maxLength. Through an SDK helper, a 120-character summary can come back from a schema whosemaxLengthis 80.“A record that matches its schema is correct.” The repair record for T16 above matches the dispatch schema and misroutes a billing ticket. Grade meaning against labeled cases.
“The model runs the tool.” The model writes a
tool_useblock, which is only a request. In Lab 8, nothing happens untilrun_toolruns it, and the host may refuse.“A failed tool call should raise an exception.” An exception ends the exchange, so the model never learns what went wrong. A result with
is_errorlets it try again or explain the problem.
Summary¶
A parser checks syntax, a validator checks structure against a JSON Schema, and your own code checks meaning. Keep the three kinds of failure apart.
Structured outputs skip some keywords, don’t cover refusals or cut-off responses, and can change an enum value’s case. Validate every response, and bound the retries.
A tool definition has a name, a description of at least three or four sentences, and an input schema. The host still checks every input.
The tool-use loop returns one result per call, matched by
tool_use_id, in one user message. It stops on any other stop reason or at its turn limit.A scripted stand-in tests the loop’s plumbing, not the model’s choices.
Self-check¶
Answer each question before you open its answer.
A response parses as JSON, but its
queuefield is missing. Which layer catches it?Answer
The schema check, if
queueis in the schema’srequiredlist. JSON Schema treats a property as optional unlessrequirednames it, so a schema without that list accepts the record.Why do service names need a domain check after schema validation?
Answer
The input schema says only that
serviceis a string, so"chain"passes. Only the menu knows which services exist, so the host looks the name up and returns an error result for an unknown one.Where do the two results for one assistant turn go?
Answer
Together in the next user message, as two
tool_resultblocks before any text. Each carries thetool_use_idof its call, which matches the result to the call it answers.A structured-output response for the dispatch schema holds
"queue": "Billing". What happened, and what should the code do?Answer
Structured outputs don’t guarantee the case of enum values, so this can arrive with no error, and
jsonschemarejects it. The labels differ in more than case, so the code can lowercasequeuebefore validating, as the guide recommends.A program sends
tool_choice: {"type": "tool", "name": "find_service"}to Claude Opus 5.5. What happens, and what should it send instead?Answer
A 400 error, because Opus 5.5 rejects forced tool use. Send
auto, or leavetool_choiceout, and say in the description and system prompt when to usefind_service.
Further reading¶
Anthropic, Structured outputs. The JSON Schema features it supports, and the cases where a response can still break its schema.
Anthropic, Define tools. A good and a poor tool description side by side, and which models reject forced tool use.
Anthropic, Handle tool calls. The loop’s steps, the format of a
tool_result, and how to report a failure withis_error.Anthropic, Tool use with Claude. Client and server tools, when Claude calls a tool, and what tools add to a request’s cost.
JSON Schema, Object. How
properties,required, andadditionalPropertiesdecide which objects are valid.