agentleFS
lauren-frameworklauren-framework/lauren-ai/skills/json-schema-enforcement/SKILL.md

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.

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
  1. Very specific:

    When you control the full request, prefer StructuredLLM over prompt hacks: it binds the Pydantic schema to a tool call, guaranteeing valid …

    line 97

≈ “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 — 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 exc

Pattern: 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

FileContents
src/lauren_ai/_output_parsers/JSONOutputParser, PydanticOutputParser, RetryOutputParser
src/lauren_ai/_transport/_structured.pyStructuredLLM — schema-enforced completions

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.