Структурный вывод

Получение структурированных данных (JSON) от AI моделей

Структурный вывод

Структурный вывод позволяет получать ответы от AI моделей в строгом JSON формате, соответствующем заданной схеме.

Поддержка структурного вывода зависит от модели. Проверяйте возможности в каталоге моделей.

Зачем это нужно?

СценарийПольза
Парсинг данныхИзвлечение структурированной информации из текста
API интеграцииПолучение данных в формате, готовом для обработки
ВалидацияГарантия соответствия ответа заданной структуре
АвтоматизацияНадёжная интеграция с бизнес-процессами

Способы получения структурного вывода

1. response_format (рекомендуется)

Надёжнее всего использовать параметр response_format с JSON Schema:

curl -X POST "https://api.usellm.ru/v1/chat/completions" \
  -H "Authorization: Bearer <USELLM_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "messages": [
      {"role": "user", "content": "Извлеки информацию о товаре: iPhone 15 Pro, 256GB, цена 89990 рублей, в наличии"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "product",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "storage": {"type": "string"},
            "price": {"type": "number"},
            "in_stock": {"type": "boolean"}
          },
          "required": ["name", "storage", "price", "in_stock"],
          "additionalProperties": false
        }
      }
    }
  }'

2. json_object (простой JSON)

Для простых случаев, когда схема не критична:

curl -X POST "https://api.usellm.ru/v1/chat/completions" \
  -H "Authorization: Bearer <USELLM_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "messages": [
      {"role": "system", "content": "Всегда отвечай в формате JSON с полями: name, price, currency"},
      {"role": "user", "content": "Цена на MacBook Air?"}
    ],
    "response_format": {"type": "json_object"}
  }'

Примеры схем

Извлечение контактов

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "email": { "type": "string", "format": "email" },
    "phone": { "type": "string" },
    "company": { "type": "string" }
  },
  "required": ["name"]
}

Анализ отзыва

{
  "type": "object",
  "properties": {
    "sentiment": {
      "type": "string",
      "enum": ["positive", "negative", "neutral"]
    },
    "score": { "type": "number", "minimum": 1, "maximum": 5 },
    "topics": {
      "type": "array",
      "items": { "type": "string" }
    },
    "summary": { "type": "string" }
  },
  "required": ["sentiment", "score", "summary"]
}

Список задач

{
  "type": "object",
  "properties": {
    "tasks": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "title": { "type": "string" },
          "priority": { "type": "string", "enum": ["low", "medium", "high"] },
          "due_date": { "type": "string", "format": "date" }
        },
        "required": ["title", "priority"]
      }
    }
  },
  "required": ["tasks"]
}

Параметр strict

ЗначениеОписание
trueОтвет точно соответствует схеме. Рекомендуется.
falseМодель может отклоняться от схемы. Не рекомендуется.

При strict: true модель гарантированно вернёт JSON, соответствующий схеме, или ошибку.

Обработка массивов

Для извлечения списка объектов:

curl -X POST "https://api.usellm.ru/v1/chat/completions" \
  -H "Authorization: Bearer <USELLM_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "messages": [
      {"role": "user", "content": "Извлеки все упомянутые компании: Apple выпустила iPhone, Google показала Pixel, Microsoft представила Surface"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "companies",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "items": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "company": {"type": "string"},
                  "product": {"type": "string"}
                },
                "required": ["company", "product"],
                "additionalProperties": false
              }
            }
          },
          "required": ["items"],
          "additionalProperties": false
        }
      }
    }
  }'

Советы и лучшие практики

Следующие шаги