惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
小众软件
小众软件
美团技术团队
Martin Fowler
Martin Fowler
爱范儿
爱范儿
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
J
Java Code Geeks
B
Blog
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Fix Bad Structured Output by Feeding the Error Back to th...
Mukunda Rao · 2026-05-26 · via DEV Community

You asked the model to return JSON. It returned almost-JSON with a trailing comma. Your parser crashed. You want to retry, but just resending the same prompt will probably produce the same bad output.

The better approach: tell the model what went wrong. Append the parse error as a follow-up message. Ask for a corrected response.

llm-structured-retry implements this pattern.


The Shape of the Fix

from llm_structured_retry import StructuredRetry, StructuredRetryExhausted

def call_json(prompt: str) -> dict:
    retry = StructuredRetry(
        max_attempts=3,
        parser=json.loads,  # your parser
        error_formatter=lambda e: f"Parse failed: {e}. Return valid JSON only.",
    )

    return retry.call(
        fn=lambda: call_llm(prompt),
        extract_text=lambda r: r.content[0].text,
    )

Enter fullscreen mode Exit fullscreen mode

On parse failure, StructuredRetry appends the error message as a new user turn and calls the model again. The model sees what it returned, sees what broke, and gets a chance to fix it.


What It Does NOT Do

llm-structured-retry does not fix the output automatically. It asks the model to fix it. Whether the model succeeds depends on the model's understanding of the error.

It does not implement a general retry for all errors. It is specifically for cases where parsing the model's output fails and you want to use the parse error to guide a correction.

For rate limit retries and provider availability retries, use llm-retry-py. That is a different problem.


Inside the Library

The retry loop builds a conversation that includes the previous failed attempt:

def call(self, fn: Callable[[], T], extract_text: Callable[[T], str]) -> Any:
    messages = []

    for attempt in range(self._max_attempts):
        response = fn()
        text = extract_text(response)

        try:
            return self._parser(text)
        except Exception as e:
            if attempt == self._max_attempts - 1:
                raise StructuredRetryExhausted(
                    f"Failed after {self._max_attempts} attempts",
                    last_output=text,
                    last_error=str(e),
                )

            error_msg = self._error_formatter(e)
            messages = [
                {"role": "assistant", "content": text},  # what model returned
                {"role": "user", "content": error_msg},  # what broke
            ]

            # Next call includes the error conversation
            original_fn = fn
            fn = lambda: call_llm_with_history(messages, original_fn)

Enter fullscreen mode Exit fullscreen mode

The key: the model sees its own previous output alongside the error. This is the minimal context it needs to understand what went wrong and produce a corrected version.

StructuredRetryExhausted carries last_output and last_error so you can log both when all attempts fail. This tells you whether the model was consistently producing the same malformed output (prompt issue) or whether it was improving but not quite getting there (model capability issue).


When to Use It

Use it when you need structured output (JSON, YAML, specific format) from a model and you cannot use provider-native structured output modes.

Use it when provider-native JSON mode is not available for your use case (certain tool configurations, certain models) or when you need YAML or another format that the provider does not support natively.

The error feedback pattern works best when the error message is specific. "Parse failed: Expecting property name enclosed in double quotes: line 3 column 1 (char 45)" tells the model where the problem is. "Parse failed" tells it nothing useful.


Install

pip install git+https://github.com/MukundaKatta/llm-structured-retry

Enter fullscreen mode Exit fullscreen mode

from llm_structured_retry import StructuredRetry, StructuredRetryExhausted
import json, yaml

# JSON extraction
json_retry = StructuredRetry(
    max_attempts=3,
    parser=json.loads,
    error_formatter=lambda e: (
        f"Your response was not valid JSON. Error: {e}\n"
        "Return ONLY the JSON object, no explanation, no markdown code blocks."
    ),
)

# YAML extraction
yaml_retry = StructuredRetry(
    max_attempts=3,
    parser=yaml.safe_load,
    error_formatter=lambda e: (
        f"Your response was not valid YAML. Error: {e}\n"
        "Return ONLY the YAML content, properly indented."
    ),
)

# Custom parser
def parse_numbered_list(text: str) -> list[str]:
    lines = text.strip().split("\n")
    items = []
    for line in lines:
        if line and line[0].isdigit():
            items.append(line.split(".", 1)[1].strip())
    if not items:
        raise ValueError("No numbered items found in response")
    return items

list_retry = StructuredRetry(
    max_attempts=2,
    parser=parse_numbered_list,
    error_formatter=lambda e: (
        f"Your response did not contain a numbered list. Error: {e}\n"
        "Return items as a numbered list: 1. Item one\n2. Item two"
    ),
)

Enter fullscreen mode Exit fullscreen mode


Sibling Libraries

Library What it solves
llm-retry-py Retry on rate limits, timeouts, provider errors
llm-output-validator Rule-based validation of output shape
tool-arg-coerce-py Coerce parsed output to expected types
agentvet Validate tool arguments before execution
llm-fallback-chain Fall through to backup provider on persistent failure

The structured output pipeline: llm-structured-retry for parse-error-guided correction, llm-output-validator for shape validation after parsing, tool-arg-coerce-py for type coercion on parsed values.


What's Next

Schema-aware error messages: if you pass a JSON schema alongside the parser, the error formatter could generate a schema-specific error message ("Field 'priority' is required but missing" instead of "KeyError: 'priority'"). This would make correction more targeted.

Partial repair before retry: for JSON specifically, try json5 or demjson to parse leniently before giving up and retrying with error feedback. Some models produce consistently fixable JSON (missing quotes, trailing commas) that a lenient parser can handle without retry overhead.

Streaming retry: for streaming responses, detect parse failure on the complete response and retry. Streaming complicates the history accumulation because you need to collect the full text before parsing.


Built as part of the agent-stack family: composable Python primitives for production LLM agents.