Skip to lesson

NVIDIANVIDIA-Certified Professional: Agentic AI2026-102.1 Engineer prompts and dynamic prompt chains for reliable performance.

Enforce answer schemas and bound their repair

Completed by the knowledge check

Learning objective

Enforce structured outputs with JSON schemas and validate or repair responses.

Core idea

Structured output turns an answer into data that software can inspect. Asking for JSON, generating data constrained by a schema, and accepting a validated business result are different steps. A syntactically valid object can omit a required value, contain an unsupported decision, or refer to a source that does not exist.

Choose a generation mechanism that the model and integration support, then validate the returned object before accepting it. Repair is another generation attempt after a classified failure; it consumes time and can change meaning. The goal is a usable result, not an unlimited conversation with a parser. See 1.6.1 for validation between workflow stages; this lesson focuses on the model’s answer interface.

How it works

Specify the answer precisely

Recall from 0.6 that properties, required, and additionalProperties define different parts of the answer shape; here you use that shape to validate and repair generated results.

For an application-defined classification result, a compact schema can make the supported outcomes explicit:

{
  "title": "CaseDisposition",
  "description": "A proposed case disposition for application validation.",
  "type": "object",
  "properties": {
    "decision": { "enum": ["accept", "review"] },
    "source_id": { "type": "string" }
  },
  "required": ["decision", "source_id"],
  "additionalProperties": false
}

title and description also meet LangChain’s documented requirement for JSON Schema dictionaries used in its structured-output strategies. The schema rejects an absent source_id or an extra approved_by field. It does not establish that a supplied source supports acceptance.

Keep structural and business validation separate. After schema validation, resolve source_id against the records supplied to this request and check whether the source supports decision. An empty or fabricated source identifier must not become acceptable merely because it has type string. Give uncertain cases an explicit supported outcome instead of forcing the model to invent a complete record.

Choose the enforcement path

Recall from 0.6 the serving-side path: NIM LLM deployments expose vLLM-backed POST /v1/chat/completions, and vLLM documents response_format with type: "json_schema". Check the running NIM container’s /docs for its accepted request schema and parameters before using that path. NVIDIA directs full parameter checks to that explorer or the vLLM API documentation.

In LangChain’s Python create_agent, response_format selects the structured-answer strategy. ProviderStrategy uses provider-native structured output; ToolStrategy represents the answer through tool calling. The agent returns its structured result in the structured_response state key. These are LangChain APIs, not NeMo Agent Toolkit YAML keys.

A JSON Schema dictionary must be wrapped in an explicit ProviderStrategy or ToolStrategy. When you pass a schema type directly, LangChain chooses ProviderStrategy if the selected model and provider support native structured output, and ToolStrategy otherwise. JSON Schema dictionaries do not receive that automatic selection.

Provider-native enforcement depends on the selected model and provider. The ProviderStrategy.strict parameter requires langchain>=1.2 and is supported by some providers; it is not a universal switch for every compatible endpoint. If you also supply tools, the model must support the combination of tools and structured output. Confirm the actual integration before choosing this path.

ToolStrategy requires tool-calling support. Its schema is the answer’s shape, not permission to execute a business action. A structured disposition proposal and an API that commits a disposition remain separate operations, even if both use a tool-shaped interface. This distinction prevents an extraction task from accidentally acquiring write authority.

Validate the returned representation

Validation, semantic checks, and the repair budget apply whichever supported path generated the object.

LangChain documents different return representations: Pydantic schemas return validated model instances, while JSON Schema dictionaries return dictionaries. Design the consumer for the representation you selected. Do not accept a raw text completion merely because another branch of the application expects structured_response.

NVIDIA NeMo Agent Toolkit functions provide Pydantic input and output schemas for runtime validation and conversion. You can put a LangChain-based structured-answer operation inside a registered custom function using FunctionInfo.from_fn(), then expose the accepted result through a typed function interface. Choose the function’s types to preserve the distinction between a validated result and a failure outcome.

