Let's talk.

Whether it's a project, a role, or you just want to say hi, my inbox is open.

kadhar.mfn@gmail.com
AboutExperienceProjectsWritingResearchFree guidesFree ebookToolsGames

© 2026 Kadharmoideen Fadurudeen. Made with care.

kadhar.
AboutExperienceProjectsWritingResearchFree guides
Tools
Say hello
Back to Blog
AI Engineering
December 5, 2026
12 min read

Structured Output and Tool Calling: Getting Reliable JSON from LLMs

Prompt-only vs JSON mode vs structured outputs, how Claude, OpenAI and Gemini do it, schema design that helps the model, the validation you still need, and how tool calling works under the hood. With an interactive demo of what each layer catches.

The moment an LLM's output feeds into code instead of a person, “mostly right” stops being good enough.

A person reading a chat reply shrugs off an extra sentence or a slightly different format. A parser doesn't. One “Sure, here's your JSON!” and the request fails. One field called customerName instead of customer and data quietly goes missing.

This is the plumbing under almost every serious AI feature: extracting data from documents, classifying tickets, filling forms, and every agent that calls a tool. Getting it right is mostly solved now, as long as you use the right mode and still check what comes back.

Three levels of “please reply in JSON”

1. Ask in the prompt

“Respond only with JSON in this format.” It works most of the time, which is the problem. At volume, “most of the time” means a steady trickle of preambles, code fences, trailing commas and renamed fields.

2. JSON mode

The API guarantees the output parses as JSON. It doesn't guarantee it's your JSON. Keys, types and nesting are still up to the model.

3. Structured outputs

You pass a JSON Schema and the API constrains generation to it. This is called constrained decoding: at every step, the model may only choose tokens that keep the output valid against the schema. A quote where a number should be simply isn't an option. When the response finishes, it matches the schema.

Level 3 is the default choice today. But notice the words “when the response finishes”. The schema fixes the shape. It can't fix everything else.

What each layer actually catches

Here's the same task, pulling an order out of a customer email, done four ways. A real app needs three checks, and each approach fails at a different one.

Extract the order from a customer email, using

“Reply with JSON only.” Usually works. Sometimes the model is helpful in the wrong way.

What the model returned

Sure! Here's the order:
```json
{ "customer": "Dana Lee", "items": [{ "sku": "MUG-01", "qty": 2 }], }
```
  1. 1. Parses as JSONJSON.parse
  2. 2. Matches the schema (never reached)Zod or JSON Schema validation
  3. 3. Passes business rules (never reached)qty > 0, date in the future, known SKU

A friendly preamble, a code fence and a trailing comma. JSON.parse throws before you get anywhere.

The pattern to take away: structured outputs remove the first two classes of failure, which used to be most of them. The third check, “does this make sense?”, is always yours.

How Claude, OpenAI and Gemini do it

All three support schema-constrained output and strict tool inputs. The parameter names and schema limits differ. From each provider's docs as of December 2026:

Claude

Structured output:
output_config with format type json_schema and your schema
Strict tools:
Add strict: true to a tool definition
Watch for:
No recursive schemas, no numeric or string length limits. The first request with a new schema is slower while it's compiled; the result is cached.

OpenAI

Structured output:
text.format with type json_schema, strict: true and your schema
Strict tools:
strict: true on the function definition
Watch for:
Every field must be in required and additionalProperties must be false. Make a field optional by allowing null.

Gemini

Structured output:
response_format with mime_type application/json and your schema
Strict tools:
Function declarations with a parameters schema
Watch for:
Supports minimum, maximum and recursive $ref, but ignores length limits like minLength. Very large schemas can be rejected.

Because support for JSON Schema features varies, keep schemas to the common core: objects, arrays, strings, numbers, booleans, enums, nullable fields and descriptions. Do range and length checks in your own validation instead of relying on the schema.

Here's an order-extraction call on Claude:

const orderSchema = {
  type: "object",
  properties: {
    customer: { type: "string", description: "Full name as written in the email" },
    items: {
      type: "array",
      items: {
        type: "object",
        properties: {
          sku: { type: "string", enum: ["MUG-01", "TEA-02", "BAG-03"] },
          qty: { type: "integer", description: "Number of units, at least 1" },
        },
        required: ["sku", "qty"],
        additionalProperties: false,
      },
    },
    deliveryDate: {
      type: ["string", "null"],
      description: "ISO date (YYYY-MM-DD) if the customer asked for one, otherwise null",
    },
  },
  required: ["customer", "items", "deliveryDate"],
  additionalProperties: false,
}

const response = await client.messages.create({
  model: "claude-sonnet-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: `Extract the order:\n\n${email}` }],
  output_config: { format: { type: "json_schema", schema: orderSchema } },
})

Design schemas that help the model

The schema is part of the prompt. A good one makes the right answer easier to produce.

  • Use descriptions as instructions. “ISO date if the customer asked for one, otherwise null” tells the model exactly what to do in the edge case.
  • Give it a way to say “not there”. A nullable field or an “unknown” enum value. Without one, a schema that demands a date will get an invented date.
  • Prefer enums to free text. Categories, statuses, SKUs. An enum can't be misspelled.
  • Keep it flat and small. Deep nesting and dozens of optional fields make outputs worse and can hit provider limits. Split big extractions into steps.
  • Put reasoning before the answer. The model writes fields in order. A short “reason” field before a “category” field lets it think first, then decide.
  • Name fields like you would for a colleague. deliveryDate beats dd. The model reads the names, too.

Validate anyway

Four things the schema guarantee doesn't cover:

  • Truncation. If the response hits max_tokens, the JSON is cut off. Check the stop reason before parsing.
  • Refusals. For unsafe requests the model may decline, and the refusal won't match your schema.
  • Wrong values. Right type, wrong fact: zero quantities, past dates, a customer name copied from the signature of the wrong person.
  • Unsupported constraints. Limits the provider ignores, like string lengths, are only enforced if you enforce them.

So parse with a validation library and add your business rules on top. With TypeScript, Zod gives you the runtime check and the type in one place:

import { z } from "zod"

const Order = z.object({
  customer: z.string().min(1),
  items: z.array(z.object({ sku: z.enum(["MUG-01", "TEA-02", "BAG-03"]), qty: z.number().int().positive() })).min(1),
  deliveryDate: z.string().date().nullable(),
})

function readOrder(response) {
  if (response.stop_reason === "max_tokens") throw new Error("Cut off: raise max_tokens")
  const text = response.content.find((block) => block.type === "text")?.text ?? ""
  const order = Order.parse(JSON.parse(text)) // shape and basic rules
  if (order.deliveryDate && new Date(order.deliveryDate) < new Date()) {
    throw new Error("Delivery date is in the past") // business rule
  }
  return order
}

When validation fails, one retry with the error message included (“deliveryDate was in the past, the email says next Friday, today is Monday 1 December”) fixes most cases. If the retry fails too, send it to a person rather than looping. Count these failures. They make excellent eval cases.

Tool calling is structured output with a loop

Tool calling (or function calling) uses the same machinery. You describe each tool with a name, a description and a JSON Schema for its inputs. Instead of answering, the model can reply “call get_order_status with { orderId: "ORD-1042" }”. Your code runs it, sends the result back, and the model continues until it has an answer.

const tools = [{
  name: "get_order_status",
  description: "Look up the shipping status of one order by its ID, like ORD-1042.",
  strict: true,
  input_schema: {
    type: "object",
    properties: { orderId: { type: "string" } },
    required: ["orderId"],
    additionalProperties: false,
  },
}]

const messages = [{ role: "user", content: question }]
while (true) {
  const response = await client.messages.create({ model, max_tokens: 1024, tools, messages })
  messages.push({ role: "assistant", content: response.content })
  if (response.stop_reason !== "tool_use") return response // final answer

  const results = []
  for (const call of response.content.filter((block) => block.type === "tool_use")) {
    const output = await runTool(call.name, call.input, { userId }) // your code, your permissions
    results.push({ type: "tool_result", tool_use_id: call.id, content: JSON.stringify(output) })
  }
  messages.push({ role: "user", content: results })
}

