К основному содержанию
скилл CX Codex

structured-output-extractor — скилл для Claude Code

Помогает извлекать из ответов LLM типизированные данные через JSON Schema, Zod и function calling. Нужен для парсинга JSON и проверки результата.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add patricio0312rev/skills --skill structured-output-extractor -a claude-code
Открыть на GitHub

Что делает structured-output-extractor

Скилл задаёт рабочий процесс для извлечения данных из ответов LLM: сначала описывается схема, затем выбирается способ получения результата, ответ проверяется, а ошибки обрабатываются повтором или запасным сценарием. В нём разобраны JSON Mode, Structured Outputs, function calling и tool use.

Материалы содержат примеры на TypeScript с openai, JSON-схемами и zod. Показаны извлечение контактов, сущностей и классификация сообщений, а также проверка полей через Zod. В примерах используются модели OpenAI, поэтому код рассчитан на интеграцию с OpenAI API.

Скилл доступен для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode. Для Claude Code после установки файл лежит в ~/.claude/skills/structured-output-extractor/SKILL.md.

Какие задачи решает

  • извлечь контакты из текста в JSON
  • описать типизированную схему ответа LLM
  • проверить результат через Zod
  • вызвать функцию с аргументами из ответа модели
  • классифицировать сообщение по заданным полям

Примеры запросов агенту

  • Извлеки из текста контакты и верни результат по схеме с именем, email, телефоном и компанией.
  • Опиши схему Zod для отзыва о товаре и проверь ответ модели.
  • Настрой function calling для извлечения людей, организаций, мест и дат.

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

1Через Skills CLI (Vercel)

npx skills add patricio0312rev/skills --skill structured-output-extractor -a claude-code

2Вручную: положить файлы

~/.claude/skills/structured-output-extractor/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/structured-output-extractor/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о structured-output-extractor

Как установить structured-output-extractor в Claude Code?

Выполните npx skills add patricio0312rev/skills --skill structured-output-extractor -a claude-code. После установки файл будет доступен по пути ~/.claude/skills/structured-output-extractor/SKILL.md.

Что делает structured-output-extractor?

Скилл помогает получать из ответов LLM данные по заданной структуре. Он описывает JSON Mode, Structured Outputs, function calling, tool use и проверку через Zod.

С какими платформами работает structured-output-extractor?

Скилл предназначен для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode.

Исходный текст

SKILL.md · MIT
---
name: structured-output-extractor
description: Extracts structured data from LLM responses using JSON schemas, Zod validation, and function calling for reliable parsing. Use when users request "structured output", "JSON extraction", "parse LLM response", "function calling", or "typed responses".
---

# Structured Output Extractor

Extract reliable, typed data from LLM responses.

## Core Workflow

1. **Define schema**: Create data structure
2. **Choose method**: Function calling vs prompting
3. **Generate response**: Call LLM with structure
4. **Validate output**: Parse and verify
5. **Handle errors**: Retry or fallback

## Methods Comparison

| Method | Reliability | Flexibility | Best For |
|--------|-------------|-------------|----------|
| OpenAI JSON Mode | High | Medium | Simple JSON |
| Function Calling | Very High | High | Complex schemas |
| Instructor | Very High | High | Python/TS apps |
| Zod + Prompting | Medium | High | Custom parsing |

## OpenAI Structured Outputs

### JSON Mode

```typescript
// extractors/json-mode.ts
import OpenAI from 'openai';

const openai = new OpenAI();

interface ExtractedData {
  name: string;
  email: string;
  phone?: string;
  company?: string;
}

export async function extractContactInfo(text: string): Promise<ExtractedData> {
  const response = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    response_format: { type: 'json_object' },
    messages: [
      {
        role: 'system',
        content: `Extract contact information from text. Return JSON with:
{
  "name": "string",
  "email": "string",
  "phone": "string or null",
  "company": "string or null"
}`,
      },
      { role: 'user', content: text },
    ],
  });

  return JSON.parse(response.choices[0].message.content!);
}
```

### Structured Outputs (Beta)

