"Not a Pentest" Notice: This guide is for securing your own LLM output pipelines. No attack tools.
LLM Output Schema Validation: Securing Structured Outputs 2026
LLM outputs are untrusted input for all downstream systems. Without schema validation, prompt-injected outputs can corrupt databases, abuse APIs, or leak PII.
1
Define JSON Schema for LLM Outputs
Define a strict schema for every LLM output type. Reject anything that doesn't conform — never pass unvalidated output downstream.
# JSON Schema for agent decision output
{
"type": "object",
"required": ["action", "confidence", "reasoning"],
"additionalProperties": false,
"properties": {
"action": { "type": "string", "enum": ["approve","reject","escalate"] },
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
"reasoning": { "type": "string", "maxLength": 500 }
}
}2
Moltbot Output Validation Pipeline
Every LLM output passes through schema validation, PII scanning, and content policy checks before reaching downstream systems.
# Moltbot output pipeline config
output_pipeline:
stages:
- name: schema_validation
schema_file: "schemas/agent-decision.json"
on_failure: reject_with_fallback
- name: pii_scan
patterns: [email, phone, credit_card, iban]
on_detection: redact
- name: content_policy
rules: [no_system_prompt_leak, no_credentials]
on_violation: reject_and_log
fallback:
action: "escalate"
confidence: 0
reasoning: "Validation failed — human review required"3
Pydantic Type Safety (Python Agents)
Use Pydantic BaseModel for type-safe LLM output parsing with automatic validation and safe fallbacks.
from pydantic import BaseModel, Field, validator
from typing import Literal
class AgentDecision(BaseModel):
action: Literal["approve", "reject", "escalate"]
confidence: float = Field(ge=0, le=1)
reasoning: str = Field(max_length=500)
def parse_output(raw: str) -> AgentDecision:
try:
return AgentDecision.model_validate_json(raw)
except Exception as e:
log_validation_error(e, raw)
return AgentDecision(
action="escalate", confidence=0.0,
reasoning="Validation failed — human review required"
)4
PII Detection & Redaction
LLMs can accidentally include PII from context. Automatic detection and redaction before output reaches any downstream system.
# Moltbot PII scanner
pii_scanner:
enabled: true
mode: redact
detectors:
- type: regex
name: email
pattern: '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+'
replacement: "[EMAIL REDACTED]"
- type: ml_model
name: presidio
entities: [PERSON, IBAN, CREDIT_CARD]
confidence_threshold: 0.8
action: redact
audit:
log_all_detections: true
alert_on: [CREDIT_CARD, IBAN]Frequently Asked Questions
Why is LLM output schema validation a security control, not just quality control?
Schema validation is a security control because: 1) Prompt injection containment — even if an attacker injects instructions, a strict output schema limits what the agent can return. 2) Data exfiltration prevention — schema validation blocks LLMs from including sensitive data in responses. 3) Downstream injection prevention — LLM outputs reaching databases or APIs can carry injected payloads; schema validation sanitizes them. 4) Agentic loop safety — in multi-agent systems, one agent's output is another's input. Schema validation prevents malicious content from propagating through agent chains.
How do I handle LLM outputs that fail schema validation?
1) Never pass failed outputs downstream — always substitute a safe fallback (e.g., action=escalate, confidence=0). 2) Retry once with an explicit formatting instruction if the failure looks like a formatting error. 3) Log everything — raw output (without PII), the validation error, and the action taken. 4) Alert on patterns — a spike in validation failures could indicate a prompt injection campaign. Set alerts on failure rates >2%. 5) Human escalation — for high-stakes decisions, route validation failures to a human reviewer.
What is the difference between output filtering and schema validation?
Output filtering removes unwanted content (keyword blocking, PII redaction). Schema validation enforces structure (output must match a defined type and shape). Both are needed: schema validation rejects malformed outputs; content filtering catches injected content within valid-schema responses. Use both in sequence: validate schema first, then filter content on the validated fields.
Further Resources
Validate LLM outputs automatically?
Moltbot enforces schema validation and PII redaction for all LLM outputs — configurable, auditable.
🛡️ Free Security Check