llm-structured-output
Что он делает
Этот скилл помогает ИИ извлекать конкретную структурированную информацию (например, данные в формате JSON) из текста, а не просто генерировать свободный текст. Он гарантирует, что извлеченная информация соответствует заданному формату и надежна для использования в других частях программы.
Когда использовать
- ✓Когда нужно, чтобы ИИ возвращал данные в точном формате, например список позиций или контактные данные.
- ✓Когда вы создаете системы, где результат ИИ должен напрямую использоваться другим ПО (например, для сохранения в базу данных).
- ✓Когда ИИ возвращает неаккуратные или неправильно оформленные данные и вам нужно надежное решение.
Ссылка на скилл
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/llm-structured-output/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Извлеки имя, электронную почту и номер телефона из этого сообщения и верни их в формате JSON: «Здравствуйте, меня зовут Мария Силва, мои контакты: maria.silva@email.com, телефон 11 98765-4321.»”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
ИИ получает инструкцию следовать «схеме» (шаблону того, как должны быть организованы данные), а также использует специальные средства каждого провайдера ИИ (OpenAI, Anthropic, Google), чтобы результат точно соответствовал схеме.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
LLM Structured Output
What This Skill Does
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.
When to Use This Skill
- The user needs to extract structured data (JSON objects, arrays, enums) from an LLM response
- The user is building a pipeline where LLM output feeds directly into code (database writes, API calls, UI rendering)
- The user asks about
response_format,json_mode,json_object, orjson_schemain OpenAI - The user asks about using Anthropic's
tool_useortool_resultblocks for data extraction (not for actual tool execution) - The user asks about Zod schemas with
zodResponseFormat()from theopenainpm package - The user needs to parse LLM output into Pydantic models using
instructor,marvin, or manual validation - The user is getting malformed JSON, missing fields, or wrong types from LLM responses and needs a fix
- The user asks about
controlled generation,constrained decoding, orgrammar-based samplingin local models
Do NOT use this skill when:
- The user wants free-form text generation (summaries, essays, chat)
- The user is asking about Zod for form validation or API input validation (use
zod-validation-expertinstead) - The user needs prompt engineering for better text quality (not structure)
- The user wants to call real external tools/APIs (this skill covers using tool_use as a structured output hack, not actual tool orchestration)
Core Workflow
Identify the target schema. Ask the user what fields they need extracted. Define every field with its type, whether it's required or optional, and valid enum values if applicable. Do not proceed without a concrete schema.
Choose the provider-appropriate method:
- OpenAI (gpt-4o, gpt-4o-mini): Use
response_format: { type: "json_schema", json_schema: { ... } }. This enables Structured Outputs with guaranteed schema conformance via constrained decoding. - Anthropic (Claude): Define a single tool with the target schema as
input_schemaand settool_choice: { type: "tool", name: "extract_data" }. Claude returns the structured data in thetool_usecontent block. - Google (Gemini): Use
generationConfig.responseSchemawith a JSON Schema object and setresponseMimeType: "application/json". - Local models (llama.cpp, vLLM): Use GBNF grammars or
--json-schemaflag for constrained decoding at the token level.
- OpenAI (gpt-4o, gpt-4o-mini): Use
Write the schema definition in the user's language. For Python, define a Pydantic
BaseModel. For TypeScript, define a Zod schema and convert it withzodResponseFormat(). For raw API calls, write JSON Schema directly.Include field-level descriptions in the schema. Every field should have a
descriptionstring 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 baresentiment: strwith no context.Set the system prompt to reinforce structure. Tell the model its job is data extraction, not conversation. Example:
"You are a data extraction system. Analyze the input and return the requested fields. Do not include explanations outside the JSON structure."If using OpenAI's
json_schemamode, set"strict": truein the schema definition. This activates constrained decoding where the model can only output tokens that conform to the schema. Withoutstrict: true, the model may still produce invalid JSON.If using Anthropic's tool_use approach, extract the structured data from
response.contentby finding the block wheretype == "tool_use"and reading itsinputfield. Do not parse the text blocks — the structured data lives exclusively in the tool_use block.Validate the response against the schema in your application code. Even with constrained decoding, validate with Pydantic's
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.
…
Частые вопросы
Почему ИИ иногда возвращает некорректный JSON?
Это может случиться, если ИИ неправильно проинструктирован о формате или если провайдер не имеет надежного механизма, заставляющего результат соответствовать схеме. Этот скилл как раз объясняет, как пользоваться такими механизмами.
Что такое «схема»?
Схема это как форма или чертеж, который задает структуру ожидаемых данных: какие поля должны быть, какой тип информации в каждом поле (текст, число и т. д.) и обязательны ли они.
Работает ли это с любым ИИ?
Этот скилл показывает, как это делать с API крупных провайдеров, таких как OpenAI, Anthropic и Google. Для моделей, которые работают локально, тоже существуют похожие техники.
Подробности
Оригинальное описание автора
Get reliable JSON, enums, and typed objects from LLMs using response_format, tool_use, and schema-constrained decoding across OpenAI, Anthropic, and Google APIs.
Популярность
- Звёзды на GitHub
- 48k
- Место в рейтинге
- #5091
- Лицензия
- MIT
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
00-andruia-consultant
48kПомогает агенту начинать или улучшать ИИ-проекты: анализирует код, подбирает инструменты и составляет план на испанском.
007
48kАгент проводит аудит безопасности и моделирование угроз для защиты проектов.
10-andruia-skill-smith
48kПомогает агенту создавать и улучшать ИИ-инструменты: описание работы, документация и проверка структуры.
20-andruia-niche-intelligence
48kАгент составляет обзор отрасли: контекст, правила, паттерны использования и риски по надёжным источникам.
Похожие скиллы
writing-skills
311kУчит агента писать новые скиллы и сначала проверять каждый из них, убеждаясь, что скилл действительно меняет поведение агента.
writing-for-agents
310kОбъясняет, как писать понятные инструкции для ИИ-агентов, включая скиллы и файлы AGENTS.md и CLAUDE.md, чтобы агент вел себя предсказуемо.
bengali-nlp
280kАгент обрабатывает текст на бенгальском. Помогает работать с языком, нормализует текст и учитывает его особенности.