Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 8: Structured output and tools

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:

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 recordFails atMessage
Single quotes: {'service': 'flat', …}ParsingExpecting 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 fieldrequired'approved' is a required property
An extra "rush": trueadditionalPropertiesAdditional 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:

  1. Syntax. json.loads returns a Python value, or raises json.JSONDecodeError.

  2. Structure. The validator checks fields, types, and allowed values, or raises jsonschema.ValidationError.

  3. 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:

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:

  1. Request 1 stops with "max_tokens". The program doesn’t parse it, and retries with a larger max_tokens, as the guide advises for a cut-off structured response.

  2. Request 2 ends with "end_turn", but gives brakes 25 minutes. It fails the menu check, so the program retries and says why: a brake job takes 40 minutes.

  3. 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:

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:

  1. Send the conversation with the tools list.

  2. If the stop reason is "tool_use", run the tool that each tool_use block names, with its input.

  3. Add the response’s content, unchanged, to the history as an assistant message.

  4. Add one user message with one tool_result block for each tool_use block, even for a call that failed. Each result’s tool_use_id is the id of the call it answers. The results come first in that message; any text goes after them.

  5. 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

Summary

Self-check

Answer each question before you open its answer.

  1. A response parses as JSON, but its queue field is missing. Which layer catches it?

    Answer

    The schema check, if queue is in the schema’s required list. JSON Schema treats a property as optional unless required names it, so a schema without that list accepts the record.

  2. Why do service names need a domain check after schema validation?

    Answer

    The input schema says only that service is 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.

  3. Where do the two results for one assistant turn go?

    Answer

    Together in the next user message, as two tool_result blocks before any text. Each carries the tool_use_id of its call, which matches the result to the call it answers.

  4. 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 jsonschema rejects it. The labels differ in more than case, so the code can lowercase queue before validating, as the guide recommends.

  5. 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 leave tool_choice out, and say in the description and system prompt when to use find_service.

Further reading