Skip to content

Lesson 18 ยท Tools and Structured Output

Structured Outputs: Reliable JSON from Claude

Get machine-readable JSON from Claude with output_config.format and a JSON Schema, learn the schema limits, and still validate meaning in your own code.

A program cannot use "Sure! Here's the information you asked for..." It needs data with known fields. Asking for JSON in the prompt often works, but a stray sentence or a missing field breaks your code. Structured outputs constrain the response to a JSON Schema that you provide.

  • JSON outputs, set with output_config.format, shape Claude's final answer.
  • Strict tool use, set with strict: true on a tool, checks tool names and inputs against the tool's schema.

This lesson covers the first. The next one covers tools. For the general idea, see structured outputs in the generative AI tutorial.

A real request

Python
import json
import anthropic

client = anthropic.Anthropic()

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "email": {"anyOf": [{"type": "string"}, {"type": "null"}]},
        "topic": {"type": "string", "enum": ["demo", "billing", "other"]},
    },
    "required": ["name", "email", "topic"],
    "additionalProperties": False,
}

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=2000,
    messages=[{"role": "user", "content": "Extract the contact: Ana Ruiz wants a demo."}],
    output_config={"format": {"type": "json_schema", "schema": schema}},
)

if response.stop_reason == "end_turn":
    text = next(b.text for b in response.content if b.type == "text")
    data = json.loads(text)
    print(data)
else:
    print("No complete result:", response.stop_reason)

The JSON arrives as text in a text block. Check stop_reason first: if the output was cut off or the model declined, you may not have JSON that matches the schema.

In Python, the SDK also has a helper that accepts a Pydantic model: client.messages.parse(..., output_format=MyModel), and you read response.parsed_output.

Design the schema well

  • Give fields clear names, and add description text where the meaning is not obvious.
  • Use enum for fixed choices.
  • Give the model an honest way to say "unknown": allow null, or include an unclear choice. If a required string has no real value, the model still has to put something there.
  • Keep it as flat and small as the job allows.

What the schema language supports

As of December 2026, supported features include objects, arrays, strings, numbers, integers, booleans and null, enum, const, anyOf, internal $ref, some string formats such as date and email, and additionalProperties: false, which objects require. Documented limits include:

  • No recursive schemas.
  • No numeric limits such as minimum, and no string length limits.
  • Array minItems only 0 or 1.
  • No external references.

Unsupported features in a raw schema cause a 400 error. SDK helpers can remove some constraints from the schema, describe them in text and, when they validate responses, still check them on your side. Read the structured outputs page for the full list.

Practical notes: the first request with a new schema can be slower while the schema is compiled, the format adds some input tokens, and changing the format invalidates the prompt cache for that conversation.

Valid shape is not correct data

A schema guarantees structure, not truth. {"amount": 900} is valid even if the invoice says 90. Your code still needs checks that the schema cannot express:

  • Ranges, such as a positive amount.
  • Cross-field rules, such as a total that equals the sum of its lines.
  • Facts in your own records, such as whether a customer ID exists.
  • Evidence: does the value appear in the source text?
Python Check meaning after the shape is correct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The JSON parses perfectly and still has two serious errors. Decide what happens next: retry once with the error message, send the item to a person, or reject it. Do not "fix" money by guessing. In real systems, store money as integers in minor units, or use a decimal type, instead of floating-point numbers.

When JSON comes from other sources

If you do not use a schema feature, you must parse defensively. This helper checks required keys and types, and rejects extras.

Python Validate required keys and reject extras

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What to do with a failed check

A failed business check is useful information. Handle it in a fixed order.

  1. Check your own input. Was the document complete and readable? A second model call cannot recover a missing page.
  2. Retry once with the specific error, such as "the lines add up to 95 but the total is 120; copy both exactly as written". Do not tell the model which value to make correct, or it may simply change numbers to satisfy your rule.
  3. Send it to a person with the original text, the extracted record and the reason for the failure.
  4. Record the case in your test set, so that you can see whether later changes handle it better.

A document can itself be inconsistent. If an invoice really does state the wrong total, the correct result is a faithful record plus a warning, not a repaired record.

Version your schema

Programs downstream depend on your field names and types. Treat a schema change like any interface change: name a version, update the validation code and tests together, and decide how to read old records. Keep the schema in one place in your code, so that the API request and your validator cannot drift apart without anyone noticing.

Test the unhappy paths

Include inputs that have nothing to extract, two possible answers, another language and text that tries to give instructions. For each one, decide the correct record in advance. An empty or all-null result is often the right answer, and your code should treat it as normal.

Common mistake: marking every field required with no way to express "missing". That pushes the model to fill gaps. Allow null or "unclear", then handle those cases openly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which request field sets a JSON Schema for the final answer?

    Use output_config with a format of type json_schema.
  2. 2. What does a matching schema guarantee?

    You still need business and evidence checks.
  3. 3. An email address may be absent from the source. What is a good schema design?

    Give the model an honest way to report a gap.
  4. 4. What should you check before parsing the JSON?

    Truncated or declined responses may not contain complete JSON.

Summary

  • output_config.format with a JSON Schema constrains the final answer.
  • Design for missing values and know the unsupported schema features.
  • Check stop_reason, parse, then validate meaning in code.
  • Route doubtful records to a person.

Next: Tool Use with the Claude API

Your progress is saved in this browser. No account needed.