Structured AI responses: validation before changing data

Three sequential checks separate readable JSON, a valid structure, and agreement with a specific context. The result remains a candidate for review.

Form, structure and agreement with the source need separate checks.
Form, structure and agreement with the source need separate checks.

A model response can look ready to save: a title, short summary, category, and several facts are already assembled into JSON. The program successfully reads that text, and immediately updating the card becomes tempting. Yet a readable document and an acceptable change raise different questions. Are there conflicting keys? Are all required fields present? Does the response refer to the exact source revision requested?

This boundary needs a sequence of checks with visible rejection reasons. We will use an independent exercise for Python 3.10+ with jsonschema 4.26.0. Its responses are handwritten synthetic fixtures; the exercise uses no model, external provider, or CMS. This lets us examine the receiving code without presenting prepared examples as evidence of actual generation quality.

Three levels answer different questions

Imagine a card for a training workshop. The trusted local context specifies 12 places, a duration of 90 minutes, and mandatory reservations. The candidate must return these structured facts, a title, a summary, a locale, and a reference to the source. Its category, tags, and related records must come from an allowed set.

LevelWhat it checksExample rejection
JSON readingUnambiguous decoding within explicit limitsA duplicate key or invalid UTF-8
JSON SchemaFields, types, constraints, and a closed structureMissing summary or an added publish_now
Domain contextAgreement with the specific taskCorrect structure, but 120 places instead of 12

After rejection, the next level does not run. This makes the outcome understandable: a syntax error does not turn into a missing-category message. Passing every level produces a candidate for review. This example has no function that writes to a CMS.

Start with bytes, before fields

The local reader accepts at most 8192 bytes and decodes only UTF-8. The limit concerns bytes: Ukrainian text can exceed it sooner than ASCII text with the same number of characters. File reading is bounded in advance; one additional byte is enough to detect an oversized input.

Python's standard module supports custom handling of key pairs and numeric constants; by default, it accepts repeated names and non-number values such as NaN. The json documentation describes this behavior. In the exercise, a repeated key causes rejection at any depth:

def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    result: dict[str, Any] = {}
    for key, value in pairs:
        if key in result:
            raise InputRejected("duplicate_key")
        result[key] = value
    return result

Separate checks reject infinite numbers, overflow during numeric conversion, invalid encoding, and unpaired Unicode surrogates. Containers are limited to 16 nesting levels, and numeric representations to 64 characters. Brackets inside strings do not count as nesting. These are explicit policies for a small exercise, not evidence that a network service can withstand every form of resource exhaustion.

The numeric fields in this schema must be integers. A decimal representation is accepted only if conversion to float loses no precision: 7.0 remains allowed, while 12.0000000000000001 cannot silently become 12. Comparing values constructed from text and float uses the Decimal interface. A mismatch or an inability to make this exact comparison causes number_precision_loss rejection. This is a limited numeric policy for the exercise; it is not intended to accept arbitrary decimal measurements.

Nothing is silently repaired. Removing an extra comma or choosing the last duplicate field would change the input before validation. When a repair is needed, it should produce a new candidate that passes through the same gates again.

The schema closes the response structure

The root object contains source_id, source_revision, locale, title, summary, category, tags, related_ids, and facts. The nested facts object is also closed. An unknown publish_now field is rejected; it cannot silently attach an action to an ordinary description.

In JSON Schema, fields listed in properties do not automatically become mandatory: required is needed. additionalProperties: false disallows unknown properties. The JSON Schema object reference explains these rules. Each nested object needs its own boundary.

The exercise's schema also specifies text lengths, fact types, array limits, and unique array elements. The string “7” cannot replace a numeric revision, and true cannot become a seat count. In the validation specification, integer means a number without a fractional part; this exercise does not need a lexical rule forbidding a decimal point in its written representation.

Draft202012Validator is selected explicitly. First, check_schema checks the schema itself; then iter_errors collects candidate violations, following the jsonschema API. The documents are local and contain no references to other schemas. No schema is downloaded from an address that the response might supply.

Correct structure does not yet match the task

The value 120 is an integer within the allowed capacity range. A candidate with that many places therefore passes the schema. The error becomes visible only when compared with the independent context, which specifies 12. Similarly, the presence of a locale field does not establish that the requested language was returned.

