# JenVid media API (skill for AI coding tools)

Generate images, video and audio with one HTTP API. This file is self-contained: read it, then call the API.
Machine-readable spec: `https://jenvid.com/openapi.yaml`. Human docs: `https://jenvid.com/docs`.

- **Base URL:** `https://jenvid.com` (the site origin, without `/v1`). Every path below starts with `/v1/...` and is appended to it, for example `https://jenvid.com/v1/media/generate`.
- **Auth:** `Authorization: Bearer $JENVID_API_KEY` on every call (`X-API-Key: $JENVID_API_KEY` is accepted too). Keys look like `gj_live_<prefix>_<secret>` and are created in the
  API console (`https://jenvid.com/console/keys`). Never put a key in client-side code, URLs or logs.
- **Money:** everything is priced in credits, shown as exact decimal strings with six decimals (`"0.250000"`). `$1 = 10 credits`.
  Credits are held when a task is accepted, charged when it succeeds and refunded when it fails or is cancelled.
  Credits are valid for 30 days from when they are added (the ones that expire first are spent first); `GET /v1/balance` shows `expiring[]` and `next_expiry`.
- **Scopes:** a key needs `generate` to submit and cancel, `read` to poll tasks and fetch the notify secret, `assets` for uploads.
  A key with only `generate` can submit but gets `403 forbidden` when polling, so tick both when you create it.
- **Format:** JSON in, JSON out, UTF-8 (errors too: an unknown `/v1` path is a JSON `404 invalid_request`). Request bodies are limited to 256 KiB. Every response has an `X-Request-Id` header.

## 1. Discover models

```
GET /v1/media/models            # optional ?type=image|video|audio; needs a key; full list, no cursor
GET /v1/models/{id}/pricing     # price range and a flat `options` list (one value of one input, others at defaults and the lowest count; per billing unit for per_second/per_megapixel/per_unit models, otherwise the total for one output; `price: null` = unsupported), plus `billing_unit`, `version`, `complete` and an always-empty deprecated `lines`
GET /api/public/models          # no key needed: published models and prices, without `params`
```

Without a key, browse `https://jenvid.com/models`; each model page shows its parameters and a ready-made request.

Each model has `id`, `name`, `output_group`, `pricing` (`from`, `unit` = `per_image|per_second|per_megapixel|per_unit|per_request`, `options` = `{version, complete, dimensions[], combinations[]|null}` with exact decimal-string totals and `supported:false, total:null` for unsupported combinations; `complete: false` means only `from` is known, so ask `POST /v1/quotes`; `quote_required` is false only when nothing can change the total; a variable output count makes it true, and a per-image price stays per image, so multiply by the count), `price_range` (min..max credits at default options) and `params`: the list of
accepted parameters for its default mode. A param is `{key, label, type, required, default?, min?, max?, options?[{code,label}]}`.
Send **option codes** (not labels) for enum params. File params (`type: file` / `file[]`) take an https URL or
`{"asset_id": "<uuid>"}` of an asset you uploaded (`POST /v1/assets/uploads`, then `POST /v1/assets/{id}/complete`).
Upload: `POST /v1/assets/uploads` with `{mime, bytes}` returns `upload: {method, url, headers, auth, expires_at}`. `PUT` the raw file
bytes to `upload.url` with exactly `upload.headers`; when `upload.auth` is `same_as_request` (usual) also send
`Authorization: Bearer <your key>`, when it is `none` the URL is pre-signed and must get no Authorization header. A file must match
the slot: image slots take images only, video slots video, audio slots audio (otherwise 422 `INVALID_INPUT`, nothing is charged).
`modes` lists other modes (for example image-to-video) with their own `params`; pass one as `mode` in the generate call.

## 2. Generate

```
POST /v1/media/generate
Content-Type: application/json
Idempotency-Key: <unique string, optional but recommended>   # 1-200 chars of A-Za-z0-9._:-

{
  "model": "gpt-image-2.6-flare-2k",
  "prompt": "a lighthouse at dusk, film photo",
  "params": {"aspect_ratio": "16:9"}
}
```

Optional: add `"notify_url": "https://your-server.example/hooks/jenvid"` (your own public https endpoint) to receive a callback.

