AISchemaGate

Architecture

Why JSON Mode, Zod, and Pydantic Aren't Enough for Production Agent Loops

JSON mode and structured outputs make a model emit JSON that matches a schema. Zod, Pydantic, and Instructor turn that JSON into a typed value in one language. Production loops fail in the gap between "this parsed" and "this is a value our systems are allowed to act on."

The failures are loaded in the Live Playground. Each one is valid JSON.

Where each layer stops

ConcernStructured outputsZod, Pydantic, InstructorAISchemaGate
Well-formed JSONJSON mode promises an object. Strict mode promises the schema you sent.The parser accepts whatever that schema describes.Runs on the object the provider already returned.
min, max, pattern, enumEnforced only when that keyword is in the provider's subset for that model. Other providers reject the request or skip the keyword.Enforced in the process where you wrote the constraint.Enforced from one versioned YAML contract, in Python and TypeScript.
Enum casing and invented labelsCase-sensitive if the enum was in the schema. A plain string field accepts usd and Billing & Invoices.z.enum and Literal are case-sensitive. A bare str accepts the invented label.The violation names the field, the allowed set, and the actual value.
Undeclared tool-call keysadditionalProperties: false when the provider requires it. A loose tool schema keeps extra keys.Zod strips unknown keys by default. Pydantic ignores them unless extra is forbid. The call still succeeds.compliance_mode: true rejects undeclared fields and drops them before quarantine and forward.
Same rule in both languagesThe schema is whatever that request sent.A Zod schema and a Pydantic model are two sources of truth.One contract name. Both SDKs call the same engine.
PII before logs and databasesThe response is the raw model text.You mask it if that code path remembers to.mask, hash, drop, and redact run before the audit log, quarantine, and forward.
Failure you can re-promptA grammar miss is often a provider error, not a field path with expected and actual.A ZodError or ValidationError in that process. Instructor retries from that error.A violation list, appended as a user message. Default 2 retries, hard cap 5.
Audit and replayProvider logs.Whatever that service logged.Quarantine on the shared engine. Replay against a corrected contract version.

Value drift survives a type schema

strict: true certifies conformance to the schema in that request. Teams usually send types and required keys, because that subset is the one every provider accepts. Against that schema, total_amount: -49.99 is a number, currency: "usd" is a string, and confidence: 1.4 is a number. JSON mode (json_object) does not even promise those types.

Numeric minimum / maximum, regex pattern, and enum casing are where providers diverge. One model's grammar enforces the keyword. Another rejects the request because the pattern dialect is outside its subset. A third ignores the keyword and returns the bad value with a 200. The contract check is the same function on the parsed object either way.

Zod and Pydantic catch the drift when the constraint is in that schema. z.number() and a Pydantic float do not. The snippets below are the schemas that let the playground failures through.

Vercel AI SDK · type schema
import { generateText, Output } from 'ai';
import { z } from 'zod';

const { output } = await generateText({
  model: 'openai/gpt-4o-mini',
  prompt,
  output: Output.object({
    schema: z.object({
      invoice_id: z.string(),
      total_amount: z.number(),
      currency: z.string(),
      customer_email: z.string(),
    }),
  }),
});
// total_amount -49.99, currency "usd", and the raw email all validate.
Instructor · bare Pydantic model
import instructor
from pydantic import BaseModel

class Ticket(BaseModel):
    category: str
    confidence: float

client = instructor.from_provider("openai/gpt-4o-mini")
ticket = client.create(
    response_model=Ticket,
    messages=[{"role": "user", "content": prompt}],
    max_retries=2,
)
# "Billing & Invoices" and confidence 1.4 both parse.
The contract those objects fail
name: "extract_invoice_v1"
compliance_mode: false
ontology:
  entities:
    - name: total_amount
      type: number
      required: true
      min: 0
      max: 1000000
    - name: currency
      type: string
      required: true
      enum: ["USD", "EUR", "GBP"]
    - name: customer_email
      type: string
      required: true
      transform:
        kind: mask
        style: opaque

Open the invoice and ticket examples in the live playground to see the violation report.

Invoice drift · Ticket taxonomy

Python services and TypeScript agents drift apart

A Next.js route on Vercel and a Python worker can both be correct and still disagree. Someone adds GBP to the Zod enum on Friday. The Pydantic model in the worker still has two currencies on Monday. Instructor retries against the Python model only. Structured outputs enforce whichever schema that call attached.

AISchemaGate is one deployed contract. contract_id is the YAML name or the UUID. The Python package aischemagate and @nightmoose/aischemagate both call POST /egress/{contract_id}. Pin version when a route must stay on a known revision.

Tighten the local model too. That check is real. It is not the contract the other language will run, and it does not leave a quarantine row.

Pydantic, strict in this process
from typing import Literal
from pydantic import BaseModel, Field

