Make AI Features Safer with Contract-Based Output Validation

Make AI Features Safer with Contract-Based Output Validation

AI output can look correct and still break the software around it. This guide shows how to validate model responses before your application uses them.

Why AI output needs contracts

Traditional APIs promise a known structure. AI models generate text from probabilities. They can omit fields, rename keys, or return the wrong data type.

A data contract defines what the application accepts. JSON Schema is a declarative language for defining JSON structure and constraints. A validator checks whether JSON data follows that schema.

Place this contract between the model and your business logic. Do not let a response update a database, call a tool, or trigger a workflow first.

Design the smallest useful schema

Start with the fields that downstream code truly needs. Make critical fields required. Use clear types and narrow allowed values.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "decision": {
      "type": "string",
      "enum": ["approve", "review", "reject"]
    },
    "reason": {
      "type": "string",
      "minLength": 1
    },
    "confidence": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    }
  },
  "required": ["decision", "reason", "confidence"],
  "additionalProperties": false
}

This example describes a review decision. The enum limits decision names to three values. The numeric limits keep confidence between zero and one.

Keep the schema smaller than the prompt. Every extra field creates another failure case. Put explanatory text in descriptions. Put enforceable rules in validation keywords.

JSON Schema separates annotations from validation keywords. Descriptions explain intent. Keywords such as type and required define constraints.

Validate before side effects

Once the schema exists, validate every response before your application acts on it. Parse the response first. Then validate the parsed object.

raw = model.generate(request)
data = parse_json(raw)

if not validate(data, decision_schema):
    record_failure(raw)
    return manual_review()

return apply_decision(data)

The validator should reject missing fields, wrong types, unknown keys, and invalid values. It should also record the failure reason.

Do not silently repair important fields. Guessing a missing decision can create a business error. A safe failure path can send the item to review, retry with a bounded policy, or return a clear error.

Keep raw model output separate from trusted application data. Restrict access to raw content when it may contain personal or confidential information.

Use provider controls carefully

Some model APIs support structured output. These features can constrain responses to a supplied schema. Google’s Gemini documentation says structured output can produce predictable, typed results. It also supports schemas through Pydantic and Zod.

Provider enforcement does not replace local validation. Gemini supports only a subset of JSON Schema. Its documentation says some constraints are ignored during generation.

For example, Gemini does not enforce minLength during constrained decoding. The documentation recommends validating such constraints in the client application.

Use the same versioned schema that your application expects. Record the provider, model, schema version, and validation result for each request.

Test contracts like code

Store schemas in source control. Review changes like API changes. A field rename can break clients even when the model output looks reasonable.

Build tests for valid outputs and common failures. Include missing fields, extra fields, wrong types, empty strings, extreme numbers, and malformed JSON.

Run the schema against real examples before deployment. Add difficult cases from production failures. Track validation failure rates by model version and prompt version.

Schema validation checks shape. It does not prove that the answer is true, safe, or relevant. Google recommends handling schema-compliant outputs that are still semantically incorrect.

This design treats the model as one unreliable component in a larger system. The schema creates a boundary. Validation protects the boundary. Monitoring shows when the boundary begins to fail.

References

Google. (n.d.). Structured outputs. Google AI for Developers. https://ai.google.dev/gemini-api/docs/structured-output

JSON Schema. (n.d.). Creating your first schema. https://json-schema.org/learn/getting-started-step-by-step

JSON Schema. (n.d.). What is JSON Schema? https://json-schema.org/overview/what-is-jsonschema