- The model id and params above are a real published model of this site; other models have other params, so read them from `/v1/media/models` first.
- A param you leave out uses the model's default. Video models usually need `duration`, `resolution` and `aspect_ratio`, for example `"model": "magi-2-1080p-12s", "params": {"duration": 6, "resolution": "1080p", "aspect_ratio": "16:9"}`.
- `model` required. `prompt` is a shortcut for the model's prompt param. `params` holds every other value.
- `mode` (optional): capability such as `i2v`; the model default otherwise.
- `strategy` and `custom_line_ids` are deprecated and ignored (also on key create/update, where they are accepted and discarded); do not send them.
- Sending `prompt` to a model that has no prompt field returns `422 invalid_request` ("This model does not take a prompt").
- Every key must be declared by the model. An undeclared key (a typo such as `resoultion`, or an unknown top-level key) returns `422 unknown_input` with `error.details` `{field, suggestion?}`; nothing is held or charged. The suggestion is a hint: fix the key yourself. This also applies to keys inside `object` params: an undeclared child is rejected as `field.child` (earlier such children were silently dropped). `@image1`/`@video1`/`@audio1` mentions do not exist in the API: send plain prompt text (the studio's request-local, per-kind `@imageN`/`@videoN`/`@audioN` labels are not parsed here).
- `notify_url` (optional): public https URL (port 443 or 8443). Receives the final task body.
- Response `202` (with a `Location` header): `{"task_id": "<uuid>", "state": "queued", "credits_held": "0.250000"}`.
- Repeating a request with the same `Idempotency-Key` and body returns the original task (`200`, `Idempotent-Replayed: true`);
  the same key with a different body is `409 invalid_request`. Always send a key when your code may retry.
- The older resource-style API (`POST /v1/generations` with `inputs`, then `GET /v1/generations/{id}` and `/result`) keeps working, but new code should use the media API described here.

## 3. Poll or receive a callback

```
GET /v1/media/tasks/{task_id}
```

```json
{
  "task_id": "…",
  "state": "queued | running | succeeded | failed | cancelled",
  "is_final": false,
  "progress": 40,
  "outputs": [{ "url": "https://jenvid.com/o/…", "type": "image", "url_expires_at": "2026-10-26T10:00:00.000Z", "file_expires_at": "2026-10-26T10:00:00.000Z", "expires_at": "2026-10-26T10:00:00.000Z", "width": 1024, "height": 1024 }],
  "error_code": null,
  "error_message": null,
  "cancellation": null,
  "credits": { "held": "0.250000", "captured": "0.000000", "refunded": "0.000000", "net": "0.000000" }
}
```

Poll **every 5 seconds** until `is_final` is true. On `succeeded`, each `outputs[].url` works without signing in until
`url_expires_at` (UTC, ISO 8601), which for generated files is the same moment as `file_expires_at`: 24 hours after the
output was completed (generated files are kept for 24 hours only). Polling returns the same URL and does not extend it. `expires_at` is a deprecated alias of `file_expires_at`.
Anyone with the link can download the file, so treat it as a secret (do not log or share it); disabling an API key does not revoke
links already issued. Download what you need before it expires: afterwards the link answers `410` with `error.code` `OUTPUT_EXPIRED`.
Uploads are kept for 30 days.
Cancel with `POST /v1/media/tasks/{task_id}/cancel` (scope `generate`; the response's `cancellation` is a plain string: `cancelled`, `requested` or `not_cancellable`; the additive `cancellation_details` is the object `{state, requested_at}`).
`requested` is not a cancellation: the job may still finish and be charged, and the request alone does not release credits (the final outcome decides). While a request is pending, polling the task (a GET) shows `cancellation` and `cancellation_details` as the object `{"state": "requested", "requested_at": "…"}`; `cancellation` is `null` when nothing was requested.

`notify_url` callbacks are separate from the account webhooks in the console (`generation.*` events, other retry schedule). If you passed `notify_url`, the same body is POSTed to it once the task is final: immediately, then retried after 10 s, 30 s and
60 s until you answer 2xx. Verify the signature before trusting it. Headers: `JenVid-Signature: v1=<hex>`,
`JenVid-Timestamp`, `JenVid-Event-Id`, `JenVid-Event-Type: media.task`. The signature is HMAC-SHA256 over
`"<timestamp>.<raw body>"` with the secret from `GET /v1/media/notify-secret`; reject timestamps more than 300 s off and ignore
event ids you have already handled.

## 4. Errors

Errors are `{"error": {"code", "message", "retryable", "request_id"}}` with an HTTP status. **Retry only when `retryable` is true**
(wait for `Retry-After` if present, otherwise back off 5 s, 15 s, 45 s); permanent errors will fail the same way again.

| code | HTTP | retry | what to do |
|---|---|---|---|
| `invalid_request` | 400/404/409/413/415/422 | no | fix the request; `error.details.errors[]` lists bad params |
| `unknown_input` | 422 | no | a key the model does not declare; see `error.details.field` |
| `unauthorized` | 401 | no | check the key |
| `insufficient_balance` | 402 | no | the user must redeem a code in the console |
| `quota_exceeded` | 402 | no | the key budget or account limit is used up |
| `forbidden` / `model_not_allowed` | 403 | no | key lacks the scope or model |
| `ip_not_allowed` | 403 | no | call from an allowed address (the message names the one we saw); nothing was charged |
| `key_config_error` | 403 | no | the key's configuration does not allow this model; check it in the console |
| `model_not_found` | 404 | no | use an id from `/v1/media/models` |
| `content_policy_violation` | 422 | no | change the prompt or inputs |
| `rate_limited` | 429 | yes | slow down |
| `channel_unavailable` | 503 | yes | the model is temporarily unavailable; retry later |
| `upstream_error` | 502 | yes | the model failed; resubmit |
| `timeout` | 504 | yes | resubmit |
| `server_error` | 500 | yes | resubmit with the same `Idempotency-Key` |

A task that fails after being accepted ends with `state: "failed"` and the same `error_code` values; its credits are refunded.
Default limits: 60 requests per minute per key and 120 per minute per account. Successful responses and 429s carry
`X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (unix seconds); a 429 also has `Retry-After`. Other errors
(401, 402, 403, 422) carry only `X-Request-Id`. Every response has `JenVid-Api-Version`.

## 5. Manage keys (optional)

A **management key** (create one in the console) can call `GET/POST /v1/keys` and `GET/PATCH/DELETE /v1/keys/{id}` for its own
account, and nothing else. New keys can never exceed the creating key (scopes, models, budget, rate limit, IP range, expiry).
`GET /v1/keys` returns the full list (no cursor). There is no rotate call: to rotate without downtime, `POST /v1/keys` for a
new key, deploy it, then `DELETE /v1/keys/{id}` the old one. Useful fields: `label`, `scopes` (`generate`, `read`, `assets`, `redeem`), `budget` (credits string), `rate_limit_per_minute`,
`model_allowlist`, `excluded_models`, `ip_allowlist` (IPs or CIDR ranges, IPv4 and IPv6), `expires_at`.
The secret of a new key is returned once in `key`.

## Minimal client

```python
import os, time, uuid, requests

BASE = "https://jenvid.com"
H = {"Authorization": f"Bearer {os.environ['JENVID_API_KEY']}"}

def generate(model, prompt, **params):
    r = requests.post(f"{BASE}/v1/media/generate", headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                      json={"model": model, "prompt": prompt, "params": params}, timeout=30)
    r.raise_for_status()
    task = r.json()["task_id"]
    while True:
        t = requests.get(f"{BASE}/v1/media/tasks/{task}", headers=H, timeout=30).json()
        if t["is_final"]:
            if t["state"] != "succeeded":
                raise RuntimeError(f"{t['error_code']}: {t['error_message']}")
            return [o["url"] for o in t["outputs"]]
        time.sleep(5)
```

## Rules for agents

- Pick the model from `/v1/media/models`; do not guess ids or parameter names.
- Check `price_range` / `/pricing` before expensive requests and tell the user the cost in credits.
- Use one `Idempotency-Key` per logical job and reuse it on retries, so a retry never charges twice.
- There is no endpoint to list tasks: store each `task_id`. If you lost one, repeat the submit with the same `Idempotency-Key` to get it back.
- Never log or echo the API key or signing secret. Never retry non-retryable errors.

## Use through MCP

Assistants that support the Model Context Protocol do not need to write HTTP calls: JenVid runs a remote MCP server at
`https://jenvid.com/mcp` (Streamable HTTP) with the same key in the same header (`Authorization: Bearer $JENVID_API_KEY`).
Tools: `list_models`, `get_model`, `generate`, `get_task` (waits up to 50 s per call), `cancel_task`, `get_balance`.
They follow the same rules, limits and prices as the endpoints above. Setup for each client: `https://jenvid.com/docs/mcp`.