Schema validation is only one layer. Check the business conditions after structural acceptance and before any write or user-visible commitment. A well-formed object with a contradicted disposition is a semantic failure. Repeating the schema validator cannot repair missing source information.

Repair the failure you actually have

LangChain’s ToolStrategy.handle_errors controls feedback for structured-output errors and defaults to True, which feeds errors back for another attempt. True catches errors with the default feedback; a string supplies fixed feedback; an exception type or tuple restricts which errors are handled; a callable constructs feedback; False lets errors propagate. The documented error classes include StructuredOutputValidationError for schema failures and MultipleStructuredOutputsError for multiple structured answers.

For a service that owns a strict repair budget, choose handle_errors=False and catch StructuredOutputValidationError or MultipleStructuredOutputsError in the surrounding application function. Permit, for example, one additional invocation with concise validation feedback and the original source material. Count it explicitly and reject another failure.

Do not repair by silently substituting business values. A missing identifier may require another lookup or a review outcome; guessing it changes the decision. Revalidate a repaired answer from the beginning, including source checks. An API timeout belongs to transport recovery, not schema repair, and a prohibited request must not be rewritten until it looks acceptable.

A schema failure gets one counted repair, and the repaired answer is revalidated from the beginning.

A schema failure gets one counted repair, and the repaired answer is revalidated from the beginningStarts at a generation attempt and goes to schema validation. A schema failure gets one additional invocation, which loops back to be revalidated from the beginning; another failure is rejected. After structural acceptance the business conditions are checked: a missing identifier leads to a review outcome rather than repair, and an answer whose source supports its decision becomes the accepted result.schema failureanother failurestructural acceptancemissing identifiersource supports decisiongeneration attemptschema validationone additionalinvocationrejectbusiness conditionsreview outcomeaccepted result

Key distinctions and trade-offs

Choose the mechanism by the failure you need to prevent:

ApproachDeciding conditionMechanismCost or limitation
Prompt-only formattingText output remains acceptableInstructions and examplesFormat compliance remains a model behavior
NIM serving-side schemaThe container supports the requested schema parameters/v1/chat/completions, response_format, /docsVerify the deployed backend’s accepted request
Native structured outputThe model and provider support itProviderStrategyProvider-specific schema and strictness support
Tool-shaped answerTool calling is supportedToolStrategyError feedback can trigger more inference
Consumer validationSoftware needs an accepted resultJSON Schema and typed function outputStructure cannot prove source truth
RepairA classified defect can be correctedError feedback and an explicit attempt budgetAdded latency and possible semantic drift

Architecture / decision scenario

An insurance analytics team classifies 5,000 claim summaries nightly. It permits no automatic claim payment; the output is an analyst worklist. In a 100-record trial, prompt-only JSON produces 12 malformed records. A tool-calling candidate produces three structural failures and nine valid objects with unsupported source identifiers.

A practitioner proposes repairing all 12 candidate failures by asking the model to fill missing data. The service owner chooses ToolStrategy for the tested tool-capable model, validates the schema, and resolves each source_id against that claim’s permitted records. The nine source failures go to analyst review. Only structural failures can use one repair invocation, with handle_errors=False exposing the exception to the budget owner.

The batch has a 30-minute deadline and an application allowance of at most two generation attempts per record. Repair cannot expand into an unbounded loop. The schema owner maintains the output shape; the claims owner defines source sufficiency. The tempting universal-repair policy loses because valid-looking invented identifiers would corrupt the worklist while hiding the real failure rate.

Common exam traps

  • Passing a JSON Schema dictionary directly to response_format and expecting automatic strategy selection.
  • Equating parseable JSON with a schema-valid and factually supported answer.
  • Treating strict or provider-native enforcement as universal.
  • Confusing an answer encoded as a tool call with an authorized external action.
  • Treating error feedback as a complete attempt or elapsed-time budget.

What to remember

Specify the shape, select a supported generation strategy, and validate the returned result. Then check the business meaning against permitted sources. Repair only eligible defects, within an explicit budget, and validate the repaired result as rigorously as the first attempt.

Knowledge check

References