Script icon
Docker icon
If icon
SlackIncomingWebhook icon
Pause icon
Log icon
Return icon
Webhook icon

AI LLM Structured Output Drift & Pydantic Validation Gate

Validates LLM-generated JSON payloads against strict Pydantic schemas, repairs minor syntax drift, and pauses for human review before database ingestion.

Categories
AI

Orchestrates an automated quality assurance guardrail for generative AI applications by validating LLM-generated JSON responses against strict Pydantic schemas, automatically repairing common syntax drift, and halting pipelines with human-in-the-loop review before corrupted data enters downstream production databases.

How it works

  1. Payload Ingestion: Intercepts LLM JSON responses generated by OpenAI, Gemini, or Claude via webhook or upstream subflow tasks.
  2. Pydantic Schema Contract Validation: Validates field types, regex patterns, required keys, and allowed enum constraints inside an isolated Python Docker container.
  3. Automated Normalization: Automatically normalizes trivial discrepancies (such as enum aliases or Markdown backtick wrappers) without failing the execution.
  4. Quarantine & Human Review: If severe schema mutations occur (missing mandatory IDs or unparseable JSON), the flow dispatches a Slack alert and triggers an interactive Kestra Pause task.

Architecture diagram

flowchart TD
    A[inbound_llm_payload_webhook Trigger] --> B[validate_and_repair_schema Python Script]
    B --> C[check_validation_gate Flowable If]
    C -- Schema Invalid --> D[notify_slack_ai_drift Webhook]
    D --> E[pause_for_human_review Pause]
    C -- Schema Valid --> F[log_schema_validated Log]
    E --> G[export_validation_manifest Return]
    F --> G

Architecture components

  • Trigger (inbound_llm_payload_webhook): Enables AI microservices to submit raw LLM responses for immediate validation.
  • Inspection Task (validate_and_repair_schema): Uses Pydantic to validate schemas, catch missing keys, and sanitize valid payloads.
  • Evaluation Gate (check_validation_gate): Evaluates operational safety boundaries using deterministic boolean branching.
  • Human-in-the-Loop Review (pause_for_human_review): Quarantines broken payloads for up to 12 hours, giving data stewards time to review.
  • Manifest Return (export_validation_manifest): Emits clean, sanitized JSON ready for relational database loading.

Key capabilities

  • Deterministic AI Quality Gating: Replaces prompt-based guesswork with strict Pydantic Python type validation.
  • Automated Syntax Normalization: Automatically strips Markdown codeblocks and repairs trivial enum alias mutations.
  • Zero-Downtime Data Quarantine: Prevents malformed LLM outputs from corrupting production PostgreSQL, BigQuery, or Snowflake tables.
  • Interactive Human Oversight: Native Kestra Pause task allowing engineers to review and resume quarantined payloads with one click.

What you get

  • 100% schema compliance guarantee for LLM-extracted data entering production pipelines.
  • Protection against silent non-deterministic AI mutations and hallucinated object keys.
  • Immediate Slack alerts detailing exact Pydantic validation error paths.
  • Sanitized, type-checked JSON payloads ready for downstream relational inserts.

Who it's for

  • AI Engineers building production RAG, document extraction, and autonomous agent workflows.
  • Data Platform Teams ingesting unstructured text processed by foundational models.
  • MLOps Practitioners establishing automated CI/CD guardrails for LLM application outputs.

Why orchestrate this with Kestra

  • Native Container Isolation: Executes Pydantic validation suites in sandboxed Python containers without external dependencies.
  • Built-in Human-in-the-Loop: Leverage native Kestra Pause and Resume states without writing custom database review queues.
  • Decoupled Secret Management: Securely handles webhook authentication keys and Slack webhooks through encrypted Kestra secrets.
  • Auditability: Complete historical record of all validated and quarantined LLM outputs stored in execution history.

Use cases

  • Invoice & Receipt Information Extraction: Validate vendor names, line items, and totals before ERP system ingestion.
  • Customer Support Ticket Auto-Categorization: Ensure LLM ticket classifications adhere strictly to allowed routing enum values.
  • Regulatory Compliance Document Parsing: Verify that all required legal clause fields are present in extracted contracts.

Inputs

Name Type Default Description
llm_output_payload STRING (Sample invoice JSON) Raw JSON string or markdown block returned by the LLM agent.
target_schema_model SELECT InvoiceExtraction Target Pydantic schema contract to enforce.
auto_repair_with_llm BOOL True Attempt automated normalization of trivial schema discrepancies.
alert_on_drift BOOL True Toggle whether Slack webhook alerts are dispatched upon validation failure.

Expected outputs

  • {{ outputs.validate_and_repair_schema.vars.is_valid }}: Boolean flag indicating whether the payload conforms to the schema.
  • {{ outputs.validate_and_repair_schema.vars.was_repaired }}: Boolean flag indicating whether automated normalization was applied.
  • {{ outputs.validate_and_repair_schema.vars.validation_errors_count }}: Number of Pydantic validation constraint violations.
  • {{ outputs.validate_and_repair_schema.vars.error_summary }}: Text summary of the validation error path and failure reason.
  • {{ outputs.validate_and_repair_schema.vars.sanitized_payload }}: Fully validated, clean JSON string ready for downstream tasks.

Prerequisites

  • Docker daemon available to Kestra workers for container execution.
  • Slack Incoming Webhook URL configured in Kestra secrets under SLACK_WEBHOOK_URL.
  • Webhook authentication key configured under AI_GATE_WEBHOOK_KEY.

Secrets

  • SLACK_WEBHOOK_URL: Slack Incoming Webhook endpoint for team alerts.
  • AI_GATE_WEBHOOK_KEY: Secret authentication key for the inbound webhook trigger.

Quick start

  1. Register SLACK_WEBHOOK_URL in your Kestra namespace secrets.
  2. Import this blueprint into the company.ai namespace.
  3. Run a manual execution with the default input to observe automated enum normalization (US_DOLLAR -> USD).
  4. Connect the inbound webhook URL to your upstream LangChain, LlamaIndex, or agentic workflow output pipeline.

Common pitfalls and troubleshooting

  • Markdown Codeblocks: LLMs often wrap JSON in json ... ; ensure parsing scripts strip backticks before loading.
  • Null vs Missing Fields: In Pydantic v2, explicitly mark optional fields as Optional[T] = None to avoid false-positive validation errors.
  • Float vs Decimal Precision: For financial data, consider using Python Decimal to avoid floating-point rounding discrepancies.

How to extend

  • Database Insert Task: Add an io.kestra.plugin.jdbc.postgresql.Queries task to automatically insert the sanitized JSON into production tables upon validation clearance.
  • Corrective LLM Re-Prompting: Add a subflow task that sends the Pydantic error trace back to the LLM with instructions to regenerate only the failing fields.
  • Schema Registry Integration: Dynamically pull JSON Schema definitions from Confluent Schema Registry or AWS Glue.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.