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.
In this repository65 other files it gives its agents.
- AGENTS.mdAGENTS.md
- skills/building-agents/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms-full.txtllms.txt
- llms.txtllms.txt
- adding-guardrailsSkill
- agent-health-timeoutSkill
- agent-permission-scopingSkill
- agent-session-isolationSkill
- agent-step-loggingSkill
- agent-supervisor-routerSkill
- agent-telemetrySkill
- async-agent-backgroundSkill
- building-agentsSkill
- building-teamsSkill
- building-toolsSkill
- calendar-scheduling-toolSkill
- callback-tracing-handlerSkill
- chain-of-thought-promptingSkill
- chat-model-configurationSkill
- code-execution-sandboxSkill
- common-agent-patternsSkill
- context-window-managementSkill
- conversation-memorySkill
- conversation-state-dbSkill
- database-query-toolSkill
- document-loadersSkill
- document-rerankingSkill
- email-notification-toolSkill
- embedding-model-ingestionSkill
- fallback-model-chainSkill
- few-shot-injectionSkill
- filesystem-toolSkill
- human-in-the-loopSkill
- hybrid-searchSkill
- inspecting-streamsSkill
- integrating-with-laurenSkill
- json-schema-enforcementSkill
- llm-provider-connectionSkill
- llm-rate-limitingSkill
- long-term-vector-memorySkill
- managing-memorySkill
- migrating-to-lauren-aiSkill
- multi-agent-delegationSkill
- multi-tool-orchestrationSkill
- multi-turn-tool-stateSkill
- output-guardrailsSkill
- plan-and-execute-agentSkill
- prompt-injection-defenseSkill
- prompt-versioningSkill
- rag-pipelineSkill
- react-agent-loopSkill
- rest-api-toolSkill
- securing-agentsSkill
- semantic-cacheSkill
- streaming-response-handlerSkill
- structured-output-parsingSkill
- sub-agent-spawningSkill
- system-prompt-templatingSkill
- testing-agentsSkill
- The first 60 shown.
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
- Very specific: line 19
Use RetryOutputParser to wrap any parser with automatic retry:
- Very specific: line 141
Always set a reasonable max_retries (2–3).
≈ “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.
Files
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, PydanticOutputParserUse 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_responseValidator 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 checkFull 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.contentUsing 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 instancePitfalls
- 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.
RetryOutputParserin lauren-ai wraps a parser;ResponseValidatorhere 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.
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
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.

