/llm-patterns:structured-generationfrom llm-patterns
Use when LLM output must conform to a specific schema, type, or format — JSON responses, typed function returns, database records, API payloads. Apply when free-text LLM output breaks downstream parsing, requires fragile regex extraction, or produces inconsistent shapes across calls. Covers schema enforcement, output typing, validation, and error recovery.
Ships in llm-patterns. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
An LLM is a function. Like any function, it should have a defined return type. Structured Generation constrains the output to a schema so the caller can rely on the shape without parsing or guessing.
The constraint happens at three possible levels — use the strongest one available:
| Level | Mechanism | Reliability |
|---|---|---|
| API-enforced | response_format / JSON mode / tool definitions | Highest — model is constrained at decode time |
| Schema-in-prompt | JSON Schema or TypeScript type in the system prompt | Medium — model usually complies but can drift |
| Post-parse validation | Parse output, validate against schema, retry on failure | Lowest — fallback, not primary strategy |
Always prefer API-enforced when available. Schema-in-prompt is the fallback. Post-parse validation is the safety net — never the only mechanism.
Most modern LLM APIs support constraining output to a schema at decode time. This is the most reliable approach.
from anthropic import Anthropic
client = Anthropic()
# Define the schema as a tool — the model is constrained to call it
tools = [{
"name": "extract_invoice",
"description": "Extract structured invoice data from text",
"input_schema": {
"type": "object",
"properties": {
"vendor_name": {"type": "string"},
"invoice_number": {"type": "string"},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"quantity": {"type": "integer"},
"unit_price": {"type": "number"}
},
"required": ["description", "quantity", "unit_price"]
}
},
"total": {"type": "number"},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]}
},
"required": ["vendor_name", "invoice_number", "line_items", "total", "currency"]
}
}]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
tool_choice={"type": "tool", "name": "extract_invoice"},
messages=[{"role": "user", "content": f"Extract invoice data:\n\n{invoice_text}"}]
)
# Output is guaranteed to match the schema
invoice_data = response.content[0].input # typed, validated
When API-level enforcement is not available, embed the schema in the prompt. Less reliable but still effective with clear instructions.
EXTRACTION_PROMPT = """Extract the following fields from the text.
Return ONLY valid JSON matching this exact schema:
{
"vendor_name": string,
"invoice_number": string,
"line_items": [{"description": string, "quantity": int, "unit_price": float}],
"total": float,
"currency": "USD" | "EUR" | "GBP"
}
Do not include any text before or after the JSON.
Text:
{input_text}
"""
Pair with validation: always parse and validate the output against the schema. Retry with the error message if validation fails.
Even with API-enforced schemas, validate the semantic content (not just the shape). A structurally valid response can be semantically wrong.
from pydantic import BaseModel, field_validator
class InvoiceExtraction(BaseModel):
vendor_name: str
invoice_number: str
line_items: list[LineItem]
total: float
currency: str
@field_validator('total')
def total_must_match_items(cls, v, info):
expected = sum(item.quantity * item.unit_price for item in info.data.get('line_items', []))
if abs(v - expected) > 0.01:
raise ValueError(f"Total {v} does not match sum of line items {expected}")
return v
def extract_invoice(text: str, max_retries: int = 2) -> InvoiceExtraction:
for attempt in range(max_retries + 1):
raw = call_llm(text)
try:
return InvoiceExtraction.model_validate(raw)
except ValidationError as e:
if attempt == max_retries:
raise
# Include the error in the retry prompt so the model can self-correct
text = f"{text}\n\nPrevious attempt failed validation: {e}\nPlease correct."
Wrap every LLM call in a function with typed inputs and outputs. The caller never sees raw LLM output.
def classify_support_ticket(ticket_text: str) -> TicketClassification:
"""LLM-powered function with a typed return value."""
response = client.messages.create(
model="claude-sonnet-4-6",
tools=[CLASSIFICATION_TOOL],
tool_choice={"type": "tool", "name": "classify_ticket"},
messages=[{"role": "user", "content": ticket_text}]
)
return TicketClassification.model_validate(response.content[0].input)
For classification tasks, constrain outputs to a defined set of values.
class SentimentResult(BaseModel):
sentiment: Literal["positive", "negative", "neutral"]
confidence: float # 0.0 to 1.0
reasoning: str # model explains its classification
For long-running extractions, stream partial results and validate incrementally.
# Stream JSON objects as they are produced
async for partial in stream_structured(prompt, schema=OrderList):
if partial.is_complete_item():
yield validate_and_store(partial.item)
What SKILL.md sets; muted values are Claude Code's defaults
10 skills in this plugin
/agent-loopUse when a task requires autonomous multi-step reasoning — the LLM must observe, decide, act, and iterate until a goal is met or a termination condition is reached. Apply when a single prompt cannot solve the task, the number of steps is not known in advance, and the next step depends on the result of the previous one. Covers ReAct, Plan-and-Execute, state management, termination, and guardrails for autonomous agents./evaluation-harnessUse when you cannot systematically measure whether your LLM feature is working correctly. Apply when testing is based on vibes rather than metrics, when you cannot detect regressions after prompt changes, or when production quality is unknown. Covers evaluation datasets, metrics, regression testing, LLM-as-judge, and production monitoring for non-deterministic systems./graceful-degradationUse when an LLM-powered feature must remain functional when the primary model is slow, down, over budget, or producing low-quality results. Apply when building any production AI feature that users depend on. Covers fallback chains, semantic routing, circuit breakers, cost management, and degradation levels./guardrailsUse when LLM inputs or outputs must be validated for safety, policy compliance, schema conformance, or content appropriateness before they reach users or downstream systems. Apply when LLM responses could contain harmful content, PII leakage, prompt injection, off-topic responses, or policy violations. Covers input validation, output validation, content filtering, and prompt injection defence./llm-pattern-selectionINVOKE THIS FIRST before designing any LLM-powered feature. Use when integrating an LLM as a component in a software system — not as a chat interface, but as a decision-making, data-processing, or logic-executing building block. Maps the friction you feel to the pattern that removes it./prompt-engineeringUse when prompts are ad-hoc strings scattered through code, hard to test, version, or maintain. Apply when building any LLM-powered feature to ensure prompts are treated as first-class engineering artifacts — versioned, tested, composable, and separated from application logic. Covers prompt structure, template patterns, few-shot design, chain-of-thought, and prompt chaining.npx claudepluginhub entelligentsia/skillforge --plugin llm-patternsOther plugins' skills for the same job