SysDesignAtlas

Structured Output & Tool Contracts

Getting reliable machine-readable output from a probabilistic system — schema design, constrained decoding, validation and repair, and idempotent tool execution.

HLDMedium10 min readaistructured-outputjson-schematools
Confidence

#The interface problem

The moment a model's output feeds a program rather than a human, you need a contract. And you're asking a system that samples from a probability distribution to satisfy a schema exactly, every time.

#Four levels of guarantee

ApproachGuaranteeCost
Ask nicely in the promptNone; ~1–5% failureFree
Few-shot examplesBetter; still probabilisticPrompt tokens
Retry on parse failureEventually succeeds, usuallyFull extra generations; unbounded tail latency (a request that fails three times takes four full generations)
Constrained decodingAbsolute — invalid output is unrepresentableSmall per-step masking cost
Fine-tuning for formatHigh, not absoluteTraining cost

Constrained decoding is the right default whenever the runtime supports it, and the mechanism is worth understanding because it explains why the guarantee is absolute rather than statistical.

Recall from decoding strategies that each step produces a score for every possible token, and one is then chosen. Constrained decoding works out which tokens would make the output invalid given what has been generated so far, and sets their scores to negative infinity before the choice happens. The malformed option isn't unlikely — it isn't on the menu.

   Schema: { "status": "ok"|"error", "count": integer }

   Generated:  {"status": "

   Valid next tokens:  o | e     (only "ok" or "error" can follow)
   Everything else:    masked to −∞

   → the state machine, not the model, enforces the grammar

The schema is compiled into a state machine (an automaton): a small graph that tracks where you are in the output — "just opened the object", "inside the status string" — and, for each of those states, which tokens may come next. Efficient implementations (XGrammar, Outlines, llama.cpp GBNF) precompute the allowed-token mask per automaton state, so the per-step cost is a bitmask lookup rather than a schema evaluation — near-zero overhead in practice.

#Schema design

Schemas written for a model differ from schemas written for a programmer.

   ✗ HARD FOR A MODEL

     { "d": "string",              // what is d?
       "t": 0,                     // what unit? what scale?
       "f": ["a", "b"],            // what do these mean?
       "meta": {}                  // unconstrained free-for-all
     }

   ✓ EASY FOR A MODEL

     { "due_date": "YYYY-MM-DD or null if not stated",
       "priority": "low" | "medium" | "high",
       "estimated_hours": number between 0.5 and 40,
       "tags": array of up to 5 strings from the allowed list,
       "confidence": "high" | "medium" | "low"
     }

Rules that measurably improve accuracy:

  • Descriptive names. The field name is a prompt. customer_email_address beats email beats e.
  • Enums over free strings. A closed set is both easier for the model and enforceable in the schema.
  • Descriptions on every field, including the format and what to do when the information is absent.
  • Flat over nested. Deep nesting increases error rates; three levels is a reasonable ceiling.
  • Order fields by dependency. Models generate left to right, so a field that depends on reasoning should come after a field that holds the reasoning. Put reasoning before answer and the answer improves — by the time the model writes the answer, its own analysis is already in the text it's continuing from.

That last one is worth emphasising: field order is a chain-of-thought lever. {"answer": ..., "reasoning": ...} produces a guess followed by a rationalisation. {"reasoning": ..., "answer": ...} produces analysis followed by a conclusion. Same schema, materially different accuracy.

#Validation and repair

Even with constrained decoding you need semantic validation, because the schema only enforces shape.

   LAYERS OF VALIDATION

   1. Syntactic     is it parseable?
                    → constrained decoding makes this always yes

   2. Schema        do types and required fields match?
                    → also guaranteed by constrained decoding

   3. Semantic      are the VALUES sensible?
                    · does that customer ID exist?
                    · is the date in the future when it must be?
                    · does the total equal the sum of line items?
                    → NOT guaranteed. This is your job.

   4. Business      is this action permitted for this user
                    in this context?
                    → definitely your job, and a security boundary

Repair loops handle semantic failures: return the specific error to the model and ask for a correction.

   attempt 1 → {"customer_id": "CUST-99999"}
   validate  → error: customer CUST-99999 not found
   attempt 2 → feed the error back as an observation
             → {"customer_id": "CUST-10432"}   ✓

   Cap repairs at 1-2 attempts. Beyond that the model is
   usually stuck and you're paying for a loop that won't
   converge — fall back to a human or an error.

The error message quality matters as much as in any API: "customer_id: no customer found with ID CUST-99999. Use search_customer to find the correct ID." produces a recovery; "validation failed" produces another wrong guess.

#Tool contracts

Tool calls are structured output with a side effect attached, which raises the stakes considerably.

Other properties a good tool contract has:

  • Explicit reversibility. Mark each tool read-only, reversible, or irreversible. The approval policy and the retry policy both depend on this label: a read-only tool can be retried freely and auto-approved, while an irreversible one needs an idempotency key and probably a human sign-off.
  • Bounded results. A tool returning unbounded data blows the context budget. Paginate, and say so in the response.
  • Actionable errors. Structured, with a hint about what to do instead.
  • Timeouts everywhere, with the remaining budget propagated from the caller — if the run has 8 seconds left, the tool is told "you have 8 seconds", not left to use its own 30-second default.

#Streaming structured output

Streaming a JSON object is awkward: it isn't parseable until the closing brace, so the user watches a spinner while the model writes.

Options:

  • Partial JSON parsing. Incrementally parse the prefix, completing open structures speculatively — treat {"title": "Quarterly rev as if it were {"title": "Quarterly rev"} for now. Lets you render fields as they arrive. Libraries exist; the edge cases are fiddly.
  • Field-by-field streaming. Emit each completed field as a separate event. Cleaner, requires a custom protocol.
  • Split the call. Stream the prose for the user, then make a separate constrained call for the structured part. Two calls, much simpler, and often the best user experience.
  • Order for perceived latency. Put the fields the UI shows first first, so something appears quickly.

#When not to use structured output

Constrained generation has a real cost beyond compute: forcing a model into a rigid schema can reduce quality on tasks that need open reasoning. The model spends capacity satisfying the grammar rather than thinking.

The reliable mitigation is a reasoning field first, as above — give it room to think inside the structure. Where that isn't enough, a two-call approach (reason freely, then extract) usually beats a single heavily-constrained call.

#Check yourself

Why does a small parse-failure rate matter?Show answer
It compounds: 2% per call leaves 0.98²⁰ ≈ 67% of 20-step runs succeeding on format alone; at 0.1% it's 98%. Driving it to zero beats any retry logic.
Why is constrained decoding's guarantee absolute?Show answer
At each step, tokens that would break the grammar are masked to −∞ before choosing — invalid output isn't unlikely, it's unrepresentable. Precomputed masks make it nearly free.
What does constrained decoding not fix, and the remedy?Show answer
Content: schema-valid output can be fabricated, and a forced schema makes the model guess. Put uncertainty in the schema — nullable fields, confidence, an "insufficient information" variant.
What makes a schema easy for a model?Show answer
Descriptive field names, enums over free strings, a description per field including what to do when information is absent, shallow nesting, and dependency-ordered fields.
Why is field order a chain-of-thought lever?Show answer
Models generate left to right: reasoning before answer yields analysis then conclusion; answer before reasoning yields a guess then a rationalisation.
What validation remains after constrained decoding?Show answer
Semantic (does the ID exist, do totals add up) and business (is this action allowed for this user). Repair loops return specific, actionable errors and stop after 1–2 attempts.
How should idempotency keys for tool calls be built?Show answer
Derived from content — hash(run ID, step index, tool name, arguments) — not a fresh UUID per attempt, so replays and retries produce the same key and execute once.
How do you stream structured output?Show answer
Partial JSON parsing, field-by-field events, or splitting into a streamed prose call plus a separate constrained call — and put the fields the UI shows first first.

#What to carry forward

  • Per-call failure rates compound. 2% per call is a third of 20-step runs failing.
  • Constrained decoding makes invalid output unrepresentable — the only approach with a real guarantee.
  • It constrains format, not content. Put uncertainty in the schema, or you force a guess.
  • Field order is a chain-of-thought lever. Reasoning before answer.
  • Semantic and business validation are still yours. Repair loops need actionable errors and a cap.
  • Derive idempotency keys from trajectory position and arguments, never fresh per attempt.
  • Mark every tool read-only, reversible, or irreversible — retry and approval policy both depend on it.
00:00
/ 10m