Typorithm · medium

Structured Output (JSON)

structured-outputllmtoolsschema
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Structured Output (JSON)

0%

Prompt Engineering

To get reliable structured JSON, define a tool with an input_schema and force it with tool_choice; the model returns arguments matching the schema instead of free text, far more reliably than asking for JSON in prose.

Asking a model to 'return JSON' in prose is fragile — it may add prose, miss a field, or produce invalid JSON. Tools solve this by giving the model a typed shape to fill in.

You define a tool with a name and an input_schema (JSON Schema). The schema declares the fields and types you expect, and the model returns arguments that conform to it.

Setting tool_choice to { type: "tool", name: "extract" } forces that exact tool, so every response is a structured tool call matching the schema — the reliable way to get machine-readable output.

01

Define a tool with name + input_schema (JSON Schema).

02

tool_choice forces a specific tool to be called.

03

Schema-matched arguments beat JSON-in-prose for reliability.

const msg = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  tools: [{ name: "extract", input_schema: schema }],
  tool_choice: { type: "tool", name: "extract" },
  messages,
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Balanced model

claude-sonnet-4-6 is the balanced model — plenty capable for reliable extraction at lower cost than Opus.

model: "claude-sonnet-4-6",

2. Define a tool

A tool is defined by a name and an input_schema (JSON Schema) describing the shape of its arguments.

tools: [{ name: "extract", input_schema: schema }],

3. The schema

input_schema is the JSON Schema the model's returned arguments must match.

input_schema: schema

4. Force the tool

tool_choice with type "tool" forces the model to call exactly that tool, guaranteeing structured arguments back.

tool_choice: { type: "tool", name: "extract" },

5. The input

The messages list carries the text you want the model to extract structured data from.

messages,

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Structured Output (JSON): Lesson & Practice · Typorithm | ApplyDjinn