---
title: "Advanced usage & API reference · AGI Plan"
url: https://agiplan.dev/en/docs/advanced
description: "For people writing their own code: every request and response header, how to control output caps and routing, the full image and video APIs, and exactly how billing works."
language: en
markdown: https://agiplan.dev/en/docs/advanced.md
---

[← Back to home](https://agiplan.dev/en)

Developer docs

# Advanced usage & API reference

For people writing their own code: every request and response header, how to control output caps and routing, the full image and video APIs, and exactly how billing works.

**Last updated**

2026-11-23

## Request headers

All three protocol endpoints (`/v1/chat/completions`, `/v1/messages`, `/v1/responses`) accept these headers. Names are case-insensitive. Everything except `Authorization` is an optional preference: **out-of-range values are clamped, never rejected**.

| Header | Value | Effect |
| --- | --- | --- |
| `Authorization` | `Bearer ap_live_…` | Required on every `/v1/*` endpoint. See Authentication in the quick start |
| `X-AGIPlan-Difficulty` | decimal 0–1 | Overrides the difficulty estimate for this request. Only affects how `auto`, `auto-fast` (it sets the minimum tier), `auto-cn` and custom models pick a tier; ignored when you name a model directly |
| `X-AGIPlan-First-Byte-Timeout-Ms` | ms, clamped to 5,000 – ceiling | How long to wait for the first byte before abandoning a route and trying the next (switching before the first byte never gives you half an answer). The ceiling grows with input: 60 s, plus 15 s per 50K input tokens, max 180 s |
| `X-AGIPlan-Scene` | `web` / `agent` / `batch` / `chat` | Tells the scheduler what kind of request this is: `web` means someone is watching for the first token, so speed wins, and a short request (under 8K input tokens) waits at most 30 s for the first byte before switching routes unless you set a duration with the header above; `agent` is a coding agent, so stability wins and the quality tolerance is tightest; `batch` means nobody is waiting, so cost wins; `chat` balances the three. Omit it and we infer the scene from the request (streaming or not, number of tools, turns, client identifier); unknown values are ignored. Affects which model `auto` picks and how we choose among the routes serving the same model. **It stacks with the key's routing preference**: the scene sets the baseline, and the key's preference (speed / cost / cache) shifts it by a bounded amount; an Auto preference leaves it unchanged |
| `X-AGIPlan-Strict-Max-Tokens` | `1` / `true` / `yes` / `on` | Require a strict output cap: only route to lines that honour `max_tokens`; lines with the `loose_max_tokens` capability are skipped. See Output cap below |
| `anthropic-version` | e.g. `2023-06-01` | Send it as the official SDK does on `/v1/messages` |
| `anthropic-beta` | comma-separated | Forwarded to Claude lines through an allow-list; anything not on it is removed and listed in `x-agiplan-dropped-params` as `anthropic-beta:name` |

## Response headers

Successful responses from the three text-protocol endpoints (`/v1/chat/completions`, `/v1/messages`, `/v1/responses`) carry these headers; refusals have no trace or actual model (nothing ran) but still carry the three quota headers, and a 429 also carries `retry-after` (rules in the table below). **Image endpoints** carry only `x-agiplan-trace`, `x-agiplan-model-actual`, `x-agiplan-cu` and (after a switch) `x-agiplan-failover` on success — **no quota headers and no `x-agiplan-billed-group`**. **The video endpoints carry no `x-agiplan-*` headers at all**: report problems with the job `id`, and read the charge from the job's `cu`.**When reporting a problem, include `x-agiplan-trace`** — it pulls up the full routing trace for that call (see Traces in the quick start).

| Header | Example | Meaning |
| --- | --- | --- |
| `x-agiplan-trace` | `tr_9f3c…` | Trace ID of this call |
| `x-agiplan-model-actual` | `gemini-3.8-flash` | The model that actually served the request. With `auto`, a custom model, or a capability switch it can differ from what you sent |
| `x-agiplan-model-requested` | `gemini-3.8-flash` | Only when **the model you named was swapped**: the model you named (the previous row is the one that served). See Capability flags |
| `x-agiplan-model-swap` | `missing:tools` | Comes with the previous header: which capability the named model lacked |
| `x-agiplan-billed-group` | `fast` | Which tier's quota the call was billed against |
| `x-agiplan-failover` | `true` | A route switch happened before the first byte. Present only when it happened (a switch after the stream opened but before any content can't change headers already sent; it shows only in the usage trace) |
| `x-agiplan-quota-session` / `-week` / `-month` | `remaining=72%; resets=2026-10-11T08:00:00.000Z` | Remaining share and reset time of each quota window. Also sent on 429 so you can decide how long to back off |
| `x-agiplan-dropped-params` | `temperature,content[].image_url` | Parameters that were dropped or downgraded. We never swallow parameters silently |
| `x-agiplan-max-tokens-default` | `32000` | You sent no `max_tokens` (`max_output_tokens` on Responses); this is the cap we set for you, exactly as sent to the model (see Output cap below) |
| `x-agiplan-cu` | `51.462` | Image endpoints: CU charged for this call |
| `x-agiplan-demo` | `true` | Only on responses from the test model test-nl-astra: this reply came from the local generator, not a model — 0 CU |
| `retry-after` | `30` | On 429: suggested wait in seconds. Same rule on all five entry points (three text protocols, images, video): when a quota window blocks you, the seconds until it resets; when concurrency is full, `2`; when every model service that can take the request is full (`upstream_busy`), the shortest wait those services gave (`10` if none, at most `60`); a 429 that can't say when it clears carries none. Result-link rate limits always send `60` |

## Output cap (max_tokens)

- **Default cap when omitted**: Chat without `max_tokens` / `max_completion_tokens` and Responses without `max_output_tokens` default to a declared 64000 (so reasoning models and long answers aren't choked by a tiny fixed cap) — output is reserved at 16000, and the cap sent to the model is that reservation plus the per-request overrun allowance, narrowed to fit the chosen route's context window; if a route rejects a cap that large, we lower it once and resend (using the route's reported limit, or 4096). The value sent appears in `x-agiplan-max-tokens-default`. On Messages `max_tokens` is required; if omitted we fill in 4096.
- **When the cap we set for you is hit** (Responses without `max_output_tokens`): the stream ends with `response.completed` whose `status` honestly says `incomplete` (with `incomplete_details`) rather than `response.incomplete` — the cap is ours, and Codex treats the latter as a dropped stream and resends the same request five times. If you set `max_output_tokens` yourself you get `response.incomplete` as OpenAI sends it.
- **Reserved by the cap, billed by actual usage.** A call reserves quota for the worst case (input + max_tokens) and settles on the usage the model reports, refunding the difference. An oversized cap only holds extra quota while the call runs; it never costs more.
- **Some lines do not guarantee `max_tokens`**: the model may produce more than the cap and still report a normal finish. These lines carry `loose_max_tokens` in `capabilities` on `/v1/models`, shown as “Soft max_tokens” in the console. **They are routed normally and output beyond the cap is billed at actual usage.**
- **When you need a strict cap** (token-budgeted jobs, code that depends on where output stops, batch work), send `X-AGIPlan-Strict-Max-Tokens: 1`: routing skips `loose_max_tokens` lines, and `auto` or tier names move to lines that honour the cap. If you name a model that only has such lines, or no tier we can lift to has a line that honours the cap, you get 400 `strict_max_tokens_unavailable` instead of a silently substituted model — **retrying will not change the result**; drop the header or pick another model / tier.

```
curl https://agiplan.dev/v1/chat/completions \
  -H "Authorization: Bearer $AGIPLAN_KEY" \
  -H "X-AGIPlan-Strict-Max-Tokens: 1" \
  -H "Content-Type: application/json" \
  -d '{"model":"auto","max_tokens":200,"messages":[{"role":"user","content":"Summarise this code in three sentences"}]}'
```

Require a strict output cap

## Capability flags

Each model in `GET /v1/models` has a `capabilities` array. **Routing enforces it**: if a request needs a capability (for example it has `tools`) and a line lacks it, that line is never chosen; if you name a model without it (judged by the routes that can take requests right now — a capability only suspended routes offer doesn't count, and the model you are switched to always has a working route), the gateway doesn't fail the request — it switches to a model that has it and bills that model. **A swap is always visible**: the headers `x-agiplan-model-actual` (served), `x-agiplan-model-requested` (named) and `x-agiplan-model-swap` (what was missing); a top-level `agiplan` object in the response (`model_requested`, `model_actual`, `missing_capabilities`, `notice`) — in the body when not streaming, in the first frame when streaming (the first Chat Completions chunk, `message_start.message` in Messages, `response.created.response` in Responses), with nothing inserted into the model's output; the row in the console's usage detail is tagged "Requested X → served by Y (X lacks …)" and the "Model swapped only" filter finds them; and the first swap on a key in 24 hours leaves an in-app note under Notifications (no email). Which model a tool-less model switches to is stated on that model's entry under Models & prices. To always get the named model, don't send capabilities it lacks.

| Flag | Meaning |
| --- | --- |
| `tools` | Tool calling (function calling). Required by coding agents such as Codex and Claude Code |
| `vision` | Image input: OpenAI `image_url`, Anthropic `image` blocks and Responses `input_image` are all translated |
| `json` | JSON mode / structured output (`response_format`) |
| `long` | Long context |
| `thinking` | Extended thinking can be enabled |
| `responses` | Native Responses protocol; Codex-specific items pass through unchanged. Only requests whose history holds items like `compaction` / `web_search_call` / `local_shell_call` need it; `apply_patch`, namespace tools and `include` don't, so naming Claude still runs Claude |
| `image` | Image model: use `/v1/images/generations` and `/v1/images/edits` |
| `video` | Video model: use `/v1/videos` |
| `quality:<value>` | `quality` values an image line accepts (e.g. `quality:high`). Lines that do not list the requested quality are skipped |
| `loose_max_tokens` | This line does not guarantee `max_tokens`; see the previous section |
| `thinking_forced` | Thinking enabled by default: the model always reasons first and thinking tokens count as output. `auto` and tier routing skip it when `max_tokens` is small (under 1024); if you specify it directly, leave room in the output cap |
| `resume_instruct` | Resumable: when a streamed answer is cut off part-way, the gateway can have this model continue from where it stopped and splice the rest into the same stream (see "Resuming a stream cut off mid-way" under Billing, precisely). It only changes how interruptions are handled, not capabilities or price |
| `resume_prefill` | Resumable via partial-answer prefill |

## Test model test-nl-astra (no key required)

`test-nl-astra` is a **locally generated test model** for client-integration debugging: all three text endpoints (`/v1/chat/completions`, `/v1/messages`, `/v1/responses`) accept it by name and it works **without an Authorization header**. The reply is not model output and comes in two parts: first a **native thinking block** on each dialect's own reasoning channel — `reasoning_content` on Chat Completions, a signed `thinking` block on Messages, a `reasoning` item on Responses; then the visible text — a dot-matrix picture (two variants, alternating) plus a **system status report for this very request** (account, subscription, balance, three-window usage, reset cards, node, protocol layer, UA, IP, trace id, streaming flag, …). Streamed at **50 tokens/second**, which is exactly what you need to tune thinking-block display, progress bars and interruption handling.

```
# No key, streaming
curl -N https://agiplan.dev/v1/chat/completions \
  -H 'content-type: application/json' \
  -d '{"model":"test-nl-astra","messages":[{"role":"user","content":"hi"}],"stream":true}'
```

- **Always 0 CU**: the catalog lists 0 for input, output and both cache rates; the million-token context (`context_k: 1000`) is a declaration — send requests of any length.
- **Key optional**: with a valid key, the report includes that account's subscription, balance, three-window usage and available reset cards, and a 0 CU row lands in the console's usage detail (with a trace id you can expand); without one (or with an invalid one) it is an anonymous call, the report says so, and **nothing is recorded**.
- **Zero retention**: request and reply content is never stored, neither is `client_ip`; `/v1/responses` keeps no session — a `previous_response_id` is ignored and the test model never produces a resumable session id.
- **Not in routing**: `auto`, `auto-fast`, capability groups and custom models never dispatch to it — specify it explicitly; it is also excluded from status-page statistics. The console and the public Models page list it separately, tagged “Test”.
- **Rate limits**: 30 calls per minute and at most 4 concurrent streams per IP (beyond that: 429 `demo_rate_limited` / `demo_busy`). Do not use it for load testing.
- The status report is troubleshooting material for yourself: copy it to support staff if you hit a problem, but **do not send it to strangers** — it contains your account details.

## Images: /v1/images/generations and /v1/images/edits

Request bodies match OpenAI. `edits` takes multipart uploads of the source image (`image` or `image[]`, **up to 16**) and an optional `mask`, **each file (mask included) at most 10 MB**; other parameters are the same.

| Parameter | Notes |
| --- | --- |
| `model` | Defaults to `gpt-image-2`. An image model from `/v1/models` (`kind: "image"`). With the model name, its lines are tried **cheapest first** and you pay for the line that made the image. With a line name (the model's `pinnable`, e.g. `gpt-image-2-vip`, `nano-banana-2-cl`) you **stay on that line** at its price |
| `prompt` | Required |
| `size` | Defaults to `1024x1024`. `WIDTHxHEIGHT`, e.g. `1024x1024`, `2048x1152`. Tiered by the long edge: ≤1024 is 1K, ≤2048 is 2K, ≤4096 is 4K, and **priced per tier**. Asking a model for a tier it cannot produce returns `size_unavailable` |
| `n` | Defaults to 1; 1–4. **Billed per image actually produced**: 3 out of 4 succeeding bills 3 |
| `quality` | `auto` / `low` / `medium` / `high`; some models add `xhigh` / `max`. Check the model's `quality:*` flags. If none of the model's routes for that size accept your value, you get 400 `quality_unavailable` with the accepted values in the message |
| `response_format` | Omitted or `b64_json`: base64 (the default, as with OpenAI). `url`: a link on our own domain, `https://agiplan.dev/v1/media/<id>`, **kept for 7 days** |

- Responses look like `{created, data:[{b64_json}], output_format, size, quality}`. **`output_format` is reported truthfully as `png` / `jpeg` / `webp`** — models differ, so pick the file extension from it rather than always saving `.png`.
- Failed generations (moderation, line fault, timeout) **are not billed**. Moderation failures return 400 `upstream_rejected`; another route will usually refuse too, so rewrite the prompt. **Requests with reference images** (`/v1/images/edits`): some models give no explicit refusal for a reference image that fails moderation — they simply produce no image. When two routes both produce nothing, the request also returns 400 `upstream_rejected` and no further route is tried; use a different image or change the description, or retry later if you are sure the content is fine. Generation cannot be cancelled once dispatched: if the client disconnects mid-generation, a generation the scheduling gateway has already dispatched usually finishes anyway, and **completed images are billed per piece** (the cost is incurred either way — same policy as streaming chat since 2026-10-12).
- Prices: `pricing.per_image` on image models in `/v1/models` gives, for `1k` / `2k` / `4k`, `cu` (from: the cheapest line) and `cu_max` (the dearest), plus the pay-as-you-go CNY; `pinnable` lists each pinnable line with its own price.
- References: for most models the input images sent to `/v1/images/edits` **cost nothing extra**; you pay per output image, same as generation. **The exception is `minimax-h3-image` / `minimax-h3-image-highspeed`**: each reference image adds a charge, shown in `/v1/models` as `pricing.per_reference_image` (null for models that don't charge for references).
- **How `minimax-h3-image` / `minimax-h3-image-highspeed` differ**: if `size` is under 655,360 pixels (e.g. the 1K `1024x576`), the image is made at the same ratio and tier (`1024x576` comes out 1360×768) and billed at that tier; ratios beyond 3:1 come out at 3:1. `quality` is ignored (no error, default output). **`mask` is not supported** and returns 400 `upstream_rejected`. Output defaults to JPEG (check `output_format`), and each image carries `revised_prompt` (the prompt the model actually used after rewriting). For usage-based billing see "Billing, precisely".
- **`minimax-h3-image` has two lines** (since 2026-11-18): requests go to the cheaper one first (about 45% of the other line's price; `minimax-h3-image-eco` under `pinnable`). When it is offline or its queue is too long, the request moves to the other line and is billed at that line's price — `cu` and `cu_max` in `per_image` are these two prices. The cheaper line differs from the notes above: the prompt must **pass content moderation** before anything is generated; a rejected prompt returns 400 `upstream_rejected` and is not billed, and moderation cannot be turned off. `size` is produced exactly as requested (each side at least 256, ratio up to 4:1). `quality` accepts `low` / `medium` / `high` (it only matters below 2048², `low` is fastest). All tiers come out as JPEG (`output_format` says `jpeg`); there is no `revised_prompt`. Reference images also add a charge (a lower one, see the range in `per_reference_image`); billing is per image by tier only, with no usage floor. The model was trained on detailed English descriptions of the whole image, so be specific, and put any text that should appear in the image in quotes. At peak times requests queue instead of failing, and the wait counts toward the request's duration.
- **Common `edits` error codes**: `invalid_multipart` (400, not multipart/form-data), `missing_image` (400, no source image), `too_many_images` (400, more than 16), `image_too_large` (413, a file over 10 MB).

## Video: /v1/videos (asynchronous)

A clip takes one to several minutes, so video is an **asynchronous job**: submit to get a job ID, poll for progress, fetch the clip when done. You are billed only when the clip is delivered.

| Endpoint | Notes |
| --- | --- |
| `POST /v1/videos` | Submit; returns 202 with the job object |
| `GET /v1/videos/{id}` | Poll. Every 3–5 seconds is fine; polling itself advances the job and never costs anything |
| `GET /v1/videos/{id}/content` | Download the clip (mp4). Needs your key; supports Range (seeking) |
| `GET /v1/videos` | The 50 most recent jobs for this key's account |
| `DELETE /v1/videos/{id}` | Delete a finished job and its clip; needs the `chat:write` scope. Running jobs cannot be deleted (409) because the scheduling gateway has already dispatched it and generation has started |

| Parameter | Notes |
| --- | --- |
| `model` | Defaults to `minimax-h3`. A video model (`minimax-h3`, `wan-3.0`; resolutions and durations per model in the table below). Billed per line like images: the model name starts on the cheapest line, a `pinnable` line name stays on that line |
| `prompt` | Required, up to 4,000 characters. **Shot lists work best**: duration, style, timed shots, dialogue, sound design, negatives |
| `resolution` | `minimax-h3`: `480p` / `768p` / `1080p`; `wan-3.0`: `480p` / `720p` / `1080p`. Per the model's `pricing.per_second` in `/v1/models`. Defaults to the model's lowest tier |
| `seconds` | Integer, defaults to 5. The range depends on model and resolution (table below); outside it you get `invalid_duration` with that model's range in the message (`duration` also accepted) |
| `aspect_ratio` | `16:9` (landscape, default) or `9:16` (portrait) |
| `images` | Optional reference images, up to 9. `http(s)` URLs or `data:image/…;base64,…`. Base64 references may total at most 8 MB **combined**; use URLs or the [asset library](https://agiplan.dev/en/docs/advanced#assets) for larger files |
| `audios` | Optional reference audio (voice, music), up to 3, same formats (counts toward the same base64 total as `images`) |
| `assets` | Optional ids of assets in the [asset library](https://agiplan.dev/en/docs/advanced#assets) (`ast_…`). Counted together with `images` / `audios` |
| `seed` | Optional integer; keeps results closer to the previous run when nothing else changes |

| Model | Resolutions | Duration (whole seconds) | Notes |
| --- | --- | --- | --- |
| `minimax-h3` | `480p` / `768p` / `1080p` | 1–15; at most 10 at `1080p` | Text-to-video, reference images + reference audio; generates a soundtrack and dialogue |
| `wan-3.0` | `480p` / `720p` / `1080p` | 3–30 | Text-to-video, reference images and reference audio |

```
import time, requests

H = {"Authorization": "Bearer ap_live_your_key"}
job = requests.post("https://agiplan.dev/v1/videos", headers=H, json={
    "model": "minimax-h3",
    "prompt": "6 seconds | premium product ad | macro photography ...",
    "resolution": "768p", "seconds": 6, "aspect_ratio": "16:9",
}).json()

while job["status"] in ("queued", "in_progress"):
    time.sleep(4)
    job = requests.get(f"https://agiplan.dev/v1/videos/{job['id']}", headers=H).json()

if job["status"] == "completed":
    print(job["url"], job["cu"])   # url is on our domain, valid for 7 days
else:
    print(job["error"])            # failures are not billed
```

Submit and poll (Python)

- Job fields: `id`, `status` (`queued` → `in_progress` → `completed` / `failed`), `progress` (0–100), `model`, `resolution`, `seconds`, `aspect_ratio`, `cu`, `created_at`, `completed_at`, `url`, `expires_at`, `error`, `retries`.
- **Automatic retry**: if generation fails mid-way or stalls, the system may switch to another route and regenerate, at most 2 times. The job id stays the same, `status` stays `in_progress`, `progress` restarts from 0, and `retries` counts the retries so far. Billing is unchanged: you are charged once, only when the clip is delivered. Jobs rejected by moderation and jobs with references in the request body (`images` / `audios`) are not retried automatically; jobs that only use library assets (`assets`) can be.
- **Billing**: the job reserves per-second price × seconds at submit and is charged when the clip is delivered; failures, moderation rejections and timeouts (no clip after 25 minutes) are free and the reservation is released. A running job holds one concurrency slot.
- **Common error codes**: `invalid_resolution`, `invalid_duration`, `invalid_aspect_ratio`, `too_many_images`, `too_many_audios`, `invalid_asset`, `invalid_seed`, `prompt_too_long` (bad parameters, 400); `resolution_unavailable` (503, no route can produce that resolution right now — pick another or retry later); `video_not_found` (404, no such job or not yours); `video_not_ready` (409, fetching the clip before it is done); `video_in_progress` (409, deleting a running job); `assets_too_large` (413, base64 references over the combined limit), `too_many_asset_bytes` (400, referenced assets over the combined limit); `content_rejected`, `generation_failed` (safe to resubmit), `timeout`, `upstream_lost` (reported in the job's `error`).
- Clips are **kept for 7 days**, then deleted. Download anything you want to keep.

## Asset library: /v1/assets (upload references once, reuse them)

The asset library requires an active plan (personal or your organization's, including custom enterprise plans), or pay-as-you-go turned on with a positive balance. Sending and storage are both **charged in CU with no free allowance**, from your plan's quota like any other call (see "Charges" below). Store reference images and audio in the asset library first, then pass only asset ids when you generate a video. Files are **uploaded straight to object storage** and never pass through our gateway, so request-body limits don't apply; identical files are stored once and can be referenced again. References added in the console's online video page live in the same library.

| Endpoint | Description |
| --- | --- |
| `POST /v1/assets` | Register a file to upload. Returns the asset object plus a one-time `upload` target. If the same file (by `sha256`) is already in your library you get that asset back with `upload: null` — no need to upload again |
| `PUT <upload.url>` | PUT the raw file there, **sending every header in `upload.headers`** (the content type is part of the signature); **the file size is signed too**, so the body must be exactly the `bytes` you registered or storage rejects it (403). Valid for 15 minutes; no API key needed |
| `POST /v1/assets/{id}/confirm` | Confirm once the upload finishes. We check size and file signature; on success `status` becomes `ready` and the asset can be referenced. Confirming twice is harmless |
| `GET /v1/assets` | List assets (most recently used first, 60 per page, `?kind=image\|audio`, `?offset=`) with `usage` (bytes used, count, cap, frozen state, the two CU rates, today's storage charge, this month's charges) |
| `GET /v1/assets/{id}` | Fetch one asset |
| `DELETE /v1/assets/{id}` | Delete, effective immediately. Video jobs that reference it and haven't finished may fail (failed jobs are not charged) |

| Register field | Description |
| --- | --- |
| `kind` | `image` or `audio` |
| `mime` | Images: `image/png`, `image/jpeg`, `image/webp` (no SVG). Audio: `audio/mpeg`, `audio/wav`, `audio/mp4`, `audio/m4a`, `audio/aac`, `audio/ogg` |
| `bytes` | File size in bytes. Images up to 20 MB, audio up to 50 MB; an upload larger than declared is deleted |
| `sha256` | SHA-256 of the file contents (64 lowercase hex chars), used for de-duplication |
| `name` | Optional file name, so you can recognise it in the console |

```
import hashlib, requests

H = {"Authorization": "Bearer ap_live_your_key"}
data = open("product.png", "rb").read()

a = requests.post("https://agiplan.dev/v1/assets", headers=H, json={
    "kind": "image", "mime": "image/png", "bytes": len(data),
    "sha256": hashlib.sha256(data).hexdigest(), "name": "product.png",
}).json()
if a["upload"]:                      # None when the same file is already stored
    requests.put(a["upload"]["url"], headers=a["upload"]["headers"], data=data).raise_for_status()
    a = requests.post(f"https://agiplan.dev/v1/assets/{a['id']}/confirm", headers=H).json()

job = requests.post("https://agiplan.dev/v1/videos", headers=H, json={
    "model": "minimax-h3", "prompt": "The product from <Picture 1> slowly turns 360° on a white turntable...",
    "resolution": "768p", "seconds": 6, "aspect_ratio": "16:9",
    "assets": [a["id"]],
}).json()
```

Upload a reference image and use it in a video (Python)

- **Referencing**: put asset ids in `assets` on `/v1/videos`. They can be mixed with `images` / `audios`, and counts are combined (up to 9 images, 3 audio clips); the assets referenced by one generation may total at most 100 MB. Ordering: `images` first, then the images in `assets` in the order given — `<Picture N>` in your prompt counts in that order.
- **Retention**: assets not referenced for 30 days are deleted automatically; every use resets the clock. Registrations not confirmed within 60 minutes are discarded.
- **Limits**: up to 200 GB and 500 assets, at most 300 registrations per day. When it's full, delete something first.
- **Charges (in CU, no free allowance)**: each is its own usage record, listed separately in your console usage, with model ids `asset-transfer` (sending) and `asset-storage` (storage). ① **Sending**: every generation — including automatic retries on another route — sends the referenced library assets to the model once, about 1053 CU per GB, charged at submission — **if the generation fails the video isn't charged, the sending is**; submissions that never went through aren't charged. ② **Storage**: assets in your library are charged once a day on the amount stored at the time, about 8.3 CU per GB per day. Both come from whoever pays for the call: plan quota, then pay-as-you-go from your balance when quota runs out or there's no plan (the key must allow pay-as-you-go). If sending can't be charged, the whole submission is refused (`quota_exceeded` 429 / `no_subscription` 403, with the message saying it's the asset sending). References attached directly to a request don't go through the library and aren't charged.
- **If storage can't be charged**: the library can't be referenced and uploads are blocked (`asset_frozen` / `asset_library_frozen`, 403); it resumes on the next charge (an hourly job) once quota resets or you top up, and the uncharged days aren't collected later. After 7 consecutive days, all assets are deleted (least recently used first).
- **Automatic retry**: video jobs that only use library assets can be regenerated on another route by the scheduling gateway if the line fails mid-way (we re-sign the asset links). Jobs with `images` / `audios` in the request body cannot.
- **Common error codes**: `asset_not_found` (404, no such asset, deleted, or not yours); `asset_size_mismatch` (400, the uploaded byte count differs from what was registered — upload again); `asset_check_unavailable` (503, we can't verify the file contents right now — confirm again shortly); `asset_library_requires_plan_or_balance` (403, no active plan, and pay-as-you-go is off or there's no balance); `invalid_asset_type`, `invalid_asset` (400); `asset_too_large` (413); `asset_quota_exceeded`, `asset_count_exceeded` (400, library full); `asset_upload_rate` (429); `asset_not_uploaded`, `asset_bad_content` (on confirm: upload not finished / content doesn't match the type); `asset_intent_expired` (410, register again); `invalid_asset_ref` (the asset doesn't exist, was deleted, or isn't yours).

## Result links (/v1/media)

- `response_format: "url"` images and a video job's `url` look like `https://agiplan.dev/v1/media/<id>`. **The link is the credential** (a 128-bit random ID), so no key is needed and it can go straight into `<img>` / `<video>`.
- Opening it redirects (302) to a storage URL **valid for 2 minutes**. Always use `/v1/media/<id>` itself; do not store the redirect target. A download started within that time runs to the end; seeking after a long pause opens the link again.
- To stop forwarded links from being abused, opens are capped per file per hour (30), per IP per minute (20) and across all of one account's files per hour (300); beyond that you get 429 `rate_limited` with `retry-after: 60`. Fetching `/v1/videos/{id}/content` with your key counts against the same caps. When site-wide egress runs too high we pause signing and return 503 `busy`; storage being briefly unavailable returns 503 `storage_unavailable`; a missing or expired file returns 404 `not_found`. Normal playback, downloads and seeking never reach these caps.
- **Download traffic** (charged from 2026-10-20, Beijing time; free before then): every open charges **the owner** once for the file's size (including opens by people the link was forwarded to; repeated opens of the same file from the same source within 2 minutes — a player reading in ranges, a page re-rendering — count once), at the same rate as sending assets, about 1053 CU / GB, with no free allowance. Like any other call it comes out of the owner's plan quota, then pay-as-you-go from the balance when quota runs out or there is no plan, and it is listed separately in usage as `media-download` (result downloads). If it cannot be charged: within **1 hour** of generation the file still opens and that open is not collected later; after that, other people opening it get `media_traffic_unpaid` (402) until the owner has quota or balance again; the owner can always view it in the console.
- **Kept for 7 days**, then 404.

## Tickets: /v1/tickets (your tickets, with your key)

These are **the same tickets** as Support in the console: same queue, same open-ticket limits, same image rules, answered in the same place. Useful for filing errors automatically and reading replies in your own tools. Reading needs the `usage:read` scope; opening, replying and uploading need `chat:write` (keys without scope limits can do both). You only see and act on your own account's tickets; anyone else's reference returns 404.

| Endpoint | What it does |
| --- | --- |
| `GET /v1/tickets` | Your tickets, most recently updated first. `?limit=` (default 20, max 100), `?offset=`; returns `data` and `has_more` |
| `GET /v1/tickets/{ref}` | One ticket (`ref` starts with `T-`) and its full `messages`. Which support agent replied is not returned |
| `POST /v1/tickets` | Open a ticket: `subject` (2–200 chars), `body` (4–8000), `kind` (`issue` / `idea` / `feedback`, default `issue`), `trace_id` (optional, kept for `issue` only), `attachments` (optional image IDs). Returns 201 and the ticket |
| `POST /v1/tickets/{ref}/messages` | Reply: `body`, `attachments`; `body` may be empty when you attach images. The ticket goes back to in-progress; closed tickets can't be replied to (409 `ticket_closed`) |
| `POST /v1/tickets/attachments` | Upload one image: `{"image": "data:image/png;base64,…"}`, PNG / JPEG / WebP, up to 5 MB. Returns an `id` to put in `attachments` (up to 4 per message); uploads that are never attached are removed after a day |
| `GET /v1/tickets/attachments/{id}` | View an image in a ticket: call it with your key and it redirects (302) to a short-lived URL. Only the ticket's owner can view it |

| Error code | Meaning |
| --- | --- |
| `ticket_not_found` | 404: no such ticket, or it isn't on this key's account |
| `attachment_not_found` | 404: no such image, it has expired, or it isn't in one of your tickets |
| `too_many_open_tickets` | 409: too many open tickets of this kind (issues and ideas are counted separately); add to an existing one |
| `ticket_closed` | 409: the ticket is closed; open a new one and mention the old reference |
| `invalid_subject` / `invalid_body` / `invalid_kind` / `invalid_attachments` / `invalid_image` | 400: bad parameter; `message` says what's expected |
| `rate_limited` | 429: more than 30 new tickets plus replies in an hour; image uploads are capped at 40 an hour |

```
import base64, requests

H = {"Authorization": "Bearer ap_live_your_key"}
img = "data:image/png;base64," + base64.b64encode(open("error.png", "rb").read()).decode()
att = requests.post("https://agiplan.dev/v1/tickets/attachments", headers=H, json={"image": img}).json()

t = requests.post("https://agiplan.dev/v1/tickets", headers=H, json={
    "subject": "Occasional 502s in a batch job",
    "body": "Since 14:00 today two or three in every hundred requests return 502; trace below.",
    "trace_id": "tr_…",
    "attachments": [att["id"]],
}).json()

detail = requests.get(f"https://agiplan.dev/v1/tickets/{t['ref']}", headers=H).json()
for m in detail["messages"]:
    print(m["from"], m["at"], m["body"])
```

Open a ticket with a screenshot, then read the replies (Python)

- **Spotting a new reply**: `last_from` is `staff` and `status` is `waiting_user`. We also email the account address as usual when we reply.
- `status`: `open` in progress, `waiting_user` awaiting your reply, `resolved`, `closed`. It follows whoever spoke last; the API doesn't change status.
- Please don't paste whole requests or responses into a ticket, only the relevant error lines. We don't store request bodies; a trace ID is enough for us to find the call's model and billing.

## Billing, precisely

- **Text**: input, output, cache-read and cache-write tokens as reported by the model are priced separately (rates on Models & prices). Every line has its own rate; you pay the rate of the line that served you, and `x-agiplan-model-actual` tells you which model that was. So the `pricing` of text models in `/v1/models`, and the prices marked "current lowest" on Models & prices, are the rates of **the cheapest line available right now** (lines tripped or drained don't count, and it changes as lines do); a given call may cost more, and usage details are the record. With no line available, the listed rate is the registered one.
- **The console's usage page hides cache hit rates and per-call CU by default**: calls within your plan say "Included in plan", and chat, images and video show a share of this month's quota; every call paid from balance still shows its CU and amount. By default the cache tag only marks rebuilds caused on our side (failover; or the line not holding the cache while the request's beginning was unchanged). Turn on advanced mode on the [Account page](https://agiplan.dev/en/app/account#advanced) to see hit rates, CU, all five cache reasons and the routing timeline per row. **Billing is identical in both modes**; the usage export (CSV, with `paid_by` and `bill_yuan` columns; `paid_by` is `quota` for plan quota, `boost` for a boost pack or `balance` for balance, and `bill_yuan` is filled only on rows paid from balance) and the `usage` field in responses always carry every figure; see section 17 of the Balance & Billing Terms.
- **Prompt caching for Claude is automatic**: when a request to a Claude model (via `/v1/messages`, `/v1/chat/completions` or `/v1/responses`) carries no `cache_control` at all, the gateway sets the breakpoints for you: one at the end of the system prompt, plus one on the last message for multi-turn conversations or requests with tools. If you set any `cache_control` yourself, yours are used as-is and none are added. The first write is billed at the cache-write rate (about 1.25× input); the same prefix afterwards at the cache-read rate (about 0.1×). Prefixes shorter than the model's minimum cacheable length (about 1,024 tokens) are not cached and cost nothing extra. Usage details show how much each call read and wrote.
- **When a model's reported usage is clearly wrong, output is billed as actually produced**: if the model reports far more output tokens than the content actually delivered to you, at an impossible speed (over a thousand tokens per second across the whole call), output is billed by the content actually produced — the response's `usage` (the final frame when streaming) carries that same number, matching what you're billed — and the call's trace in your usage details records what the model originally reported. Hidden reasoning (models that return only the conclusion and don't stream their reasoning) is unaffected: they report more, but at a normal speed. Input works the same way: if the reported input (including cache reads and writes) is larger than this request could possibly use — more than 8× our local estimate and over 1M tokens (or the model's context window) above it — input is billed at the local estimate plus a margin, and the trace records what was originally reported; normal requests with long documents or images come nowhere near that line.
- **Streams cut off mid-way**: output already produced is billed. After a disconnect the scheduling gateway reads the generation to the end to get the true usage, so a disconnect never skews billing either way. From the moment you disconnect, that call no longer counts against your concurrency limit, so you can send the next request right away. If the model service itself fails mid-way without reporting usage, input is billed at our local estimate; the part of it that this conversation's previous turn had already cached on the same line (within 5 minutes, or within an hour when that turn wrote a one-hour cache) is billed as a cache read rather than at the full input rate, and the trace says how much.
- **Resuming a stream cut off mid-way** (rolling out; until it reaches you, the previous item applies): when the connection drops after part of the answer has reached you, the gateway first tries to have the same model continue from where it stopped and splices the rest into the same stream — you get one complete answer with a normal end marker and never see `upstream_interrupted`. Text and tool arguments are only resumed on models flagged `resume_instruct`; a cut before any text (thinking only) resends the original request, and a cut right after a complete tool call simply ends the turn there (no new model call, nothing extra charged). **The continuation is recorded separately and billed as usual**: the part before the cut is billed as in the previous item; the continuation is a new model call with its own row in your usage details (its trace ID is this call's trace ID plus `-r1`, `-r2`, …), billed at **the rate of the line that actually completed it** (the lower-of-two-lines rule for failover does not apply). Its input is the whole context resent for the continuation, the part already delivered and a short instruction to continue, with what the model reports as cache hits billed as cache reads; its output is what the model actually produced, including thinking it produced again and did not pass to you and repeated text removed to line up with the cut, and that row's trace says roughly how much of it reached you. Before resuming we place a separate hold for it; **if your quota or balance cannot cover it we do not resume** and send `upstream_interrupted` as before. A continuation that does not connect, or that is abandoned before delivering anything (if it does not line up because the model repeats itself, explains or rewrites, we would rather not deliver it), is not billed. The output in the stream's final `usage` frame is the sum of both rows; its input is the first part's only (clients use it to estimate context use), and the continuation's input is in your usage details. The trace in your usage details says where it was cut and how it was resumed.
- **The same request sent again right away** (rolling out): if your client disconnects and immediately resends the identical request (Claude Code and Codex do this after a timeout) while the first one is still reading the model's output, the gateway attaches to it and replays it to you from the start instead of having the model answer again. **This second call is not charged again**: the first is billed by actual usage as above, and the second still gets a row in your usage details at 0 CU whose trace names the call that was billed (by its trace ID) — one model call is charged only once. Only a call whose client has already disconnected is picked up; two identical requests sent at the same time are billed separately.
- **Images** per image, **video** per second, **billed per line** like text: a model has several lines, each at its own price; we start on the cheapest and, if we switch, bill the line that served you, so `/v1/models` gives a range per tier (`cu` to `cu_max`). The hold uses the dearest candidate and the charge is the actual line; the difference is released at once. For most models references cost nothing extra (those that charge show `pricing.per_reference_image`). Failures are free.
- **`minimax-h3-image` / `minimax-h3-image-highspeed` have a usage floor** (except on the `minimax-h3-image-eco` line, which bills by tier only): these models are priced by tokens (prompt, references and output each at their own rate), and the per-image price is set from the official reference usage. If a very long prompt or very large references push the usage-based price above "tier price × images + reference charge", **you pay the usage-based price** (same markup); otherwise you pay the tier price, with no refund for lighter usage. Only images actually produced count.
- **Calls routed by the laddered auto count at 0.8× CU**: when you use `auto` (or `auto-fast` / `auto-cn`, which build on it) and the call was actually routed by the ladder, the CU charged is 0.8× what the rates give, and the trace says so. `auto-max`, named models, tier names and custom models are not discounted, and neither is auto before the ladder reaches your account.
- **Failed attempts are never billed**: route switches before the first byte, all lines failing (503) and refusals (4xx) cost nothing. When we switch, you pay **the price of the line that completed the request** (for a period before this it was the lower of that line and the line routing picked first; see Failover in the Uptime Commitment for the dates), and where the first line was cheaper the trace shows both figures; if you'd rather not be billed on another line, turn failover off in your custom model policy or set your key to “Cost”; the abandoned attempts (including a retry on the same line, and a duplicate sent to beat a slow first byte and then cancelled) are not passed on to you even if they already cost us — we absorb that. A stream that has started but stalls, drops or reports the model service busy before handing you any content (text, thinking or tool calls) is also restarted on another line of the same model within the same request, so you receive one complete answer; the headers are already out by then, so there is no `x-agiplan-failover`, and the trace in your usage details records the switch.
- **Boost packs**: when any of your plan's three windows (5-hour / weekly / monthly) is used up and you hold a usable boost pack, the call is paid from the pack automatically instead of returning 429. The order is **plan quota → boost pack → pay-as-you-go**: while you have a pack we use it first and leave your balance alone. Calls paid from a pack are metered in CU by the same rates and **do not count towards the three windows**; your usage details show the pack as the source, and the export has `paid_by` = `boost` with an empty `bill_yuan` (you paid when you bought the pack). With several packs, the one expiring first is used first, and one call may span two packs. The hold at the start of a call is taken from what is left in the pack, and if that cannot cover a full answer we narrow this call's output cap; the small amount by which actual usage exceeds what was left in the pack is recorded as usage and not charged. **When a window is only held up by other requests you have running at the same moment, and is not actually used up, we do not touch the pack** — you get the usual 429 and can retry once those requests finish, and this does not fall through to your balance even with pay-as-you-go on. On the boost bar in the console you can turn off "also use boost packs when the 5-hour window runs out"; packs are then used only when the weekly or monthly quota is used up (while only the 5-hour window is in the way, calls are handled as if you had no pack). Packs apply to personal plans only: organization keys never draw from them, and without an active plan a pack is not drawn from (its validity keeps running) and becomes usable again once the plan is back. `GET /v1/quota` reports the pack balance you can use right now in its `boost` field (`remaining_cu`, plus the earliest expiry as `next_expires_at`), or `null` when you have no usable pack — when a window's `remaining_percent` is 0 but `boost.remaining_cu` is above 0, calls still go through.
- **Model-restricted boost packs** (complimentary trial credit may carry this restriction; purchased packs never do): they only apply to the models listed on the pack, and the request's `model` must **specify one of them directly**. `auto`, capability group names and custom models do not count, even if the call ends up on the same model. When both a restricted and an unrestricted pack could cover a call, the restricted one is drawn first. A pack can carry two more flags: **use first**: calls that specify those models draw from the pack even while plan quota remains, and do not count toward the three windows (if the pack cannot hold the call, the output cap is not narrowed; that call simply uses plan quota); **works without a plan**: with no active plan, calls that specify those models still go through and draw from the pack, while other models still return `403 no_subscription` and other boost packs stay frozen. In `GET /v1/quota`, `boost.remaining_cu` is the total across all packs; when restricted packs exist there is also a `boost.model_packs` array whose items have `models`, `remaining_cu`, `expires_at` and `use_first`. With no plan but a works-without-a-plan pack, the endpoint returns 200 with `plan: null` (`payg` if pay-as-you-go is on), `windows: null` and the same `boost`.
- **Pay-as-you-go from balance** (quota used up, or no subscription): each call is converted at ¥1 = 500 CU and accumulated to ¥0.00001; **we deduct in ¥0.01 increments** and carry the fraction to later calls instead of rounding each call up. If a call started with enough balance and ceiling but its actual usage exceeds your remaining available balance or monthly ceiling when it completes, the call still finishes: we deduct down to zero (or up to the ceiling) and record the difference as a **pending charge**, shown in the console; it is collected first as soon as you have available balance again (a top-up, or next month's ceiling), and pay-as-you-go stays paused until it is settled (the 429 / 403 says whether it is the balance or the ceiling). A pending charge is not debt: it never makes your balance negative and carries no interest or late fee (Balance and Billing Terms 3.4, from 2026-10-20).
- **The hold is estimated on the line routing picked first, tool definitions included**; if we switch to a pricier line the hold is topped up for that line, and the charge is for the line that actually served you. The hold only affects concurrency and admission, never the amount charged.
- **Billed on top of the list rates** (only for usage that the called model itself really charges extra for, by that model's rules; listed per model as `pricing_tiers` in `/v1/models` and in the console's model details): **long-context tier** — when input (including cache) exceeds the threshold (272K for the GPT family today) the whole call is multiplied (input and cache × 2, output × 1.5); **one-hour cache writes** — cache writes marked `ttl: "1h"` in `cache_control` are charged at the input rate × 2 (five-minute writes keep the cache-write rate); **fast mode** — `speed: "fast"` on `/v1/messages` multiplies the whole call by the model's fast factor; **web search** — the Responses `web_search` tool and Anthropic server-side search are charged per search; **hosted image generation** — the Responses `image_generation` tool is charged per image. All of this is included in the call's CU, and the trace in your usage history says which item was added. They apply **only on routes that charge for these add-ons**; routes that waive them add none (`pricing_tiers.applies_on` is `metered_lines_only`, and `some_lines_exempt: true` is set when exempt routes exist for the model).
- **Retired models**: naming one returns `410 model_retired`; nothing is sent or billed, and the message names a replacement.

## When to retry

| Situation | Advice |
| --- | --- |
| 429 `quota_exceeded` / `concurrency_exceeded` | Check `retry-after` and the three quota headers; for concurrency, wait for earlier calls to finish |
| 429 `upstream_busy` | The model services are full; the gateway already waited a moment for a slot (3 s for web chat, 5 s for chat, 20 s for coding agents). Retry after `retry-after` |
| 503 `all_upstreams_failed` | Retry with exponential backoff; with `auto` the gateway has already tried other lines and tiers |
| 400 `upstream_rejected` / `capability_unavailable` | **Do not retry unchanged** — the answer will not change. Rewrite the prompt or drop the requirement |
| Mid-stream `upstream_interrupted` | Output so far is billed; a stream that fails before producing anything is not billed. Start a new request |
| A stream that errors after more than 20 seconds of waiting | Headers have already gone out as 200 (while waiting we send a keepalive every 15 seconds so idle connections are not cut: a `: keepalive` comment on Chat / Messages, a `response.in_progress` event on Responses); the error arrives as an in-stream error event with the same codes as above — handle it by code |
| Video job `generation_failed` | Not billed; resubmit |

The full error-code table is in the Error codes section of the quick start.
