Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

structured-output

БесплатноБез исполняемых скриптовНе проверен

Force LLMs to return typed, validated JSON — not free-text. Use when someone asks to "get structured data from LLM", "parse LLM response as JSON", "make AI…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Structured Output

Overview

LLMs love to ramble. When you need JSON, you get JSON wrapped in markdown. When you need a list, you get a paragraph. Structured output forces the model to return exactly the schema you define — validated, typed, and ready to use in code without parsing gymnastics.

When to Use

  • Extracting structured data from unstructured text (invoices, emails, articles)
  • Building API responses powered by LLMs that must match a schema
  • Creating reliable data pipelines where LLM output feeds into databases
  • Generating configuration files, test cases, or code from natural language
  • Any time you need JSON from an LLM, not prose

Instructions

Strategy 1: OpenAI Structured Outputs (Native)

OpenAI's JSON Schema mode (strict) constrains decoding so the reply matches your schema. Use the Responses API: responses.parse with zodTextFormat (TypeScript) or text_format= with a Pydantic model (Python). The older chat.completions.parse with zodResponseFormat still works but is the legacy path.

// openai-structured.ts — Type-safe LLM outputs with OpenAI
import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";

const openai = new OpenAI(); // reads OPENAI_API_KEY

// Strict mode: every field is required and objects take no extra keys.
// Express "maybe missing" as .nullable(), never .optional().
const ProductAnalysis = z.object({
  name: z.string().describe("Product name"),
  category: z.enum(["electronics", "clothing", "food", "software", "other"]),
  sentiment: z.enum(["positive", "negative", "neutral", "mixed"]),
  score: z.number().describe("Overall quality score from 0 to 10"),
  pros: z.array(z.string()).describe("Positive aspects"),
  cons: z.array(z.string()).describe("Negative aspects"),
  summary: z.string().describe("One-sentence summary, at most 200 characters"),
  warranty_months: z.number().nullable().describe("Warranty length, null if not mentioned"),
});
type ProductAnalysis = z.infer<typeof ProductAnalysis>;

async function analyzeReview(review: string): Promise<ProductAnalysis> {
  const response = await openai.responses.parse({
    model: "gpt-6-luna", // pick a current model; gpt-4o-mini is scheduled for removal on 2027-01-14
    input: [
      { role: "system", content: "Analyze the product review and extract structured data." },
      { role: "user", content: review },
    ],
    text: { format: zodTextFormat(ProductAnalysis, "product_analysis") },
  });

  if (!response.output_parsed) {
    // A safety refusal does not follow the schema; it arrives as a refusal item.
    throw new Error(`No parsed output (status: ${response.status})`);
  }
  return response.output_parsed;
}

Python equivalent: client.responses.parse(model=..., input=[...], text_format=ProductAnalysis) where ProductAnalysis is a Pydantic BaseModel; read response.output_parsed.

Strategy 2: Anthropic JSON outputs (output_config.format)

Claude constrains its reply to a JSON Schema through output_config.format (GA on the Claude API, Bedrock, Vertex and Foundry; supported by current Claude models). messages.parse with a Zod schema (zodOutputFormat) or a Pydantic model (output_format=) sends the schema, validates the reply and returns it typed in parsed_output. Keep max_tokens high enough: a reply cut off at the limit is not valid JSON.

// anthropic-structured.ts — Structured output from Claude
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY

const ExtractedEvent = z.object({
  title: z.string(),
  date: z.string().describe("Event date in ISO 8601 format"),
  location: z.string(),
  attendees: z.number().describe("Expected number of attendees"),
  description: z.string().describe("Brief event description"),
});
type ExtractedEvent = z.infer<typeof ExtractedEvent>;

async function extractEvent(text: string): Promise<ExtractedEvent> {
  const response = await anthropic.messages.parse({
    model: "claude-sonnet-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: `Extract event details:\n\n${text}` }],
    output_config: { format: zodOutputFormat(ExtractedEvent) },
  });
  if (!response.parsed_output) throw new Error(`No parsed output (stop_reason: ${response.stop_reason})`);
  return response.parsed_output;
}
# anthropic_structured.py
from anthropic import Anthropic
from pydantic import BaseModel

class ExtractedEvent(BaseModel):
    title: str
    date: str
    location: str
    attendees: int

client = Anthropic()
response = client.messages.parse(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Extract the event: PyData Berlin, 14 March 2027 at the Kosmos venue, about 300 attendees."}],
    output_format=ExtractedEvent,
)
print(response.parsed_output)

The AP

Полный SKILL.md на GitHub

Установить structured-output в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл structured-output?

Force LLMs to return typed, validated JSON — not free-text. Use when someone asks to "get structured data from LLM", "parse LLM response as JSON", "make AI return typed output", "validate LLM output", "extract structured data with AI", "use instructor with OpenAI", or "get reliable JSON from Claude/GPT". Covers OpenAI structured outputs, Anthropic output_config.format (JSON outputs), Instructor library, Zod schemas, Pydantic models, and retry strategies for malformed responses.

Как установить скилл structured-output?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл structured-output запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить structured-output с