# Отправка задачи генерации изображения

**API:** Model API

**Endpoint:** `POST /api/v1/images/generations`

Возвращает HTTP 202 с постоянным task_id. Опрашивайте GET /api/v1/images/generations/{task_id}. Поддерживается плоский или вложенный ввод; приоритет у вложенного input. Поля callback игнорируются. Возможности и параметры ввода зависят от настроенной модели и канала.

## Base URL

- `https://openapi.felo.ai` — Боевая среда

## Authentication

- `FeloBearerAuth` (http bearer) — API-ключ Felo, передаваемый как `Authorization: Bearer <key>`.
- `FeloApiKey` (apiKey in header `X-API-Key`) — API-ключ Felo, передаваемый как `X-API-Key: <key>`.

## Parameters

| Name | In | Required | Type | Description |
| --- | --- | --- | --- | --- |
| `X-Request-Id` | header | no | string | Необязательный ID запроса вызывающей стороны, возвращаемый в ответе для диагностики. |
| `X-Felo-Channel` | header | no | string, default: "default" | Упорядоченные публичные коды каналов через запятую. Опустите этот заголовок, чтобы использовать значение по умолчанию; default должен использоваться только сам по себе. В режиме wallet значение по умолчанию просматривает эффективный публичный порядок каналов модели в обратном направлении, пропускает неопубликованные и недоступные каналы и выбирает провайдера первого доступного канала. Оно включает доступные эндпоинты этого провайдера с тем же upstream ID модели и уровнем обслуживания. Явные каналы проверяются в порядке, указанном клиентом; отправляется только группа провайдера первого канала. Автоматического переключения на других провайдеров нет. Устаревшие заголовки провайдеров не могут переопределить маршрутизацию по каналам. |

## Request body

Required: **yes**

### application/json

Schema: `ImageGenerationRequest` (`#/components/schemas/ImageGenerationRequest`)

```json
{
  "type": "object",
  "required": [
    "model"
  ],
  "properties": {
    "model": {
      "type": "string"
    },
    "prompt": {
      "type": "string"
    },
    "input": {
      "type": "object",
      "additionalProperties": true,
      "description": "Необязательный вложенный input; имеет приоритет над плоским вводом.",
      "properties": {
        "input_references": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "image_url"
                ]
              },
              "image_url": {
                "type": "object",
                "additionalProperties": false,
                "oneOf": [
                  {
                    "required": [
                      "url"
                    ]
                  },
                  {
                    "required": [
                      "file_id"
                    ]
                  }
                ],
                "properties": {
                  "url": {
                    "type": "string",
                    "minLength": 1,
                    "pattern": "\\S",
                    "not": {
                      "pattern": "^\\s*felo_file_"
                    }
                  },
                  "file_id": {
                    "type": "string",
                    "maxLength": 80,
                    "pattern": "^felo_file_[A-Za-z0-9_-]{1,70}$",
                    "description": "Uploaded Felo file owned by the authenticated user."
                  }
                }
              },
              "role": {
                "type": "string",
                "description": "Optional asset role for models that define reference roles, e.g. refer_image, style_refer_image or subject_refer_image for Kling long images. Other channels reject it."
              }
            },
            "required": [
              "type",
              "image_url"
            ]
          },
          "description": "Reference images by URL/data URI or uploaded Felo file_id. At most 100 Felo references and 50,000,000 bytes per request; model/channel limits may be lower. Keep files until completion."
        },
        "service_tier": {
          "type": [
            "string",
            "null"
          ],
          "default": "default",
          "description": "Сейчас поддерживается только default (стандартный). Если поле опущено, равно null, содержит псевдоним или неподдерживаемую строку, используется значение по умолчанию; другие типы возвращают HTTP 400. Настроенные каналы и цены не меняются. Текстовые API передают стандартное значение провайдера; Decisions и API генерации опускают поле upstream."
        }
      }
    },
    "n": {
      "type": "integer"
    },
    "size": {
      "type": "string",
      "description": "Model-specific size. For supported Gemini token-priced image models, pixel dimensions select the nearest supported aspect ratio only; ignored when aspect_ratio is supplied. Use image_size or resolution for the resolution tier."
    },
    "image_size": {
      "type": "string",
      "enum": [
        "512",
        "1K",
        "2K",
        "4K"
      ],
      "description": "Resolution tier for supported Gemini token-priced image models. Available tiers depend on the model and channel."
    },
    "resolution": {
      "type": "string",
      "description": "Resolution tier; must agree with image_size when both are supplied."
    },
    "aspect_ratio": {
      "type": "string",
      "description": "Output aspect ratio. Supported values depend on the model and channel."
    },
    "provider": {
      "type": "object",
      "required": [
        "options"
      ],
      "additionalProperties": false,
      "properties": {
        "options": {
          "type": "object",
          "minProperties": 1,
          "maxProperties": 1,
          "additionalProperties": {
            "type": "object"
          },
          "description": "Options keyed by the slug published in the model catalog."
        }
      }
    },
    "quality": {
      "type": "string",
      "description": "Model-specific quality or resolution tier. For supported Gemini token-priced models, auto/low map to 1K, medium to 2K and high to 4K, subject to model capabilities. Explicit image_size or resolution takes precedence over these labels. Estimated reservations do not replace actual usage billing."
    },
    "input_references": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "image_url"
            ]
          },
          "image_url": {
            "type": "object",
            "additionalProperties": false,
            "oneOf": [
              {
                "required": [
                  "url"
                ]
              },
              {
                "required": [
                  "file_id"
                ]
              }
            ],
            "properties": {
              "url": {
                "type": "string",
                "minLength": 1,
                "pattern": "\\S",
                "not": {
                  "pattern": "^\\s*felo_file_"
                }
              },
              "file_id": {
                "type": "string",
                "maxLength": 80,
                "pattern": "^felo_file_[A-Za-z0-9_-]{1,70}$",
                "description": "Uploaded Felo file owned by the authenticated user."
              }
            }
          },
          "role": {
            "type": "string",
            "description": "Optional asset role for models that define reference roles, e.g. refer_image, style_refer_image or subject_refer_image for Kling long images. Other channels reject it."
          }
        },
        "required": [
          "type",
          "image_url"
        ]
      },
      "description": "Reference images by URL/data URI or uploaded Felo file_id. At most 100 Felo references and 50,000,000 bytes per request; model/channel limits may be lower. Keep files until completion."
    },
    "skill": {
      "type": "string",
      "description": "Long-image type for models that publish it in parameter_definitions, e.g. ecommerce or webpage."
    },
    "length": {
      "type": "string",
      "description": "Page length for long-image models; see applies_when in parameter_definitions for the skills it applies to."
    },
    "service_tier": {
      "type": [
        "string",
        "null"
      ],
      "default": "default",
      "description": "Сейчас поддерживается только default (стандартный). Если поле опущено, равно null, содержит псевдоним или неподдерживаемую строку, используется значение по умолчанию; другие типы возвращают HTTP 400. Настроенные каналы и цены не меняются. Текстовые API передают стандартное значение провайдера; Decisions и API генерации опускают поле upstream."
    }
  },
  "additionalProperties": true,
  "description": "Ввод, зависящий от модели, следует настроенному публичному протоколу модели."
}
```

