# Create a media generation task

Source: [Create a media generation task](<https://docs.gptunnel.ru/en/creative-lab/create-task/>)

<a id="_top"></a>
> **Note: Authentication**
>
> You need an API key to send requests. See [How to start?](<https://docs.gptunnel.ru/en/>)

<a id="creation-of-the-task"></a>
## Creation of the task

`POST https://gptunnel.ru/api/v2/media/tasks`

Use this endpoint to create a task for any media model. The response contains a task object with its ID and status. Save `id` to [poll the task](<https://docs.gptunnel.ru/en/creative-lab/get-task/>) and match it to the [webhook notification](<https://docs.gptunnel.ru/en/creative-lab/webhooks/>). The webhook sends task data when the task finishes.

### Request body

| Parameter | Type | Description |
| --- | --- | --- |
| `model` (required) | `string` | Model Identifier from GET /media/models |
| `prompt` | `string` | Text for generation. The prompt field in the model card specifies whether the field is required (required, optional, none). If max\_length or max\_bytes are specified, check the text length in UTF-8 characters or bytes respectively. |
| `params` | `object` | Generation parameters according to the schema of the selected model (resolution, duration, etc.) |
| `inputs` | `object` | Input files grouped by role in an object such as {role: \[url, ...\]}. Use public URLs or inline data: URLs. Each inline file can be up to 20 MB. |
| `webhook_url` | `string` | URL to which we will send the task object after completion. See Webhooks section |
| `idempotency_key` | `string` | Idempotency key: a repeat request with the same key returns an already created task, not a new one |
| `wait` | `boolean` | If true — wait for completion up to 30 seconds, then return the current task status. Default: false |

> **Note: How request parameters are validated**
>
> Within `params`, the API ignores keys the model does not recognize and keys whose values the model sets itself. The request proceeds and the response lists those keys and the reasons in `ignored_params`.
>
>
>
> An invalid value for a parameter the model accepts returns HTTP `400`. For example, if the maximum `duration` is 10, passing `duration: 999` returns an error.
>
>
>
> Top-level fields (`model`, `prompt`, `webhook_url`, `idempotency_key`, and `wait`) and roles in `inputs` are validated strictly. An unknown top-level field returns HTTP `400` with `code: 3`. Its name appears in `details`. Check the request schema when migrating from v1.
>
>
>
> Use the [price endpoint](<https://docs.gptunnel.ru/en/creative-lab/price/>) to validate the request before being charged. It also returns `ignored_params`.

<a id="parameter-wait"></a>
### Parameter `wait`

By default (`wait: false`), task creation returns immediately with status `queued` or `running`. Get the result by polling `GET /media/tasks/:id` or receiving a webhook.

With `wait: true`, the connection stays open until the task reaches `done` or `failed`, or for approximately **30 seconds**. If the task is still `queued` or `running` at the end of that window, the response contains its current state. Poll `GET /media/tasks/:id` or wait for the webhook to get the final result.

> **Note: After waiting, the task can still be running**
>
> `wait: true` is useful for fast models. For video and other long tasks, rely on `webhook_url` or polling because the task is unlikely to finish within the waiting window.

<a id="idempotency-key"></a>
### Idempotency Key

Set `idempotency_key` to avoid creating a duplicate task or paying twice when retrying after a network timeout. Retrying with the same key and request body returns the original task.

If you repeat the request with the same `idempotency_key`, but with a modified request body, an error will be returned `409` (`code: 23`).

<a id="example-request"></a>
### Example request

Set the environment variable `GPTUNNEL_API_KEY`. The request creates a paid task. To know the cost in advance, send the same `model`, `prompt` and `params` in [calculation of price](<https://docs.gptunnel.ru/en/creative-lab/price/>). For a new generation, set a new `idempotency_key`. If you repeat the same operation, keep the old key and body.

<a id="tab-panel-0-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
    'model': 'kling-v3',
    'prompt': 'a red fox running through snow, cinematic',
    'params': {'resolution': '1080p', 'duration': 5, 'aspect_ratio': '16:9'},
    'idempotency_key': 'fox-snow-001',
}
request = Request(
    'https://gptunnel.ru/api/v2/media/tasks',
    method='POST',
    headers={'Authorization': os.environ['GPTUNNEL_API_KEY'], 'Content-Type': 'application/json'},
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=30) as response:
    task = json.load(response)
print(task['id'], task['status'])
```

<a id="tab-panel-0-1"></a>
**cURL**

```bash
curl --request POST \
  --url 'https://gptunnel.ru/api/v2/media/tasks' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "kling-v3",
    "prompt": "a red fox running through snow, cinematic",
    "params": { "resolution": "1080p", "duration": 5, "aspect_ratio": "16:9" },
    "idempotency_key": "fox-snow-001"
  }'
```

<a id="tab-panel-0-2"></a>
**JavaScript (Node.js)**

```javascript
const key = process.env.GPTUNNEL_API_KEY
if (!key) throw new Error('Set GPTUNNEL_API_KEY')

const response = await fetch('https://gptunnel.ru/api/v2/media/tasks', {
  method: 'POST',
  headers: { Authorization: key, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'kling-v3',
    prompt: 'a red fox running through snow, cinematic',
    params: { resolution: '1080p', duration: 5, aspect_ratio: '16:9' },
    idempotency_key: 'fox-snow-001',
  }),
})
if (!response.ok) throw new Error(await response.text())
const task = await response.json()
console.log(task.id, task.status)
```

Save it `id` from the response for [task polling](<https://docs.gptunnel.ru/en/creative-lab/get-task/>). To get [notification](<https://docs.gptunnel.ru/en/creative-lab/webhooks/>), add to the field `webhook_url` your HTTPS webhook address.

<a id="file-uploads"></a>
### File uploads

Pass files in `inputs` under the roles listed in the model schema (`inputs[].role`). Each role takes an array of URLs.

```json
{
  "model": "kling-v3",
  "prompt": "animate this photo",
  "inputs": { "first_frame": ["https://example.com/photo.jpg"] }
}
```

Replace `https://example.com/photo.jpg` with a direct public URL to your image.

File can be delivered as `data:`-URL. Below is a body fragment; replace the reduced line with full file contents in Base64:

```json
{
  "inputs": { "first_frame": ["data:image/png;base64,iVBORw0KGgo..."] }
}
```

The limits are 20 MB per file and 50 MB for the entire request body. An invalid or unreadable file returns `code: 25` immediately. The service creates no task and makes no charge.

<a id="example-response"></a>
### Example response

```json
{
  "code": 0,
  "id": "6a61e021a6e77553a989c41d",
  "model": "kling-v3",
  "status": "running",
  "prompt": "a red fox running through snow, cinematic",
  "params": { "resolution": "1080p", "duration": 5, "aspect_ratio": "16:9" },
  "price": 210,
  "result": [],
  "created_at": 1784799265
}
```

If you send `webhook_url`, the response also includes a `webhook` object with the destination URL and delivery status. See [task object fields](<https://docs.gptunnel.ru/en/creative-lab/get-task/#fields-of-task-object>).

<a id="if-the-model-has-been-removed-from-service"></a>
### If the model has been removed from service

If the provider retires the requested model and the catalog lists a replacement, the API creates the task on that replacement. The request works with the same code and is billed at the requested model’s rate.

Check the response headers to see which model ran the task.

### Response headers

| Parameter | Type | Description |
| --- | --- | --- |
| `Deprecation` | `string` | Always true. Indicates that the requested model has been retired. |
| `Sunset` | `string` | Retirement date of the requested model, in HTTP-date format. |
| `x-model-requested` | `string` | ID of the model you requested. Its rate is used for billing. |
| `x-model-served` | `string` | ID of the model that runs the task. |

The task object’s `model` remains the ID you requested. The `x-model-served` response header identifies the replacement used. The creation response includes a `warnings` entry with `code: "DEPRECATED_MODEL"`. If the model has no replacement, task creation returns `410` with `code: 21`. See [Deprecated models](<https://docs.gptunnel.ru/en/getting-started/deprecated-models/>).