The context lives in a separate file selected by the program carrying out the task. The candidate cannot supply its own list of correct answers. Checks cover source identity, source revision, requested locale, allowed categories, tags, and related identifiers. A reference to the source itself is outside the allowed set. Three facts are compared without paraphrasing:

    for field, expected in trusted["facts"].items():
        if candidate["facts"][field] != expected:
            errors.append(reason("context.fact", "/facts/" + field))
    return errors

These criteria apply to this fictional card. The word trusted in a fixture's name does not authenticate a real document's origin. An application would need a separate basis for trusting its context: who supplied it, which task it belongs to, and whether the revision remains current.

Changing the expected revision from 7 to 8 should reject the previous candidate even if all its facts stay the same. The revision check protects the connection to the selected input. It neither creates a transaction nor prevents the source from changing after validation.

Some domain conditions can also be expressed through const or enum in a schema. This exercise separates them to clarify who owns the rules: the schema describes the shared card structure, while the context defines the current task. Changing the allowed related records does not change the response format itself. A valid schema still does not establish that a list placed inside it is correct.

An error in the trusted fixture also remains an error in the basis for validation. If it accidentally specifies 120 places, exact comparison will agree with that value. Checking a candidate and checking its source therefore address different questions. The teaching exercise demonstrates agreement with explicitly supplied facts, but does not establish the truth about a real workshop.

Free-form descriptions still need review

The most revealing control case contains correct facts and a false summary: it promises unlimited places, no reservation requirement, and a different duration. Within this validator's scope, the text remains an acceptable candidate for review. Its length is allowed, and there are no automatic criteria for the summary's meaning.

This case deliberately exposes the boundary. The result includes requires_human_review and explicitly identifies title and summary as fields whose content was not checked. Matching structured numbers to the source says nothing about the sentences beside them.

If a product needs an automatically accurate short description, it can build one from already checked fields using a fixed template. That is a different product requirement. Free paraphrasing needs its own criteria and assessment method; a successful schema check cannot replace that work. Even a correct description does not establish that the title is appropriate or publication is authorized.

A rejection reason should guide the next action

A rejected result contains the level, a reason code, and a path to the problematic part. A capacity error points to facts/capacity; a missing required field is reported at the schema level. The library exposes the path and the keyword of the violated rule, as described in the jsonschema error documentation. The example converts these into a small format of its own.

This result distinguishes a damaged document from an outdated revision. Automatically retrying generation after every error would be insufficient: outdated context first needs refreshing. A rejection includes no candidate to save, while an accepted result is explicitly labeled accepted_for_review.

The program does not truncate text, insert a category, or substitute the expected locale. Otherwise, success would become mixed with repairs performed by the receiver. If the next component prepares a change, it should show the concrete difference and preserve its connection to the checked candidate. The word accepted alone grants no authority to modify data.

What the local run checks

The final local run in Python 3.12.14 with jsonschema 4.26.0 confirmed all 48 predefined expectations, including the required rejections. Source files remained unchanged before and after the run. The exercise made no provider calls and wrote no CMS data.

The set includes malformed JSON, a missing field, a structurally correct but incorrect fact, and an acceptable card. It adds byte boundaries, duplicates, a mismatched locale, unrelated references, a changed trusted revision, and a description with unchecked content. Checks cover the expected level and reason, and the skipping of later levels, as well as rejection itself.

Each synthetic input has an independently recorded expectation: which level should stop it and which reason code is required. The runner does not derive the expected result from the validator's own response. Otherwise, incorrect behavior could confirm itself. Positive cases matter too: a different allowed combination of tags must remain acceptable, and brackets in a title must not break the nesting count.

The set deliberately includes a document exactly at the size limit. Rejecting every large input would not establish that the allowed boundary works correctly. These control examples make the rules observable, but their number does not measure the completeness of protection. A new kind of data or a new action will need corresponding scenarios.

The runner reads fixtures without changing them and creates a new report outside the example directory. An existing file, directory, or symbolic link at the target address causes refusal. The report records runtime versions and source checksums before and after execution; it documents one specific local run rather than assessing a model.

A future write needs a separate check that the data is still current, access rules, and a human decision about the text. Sequential gates give that action an explicit input: the candidate passed the named criteria, while unchecked properties remained visible.

  1. Knowledge & AI The prompt as a versioned artifact: preserving generation conditions
  2. Knowledge & AI A document tells the model to ignore the rules: testing the untrusted-context boundary
  3. Knowledge & AI Replacing an AI provider: capability compatibility matters more than the model name
  4. Knowledge & AI AI prepares the publication, a human decides: preserving the exact approved version

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article