agentleFS
lauren-frameworklauren-framework/lauren-ai/skills/response-validation-retry/SKILL.md

response-validation-retry

Skill0 starsChanged 6 months agoMITView on GitHub

Validates agent responses against rules or schemas and retries with a corrective prompt when validation fails. Use when the agent must return JSON, structured data, or text meeting specific criteria; when using a weaker model that occasionally produces malformed output; or when reliability is more important than latency.

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use RetryOutputParser to wrap any parser with automatic retry:

    line 19
  2. Very specific:

    Always set a reasonable max_retries (2–3).

    line 141

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Use codemap find "SymbolName" to locate any symbol before reading.

LLM Response Validation & Retry Logic

Built-in: RetryOutputParser

Lauren-AI ships RetryOutputParser in lauren_ai._output_parsers:

# NOTE: future annotations are allowed, but tool signature types must resolve at import time.
from lauren_ai import RetryOutputParser, JSONOutputParser, PydanticOutputParser

Use RetryOutputParser to wrap any parser with automatic retry:

from lauren_ai import RetryOutputParser, JSONOutputParser, AgentRunnerBase, LLMConfig
from lauren_ai._transport._mock import MockTransport

json_parser = JSONOutputParser()
retrying_parser = RetryOutputParser(parser=json_parser, max_retries=3)

Custom ResponseValidator with exponential backoff

For cases where you need custom validation logic beyond parsing:

import asyncio
from typing import Any, Callable


class ResponseValidator:
    def __init__(self, validators: list[Callable[[str], bool]], max_retries: int = 3):
        self._validators = validators
        self._max_retries = max_retries

    async def validate_and_retry(self, run_fn: Callable, prompt: str, **kwargs) -> Any:
        last_response = None
        for attempt in range(self._max_retries):
            response = await run_fn(prompt, **kwargs)
            content = response.content if hasattr(response, "content") else str(response)
            if all(v(content) for v in self._validators):
                return response
            last_response = response
            if attempt < self._max_retries - 1:
                correction = (
                    f"\nPrevious response was invalid. Please try again.\n"
                    f"Previous: {content}"
                )
                prompt = prompt + correction
                await asyncio.sleep(0.1 * (2 ** attempt))
        return last_response

Validator factories

def is_non_empty(response: str) -> bool:
    return bool(response.strip())

def is_valid_json(response: str) -> bool:
    import json
    try:
        json.loads(response.strip())
        return True
    except (json.JSONDecodeError, ValueError):
        return False

def max_length(n: int) -> Callable[[str], bool]:
    return lambda r: len(r) <= n

def contains_required_keys(*keys: str) -> Callable[[str], bool]:
    import json
    def check(r: str) -> bool:
        try:
            data = json.loads(r)
            return all(k in data for k in keys)
        except Exception:
            return False
    return check

Full example

from lauren_ai import agent, AgentRunnerBase, LLMConfig
from lauren_ai._transport._mock import MockTransport

@agent(model="claude-haiku-4-5", system="Always respond with valid JSON only.")
class JSONAgent: ...

cfg = LLMConfig(provider="anthropic", model="claude-haiku-4-5", api_key="...")
runner = AgentRunnerBase(transport=transport)

validator = ResponseValidator(
    validators=[is_non_empty, is_valid_json, contains_required_keys("result", "confidence")],
    max_retries=3,
)

async def run_json_agent(query: str) -> str:
    import json
    response = await validator.validate_and_retry(
        lambda prompt: runner.run(JSONAgent(), prompt),
        query,
    )
    return response.content

Using PydanticOutputParser

For structured output, PydanticOutputParser validates against a Pydantic model:

from pydantic import BaseModel
from lauren_ai import PydanticOutputParser

class AnalysisResult(BaseModel):
    sentiment: str
    confidence: float
    summary: str

parser = PydanticOutputParser(model=AnalysisResult)
# parser.parse(response_content) -> AnalysisResult instance

Pitfalls

  • Retries increase latency and cost — use only when correctness matters more than speed.
  • The corrective prompt ("previous response was invalid") uses tokens; for very long conversations this can exceed the context window.
  • RetryOutputParser in lauren-ai wraps a parser; ResponseValidator here wraps an entire agent run. Choose based on whether you need custom validation logic beyond parsing.
  • Always set a reasonable max_retries (2–3); infinite retries against a broken prompt will loop forever.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.