Skip to content

Structured output: JSON Schema, grammar constraints and semantic validation

14 min reading

Separate schema enforcement, grammar constraints and semantic acceptance.

Page details

GenAI · Lesson 9 of 45 · 1 / 1.3

Sources · 14 min reading · 30 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Sampling: temperature, top-p, top-k and repetition penalties through a worked distribution. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind can choose a sampling policy, but its workflow needs a structured proposal. Dev shows Maya a well-formed object with a supporting document identifier. Priya cannot find that identifier in the permitted evidence collection.

Dev: “The response matches the required shape.”

Maya: “Does that mean the workflow can accept it?”

Priya: “Check what the identifier points to. The schema cannot make a source exist.”

You will separate grammar-constrained generation, parsing, schema validation and semantic acceptance. Each boundary answers a different question; a structured proposal still needs checks against authoritative state before the application uses it.

Which guarantee does a structured response actually provide?

Grammar-based constrained decoding tracks a parser state and masks candidate tokens that cannot extend an allowed structure. JSON Schema can describe the intended object, while a runtime translates supported constraints into generation restrictions. This is different from generating unrestricted text and attempting to repair it afterward. The vLLM structured-output documentation illustrates concrete constrained-output interfaces; supported schema features remain implementation-specific.

Hypothetical scenario. A result must choose one of three status labels and supply a document identifier. Suppose eight outputs all parse, but two cite nonexistent identifiers. Structural acceptance is 8/8; full acceptance is at most (8 − 2)/8 = 6/8 = 75% for this chosen set. The grammar cannot establish that an identifier exists or that its document is permitted. Resolve those conditions against authoritative application state before acting.

Hypothetical scenario. The assistant adds a friendly sentence before its JSON and the order parser rejects the response.

In short. Validate structure at the application boundary. Check business rules after parsing.

A machine-readable proposal is still a proposal

Hypothetical scenario. An equipment assistant turns a message into a loan request. It returns an object naming an item and the number of loan days. The object parses as JSON and matches the expected field types. A developer assumes that those checks make it safe to create the loan.

The item might not exist, the person might lack permission to borrow it, or the requested dates might conflict with an existing reservation. None of those facts follows from the response being well formed. An output interface needs a clear distinction between proposed data and an authorized state change.

The goal of this chapter is to separate parsing, schema validation, and application acceptance. It also explains where constrained generation helps, why repair attempts need limits, and which evidence a validation statistic actually provides.

Put semantic validation after constrained decoding

Hypothetical scenario. A model emits a schema-valid payment proposal naming amount, currency and account. Grammar constraints can restrict syntax, and schema validation can check represented types and required fields. Neither establishes that the caller may pay that account or that the proposed amount matches an approved intention.

Put semantic validation after constrained decoding
ArtifactConcrete evidenceDecision boundary
Parsed proposaltyped fields, schema versionShape only
Semantic evidencesource refs, arithmetic, domain ruleMeaning check
Authorized operationcaller, approval fingerprint, identityEffect permission
Schema-valid proposal: Constrained output → Semantic validation.Schema-valid proposal: Constrained output → Semantic validation. Constrained output to Semantic validation: schema-valid proposal; Semantic validation to Authority / execution: only eligible meaning proceeds.Constrained outputSemantic validationAuthority /executionschema-valid proposalonly eligible meaning proceeds
Schema-valid proposal: Constrained output → Semantic validation. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Use separate parse, semantic and authority outcomes. Validation failure can request a bounded correction, but the corrected output is a new proposal requiring the same checks. Preserve the original task and remaining budget instead of granting a fresh full allowance. Tool execution starts only after application policy binds an approved fingerprint and stable business identity. A schema field called approved cannot grant its own authority.

A formatting instruction leaves several failure modes open

A model asked to return JSON can still produce incomplete text, an unexpected shape, or content that violates the task. A reply may also represent a refusal or an interrupted generation rather than the requested result. The application should recognize those outcomes instead of assuming every response is ready for the same parser.

Even complete JSON has limited meaning. It represents objects, arrays, strings, numbers, booleans, and null; it does not define your loan policy. The string “7” and the number 7 are different JSON values. A field named approved does not acquire authority because a model emitted it. The format is specified in RFC 8259.

Trying to recover arbitrary text with a broad regular expression can hide the original failure. An application might extract an object from a response while discarding a warning or accepting the wrong object. Define the accepted response envelope and error path rather than treating any braces as evidence of a valid result.