```typescript
// extractors/structured.ts
import OpenAI from 'openai';
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';

const ContactSchema = z.object({
  name: z.string().describe('Full name of the contact'),
  email: z.string().email().describe('Email address'),
  phone: z.string().nullable().describe('Phone number if available'),
  company: z.string().nullable().describe('Company name if mentioned'),
  role: z.string().nullable().describe('Job title or role'),
});

type Contact = z.infer<typeof ContactSchema>;

export async function extractContact(text: string): Promise<Contact> {
  const response = await openai.beta.chat.completions.parse({
    model: 'gpt-4o-2024-08-06',
    messages: [
      {
        role: 'system',
        content: 'Extract contact information from the provided text.',
      },
      { role: 'user', content: text },
    ],
    response_format: zodResponseFormat(ContactSchema, 'contact'),
  });

  return response.choices[0].message.parsed!;
}
```

## Function Calling

### Define Functions

```typescript
// extractors/function-calling.ts
import OpenAI from 'openai';

const openai = new OpenAI();

const functions = [
  {
    name: 'extract_entities',
    description: 'Extract named entities from text',
    parameters: {
      type: 'object',
      properties: {
        people: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              name: { type: 'string' },
              role: { type: 'string' },
              organization: { type: 'string' },
            },
            required: ['name'],
          },
        },
        organizations: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              name: { type: 'string' },
              type: { type: 'string', enum: ['company', 'nonprofit', 'government', 'other'] },
            },
            required: ['name'],
          },
        },
        locations: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              name: { type: 'string' },
              type: { type: 'string', enum: ['city', 'country', 'address', 'other'] },
            },
            required: ['name'],
          },
        },
        dates: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              text: { type: 'string' },
              normalized: { type: 'string', format: 'date' },
            },
            required: ['text'],
          },
        },
      },
      required: ['people', 'organizations', 'locations', 'dates'],
    },
  },
];

export async function extractEntities(text: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    messages: [
      {
        role: 'system',
        content: 'Extract all named entities from the provided text.',
      },
      { role: 'user', content: text },
    ],
    functions,
    function_call: { name: 'extract_entities' },
  });

  const functionCall = response.choices[0].message.function_call;
  return JSON.parse(functionCall!.arguments);
}
```

### Tool Use Pattern

```typescript
// extractors/tools.ts
import OpenAI from 'openai';

const tools: OpenAI.Chat.ChatCompletionTool[] = [
  {
    type: 'function',
    function: {
      name: 'classify_intent',
      description: 'Classify the user intent from their message',
      parameters: {
        type: 'object',
        properties: {
          intent: {
            type: 'string',
            enum: ['question', 'complaint', 'feedback', 'request', 'other'],
          },
          confidence: {
            type: 'number',
            minimum: 0,
            maximum: 1,
          },
          entities: {
            type: 'object',
            properties: {
              product: { type: 'string' },
              issue: { type: 'string' },
              sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
            },
          },
          suggestedAction: {
            type: 'string',
          },
        },
        required: ['intent', 'confidence'],
      },
    },
  },
];

export async function classifyMessage(message: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    messages: [{ role: 'user', content: message }],
    tools,
    tool_choice: { type: 'function', function: { name: 'classify_intent' } },
  });

  const toolCall = response.choices[0].message.tool_calls?.[0];
  return JSON.parse(toolCall!.function.arguments);
}
```

## Zod Schema Validation

### With Instructor-like Pattern

```typescript
// extractors/zod-extractor.ts
import { z } from 'zod';
import OpenAI from 'openai';

const openai = new OpenAI();

// Define schema
const ProductReviewSchema = z.object({
  productName: z.string(),
  rating: z.number().min(1).max(5),
  pros: z.array(z.string()),
  cons: z.array(z.string()),
  summary: z.string().max(200),
  wouldRecommend: z.boolean(),
  sentiment: z.enum(['positive', 'negative', 'mixed', 'neutral']),
});

type ProductReview = z.infer<typeof ProductReviewSchema>;

// Generate JSON schema from Zod
function zodToJsonSchema(schema: z.ZodObject<any>) {
  // Simplified - use zod-to-json-schema in production
  const shape = schema.shape;
  const properties: Record<string, any> = {};
  const required: string[] = [];

  for (const [key, value] of Object.entries(shape)) {
    const zodType = value as z.ZodTypeAny;
    properties[key] = zodTypeToJson(zodType);
    if (!zodType.isOptional()) {
      required.push(key);
    }
  }

  return { type: 'object', properties, required };
}

export async function extractReview(reviewText: string): Promise<ProductReview> {
  const schema = zodToJsonSchema(ProductReviewSchema);

  const response = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    response_format: { type: 'json_object' },
    messages: [
      {
        role: 'system',
        content: `Extract a structured product review. Return JSON matching this schema:
