Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Extract typed, validated data from LLM API responses instead of parsing free-text. This skill covers the three main approaches: OpenAI's `response_format` with JSON Schema, Anthropic's `tool_use` block for structured extraction, and Google's `responseSchema` in Gemini. You will learn when each appro
.claude/skills/llm-structured-output/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-18 | ✗→✓ | ▲ Improved | — | — |
| case-05 | ✗→✓ | ▲ Improved | — | — |
| case-03 | ✗→✗ | = Same ✗ | — | — |
| case-06 | ✗→✗ | = Same ✗ | — | — |
| case-12 | ✗→✗ | = Same ✗ | — | — |
Extract typed, validated data from LLM API responses instead of parsing free-text. This skill covers the three main approaches: OpenAI's response_format with JSON Schema, Anthropic's tool_use block for structured extraction, and Google's responseSchema in Gemini. You will learn when each approach works, when it breaks, and how to build retry logic around schema validation failures that every production system encounters.
response_format, json_mode, json_object, or json_schema in OpenAItool_use or tool_result blocks for data extraction (not for actual tool execution)zodResponseFormat() from the openai npm packageinstructor, marvin, or manual validationcontrolled generation, constrained decoding, or grammar-based sampling in local modelsDo NOT use this skill when:
zod-validation-expert instead)response_format: { type: "json_schema", json_schema: { ... } }. This enables Structured Outputs with guaranteed schema conformance via constrained decoding.input_schema and set tool_choice: { type: "tool", name: "extract_data" }. Claude returns the structured data in the tool_use content block.generationConfig.responseSchema with a JSON Schema object and set responseMimeType: "application/json".--json-schema flag for constrained decoding at the token level.BaseModel. For TypeScript, define a Zod schema and convert it with zodResponseFormat(). For raw API calls, write JSON Schema directly.description string that tells the model what to put there. Models use these descriptions as implicit prompt instructions — a field described as "The user's sentiment as positive, negative, or neutral" produces better results than a bare sentiment: str with no context."You are a data extraction system. Analyze the input and return the requested fields. Do not include explanations outside the JSON structure."json_schema mode, set "strict": true in the schema definition. This activates constrained decoding where the model can only output tokens that conform to the schema. Without strict: true, the model may still produce invalid JSON.response.content by finding the block where type == "tool_use" and reading its input field. Do not parse the text blocks — the structured data lives exclusively in the tool_use block.model_validate() or Zod's .parse() before passing data downstream. This catches semantic issues (empty strings, out-of-range numbers) that schema conformance alone cannot prevent."Your previous output failed validation: {error}. Fix the output." Cap retries at 3 attempts.pythonfrom pydantic import BaseModel, Field from openai import OpenAI from enum import Enum class Sentiment(str, Enum): positive = "positive" negative = "negative" neutral = "neutral" class ReviewAnalysis(BaseModel): sentiment: Sentiment = Field(description="Overall sentiment of the review") key_topics: list[str] = Field(description="Main topics mentioned, max 5") purchase_intent: bool = Field(description="Whether the reviewer would buy again") confidence_score: float = Field(ge=0.0, le=1.0, description="Model confidence 0-1") client = OpenAI() response = client.beta.chat.completions.parse( model="gpt-4o-2024-08-06", messages=[ {"role": "system", "content": "Extract structured review analysis."}, {"role": "user", "content": "This laptop is amazing. The battery lasts forever and the keyboard feels great. Definitely buying the next version."} ], response_format=ReviewAnalysis, ) result = response.choices[0].message.parsed # result.sentiment == Sentiment.positive # result.key_topics == ["battery life", "keyboard"] # result.purchase_intent == True
pythonimport anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, system="You are a data extraction system. Use the provided tool to return structured data.", tools=[{ "name": "extract_invoice", "description": "Extract invoice fields from text", "input_schema": { "type": "object", "properties": { "vendor_name": {"type": "string", "description": "Company that issued the invoice"}, "total_amount": {"type": "number", "description": "Total amount in USD"}, "line_items": { "type": "array", "items": { "type": "object", "properties": { "description": {"type": "string"}, "quantity": {"type": "integer"}, "unit_price": {"type": "number"} }, "required": ["description", "quantity", "unit_price"] } } }, "required": ["vendor_name", "total_amount", "line_items"] } }], tool_choice={"type": "tool", "name": "extract_invoice"}, messages=[{"role": "user", "content": "Invoice from Acme Corp: 3x Widget A at $10 each, 1x Widget B at $25. Total: $55."}] ) # Find the tool_use block — do NOT parse text blocks tool_block = next(b for b in response.content if b.type == "tool_use") invoice = tool_block.input # invoice["vendor_name"] == "Acme Corp" # invoice["total_amount"] == 55.0
typescriptimport OpenAI from "openai"; import { z } from "zod"; import { zodResponseFormat } from "openai/helpers/zod"; const EventSchema = z.object({ event_name: z.string().describe("Name of the event"), date: z.string().describe("ISO 8601 date string"), location: z.string().describe("City and venue"), attendee_count: z.number().int().describe("Expected number of attendees"), is_virtual: z.boolean().describe("Whether the event is online-only"), }); const client = new OpenAI(); const completion = await client.beta.chat.completions.parse({ model: "gpt-4o-2024-08-06", messages: [ { role: "system", content: "Extract event details from the text." }, { role: "user", content: "Tech Summit 2025 in Austin at the Convention Center on March 15th. Expecting 2000 attendees, in-person only." }, ], response_format: zodResponseFormat(EventSchema, "event_extraction"), }); const event = completion.choices[0].message.parsed; // event.event_name === "Tech Summit 2025" // event.is_virtual === false
response_format: { type: "json_object" } without a schema. This is OpenAI's legacy JSON mode — it guarantees valid JSON syntax but not schema conformance. The model can return {"result": "hello"} when you expected {"name": str, "age": int}. Always use json_schema with a full schema definition instead.tool_choice to force structured output, the data is in the tool_use content block, not in any text block. Parsing response.content[0].text will either return empty string or a conversational preamble — never the data you need.status with no description can mean HTTP status, order status, or review status. Models use field descriptions as extraction instructions. Omitting them is equivalent to omitting half your prompt.additionalProperties: true in strict mode schemas. OpenAI's strict mode requires additionalProperties: false on every object in the schema. If you set it to true or omit it, the API rejects the request with a 400 error, not at response time — you will never get a response at all.{"sentiment": "positive"} for a negative review if the source text is ambiguous. Always validate semantics in application code after schema validation.$ref pointing to the same definition) and schemas deeper than 3 levels increase decoding latency significantly and raise the probability of the model hitting max_tokens before completing the JSON structure. Flatten nested schemas where possible.refusal instead of structured data. OpenAI's structured output can return a refusal field when the model considers the request unsafe. Check response.choices[0].message.refusal before accessing .parsed. If refusal is not None, the parsed data will be None and accessing it throws an error.[] for array fields when the source text contains the data but the field description is too vague. Fix by making the description prescriptive: "List of all product names mentioned in the text. Return at least one if any product is referenced.".["Active", "Inactive"] but the model returns "active", validation fails. Either lowercase all enum values in the schema or add a normalization step before validation. OpenAI's strict mode respects exact casing; Anthropic may not.openai SDK's built-in partial parsing or buffer chunks until the stream completes. Anthropic's tool_use blocks arrive complete in a single content_block_stop event — no partial assembly needed.mood: str can return anything. A field mood: Literal["happy", "sad", "neutral", "angry"] constrains the model to exactly those values. This reduces downstream parsing logic to zero.gpt-4o is an alias that changes when OpenAI releases new versions. Structured output behavior can change between versions. Use gpt-4o-2024-08-06 explicitly so that your schema+prompt combination remains stable until you deliberately upgrade.default values in Pydantic models for optional fields. When a field might not have relevant data in the source text, define it as Optional[str] = None in Pydantic or .optional() in Zod. Without defaults, the model is forced to hallucinate a value for fields where the source text has no answer.| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-03 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-18 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-06 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-05 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-12 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-17 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-01 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-07 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-02 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-15 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-09 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-10 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-21 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-14 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-20 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-08 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-11 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-22 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-04 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-13 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-16 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-19 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +9 percentage points is the difference between those two pass rates over the 22 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
The per-case answers from this run were removed by the retention sweep, so the case table below shows the verdicts without the text either arm produced. The counts above were recorded at the time and are unaffected. Answers are now kept for 180 days.
Other measured skills in the registry, with their headline benchmark lift.