The model never executes anything. Your code does, which is where the important rules live:

  • Authorise in code, not in the prompt. runTool checks that this user may see this order. The model choosing an ID is a request, not a permission.
  • Validate arguments. Strict mode guarantees the shape. Check the values like any other user input.
  • Return errors as results. “Order not found” sent back as a tool result lets the model recover or ask a follow-up. A thrown exception just ends the conversation.
  • Cap the loop. Set a maximum number of tool rounds and a timeout per tool, so a confused model can't spin forever.
  • Make writes safe to retry. Anything that changes data should be idempotent, and the risky ones should ask a person to confirm.

Tool descriptions matter as much as code. How to write tools that models use well, and how to share them across apps with a standard protocol, is covered in the MCP guide. When several models call tools and hand work to each other, you have an agent system, covered in building a multi-agent system.

Two practical costs

  • The schema costs tokens. Providers add it to the prompt behind the scenes. A big schema on every request adds up, so keep it lean.
  • Changing it can reset caches. On Claude, a new schema is compiled on first use, so that request is slower, and changing the output format invalidates the prompt cache. Keep schemas stable, like the rest of your prompt prefix.

The second point is the same rule as in prompt caching: the stable parts of a request should actually stay stable.

Frequently Asked Questions

What is structured output in LLMs?

A mode where the API constrains the model so its response always matches a JSON Schema you provide. The model can only produce tokens that keep the output valid, so you get the right keys and types every time the response completes.

What's the difference between JSON mode and structured outputs?

JSON mode only guarantees the response is valid JSON. Structured outputs guarantee it matches your specific schema: the right fields, types and enums. Prefer structured outputs whenever the provider supports them.

Do I still need to validate structured output?

Yes. The schema covers shape, not meaning. A response can still be cut off by the token limit, be a refusal, or contain values that are well-typed but wrong, like a quantity of zero or a date in the past. Parse, validate and check business rules in your own code.

How does tool calling work?

You describe tools with a name, a description and a JSON Schema for their inputs. The model replies with a request to call one, with arguments. Your code runs the tool and sends the result back, and the model continues. The model never runs anything itself.

Why does my LLM return invalid JSON?

Usually because the format is only requested in the prompt, so the model adds explanations or code fences, or because the response hit max_tokens. Switch to the provider's structured output mode, check the stop reason, and give long responses enough token budget.

The short version

Don't ask for JSON in the prompt; use the provider's structured output mode with a small, flat, well-described schema that allows “not found”. Then check the stop reason, validate with Zod or similar, and enforce business rules yourself, with one retry before handing off to a person. Tool calling is the same idea in a loop, with one extra rule: the model requests, your code decides.

PreviousEvals for LLM Features: How to Know Your Prompt Change Didn't Break AnythingNextPrompt Injection and AI Security: A Practical Guide for App Developers

Continue Reading

Explore more articles on software engineering and technology

AI Engineering

Making AI Features Feel Fast: Streaming, Latency and UX

Time to first token vs output speed, streaming from the model to the browser in Next.js, the UX details that make streaming feel polished, and the changes that genuinely cut latency. With an interactive race between waiting and streaming.

11 min read
Read
AI Engineering

Prompt Injection and AI Security: A Practical Guide for App Developers

Why LLMs can't reliably tell instructions from data, how indirect injection hides in emails and web pages, the lethal trifecta, and the layered defences that hold: fewer capabilities, real confirmation, output control, quarantine and testing. With an interactive attack demo.

13 min read
Read
AI Engineering

Evals for LLM Features: How to Know Your Prompt Change Didn't Break Anything

Build a test set from real data, pick the right grader for each check, compare runs case by case instead of by average, run evals in CI and keep watching in production. With an interactive eval diff where the score goes up and the feature gets worse.

12 min read
Read