${JSON.stringify(schema, null, 2)}`,
      },
      { role: 'user', content: reviewText },
    ],
  });

  const data = JSON.parse(response.choices[0].message.content!);

  // Validate with Zod
  return ProductReviewSchema.parse(data);
}
```

### With Retry on Validation Error

```typescript
// extractors/retry.ts
export async function extractWithRetry<T>(
  schema: z.ZodSchema<T>,
  prompt: string,
  text: string,
  maxRetries = 3
): Promise<T> {
  let lastError: Error | null = null;

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await openai.chat.completions.create({
        model: 'gpt-4-turbo-preview',
        response_format: { type: 'json_object' },
        messages: [
          { role: 'system', content: prompt },
          { role: 'user', content: text },
          // Add error context on retry
          ...(lastError
            ? [
                {
                  role: 'user' as const,
                  content: `Previous attempt failed validation: ${lastError.message}. Please fix.`,
                },
              ]
            : []),
        ],
      });

      const data = JSON.parse(response.choices[0].message.content!);
      return schema.parse(data);
    } catch (error) {
      if (error instanceof z.ZodError) {
        lastError = new Error(
          error.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ')
        );
      } else {
        throw error;
      }
    }
  }

  throw new Error(`Failed after ${maxRetries} attempts: ${lastError?.message}`);
}
```

## Complex Extraction Patterns

### Hierarchical Data

```typescript
// extractors/hierarchical.ts
const DocumentSchema = z.object({
  title: z.string(),
  authors: z.array(
    z.object({
      name: z.string(),
      affiliation: z.string().optional(),
    })
  ),
  abstract: z.string(),
  sections: z.array(
    z.object({
      heading: z.string(),
      content: z.string(),
      subsections: z
        .array(
          z.object({
            heading: z.string(),
            content: z.string(),
          })
        )
        .optional(),
    })
  ),
  references: z.array(
    z.object({
      authors: z.array(z.string()),
      title: z.string(),
      year: z.number(),
      source: z.string().optional(),
    })
  ),
  keywords: z.array(z.string()),
});
```

### Multi-step Extraction

```typescript
// extractors/multistep.ts
export async function extractComplex(document: string) {
  // Step 1: Extract structure
  const structure = await extract(
    z.object({
      sections: z.array(z.string()),
      hasReferences: z.boolean(),
    }),
    'Identify the document structure',
    document
  );

  // Step 2: Extract each section
  const sections = await Promise.all(
    structure.sections.map((section) =>
      extract(
        z.object({
          heading: z.string(),
          summary: z.string(),
          keyPoints: z.array(z.string()),
        }),
        `Extract details from section: ${section}`,
        document
      )
    )
  );

  // Step 3: Extract references if present
  let references = [];
  if (structure.hasReferences) {
    references = await extract(
      z.array(
        z.object({
          authors: z.array(z.string()),
          title: z.string(),
          year: z.number(),
        })
      ),
      'Extract all references',
      document
    );
  }

  return { sections, references };
}
```

## Streaming Structured Output

```typescript
// extractors/streaming.ts
import { zodToJsonSchema } from 'zod-to-json-schema';

export async function* streamExtract<T>(
  schema: z.ZodSchema<T>,
  prompt: string,
  text: string
): AsyncGenerator<{ partial: any; complete: boolean }> {
  const jsonSchema = zodToJsonSchema(schema);

  const stream = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    response_format: { type: 'json_object' },
    messages: [
      {
        role: 'system',
        content: `${prompt}\n\nReturn JSON matching: ${JSON.stringify(jsonSchema)}`,
      },
      { role: 'user', content: text },
    ],
    stream: true,
  });

  let fullContent = '';

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content || '';
    fullContent += content;

    // Try to parse partial JSON
    try {
      const partial = JSON.parse(fullContent);
      yield { partial, complete: false };
    } catch {
      // JSON not complete yet
    }
  }

  // Final parse and validate
  const final = JSON.parse(fullContent);
  const validated = schema.parse(final);
  yield { partial: validated, complete: true };
}
```