class Ticket(BaseModel):
    category: Literal["billing_issue", "technical_bug", "account_access", "feature_request"]
    confidence: float = Field(ge=0, le=1)

# This process now rejects the drift. The TypeScript agent still has its own schema.
# A ValidationError here does not mask a field or write a quarantine row.
Python · same contract as the TypeScript agent
import os
from aischemagate import LLMGate

gate = LLMGate(
    api_key=os.environ["CONTRACTGATE_API_KEY"],
    contract_id="support_ticket_v1",
)
result = gate.validate_only(llm_json)
if result.ok:
    route_ticket(result.payload)
Vercel AI SDK · JSON in, contract check after
import { generateText, Output } from 'ai';
import { LLMGate } from '@nightmoose/aischemagate';

const gate = new LLMGate({
  apiKey: process.env.CONTRACTGATE_API_KEY!,
  contractId: 'extract_invoice_v1',
});
const { output } = await generateText({
  model: 'openai/gpt-4o-mini',
  prompt,
  output: Output.json(),
});
const result = await gate.validateOnly(output);
if (result.ok) storeInvoice(result.payload);

Output.json() parses JSON and does not apply a schema. validateOnly runs the contract on that object. Forward result.payload only when result.ok is true.

Undeclared keys on a tool call

A refund tool that declares order_id, amount, and reason can still receive debug_sql and internal_override. Strict structured outputs with additionalProperties: false block that on providers which honor it. The next agent in the loop often sends a looser tool schema, or a free-form object, and the extra keys return.

Default Zod strips unknown keys. Default Pydantic ignores them. The parse succeeds, the tool runs, and the injection never becomes a violation. If you strip the keys before the gate runs, the gate never sees them either. Pass the raw tool arguments.

compliance_mode: true treats every undeclared field as a violation, removes it from the payload that is quarantined or forwarded, and leaves the declared fields to the rest of the contract. The refund API is not called while the check is blocked.

Vercel AI SDK · raw tool arguments
import { LLMGate } from '@nightmoose/aischemagate';

const gate = new LLMGate({
  apiKey: process.env.CONTRACTGATE_API_KEY!,
  contractId: 'refund_tool_v1', // compliance_mode: true
});

async function issueRefund(rawArguments: string) {
  const checked = await gate.validateOnly(rawArguments);
  if (!checked.ok) return { error: checked.violations };
  return refund(checked.payload); // undeclared keys already dropped, email hashed
}
Python · LangGraph or any tool body
def issue_refund(raw_arguments: dict) -> dict:
    """LangGraph, CrewAI, or a plain tool. Check the raw arguments."""
    result = gate.validate_only(raw_arguments)
    if not result.ok:
        return {"error": result.violations}  # do not call the refund API
    return refund_api(result.payload)

Open the tool-call example

Mask the field before it hits a log

A customer email can be a perfectly valid string. JSON schema, Zod's email check, and Pydantic's EmailStr will accept it, and the address will land in the audit row, the application log, and the database you were about to insert.

Declare one transform per string field. mask with style: opaque stores ****. style: format_preserving keeps character classes. hash stores a deterministic hmac-sha256: digest keyed by a per-contract salt that never leaves the validator. drop removes the field. redact stores <REDACTED>. Validation sees the raw value, so pattern and enum still mean what you think. The transform runs after that, on both the pass path and the failure path. The raw value is not what gets written.

Quarantine, then a bounded repair prompt

A failed check returns one violation per field: the path, the rule, and the expected and actual values. The SDK formats that list into a repair hint and appends it as a new user message. The system message stays untouched. max_retries defaults to 2 and is hard-capped at 5. When the budget is exhausted, result.ok is false. The sanitized payload is still well formed. It is not safe to treat as authoritative.

The blocked object is quarantined as the transformed payload, not the raw model text. Replay runs that stored payload against a corrected contract version. AISchemaGate uses the DataContractGate engine for that log: same account, same API key, same dashboard.

Instructor's max_retries reasks from the Pydantic error in that process. The Vercel AI SDK raises NoObjectGeneratedError when its schema rejects the text. Neither of those records is the violation list the other language will send, and neither applies the contract's transforms before writing the row.

Output validation playbook · auto-repair, prompt masking, and provider quickstarts.

What a contract can promise

A pass means the object matched the rules the contract declares: types, ranges, patterns, enums, required fields, undeclared-field rejection, and the transforms on those fields. It does not mean the invoice is the one the customer sent, or that a refund is the right business action.

v1 checks a finished response. Buffer a stream yourself and pass the final object to validateOnly, or call the provider with streaming off. The caller owns the provider request. LLMGate inspects the response and runs the contract.

AISchemaGate is the model-output door. DataContractGate is the door for what your pipelines ingest. They share the engine, the tenant, and the quarantine log.

Run the three failures in the browser

Edit the YAML and the JSON, then read the violation report, the repair prompt, and the sanitized payload. When you want the same check on a real response, the SDK is the five lines under the playground.