---
name: self-correcting-schema-agent
description: An agent that retries JSON generation with schema violation feedback until the output validates — or a budget is exhausted.
title: Self-Correcting Schema Agent
category: agents-workflows
difficulty: advanced
author: admin
icon: 🧩
input: structured-data
output: structured-json
phase: post
domain: data
tags: json-validation,schema-compliance,self-correction,agent-loop,error-feedback,retry-logic,llm-output-validation,structured-generation,convergence-optimization,production-workflow
best_for:
  - API response generation with strict schema requirements
  - Structured data extraction from unstructured prompts
  - Form/survey submission with mandatory field validation
  - "LLM-powered data pipelines requiring 100% schema compliance"
---

## Description

Given a JSON schema and a prompt, runs an inner loop: generate, validate, on failure feed the specific validation error back into the next attempt. Designed for production workflows where schema-valid output is a hard requirement and a one-shot failure means a retry from scratch.

## Why it works

Most JSON validation failures are near-misses — a wrong enum value, a missing required field. One-shot prompting discards that information and starts over. Feeding the specific error back lets the next attempt fix the exact problem, which converges in 2-3 iterations for most schemas.

## How it works

1. Call the model with the prompt + the JSON schema in the system message. 2. Parse the output; run schema validation. 3. On failure, extract the specific validation error (path, expected, actual) and append it as a user message: 'Your previous output violated <path>: expected <X>, got <Y>. Fix and resubmit the full output.' 4. Retry up to N times (default 5). 5. On final failure, emit the last attempt with a failure reason for human review. 6. Record attempt counts for cost analysis.