Build an acceptance path with named boundaries

The first boundary is parsing: does the complete response satisfy the chosen data format and parser policy? The second is schema validation: does the resulting value satisfy the declared shape, required fields, types, and other encoded constraints? The third is application acceptance: does the proposal satisfy the task's factual, authorization, and state-dependent rules?

A schema for the hypothetical loan proposal might require an item identifier and an integer loan duration between 1 and 14 days, with no undeclared fields. These are chosen rules for the exercise, not a real institution's policy. JSON Schema defines vocabulary for required properties, types, numeric limits, and other constraints in its validation specification. Check the dialect and supported behavior of the implementation.

A generated proposal crosses separate validation boundaries A candidate response is parsed, checked against a schema, and evaluated against application rules before a permitted action. Rejections go to a bounded recovery path. Passing one check does not mean passing the later checks. Parseformat policyValidate schemadeclared constraintsCheck applicationfacts + permissionsPermitted actionunder app controlReject, explain a bounded error, or request reviewDo not turn failure into unbounded retries.
Each failed check needs an explicit outcome. A schema-valid value can still fail the application checks.

Keep the authoritative action outside the generated proposal. The assistant can propose an item identifier and duration; the application checks the requester and current inventory state before changing a reservation. A model-supplied identity or approval field must not substitute for the authenticated requester or the permission decision.

Work a validation funnel without changing its denominator

Hypothetical scenario; all counts are invented. Process 100 candidate responses. Six fail the parser policy, leaving 94 parsed responses. Ten of those fail the schema, leaving 94 − 10 = 84. Nine of the remaining proposals fail application checks, leaving 84 − 9 = 75 accepted proposals.

The parsed fraction is 94 ÷ 100 = 94%. Among parsed responses, the schema-pass fraction is 84 ÷ 94 ≈ 89.4%. Among schema-valid proposals, the application-acceptance fraction is 75 ÷ 84 ≈ 89.3%. End-to-end acceptance is 75 ÷ 100 = 75%. Reporting only one conditional rate can conceal where the other failures occurred.

Check the partition: 6 parsing failures + 10 schema failures + 9 application failures + 75 accepted = 100. The categories are assigned by the first failed boundary, so they do not double-count responses. Acceptance means the proposal passed the stated checks; it is not an independently measured guarantee that every accepted proposal is correct.

Suppose the policy allows one additional attempt for each parsing or schema failure. There are 6 + 10 = 16 such cases, so the maximum attempts under this rule are 100 + 16 = 116. No repair outcomes have been specified. The new acceptance rate cannot be calculated merely from the existence of a retry.

For the document assistant, keep four acceptance questions separate. Can the response be parsed into the expected structure? Does it describe the intended document and revision? May this actor use that evidence or perform that action? Is the proposed consequence allowed by the application policy? A schema can constrain fields without establishing the answers to the other questions.

A well-shaped response can fail a different boundary
Hypothetical responseStructural resultRemaining decision
Valid citation fields, obsolete policy revisionMay passReject or refresh the evidence version
Correct field types, wrong customer IDMay passValidate entity and tenant binding
Valid tool arguments, no action authorityMay passRefuse execution at the tool boundary
Malformed objectFailsBounded repair or an explicit unavailable result

Accordingly, a Pydantic-style schema gate is structural validation, not a prompt-injection defense by itself. Retrieved text can fit an allowed field while containing untrusted instructions. The tool-authority lesson places action permission at the execution boundary; the assistant case applies eligibility before evidence reaches generation.

In the wild: Structured Outputs: Making a Model’s Answer Safe to Parse

RFC 8259: JSON types and object-name interoperability rules do not encode a task's business policy.

Constrained generation and validation do different work

A constrained decoder can restrict generation to sequences compatible with a chosen formal language or supported structural rules. Efficient Guided Generation for Large Language Models develops a mechanism for guiding generation through formal constraints. The relevant guarantee concerns the constraints actually implemented, not arbitrary facts about a proposed action.

Check exactly which schema features, output limits, and interruption cases a service supports. A claim about structural output should not be extended to a complete response that was never produced. Keep independent acceptance checks at the application boundary and treat failures as part of the interface contract.

Schema versioning matters as well. Adding a required field can make older producers invalid under the new consumer rule. Allowing undeclared fields can help a controlled migration or conceal a producer mistake, depending on the contract. JSON Schema's core specification defines the framework and dialect vocabulary; the application still needs a rollout policy for its producers and consumers.