Example:

```json
{
  "model": "configured-image-model",
  "prompt": "a cat"
}
```

## Responses

### 202 — Задача принята

**application/json**

Schema: `ImageGenerationAccepted` (`#/components/schemas/ImageGenerationAccepted`)

### 400 — Некорректный запрос (неизвестная модель, смешение режимов ввода, недопустимые поля)

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 401 — Недействительный или отсутствующий API-ключ Felo

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 402 — Недостаточно средств на балансе / не выполнено требование биллинга

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 403 — Аккаунт не имеет доступа (требуется подписка или пользователь заблокирован). Отключённые модели также отклоняются до вызова upstream. Уже принятые запросы и задачи продолжают выполняться.

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 429 — Достигнут лимит запросов или расходов

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 502 — Сбой upstream-провайдера

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

### 503 — Сервис генерации или сервис биллинга временно недоступен

**application/json**

Schema: `GenerationError` (`#/components/schemas/GenerationError`)

## Schema definitions

### GenerationError

`#/components/schemas/GenerationError`

```json
{
  "type": "object",
  "description": "Конверт ошибок, совместимый с OpenAI.",
  "properties": {
    "error": {
      "type": "object",
      "required": [
        "message",
        "type"
      ],
      "properties": {
        "message": {
          "type": "string"
        },
        "type": {
          "type": "string",
          "enum": [
            "invalid_request_error",
            "server_error"
          ]
        },
        "param": {
          "type": "string",
          "nullable": true
        },
        "code": {
          "type": "string"
        }
      }
    }
  }
}
```

### ImageGenerationAccepted

`#/components/schemas/ImageGenerationAccepted`

```json
{
  "type": "object",
  "required": [
    "task_id",
    "status",
    "kind",
    "outputs"
  ],
  "properties": {
    "task_id": {
      "type": "string",
      "description": "ID задачи для опроса."
    },
    "status": {
      "type": "string",
      "enum": [
        "queued"
      ]
    },
    "kind": {
      "type": "string",
      "enum": [
        "image"
      ]
    },
    "outputs": {
      "type": "array",
      "items": {
        "oneOf": [
          {
            "type": "string",
            "format": "uri"
          },
          {
            "type": "object",
            "properties": {
              "url": {
                "type": "string",
                "format": "uri"
              },
              "watermark_url": {
                "type": "string",
                "format": "uri",
                "nullable": true,
                "description": "Optional watermarked version of this image."
              },
              "b64_json": {
                "type": "string"
              }
            }
          }
        ]
      },
      "description": "Пусто до успешного завершения задачи."
    }
  }
}
```
