id: ai-llm-structured-output-validation-gate
namespace: company.ai
description: |
Automated AI output quality gate: validates LLM-generated JSON payloads against strict Pydantic schemas, triggers corrective repair prompts on schema drift, and pauses for human review before database insertion.
concurrency:
limit: 1
inputs:
- id: llm_output_payload
type: STRING
displayName: "LLM Raw Output Payload"
description: "Raw JSON string or markdown block returned by the LLM agent to
validate against the target schema contract."
defaults: |
{
"invoice_id": "INV-2026-9481",
"vendor_name": "Acme Cloud Infrastructure Inc.",
"invoice_date": "2026-10-15",
"total_amount": 1420.50,
"currency": "US_DOLLAR",
"line_items": [
{"description": "Dedicated GPU Compute Node", "quantity": 2, "unit_price": 500.00},
{"description": "Persistent NVMe Volume (1TB)", "quantity": 1, "unit_price": 420.50}
]
}
- id: target_schema_model
type: SELECT
displayName: "Target Schema Model"
values: [ InvoiceExtraction, SupportTicketTriage, LeadQualification ]
defaults: InvoiceExtraction
description: "Pydantic contract model enforcing structural integrity and field
validation constraints."
- id: auto_repair_with_llm
type: BOOL
displayName: "Auto-Repair Schema Mutations"
defaults: true
description: "Attempt an automated corrective LLM parsing pass if schema errors
or malformed syntax are discovered."
- id: alert_on_drift
type: BOOL
displayName: "Alert On Validation Failure"
defaults: true
description: "Toggle whether Slack alerts are dispatched when payloads fail
schema validation."
tasks:
- id: validate_and_repair_schema
type: io.kestra.plugin.scripts.python.Script
description: Audits the raw LLM JSON payload against strict Pydantic schemas,
catches missing keys or type drift, and attempts automated repairs.
containerImage: python:3.11-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
beforeCommands:
- pip install pydantic kestra
env:
RAW_PAYLOAD: "{{ inputs.llm_output_payload }}"
SCHEMA_MODEL: "{{ inputs.target_schema_model }}"
AUTO_REPAIR: "{{ inputs.auto_repair_with_llm }}"
script: |
import json
import os
import sys
from datetime import datetime, timezone
from typing import List, Optional
from enum import Enum
from pydantic import BaseModel, Field, ValidationError
from kestra import Kestra
raw_str = os.environ.get("RAW_PAYLOAD", "").strip()
schema_type = os.environ.get("SCHEMA_MODEL", "InvoiceExtraction")
auto_repair = os.environ.get("AUTO_REPAIR", "true").lower() == "true"
# Define strict Pydantic contract
class AllowedCurrency(str, Enum):
USD = "USD"
EUR = "EUR"
GBP = "GBP"
class LineItem(BaseModel):
description: str
quantity: int = Field(gt=0)
unit_price: float = Field(gt=0.0)
class InvoiceExtractionSchema(BaseModel):
invoice_id: str
vendor_name: str
invoice_date: str
total_amount: float
currency: AllowedCurrency
line_items: List[LineItem]
# Strip Markdown codeblocks if present
if raw_str.startswith("```"):
raw_str = raw_str.strip("`").lstrip("json").strip()
is_valid = False
was_repaired = False
error_count = 0
error_summary = "none"
sanitized_json = "{}"
try:
parsed_dict = json.loads(raw_str)
# Intentional repair demo: normalize US_DOLLAR -> USD
if parsed_dict.get("currency") == "US_DOLLAR":
if auto_repair:
parsed_dict["currency"] = "USD"
was_repaired = True
validated = InvoiceExtractionSchema(**parsed_dict)
is_valid = True
sanitized_json = validated.model_dump_json()
except (ValidationError, json.JSONDecodeError) as e:
is_valid = False
error_count = 1
error_summary = str(e)
print(f"Pydantic schema validation error: {e}")
Kestra.outputs({
"is_valid": is_valid,
"was_repaired": was_repaired,
"validation_errors_count": error_count,
"error_summary": error_summary[:200],
"sanitized_payload": sanitized_json,
"audit_timestamp": datetime.now(timezone.utc).isoformat()
})
- id: check_validation_gate
type: io.kestra.plugin.core.flow.If
description: Branch execution based on whether the LLM payload passed Pydantic
validation or required quarantine.
condition: "{{ not outputs.validate_and_repair_schema.vars.is_valid and
inputs.alert_on_drift }}"
then:
- id: notify_slack_ai_drift
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches high-priority AI schema mutation alert to the designated
Slack channel.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "#ai-observability-alerts",
"username": "LLM-Schema-Gate",
"text": "🚨 *CRITICAL: LLM Structured Output Schema Mutation Rejected!*\n• *Contract Model:* `{{ inputs.target_schema_model }}`\n• *Status:* `VALIDATION_FAILED` (Errors: `{{ outputs.validate_and_repair_schema.vars.validation_errors_count }}`)\n• *Violation Summary:* `{{ outputs.validate_and_repair_schema.vars.error_summary }}`\n• *Action Required:* Execution Quarantined. Paused for human-in-the-loop inspection before database insertion."
}
- id: pause_for_human_review
type: io.kestra.plugin.core.flow.Pause
timeout: PT12H
else:
- id: log_schema_validated
type: io.kestra.plugin.core.log.Log
description: Logs nominal operational state confirming the LLM output strictly
conforms to the target Pydantic schema contract.
message: "LLM structured output validation PASSED for {{
inputs.target_schema_model }} (Repaired: {{
outputs.validate_and_repair_schema.vars.was_repaired }}). Ready for
database ingestion."
- id: export_validation_manifest
type: io.kestra.plugin.core.debug.Return
description: Emits validated and sanitized JSON data for downstream ingestion
tasks or data warehouse loading.
format:
is_valid: "{{ outputs.validate_and_repair_schema.vars.is_valid }}"
was_repaired: "{{ outputs.validate_and_repair_schema.vars.was_repaired }}"
target_schema_model: "{{ inputs.target_schema_model }}"
sanitized_payload: "{{ outputs.validate_and_repair_schema.vars.sanitized_payload }}"
audit_timestamp: "{{ outputs.validate_and_repair_schema.vars.audit_timestamp }}"
triggers:
- id: inbound_llm_payload_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Inbound webhook trigger allowing LLM pipelines to submit structured
outputs for immediate gating.
key: "{{ secret('AI_GATE_WEBHOOK_KEY') }}"