When helpful repair changes the business decision

Hypothetical scenario. A loan proposal asks for a duration beyond the permitted range. A generic repair step silently clips the duration to the maximum and proceeds. The resulting object passes validation, but it no longer represents exactly what the requester asked for.

That may be an acceptable product behavior only if it is deliberately specified and communicated. Otherwise the system has converted an invalid proposal into an unauthorized interpretation. A repair policy needs to distinguish formatting recovery from changing a meaningful value.

Preserve the original proposal, the validation error, and any approved correction path when diagnosing the failure. Give a retry only the bounded information needed to correct the representation. If the unresolved issue is permission or absent evidence, another formatting attempt is not the right control.

Four assumptions to make explicit

Does required mean nonempty? Requiring a property means it must be present under the schema. To prohibit an empty string or array, add the appropriate content constraint. To forbid null, specify a type that excludes it.

Does validation automatically coerce types? A library may offer coercion, but it is a policy choice. If a string is converted to a number before validation, that is a different acceptance path from strictly validating the original value. Record the chosen behavior.

Do duplicate object names have a universal interpretation? RFC 8259 recommends unique member names for interoperability and describes variation when they are duplicated. An application can reject duplicates explicitly rather than relying on an unspecified last-value or first-value rule.

Does a structural check establish current facts? Not unless those facts and the needed relationships are actually part of the checking system. A chosen shape-only schema does not consult a live inventory or grant access to it. Some richer constraints can be encoded; identify which are enforced and where.

Use structured output where a consumer needs a contract

Use this acceptance path for proposed tool arguments, extraction records, routing decisions, and other interfaces where downstream software needs explicit fields. Decide which system owns each field and which failures are retryable before adding automatic recovery.

Do not force every free-form explanation into an elaborate schema without a consumer need. Nor should structured output be sold as a substitute for factual evaluation or permissions. Its value is making a boundary testable: a response either satisfies the encoded contract or follows a defined failure path. Data-integrity and system-testing principles remain necessary beyond the generated text.

Limits of Structured Outputs: Making a Model’s Answer Safe to Parse

Parsing, schema validity and business correctness are different acceptance checks. A constrained shape does not establish source support or permission. Confirm the target schema implementation and preserve the authoritative identity and version checks required by the consumer.

Test the parsed proposal boundary

The JSON is valid and its approved field is true. May the tool run?

Reveal the design reasoning

No. Resolve approval from application-owned evidence and compare the exact arguments. Treat model-supplied authority fields as untrusted proposal data.

Decision: Declare each validation boundary and retain a useful rejection outcome.

Check yourself: which boundary failed?

  1. A response parses and matches the item/duration schema, but the requester cannot borrow that item. Is another JSON-formatting retry the right remedy?

    Identify the authority check

    No. The proposal failed authorization, not representation. Reject or route it according to the permission policy. A model rewriting the same fields cannot grant the requester access.

  2. Of 50 candidates, 5 fail parsing, 10 more fail schema validation, and 5 more fail application checks. How many are accepted, and what is the acceptance rate over all candidates?

    Keep disjoint failure counts

    50 − 5 − 10 − 5 = 30 are accepted, giving 30 ÷ 50 = 60%. This assumes the categories are counted by first failure, as in the worked funnel. It does not prove that the accepted records have no undetected errors.

  3. A schema requires a field called note with string type. Does that rule alone reject an empty string?

    Separate presence from content

    No. An empty string is present and has string type. Add a nonempty-length constraint if that is intended. Required presence, permitted type, and content limits are distinct rules.

Northwind decision log

Validate structure at the application boundary.
Check business rules after parsing.
Route invalid output to a bounded recovery path.

Go deeper: contracts, integrity, and guided generation

The database lecture teaches constraint reasoning in a different setting; it is not a JSON Schema specification.

Check the mechanism in this lesson

A grammar-constrained object cites a nonexistent document ID. Is the result valid for Northwind's workflow?

Compare the explanation

It may be structurally valid but fails semantic acceptance. Check identifier existence, source eligibility and requested authority against application state. A parser cannot make the cited document exist.

Carry the decision forward

Northwind can now name separate representation, generation and acceptance boundaries. Page 10 joins them in one bounded triage exercise: find the first failed boundary before adding more infrastructure.