Build a strict Python validation boundary for AI outputs, with JSON Schema, authorization checks, rejection tests, bounded repairs and delivery recovery.
Build a strict Python validation boundary for AI outputs, with JSON Schema, authorization checks, rejection tests, bounded repairs and delivery recovery.
A model can return valid JSON that is unsafe to execute. The object might name the wrong account, include an invented source or request an action outside the user’s permissions. Reliable automation needs several boundaries: strict parsing, schema validation, application checks and a separate decision about whether an external action is authorized.
This advanced guide implements those boundaries for a fictional support assistant. You will build a local Python validator for proposed replies, test rejected inputs and design the recovery path around failures. The example creates no external messages and assumes basic familiarity with Python functions and JSON objects.
Treat the model’s response as a proposal to your application. It can suggest a draft or an escalation, but it does not get to decide which tickets the user may access. That permission comes from authenticated application state, outside the generated object.
The same separation applies to evidence. A model can return document IDs, but your system must check those IDs against sources it actually retrieved and was allowed to read. A correctly formatted citation is not proof that a document exists or supports the proposed sentence.
Our guide to agent evaluation explains why the final outcome matters more than a convincing trace. Here, validation is one layer in that outcome: it can reject malformed proposals without establishing that every accepted reply is factually correct or appropriate to send.
Keep the execution interface smaller than the model’s vocabulary. This assistant can propose a reply or escalate; it cannot invent a new action such as closing an account. Narrow interfaces make both testing and review more manageable.
Use a versioned schema that defines required fields, permitted values and size limits. The object reference explains that listing properties does not automatically make them required or reject additional keys. Those decisions need explicit keywords.
Our example requires a schema version, ticket ID, action, reply text and evidence IDs. It rejects unexpected properties, restricts actions to two values and caps reply length and the number of source IDs. A conditional rule requires nonempty reply text when the action is draft_reply.
Keep the schema aligned with application behavior. If escalation is supposed to produce an internal handoff rather than a customer message, the application should reject reply text attached to that action. Do not let downstream code guess which fields to honor when they conflict.
The JSON Schema dialect is also part of the contract. This guide uses Draft 2020-12 and the corresponding validator. Some model-provider structured-output interfaces support a restricted subset of schema features, so check that interface separately rather than assuming it enforces every rule shown here.
The Python reference documents behavior that matters at this boundary. The standard JSON decoder accepts some nonstandard numeric constants by default, and repeated object keys can overwrite earlier values. A later schema check cannot recover a duplicate key the parser has already discarded.
Reject duplicate keys while parsing, and reject nonstandard constants such as NaN. Limit the response size before decoding to prevent obviously oversized input from consuming unnecessary resources. These checks are especially important when the output will enter an unattended workflow.
A byte limit is not a complete resource-control strategy. Very deeply nested input can still cause parsing failures, and production workers need time and memory limits appropriate to their environment. Catch parsing exceptions, validation errors and resource failures at the job boundary, then record a controlled failure without taking the proposed action.
This schema has no arbitrary numeric fields. If you add numbers later, consider finite-value checks, exact currency representation and numeric bounds separately. Valid JSON and the right numeric type do not establish that an amount or quantity is sensible for the task.
Create a clean environment and install the pinned library used for this example. The validator documentation describes schema checks and instance validation. The code below uses jsonschema 4.26.0; a different version should be tested before it replaces the pinned dependency in an operational workflow.
python3 -m venv .venv
.venv/bin/python -m pip install jsonschema==4.26.0
.venv/bin/python validate_proposal.py
The commands use macOS or Linux paths. On Windows, use the Python executable under .venv\Scripts instead. Save the following complete program as validate_proposal.py before running the final command.
import json
from jsonschema import Draft202012Validator
SCHEMA = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"additionalProperties": False,
"required": ["schema_version", "ticket_id", "action", "reply", "evidence_ids"],
"properties": {
"schema_version": {"type": "integer", "const": 1},
"ticket_id": {"type": "string", "pattern": "^T-[0-9]{3}$"},
"action": {"enum": ["draft_reply", "escalate"]},
"reply": {"type": "string", "maxLength": 1000},
"evidence_ids": {
"type": "array", "maxItems": 5, "uniqueItems": True,
"items": {"type": "string", "pattern": "^D-[0-9]{2}$"}
}
},
"if": {"properties": {"action": {"const": "draft_reply"}}},
"then": {"properties": {"reply": {"minLength": 1}}}
}
Draft202012Validator.check_schema(SCHEMA)
VALIDATOR = Draft202012Validator(SCHEMA)
def reject_constant(value):
raise ValueError("Nonstandard JSON constant: " + value)
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate JSON key: " + key)
result[key] = value
return result
def validate_proposal(raw, allowed_ticket_ids, allowed_evidence_ids):
if len(raw.encode("utf-8")) > 16384:
raise ValueError("Response exceeds the byte limit")
proposal = json.loads(raw, parse_constant=reject_constant,
object_pairs_hook=unique_object)
VALIDATOR.validate(proposal)
if proposal["ticket_id"] not in allowed_ticket_ids:
raise ValueError("Ticket is outside the authorized task")
if not set(proposal["evidence_ids"]) <= allowed_evidence_ids:
raise ValueError("Evidence is outside the authorized source set")
if proposal["action"] == "draft_reply":
if not proposal["reply"].strip() or not proposal["evidence_ids"]:
raise ValueError("Draft needs nonblank text and evidence")
elif proposal["reply"]:
raise ValueError("Escalation must not include a customer reply")
return proposal
if __name__ == "__main__":
raw = json.dumps({"schema_version": 1, "ticket_id": "T-101",
"action": "draft_reply", "reply": "Please use the reset page.",
"evidence_ids": ["D-01"]})
proposal = validate_proposal(raw, {"T-101"}, {"D-01"})
print("Validated proposal for review:", proposal["ticket_id"])
print("No message has been sent.")
Running it prints that T-101 has a validated proposal for review and that no message has been sent. The allowed ticket and evidence sets are arguments supplied by trusted application code. They must not be copied from a second field generated by the model.
The schema is checked once and the validator reused for each response. This catches errors in the contract independently of errors in individual model outputs. In a larger application, keep the schema under version control and test changes against stored examples before deployment.
Parsing establishes that the response can be interpreted as a JSON value under the chosen rules. Schema validation establishes that the resulting object has the expected structure. Business checks establish that the identifiers and action combinations fit this particular authorized task.
None of those checks proves the sentence about a reset page is correct. The application still needs to verify the evidence and have an appropriate review or quality-control policy. A source ID can be valid while the reply misstates what the source says.
The pattern constraints are deliberately narrow for a tutorial. Real applications should use their actual identifier format rather than squeezing production IDs into a three-digit example. Avoid treating a predictable ID format as an access control; authorization still depends on the trusted sets or an equivalent permission lookup.
Do not rely on format keywords without understanding the validator configuration. Some formats require a checker or additional dependencies, and format validation can differ from business validation. The example avoids that ambiguity by using explicit patterns and application checks for its limited identifiers.
A useful test set includes a valid draft, a valid escalation and malformed proposals that exercise every boundary. Test duplicate keys, additional properties, missing fields, wrong types, blank replies, repeated source IDs and oversized input. Also test a structurally valid but unauthorized ticket.
Include semantic traps. A proposal citing D-99 should fail when the permitted source set contains only D-01. An escalation carrying customer-facing reply text should also fail, even though its individual fields might otherwise satisfy the schema.
Make the expected result explicit for every fixture. The test should assert rejection, not merely print an exception that a person might overlook. Run the same fixtures when changing prompts, schemas, parsing libraries or model versions.
Keep a separate set of factual-quality examples for accepted outputs. Structural rejection tests and evidence checks answer different questions. Our code review guide covers how runnable tests and independent review complement each other when AI helps build the surrounding application.
If an output fails validation, classify the failure before deciding whether to retry. A transient provider error, truncated response and missing required field are different problems. A refusal should also be handled as its own response type rather than being repeatedly pushed through a schema-repair loop.
For a repairable formatting error, allow a small fixed number of attempts with a concise explanation of the failed constraint. Preserve the original output, error category and attempt number in an appropriately protected trace. Redact sensitive details from logs and avoid exposing internal permissions in repair instructions.
Do not ask the model to invent evidence IDs simply to satisfy the schema. If supporting material is missing, retrieve it through the authorized workflow or escalate. A validator should expose insufficient evidence, rather than encourage a more elaborate fabricated object.
After the attempt limit, stop the job or send it to review. Repeated retries cost money, increase latency and can produce an apparently valid answer that has drifted away from the original task. Track repair success separately from first-pass success.
Once a person or trusted policy authorizes a message, the application still has to deliver it reliably. Derive a stable operation ID from application state, associate it with the approved payload and store its status. Do not ask the model to invent a fresh idempotency key on every retry.
A database uniqueness constraint can prevent two local workers from reserving the same operation. The SQLite transaction documentation is useful background on the local commit boundary. That local reservation alone does not guarantee exactly-once behavior in an external messaging service.
Consider a timeout after the remote service accepted the message but before your worker saved the receipt. The outcome is uncertain, not necessarily failed. Reconcile using the service’s receipt lookup or supported idempotency mechanism before attempting another send; otherwise, a recovery loop can deliver duplicates.
An outbox can coordinate local state and pending work, but the dispatcher still needs a delivery policy for uncertain remote outcomes. Record pending, confirmed and uncertain states distinctly, retain the approved payload and require review when reconciliation cannot establish what happened.
Treat a schema change as an application change. Adding a required field, changing an enum or tightening a limit can break existing jobs. Version stored payloads and keep a deliberate compatibility or migration policy for queued proposals created under an older contract.
Monitor validation failures by category, unauthorized identifier attempts, repair counts and delivery reconciliation failures. Pair those operational measures with factual correctness and reviewer effort. A perfect schema pass rate can still accompany poor customer answers.
Our guide to reliable automations explains how checkpoints and recovery fit the broader workflow. A useful deployment preserves the distinction throughout: the model proposes, validation checks the contract, trusted code enforces permissions and the delivery system records what actually happened.
Disclaimer: AIstify is an independent media brand owned and operated by NuvexMedia LLC, publishing news, research, and insights on artificial intelligence, emerging technologies, automation, and related industries. NuvexMedia LLC invests in and collaborates with companies across the AI, technology, software, and digital innovation sectors. These relationships do not influence AIstify’s editorial coverage, and the publication maintains full editorial independence to provide accurate, timely, and objective information. © 2026 NuvexMedia LLC. All rights reserved. This content is for informational purposes only and should not be considered legal, tax, investment, financial, or other professional advice.
NSA urges faster encryption upgrades after AI discoveries, while a joint government assessment finds no immediate, widespread threat to current cryptography.