# Images and video

Make images and videos with the same key and balance as text, through tasks you create, follow and download.

Image and video models work differently from text ones: a generation takes from seconds to many minutes, so you create a **task** and come back for its result. Each model has its own settings, described by the API, and its own price per image, per second of video or per request. The price is taken from your balance when the task is created, and what the task did not cost comes back when it ends. The results are kept for up to `keep_hours`, for you to download.

## How it works

1. List the models with `GET /v1/media/models`. No key needed.
2. Read one model’s settings with `GET /v1/media/models/{id}`: `input` is a JSON Schema of what it takes, with its prices.
3. Ask what your settings would cost with `POST /v1/media/quote`. Nothing is taken.
4. Create the task with `POST /v1/media/tasks`. Its price is held from your balance.
5. Wait for it: `GET /v1/media/tasks/{id}?wait=60` answers as soon as the task ends, or after 60 seconds.
6. Download each result with `GET /v1/media/tasks/{id}/files/{n}`, before `expires_at`.
7. If you want, erase the task with `DELETE /v1/media/tasks/{id}`: the generation service is asked to delete its settings and results at once instead of when they expire.

Every call is described in the [Tasks API](https://unaligned.pw/docs/media-tasks.md); files you send and receive are in the [Files API](https://unaligned.pw/docs/media-files.md).

A program written for an OpenAI SDK can also make an image with `client.images.generate(...)`: see [the OpenAI format](https://unaligned.pw/docs/openai.md#images).

These models can also be used without writing code, from the [Studio](https://unaligned.pw/studio) on the site once you are signed in; a few modes are available through the API only.

## Example

python:

```python
import os, requests

api = requests.Session()
api.headers["Authorization"] = f"Bearer {os.environ['UNALIGNED_KEY']}"
base = "https://api.unaligned.pw/v1/media"

# Create the task. The same Idempotency-Key never makes a second one.
task = api.post(
    f"{base}/tasks",
    headers={"Idempotency-Key": "poster-0001"},
    json={
        "model": "acme/sketch-1/text-to-image",
        "input": {"prompt": "A lighthouse at dusk, oil painting"},
        "max_price": 0.05,
    },
).json()

# Wait for it to end: each call waits up to 60 s.
while task["status"] in ("queued", "running"):
    task = api.get(f"{base}/tasks/{task['id']}", params={"wait": 60}).json()

if task["status"] == "succeeded":
    for f in task["files"]:
        r = api.get(f"{base}/tasks/{task['id']}/files/{f['index']}")
        with open(f"result-{f['index']}.png", "wb") as out:
            out.write(r.content)
    # Erase it now rather than when it expires.
    api.delete(f"{base}/tasks/{task['id']}")
else:
    print(task["error"]["message"], "charged:", task["price"])
```

node:

```js
import { writeFile } from "node:fs/promises";

const base = "https://api.unaligned.pw/v1/media";
const headers = { Authorization: `Bearer ${process.env.UNALIGNED_KEY}` };

// Create the task. The same Idempotency-Key never makes a second one.
let task = await fetch(`${base}/tasks`, {
  method: "POST",
  headers: { ...headers, "Idempotency-Key": "poster-0001" },
  body: JSON.stringify({
    model: "acme/sketch-1/text-to-image",
    input: { prompt: "A lighthouse at dusk, oil painting" },
    max_price: 0.05,
  }),
}).then((r) => r.json());

// Wait for it to end: each call waits up to 60 s.
while (task.status === "queued" || task.status === "running") {
  task = await fetch(`${base}/tasks/${task.id}?wait=60`, { headers }).then((r) => r.json());
}

if (task.status === "succeeded") {
  for (const f of task.files) {
    const r = await fetch(`${base}/tasks/${task.id}/files/${f.index}`, { headers });
    await writeFile(`result-${f.index}.png`, Buffer.from(await r.arrayBuffer()));
  }
  // Erase it now rather than when it expires.
  await fetch(`${base}/tasks/${task.id}`, { method: "DELETE", headers });
} else {
  console.log(task.error.message, "charged:", task.price);
}
```

## Statuses

| Status | What it means |
| --- | --- |
| `queued` | Accepted, not started yet. A task still being created at the generation service is `queued` too. If its creation got no answer from the generation service, it ends `failed` with `lost` about ten minutes after it was created, and everything held is given back. |
| `running` | Being generated. |
| `succeeded` | Done. Its `files` can be downloaded until `expires_at`, then they are gone. |
| `failed` | Ended without a result. `error` says why, `price` what it cost. |

A task that has started can’t be stopped or cancelled: `DELETE` on a task that hasn’t ended answers `409`.

## Why a task fails

| error.code | What happened |
| --- | --- |
| `invalid_input` | The model refused these settings. |
| `content_rejected` | The model refused this content. |
| `generation_failed` | The generation failed, or it ended with nothing to deliver. |
| `timeout` | The generation took too long. |
| `lost` | We could not learn what became of the task: its answer was lost when it was created, the generation service stopped knowing it, or it was still unfinished a day after its deadline. Everything held is given back. |

## What a task costs

- The price depends on the model and on the settings that change it: the variant (`variant_fields`, such as a resolution) and the number of units (`quantity_field`, such as a duration). A quote gives the exact amount.
- When the task is created, its price is taken from your balance. If the balance doesn’t cover it, the task is refused with a `402` and nothing runs. Your balance never goes below zero for a task.
- When the task ends, it is settled at what it really cost, never more than what was held, and the rest comes back to your balance. `price` on the task is then what you paid, and `settled` is true.
- A failed task usually costs nothing. But a model can charge for content it refuses (`content_rejected`): `price` then says what was taken.
- A `lost` task costs nothing: everything held comes back.
- `max_price` caps a task: above it, the task is refused with a `409` `price_changed` and nothing is taken. The price can move between a quote and the task.

A key with a balance of its own ([Reseller API](https://unaligned.pw/docs/resellers.md)) pays its tasks from that balance. See [Billing](https://unaligned.pw/docs/billing.md) for the rest.

## Limits

- Each API key can have 10 tasks unfinished at once by default. The site, signed in, counts as one more caller with its own limit.
- A key makes as many quotes and new tasks a minute, together, as it starts text requests: 200 by default, or what you set for the key.
- Downloads have a minute of their own with the same number, and a key can have 4 under way at once.
- Uploads: 60 files an hour and 4 at once per key, and 600 an hour and 16 at once for all the keys of an account together. A failed upload counts in its hour too.
- Files you upload: images 10 MiB at most, audio and video 90 MiB by default.
- The settings of a task are 256 KiB at most, and their text 30,592 bytes at most.
- Going over a limit returns a `429` with a `Retry-After` header.

## Content rules

Whatever the model, uncensored ones included, and whether through the API or the Studio, these are never allowed:

- Sexual content involving anyone who is, or appears to be, under 18, drawn or generated included.
- A photo of a real child as input.
- An intimate or sexualised depiction of a real, identifiable person without their consent, and “undressing” a real person’s photo.
- Using a person’s likeness to harass, defraud, impersonate or mislead.
- Anything unlawful.

A request that breaks these rules is not allowed: it may be refused, and the account may be suspended or closed.

Before the settings of a quote or a task are sent to the generation service, our own content filter reads every text of them: every string, whatever its field, the words of a link included. Only a `negative_prompt` given as plain text and the references to your uploaded files (`media://…`) are not read. It looks for two things only: child sexual exploitation, and terrorism.

- A request it refuses gets a `400` `content_refused`. Nothing is sent and nothing is charged.
- The text of a refused request is kept, with your account, the key and the model, where we can read it.
- After 10 refused requests in an hour, the account’s quotes and new tasks are refused with a `429` until fewer than 10 refusals fall within the last hour: an hour at most. Uploads, downloads and reading tasks go on.
- Text longer than the filter reads whole is refused with a `400`, never read in part.
- If the filter can’t answer, the request gets a `503` and nothing is sent.

> **Warning:** Unlike a text request, a task’s settings and results are kept by the generation service, which we ask to keep them no longer than `keep_hours`: the results wait there for you. Choose a short one, or erase the task once you have its files.

## What is kept, and for how long

| What | For how long |
| --- | --- |
| A task’s settings and results, at the generation service | We ask it to keep them for up to `keep_hours`: 24 hours by default, less if you ask. `DELETE` asks it to erase them sooner; if it does not, they go at their normal expiry. The results can be downloaded until `expires_at`, then they are gone. |
| A file you upload | Until its `expires_at`. |
| The task’s record on our side: model, status, price, dates, file types and sizes | 30 days after it ended, then deleted. No setting or prompt is in it. After `DELETE`, no route shows it any more. |
| A request the filter refused | Its text is kept, with the account, key and model. |

## Giving a model a file

Some models take an image, a video or a sound: their `files` field says so. A file setting takes either a public `https` link, or the `ref` of a file you uploaded with `POST /v1/media/files` ([Files API](https://unaligned.pw/docs/media-files.md)), such as `media://5a1ad081-…`.

Inline `data:` URIs are refused with a `400`, wherever they are in the settings: upload the file instead. A link’s words are read by the content filter like any other text.

## Who sees a task

A key sees the tasks and the files it created, and no other. Your account, signed in on the site, sees those of all its keys. If you issue keys to your own customers ([Reseller API](https://unaligned.pw/docs/resellers.md)), you see the tasks their keys create.
