json-schema-enforcement
Skill0 starsChanged 6 months agoMITView on GitHub
Enforces JSON schema compliance on LLM responses using system prompt instructions, Pydantic validation, and RetryOutputParser. Use when the LLM must return a specific JSON structure and the response must be validated and retried on parse failure.
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
- 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
- response-validation-retrySkill
- 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
1 rule. About 0 are common, 0 are distinctive, and 1 is 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.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 97
When you control the full request, prefer StructuredLLM over prompt hacks: it binds the Pydantic schema to a tool call, guaranteeing valid …
≈ “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 — it gives exact file + line range and is faster than grep across the whole repo.
JSON Schema Enforcement for LLM Responses
Pattern: system prompt + Pydantic validation
from __future__ import annotations
from pydantic import BaseModel, ValidationError
class ProductInfo(BaseModel):
name: str
price: float
in_stock: bool
JSON_SYSTEM = """Always respond with valid JSON matching this schema:
{"name": "string", "price": number, "in_stock": boolean}
Do not include any text outside the JSON object."""
def parse_json_response(content: str, schema: type[BaseModel]) -> BaseModel:
try:
return schema.model_validate_json(content.strip())
except ValidationError as exc:
raise ValueError(f"Invalid JSON schema response: {exc}") from excPattern: JSONOutputParser
from lauren_ai import JSONOutputParser
parser = JSONOutputParser()
data: dict = parser.parse('{"name": "Widget", "price": 9.99}')Pattern: RetryOutputParser (retry on failure)
from lauren_ai import PydanticOutputParser, RetryOutputParser, LLMConfig
class OrderInfo(BaseModel):
order_id: str
total: float
base_parser = PydanticOutputParser(model=OrderInfo)
retry_parser = RetryOutputParser(parser=base_parser, max_retries=3)
# On parse failure, RetryOutputParser re-prompts the LLM with the error
result = await retry_parser.aparse_with_retry(
completion_fn=llm_complete_fn,
raw_output=initial_output,
)Testing valid and invalid JSON
from lauren_ai._transport import Completion, TokenUsage
from lauren_ai._transport._mock import MockTransport
mock = MockTransport()
# Valid JSON response
mock.queue_response(Completion(
id="c1", model="mock-model",
content='{"name": "Widget", "price": 9.99, "in_stock": true}',
tool_calls=[], stop_reason="end_turn",
usage=TokenUsage(input_tokens=10, output_tokens=15),
))
# Invalid JSON (for retry tests)
mock.queue_response(Completion(
id="c2", model="mock-model",
content="Sorry, I cannot provide that information.",
tool_calls=[], stop_reason="end_turn",
usage=TokenUsage(input_tokens=10, output_tokens=10),
))StructuredLLM — the recommended alternative
When you control the full request, prefer StructuredLLM over prompt hacks:
it binds the Pydantic schema to a tool call, guaranteeing valid JSON parsing
without retry logic.
from lauren_ai import StructuredLLM, LLMConfig
cfg = LLMConfig.for_anthropic()
llm = StructuredLLM(config=cfg, schema=ProductInfo)
result = await llm.generate("Describe product #42")Reference files
| File | Contents |
src/lauren_ai/_output_parsers/ | JSONOutputParser, PydanticOutputParser, RetryOutputParser |
src/lauren_ai/_transport/_structured.py | StructuredLLM — schema-enforced completions |
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.