## Error Handling

```typescript
// extractors/error-handling.ts
export class ExtractionError extends Error {
  constructor(
    message: string,
    public readonly raw: string,
    public readonly validationErrors?: z.ZodError
  ) {
    super(message);
    this.name = 'ExtractionError';
  }
}

export async function safeExtract<T>(
  schema: z.ZodSchema<T>,
  prompt: string,
  text: string
): Promise<{ success: true; data: T } | { success: false; error: ExtractionError }> {
  try {
    const data = await extractWithRetry(schema, prompt, text);
    return { success: true, data };
  } catch (error) {
    if (error instanceof z.ZodError) {
      return {
        success: false,
        error: new ExtractionError('Validation failed', text, error),
      };
    }
    return {
      success: false,
      error: new ExtractionError(
        error instanceof Error ? error.message : 'Unknown error',
        text
      ),
    };
  }
}
```

## Best Practices

1. **Use structured outputs**: OpenAI's native feature when available
2. **Define clear schemas**: Descriptive field names and descriptions
3. **Validate with Zod**: Type-safe runtime validation
4. **Retry on failure**: With error context
5. **Use function calling**: For complex schemas
6. **Handle edge cases**: Null values, empty arrays
7. **Stream for UX**: Partial results during extraction
8. **Test with variations**: Different input formats

## Output Checklist

Every structured extraction should include:

- [ ] Zod schema with descriptions
- [ ] Appropriate extraction method (JSON/function/tools)
- [ ] Runtime validation
- [ ] Retry logic with error context
- [ ] Error handling and typing
- [ ] Streaming support (if needed)
- [ ] Edge case handling
- [ ] Type-safe return values
- [ ] Comprehensive tests

© patricio0312rev · MIT · patricio0312rev/skills

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

Все скиллы по теме «ИИ и ML» →
skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. 414 180установок writing-for-agents Matt Pocock Помогает писать скиллы и документы с инструкциями для агентов. Пригодится при правках AGENTS.md, CLAUDE.md и связанных справочных файлов. 466 719установок media-use heygen-com Находит и генерирует ассеты для видео в HyperFrames — музыку, дикторский голос, аватары и эффекты. Сохраняет всё локально в assets. CX Codex +1 1 100 000установок mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. 130 949установок subagent-driven-development Jesse Vincent Скилл выполняет план через отдельных субагентов для каждой задачи и проверяет результат после каждого шага. Подходит для независимых задач в одной сессии. CX Codex 237 746установок orchestration stablyai Координирует воркеров Orca через DAG задач, циклы супервизора и цепочки сообщений. Пригодится для распределения сложной работы между агентами. CX Codex +1 350 300установок

Из того же набора36

cost-latency-optimizer Скилл разбирает, куда уходят деньги и время в LLM-приложении, и предлагает кеш, выбор модели, батчинг и сжатие промптов. CX Codex +1 322установок storybook-setup Настраивает Storybook для документации компонентов, интерактивных контролов, accessibility-проверок и визуальной регрессии. CX Codex +1 319установок rate-limiting-abuse-protection Скилл добавляет в проект ограничение частоты запросов: политики на маршрут, лимиты по IP и пользователю, скользящее окно и понятные ответы об ошибке. CX Codex +1 319установок load-test-builder Собирает нагрузочные и стресс-тесты на k6, Artillery или autocannon и помогает встроить их в CI как проверку производительности. CX Codex +1 316установок secure-headers-csp-builder Добавляет HTTP-заголовки безопасности и CSP с переходом от отчётов к блокировке. Пригодится для защиты Express-приложения от XSS и небезопасных ресурсов. CX Codex +1 306установок openapi-generator Собирает спецификацию OpenAPI 3.0/3.1 из маршрутов Express, Next.js, Fastify, Hono или NestJS — со схемами, примерами и описаниями. CX Codex +1 306установок frontend-refactor-planner Составляет поэтапный план рефакторинга фронтенда: делит крупные компоненты, упрощает состояние и улучшает доступность. Пригодится при разборе легаси-кода. CX Codex +1 305установок api-test-suite-generator Скилл сканирует определения маршрутов и генерирует тесты API на Jest, Vitest или Supertest. Пригодится, когда эндпоинты уже есть, а тестов к ним нет. CX Codex +1 303установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой