Claude and the Anthropic SDK · Chapter 9 of 21
Structured output
By the end of this chapter you can get Claude's reply as JSON that fits a schema you wrote, every time: by hand with output_config's format, and typed with a pydantic model and client.messages.parse. You will let missing fields be None instead of made up, and you will know the one case a schema cannot save you from: a reply cut off by max_tokens. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Tools and structure
- 4 tasks
- Python
- In the all labs plan
The first 2 chapters of Claude and the Anthropic SDK are free. This one comes with the all labs plan.
Why you need this
Sahay so far answers families in sentences. But Parchi's own systems need data: Kamla pastes a hospital bill into the chat, and the claims desk wants a record with the patient, the hospital, the dates, every item and the total, to file it and check it. Farhan wants the totals in a spreadsheet.
So ask Claude for JSON? Asked in words, Claude writes for a person: a friendly sentence, the JSON in a fenced block, a closing line. Your json.loads raises on the first character. Strip the fence with a regular expression, and the next reply names a field differently, or leaves one out. A program needs a guarantee, not a habit: the reply is JSON, and it fits the schema.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
json_schema.py: a schema by hand
Send "claude-opus-5-5" (max_tokens 1024) one user message: BILL (given), a blank line, then Extract this bill. With it send output_config={"format": {"type": "json_schema", "schema": schema}}, where schema is an object with patient (string), hospital (string), items (an array of objects with name, a string, and amount, an integer) and total (an integer), every field required, and "additionalProperties": False on both objects.
json.loads the reply's text and print PATIENT at HOSPITAL: N items, total ₹X (inr(total)).
- Task 2
bills.py: typed records with pydantic
Write Item (name: str, amount: int) and Bill, pydantic models: Bill has claim_id, patient, hospital, admitted, discharged (str), items (list[Item]), total (int), and bill_no and doctor (str | None).
Write extract_bill(text: str) -> Bill that sends "claude-opus-5-5" (max_tokens 1024) one user message, text then a blank line then Extract this bill., with client.messages.parse(..., output_format=Bill), and returns parsed_output (raise if it is None).
- Task 3
cut_off.py: a reply cut short
Send BILL (given), a blank line, then Extract this bill. to "claude-opus-5-5" with client.messages.create, max_tokens 100, and output_config={"format": {"type": "json_schema", "schema": anthropic.transform_schema(bills.Bill)}}. If its stop_reason is "max_tokens", print cut off at max_tokens 100: retrying with max_tokens 1024 and send it again with max_tokens 1024.
Then print stop_reason: STOP, parse the text with bills.Bill.model_validate_json(text) and print CLAIM_ID: N items, total ₹X.
- Task 4 · interview question
Interview: in_words.py
"Why not just ask Claude for JSON in the prompt?" Send "claude-opus-5-5" (max_tokens 1024) BILL, a blank line, then Extract this bill as JSON. with no format. json.loads the reply's text in a try, and print in words: NAME: MESSAGE from the exception it raises (type(e).__name__ and str(e)), or in words: parsed if it does not.
Then send BILL, a blank line, Extract this bill. with client.messages.parse and output_format=bills.Bill, and print with a format: N items, total ₹X from parsed_output.
What you will learn
- Why "reply in JSON" in the prompt is not enough, with the error it gives.
- output_config={"format": ...}: a JSON schema the reply must fit.
- Pydantic models and client.messages.parse: the schema written once as a class, the reply checked and typed (parsed_output).
- Nullable fields: an honest "not on this bill" instead of an invented value.
- The limit: max_tokens still cuts a reply, so read stop_reason first.
More in Tools and structure
Build "Structured output" yourself
Parchi, a Jaipur startup, helps families claim health insurance. You build Sahay, a claims assistant that reads bills and policies with Claude, and measure what caching, models and effort cost. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Claude and the Anthropic SDK are free. This one comes with the all labs plan.