# Nunchux AI Docs > ## Agent Instructions > Authenticate every request with your API key in the `X-API-Key` header or `Authorization: Bearer`. Keys start with `sk-nunchux-`. > Image generation is synchronous: the image is in the response. > Video generation is asynchronous: submit the job, poll its task until it reaches a terminal status, then download the output promptly, because output URLs expire. # Authentication Source: https://docs.nunchux.ai/authentication Learn how to authenticate with the Nunchux API using API keys. # Authentication ### How to authenticate your API requests ## Requirements for API calls All API requests to call any model on [Model APIs](/nunchux-optimized/overview) require authentication with your API key. Pass it in either the `X-API-Key` header or the `Authorization: Bearer` header. Both are accepted on every endpoint, and the same key works for both. > [!NOTE] > > Which header should I use? > > Either one. The examples in these docs use `X-API-Key`. The [OpenAI SDK](/nunchux-optimized/openai-compatibility) sends `Authorization: Bearer` automatically. If you send both headers, `Authorization: Bearer` takes precedence. **1. Create an Account** [Sign up](https://nunchux.ai/sign-up) for a Nunchux account. **2. Generate an API Key** Go to your [Dashboard](https://nunchux.ai/dashboard) and navigate to the API Keys section. Click "Create New Key" to generate a new API key, which you'll use to securely [access the API Reference](/nunchux-optimized/overview). > [!WARNING] > > Store your key securely — your API key is shown only once when created. Copy and store it in a secure location. If you lose it, you'll need to generate a new one. **3. Set your API Key** Once you've generated an API key, set it as an [environment variable](https://en.wikipedia.org/wiki/Environment_variable). ```bash Shell theme={"system"} export NUNCHUX_API_KEY=xxxxx ``` **4. Use the API Key** Include your API key in every request using the `X-API-Key` header. ```text Header format theme={"system"} X-API-Key: YOUR_API_KEY ``` ## Example Request ```bash cURL theme={"system"} curl -X POST https://api.nunchux.com/v1/images/generations \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "nunchux-flux.2-klein-4b", "prompt": "a serene landscape", "width": 1024, "height": 1024 }' ``` ```python Python theme={"system"} import os import requests api_key = os.environ.get('NUNCHUX_API_KEY') headers = { 'X-API-Key': api_key, 'Content-Type': 'application/json' } response = requests.post( 'https://api.nunchux.com/v1/images/generations', headers=headers, json={ 'model': 'nunchux-flux.2-klein-4b', 'prompt': 'a serene landscape', 'width': 1024, 'height': 1024 } ) ``` ```javascript JavaScript theme={"system"} const apiKey = process.env.NUNCHUX_API_KEY; const response = await fetch("https://api.nunchux.com/v1/images/generations", { method: "POST", headers: { "X-API-Key": apiKey, "Content-Type": "application/json", }, body: JSON.stringify({ model: "nunchux-flux.2-klein-4b", prompt: "a serene landscape", width: 1024, height: 1024, }), }); const data = await response.json(); ``` ## Best Practices ### Store API keys securely * Use environment variables to store API keys * Never hardcode keys in your source code * Use secret management systems in production * Rotate keys periodically ```bash theme={"system"} # Store in environment variable export NUNCHUX_API_KEY="your-api-key-here" # Use in requests curl -X POST https://api.nunchux.com/v1/images/generations \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "nunchux-flux.2-klein-4b", "prompt": "test", "width": 1024, "height": 1024}' ``` ### Use environment-specific keys Maintain separate API keys for different environments: * Development key for testing * Staging key for pre-production * Production key for live applications ### Rotate a key You can rotate a key from the dashboard without downtime. Open API Keys and select the rotate icon next to the key: * A new key is created with the same name and shown one time * The old key continues to work for 24 hours, then it stops * Update your applications to the new key in that window ### Monitor API usage Track your API usage to: * Detect unauthorized access * Optimize costs * Identify usage patterns * Plan capacity needs ### Rate Limiting Every account is limited per plan on requests per minute and simultaneous jobs. Keys billed to a team share the team's caps. Over a cap you receive a 429. The numbers and how to back off are on the [Rate limits](/rate-limits) page. # Changelog Source: https://docs.nunchux.ai/changelog Models available in the Nunchux playground and when they arrived: image, video, and avatar models, newest first. Each date is the day the model became generally available on Nunchux, per the earliest release evidence on record — a recorded enable outranks route presence, and the launch catalog is dated to the site launch. A retirement is dated to the day the model stopped serving. **November 12, 2026** * Support Nano Banana (`gemini-2.5-flash-image`), the original Nano Banana — text-to-image and image editing, at 1K. Google shuts it down on March 15, 2027, and Nunchux stops serving it one to two weeks before. **November 4, 2026** * Support Topaz Labs Wonder 4, Wonder 3.5, Bloom 2, and Gigapixel High Fidelity 3 — image upscaling and enhancement * Support Vidu Q4 preview — image-to-video and reference-to-video, with audio * Support Grok Imagine Video 1.5 — text-to-video, image-to-video, and reference-to-video, with audio * Support Grok Imagine Video 1.5 Lite — text-to-video and image-to-video, with audio **November 3, 2026** * Support the full Qwen Image 2512 — text-to-image. `nunchux-qwen-image-2512` now selects the full model. The Lightning model is `nunchux-qwen-image-2512-lightning`. * Support the full Qwen Image Edit 2511 — image editing, with up to 3 source images. `nunchux-qwen-image-edit-2511` now selects the full model. The Lightning model is `nunchux-qwen-image-edit-2511-lightning`. * Support the full Qwen Image Edit 2509 and Qwen Image Edit 2509 Lightning — image editing, with up to 3 source images. `nunchux-qwen-image-edit-2509` now selects the full model. The Lightning model is `nunchux-qwen-image-edit-2509-lightning`. **October 26, 2026** * Support FLUX.2 dev Flash — text-to-image **October 22, 2026** * Retire Veo 3.1, Veo 3.1 Fast, and Veo 3.1 Lite. Google shut down the three preview models on October 22, 2026. A submit to `veo-3.1-generate-preview`, `veo-3.1-fast-generate-preview`, or `veo-3.1-lite-generate-preview` now returns an error and produces no video. **October 19, 2026** * Support FLUX 3 Image Klein — text-to-image and image editing, with up to 10 source images **October 16, 2026** * Support Qwen Image 2.1 — text-to-image and image editing, with up to 10 source images **October 15, 2026** * Support Krea 2 Turbo — text-to-image * Support MiniMax H3 Fast — text-to-video and first and last frame to video, with audio **October 14, 2026** * Support Ideogram 4 Flash — text-to-image * Support HiDream O1 Flash — text-to-image * Support FLUX.1 dev and FLUX.2 dev — text-to-image * Support Qwen Image — text-to-image * Support Qwen Image Edit — image editing * Support several source images in image editing — up to 4 on FLUX.2 Klein 4B and 9B Edit, and up to 3 on Qwen Image Edit 2511 **October 13, 2026** * Support Z-Image Turbo — text-to-image * Support Qwen Image 3.0 and Qwen Image 3.0 Pro — text-to-image and image editing **October 12, 2026** * Support MiniMax H3 Fast — reference-to-video, with audio **October 8, 2026** * Support Nano Banana 2.1 — text-to-image and image editing **September 29, 2026** * Support Ideogram 4 — text-to-image * Support HiDream O1 — text-to-image * Support LTX 2.3 and LTX 2.5 — text-to-video and image-to-video **September 23, 2026** * Support Wan 3.0 and Wan 3.0 Prime — text-to-video, image-to-video, and reference-to-video * Support HappyHorse 1.0 and HappyHorse 1.1 — text-to-video, image-to-video, and reference-to-video * Support Wan 2.7 — reference-to-video * Support MiniMax H3 — reference-to-video **September 16, 2026** * Support Seedance 2.5 — text-to-video and image-to-video * Support Wan 2.7 — text-to-video and image-to-video **September 4, 2026** * Support Seedance 2.0, 1.5 Pro, and 1.0 Pro — text-to-video and image-to-video * Support Wan 2.6 — text-to-video and image-to-video **September 3, 2026** * Support MiniMax H3 — text-to-video and image-to-video **August 20, 2026** * Support Qwen Image 2512 — text-to-image **August 14, 2026** * Support Qwen Image Edit 2511 — image editing **July 29, 2026** * Support HeyGen Avatar V — talking-avatar video **July 27, 2026** * Support Nano Banana — text-to-image and image editing * Support Gemini 3 Pro Image — text-to-image and image editing * Support Veo 3.1 — text-to-video and image-to-video * Support HeyGen Avatar IV — talking-avatar video **June 10, 2026** * Support FLUX.1 Schnell — text-to-image **May 21, 2026** * Support Kling V1 — text-to-video and image-to-video * Support Kling V1.5 — image-to-video * Support Kling V1.6 — text-to-video, image-to-video, and multi-image * Support Kling V2 — text-to-video and image-to-video * Support Kling V2.1 — image-to-video * Support Kling V2.1 Master — text-to-video and image-to-video * Support Kling V2.5 Turbo — text-to-video and image-to-video * Support Kling V2.6 — text-to-video, image-to-video, and motion control * Support Kling V3 — text-to-video, image-to-video, omni video, and motion control * Support Kling Video O1 — omni video * Support FLUX.2 Klein 4B and 9B — text-to-image and image editing * Support Qwen Image — text-to-image and image editing * Support Wan 2.2 Lightning — text-to-video and image-to-video # Use Nunchux with coding agents Source: https://docs.nunchux.ai/coding-agents Connect Claude Code, Cursor and other AI coding tools to the Nunchux docs through MCP, llms.txt, and Markdown versions of every page. # Use Nunchux with coding agents ### Give your AI coding tool the docs it needs to write working Nunchux code AI coding tools write better API code when they read the docs directly rather than guessing. Every page of these docs is available in forms they can read, and the menu at the top of each page sends it to them in one click. ## Connect the docs MCP server The docs MCP server lets your coding tool search these docs and read any page while it works, without you pasting anything in. * **Server URL:** `https://docs.nunchux.ai/mcp` * **One click:** choose **Add MCP** in the menu at the top of any page. ```bash Claude Code theme={"system"} claude mcp add --transport http nunchux https://docs.nunchux.ai/mcp ``` ```json Cursor (~/.cursor/mcp.json) theme={"system"} { "mcpServers": { "nunchux": { "url": "https://docs.nunchux.ai/mcp" } } } ``` ## Read any page as Markdown Add `.md` to the end of any page URL to get the page as plain Markdown, for example [`/authentication.md`](https://docs.nunchux.ai/authentication.md). The page menu does the same: **Copy page** copies it, and **Open in Claude** or **Open in ChatGPT** starts a chat with the page loaded. Each Markdown page starts with a short **Agent Instructions** block: how to authenticate, and which calls are synchronous and which you poll. ## Give an agent the whole site * [`llms.txt`](https://docs.nunchux.ai/llms.txt) is an index of every page with a one-line summary, so an agent can find the page it needs. * [`llms-full.txt`](https://docs.nunchux.ai/llms-full.txt) is the full text of every page in one file, for tools that load everything up front. > [!NOTE] > > Your API key still goes in your code or environment, never in a chat. Set it as `NUNCHUX_API_KEY` and have the agent read it from there. See [Authentication](/authentication). # Content Moderation Source: https://docs.nunchux.ai/content-moderation How Nunchux checks prompts, which accounts can turn the check off for a request, and how to apply. # Content Moderation ### How Nunchux checks requests, and how an approved account turns the check off ## What Nunchux checks Nunchux checks the prompt of every request to a Nunchux Optimized model. It sends the prompt to OpenAI's moderation API while the model runs. If the check flags the prompt, Nunchux withholds the result and returns a 422 `content_policy_violation`. You are not charged for a withheld result. Moderation is on by default for every account and every request. ## Turning moderation off An account that Nunchux has approved can turn the check off for one request. Send `content_moderation: false` in the request body: ```json theme={"system"} { "model": "nunchux-flux.2-klein-9b", "prompt": "A portrait in the style of a classical oil painting", "width": 1024, "height": 1024, "content_moderation": false } ``` Turning moderation off skips Nunchux's content filter except for one check. Nunchux still sends the prompt to OpenAI's moderation API, and blocks content that OpenAI flags as sexual content involving minors. That request returns a 422 `content_policy_violation`. This check reads the prompt text, not uploaded images. Some models come from third-party providers, which apply their own moderation that Nunchux does not control. Requests without the field, or with `content_moderation: true`, are moderated as usual. An approved account can keep moderation on for some requests and turn it off for others. ## Who can turn it off Nunchux approves an account to turn moderation off. Approval covers the whole account. A personal account can apply as well as a team. An account that is not approved gets a 403 `content_moderation_not_approved` when it sends `content_moderation: false`. Nunchux does not run the request: ```json theme={"system"} { "error": { "code": "content_moderation_not_approved", "message": "This account is not approved to turn content moderation off. Remove content_moderation, or apply for approval." } } ``` The field must be the JSON value `true` or `false`. Any other value, including a string or `null`, returns a 400 `invalid_request`. ## Where the field works | Route | Where to send the field | | - | - | | `POST /v1/images/generations` | The request body | | `POST /v1/images/edits` | The request body. In a multipart form, send the form field `content_moderation` with the value `false`. | | `POST /v1/video/generations`, `POST /v1/video/animations`, `POST /v1/videos/generations` | The request body | | `POST /v1/batches` | Each request's `params`. A `content_moderation` beside `params` or at the top level returns a 400. | Partner model routes, such as `/v1/google/`, `/v1/klingai/` and `/v1/bytedance/`, do not read the field. Nunchux runs no content filter on them. The partner applies its own moderation. With the OpenAI SDK, send the field in `extra_body`, as with other Nunchux fields. See [OpenAI compatibility](/nunchux-optimized/openai-compatibility). ## How to apply Contact Nunchux to apply. Tell us the account or team, and what you will use it for. Nunchux reviews each request. # Credits & Pricing Source: https://docs.nunchux.ai/credits-pricing Understand how credits work for the Nunchux API. # Credits & Pricing ### How billing works for your API requests ## How Credits Work Nunchux uses a prepaid credit system. One credit costs \$1.00. Credits are deducted per successful request, based on the model, the [performance tier](/performance-tiers), and the output size. How a model bills depends on what it generates. | Model type | Billing basis | | - | - | | Image models | Most image models price per megapixel of the output. Ideogram 4 prices per image, by tier. | | Video models | Most are priced by the duration of the output, some also by resolution or mode. Seedance is priced per million video tokens of the finished clip, billed when it completes. | The [pricing page](https://nunchux.ai/pricing) lists the current rate for each combination. ## Tier Pricing The price of a Nunchux Optimized model depends on the tier. The FLUX, Qwen, HiDream O1, Z-Image Turbo, Krea 2 Turbo and MiniMax H3 Fast models have the Radical Speed and Radical Value tiers. MiniMax H3 Fast bills per second of output video, at a rate that also depends on the short edge. FLUX.1 dev, FLUX.2 dev, Qwen Image and Qwen Image Edit have Radical Speed only. FLUX.2 dev Flash has Radical Value only. Ideogram 4 has the Turbo, Balanced and Quality tiers, billed per image. The LTX video models have the 720p and 1080p tiers, billed per second of output video. Partner models do not use the tiers, and each one has its own price basis, such as output size, resolution, or mode. See [Performance Tiers](/performance-tiers) for a description of each tier, and the [pricing page](https://nunchux.ai/pricing) for current rates. ## Discounts Some models carry a 10% default discount off list price. Negotiated and trial discounts are a multiplier on list price, and they replace the default discount. See [Discounts](/discounts) for which models carry the default discount and how to check which discounts apply to your account. ## Checking Your Balance Check your credit balance in the [Dashboard](https://nunchux.ai/dashboard). You can also call `GET /v1/credits`, which takes no parameters and returns the account the key bills. On a [team](/teams) key, that is the team. It uses the same API key for [authentication](/authentication) as every other endpoint. ```bash curl theme={"system"} curl https://api.nunchux.com/v1/credits \ -H "X-API-Key: $NUNCHUX_API_KEY" ``` ```python python theme={"system"} import os import requests response = requests.get( 'https://api.nunchux.com/v1/credits', headers={'X-API-Key': os.environ['NUNCHUX_API_KEY']}, timeout=30, ) response.raise_for_status() print(response.json()) ``` A `200` carries the balance and the caps that apply to your plan. The API returns [standard error codes](/errors) with a JSON error body. ```json theme={"system"} { "credits_remaining": 96.49, "plan_level": "pro", "rpm_limit": 200, "concurrent_limit": 10, "period_start": "2026-10-01T00:00:00+00:00", "period_end": "2026-10-13T18:30:00+00:00", "period_gross": 3.51, "pending_discount_estimate": 0.0, "net_balance_estimate": 96.49, "spend_limit": null } ``` | Field | Type | Description | | - | - | - | | `credits_remaining` | number | Credits left on the account. One credit is \$1.00. | | `plan_level` | string | The plan the account is on. Each plan has its own caps. | | `rpm_limit` | number | Requests per minute the account's plan allows. Shared by every key billed to this account. | | `concurrent_limit` | number | Simultaneous jobs the account's plan allows. Shared by every key billed to this account. | | `period_start` | string | Start of the current billing month, in ISO 8601 UTC. | | `period_end` | string | The time of this response, in ISO 8601 UTC. | | `period_gross` | number | Credits charged so far this month, before the month-end discount credit. Requests your discount already reduced when they were charged are left out, so on an entrypoint with a discount only batch requests count here. | | `pending_discount_estimate` | number | Credits you expect back when this month's invoice closes, from your discount on batch requests. Zero without one. See [Discounts](/discounts). | | `net_balance_estimate` | number | `credits_remaining` plus `pending_discount_estimate`. | | `spend_limit` | object or null | The organization's monthly spending limit, as the API enforces it: `cap`, `spent`, `remaining`, `period` (`YYYY-MM`, UTC) and `limit_reached`. `null` when the organization has no limit. | > [!NOTE] > > Polling > > This poll is free and it never takes a job slot. It still counts toward your [requests per minute](/rate-limits). ## Credit Packages Add credits from the [Billing tab](https://nunchux.ai/dashboard/admin/billing) of your dashboard. Select a preset package, or enter a custom whole-dollar amount between $5 and $5,000. | Package | Credits | \~Images | | - | - | - | | \$10 | 10 | \~15,900 | | \$20 | 20 | \~31,800 | | \$50 | 50 | \~79,500 | > [!NOTE] > > Image estimates assume FLUX.2 Klein 4B on the Radical Value tier at 1024×1024. > This is our lowest published rate, 0.0006 credits per megapixel. Other models > and tiers have different costs per image. Top Up opens the Add Credits window, which also has a field for a promo code. See [Redeem a promo code](/promo-codes). ## Insufficient Credits If you do not have enough credits, the API returns a 402 status code. The response gives the credits required and your current balance: ```json theme={"system"} { "error": { "code": "insufficient_credits", "message": "Your account does not have enough credits for this request.", "creditsRequired": 0.005, "creditsBalance": 0.002 } } ``` See [Error Handling](/errors) for a full list of API error codes. ## Refunds Sometimes a request fails after Nunchux deducts the credits, for example because of a server error. Nunchux refunds those credits automatically. # Discounts Source: https://docs.nunchux.ai/discounts A multiplier on list price, set per entrypoint or per model. # Discounts ### A multiplier on list price, set per entrypoint or per model. ## How discounts work List price is a model's undiscounted price, as its vendor publishes it. For Nunchux-optimized models, Nunchux is the vendor. With a discount, your charge is list price × multiplier. The multiplier is specific to your account and to one entrypoint. An entrypoint is a group of models, not a single model. The multiplier comes off each charge, on every entrypoint. The `credits_used` field on `GET /v1/usage` already includes it. Batch requests are the exception. A batch request is charged without your multiplier, at the price you would pay with no discount. The difference is credited to your balance when the month's invoice closes, using your entrypoint-wide multiplier. Until then, `pending_discount_estimate` on [`GET /v1/credits`](/credits-pricing#checking-your-balance) shows the credit so far. | Entrypoint | Covers | Without a discount | | - | - | - | | `kling` | Every Kling model, mode, and duration | 10% default discount on `kling-v3` and `kling-v3-omni`. Other Kling models: list price. | | `nunchaku` | Nunchux-optimized image and video models | List price | | `google` | Every Google model: Nano Banana image | 10% default discount | | `heygen` | Every HeyGen avatar video model | 10% default discount | | `minimax` | MiniMax H3 video | 10% default discount | | `alibaba` | Every Alibaba Cloud model: Wan and HappyHorse video | List price | The Nunchux-optimized entrypoint is spelled `nunchaku` in the API, in this response and in [error bodies](/errors). ### The default discount Without a discount, some models carry a default discount: you pay list price × 0.9, which is 10% off list price. The table above shows which ones. On the others, you pay list price. `GET /v1/pricing` shows the price you pay on each model. A discount replaces the default discount. The two never combine. For example, with a `google` multiplier of 0.8 you pay list price × 0.8, not list price × 0.9 × 0.8. A row covers either every model behind its entrypoint or one model only. Entrypoints where you have no discount have no row at all. ## Entrypoint rows and model rows Each row has a `model_key`. * `model_key` is `null`: the row covers every model of the entrypoint. * `model_key` is a model id: the row covers that model only. It replaces the entrypoint row for that model. The two never combine. Exactly one multiplier applies to a request: the model's own row if it has one, otherwise the entrypoint row. Models with neither row get the [default discount](#the-default-discount) if they carry one, and list price otherwise. Model rows do not apply to batch requests yet. Batch requests use the entrypoint row. ## Checking your discounts `GET /v1/discounts` takes no parameters and returns only your own rows. It uses the same API key for [authentication](/authentication) as every other endpoint. ```bash curl theme={"system"} curl https://api.nunchux.com/v1/discounts \ -H "X-API-Key: $NUNCHUX_API_KEY" ``` ```python python theme={"system"} import os import requests response = requests.get( 'https://api.nunchux.com/v1/discounts', headers={'X-API-Key': os.environ['NUNCHUX_API_KEY']}, timeout=30, ) response.raise_for_status() print(response.json()) ``` A `200` carries a single `discounts` array, sorted by entrypoint. The API returns [standard error codes](/errors) with a JSON error body. ```json theme={"system"} { "discounts": [ { "entrypoint": "kling", "model_key": null, "multiplier": 0.9, "effective_from": "2026-06-10T00:00:00+00:00", "effective_to": null }, { "entrypoint": "nunchaku", "model_key": null, "multiplier": 0.9, "effective_from": "2026-07-01T00:00:00+00:00", "effective_to": "2026-09-30T00:00:00+00:00" } ] } ``` | Field | Type | Description | | - | - | - | | `entrypoint` | string | Which surface the discount applies to. One of the entrypoints above. | | `model_key` | string \| null | The model the row covers, or null when it covers every model of the entrypoint. | | `multiplier` | number | The fraction of list price you pay. | | `effective_from` | string | ISO-8601 timestamp with UTC offset. When the discount began. Always present. | | `effective_to` | string \| null | ISO-8601 timestamp, or null for an open-ended discount. When present, the discount ends at this instant (exclusive). | No active discount is a normal `200`, not an error. An empty array means no discount applies: each model gets the [default discount](#the-default-discount) if it carries one, and list price otherwise. ```json theme={"system"} { "discounts": [] } ``` The response carries `multiplier` and nothing precomputed, so derive any percentage you want to display yourself. > [!NOTE] > > Polling > > This is a free poll and it never takes a job slot. It still counts toward your [requests per minute](/rate-limits), and a discount changes rarely, so caching the response for minutes is fine. There is no webhook for discount changes. ## Reading the multiplier The `multiplier` field is the fraction of list price you pay. | Value | Meaning | How to display | | - | - | - | | 0 \< m \< 1 | Discount | discount = (1 − m) × 100 %, so m = 0.90 means a 10% discount | | m = 1 | List price | No discount. On a model with a default discount, this is more than you would pay without the row. | | m > 1 | Surcharge | You pay more than list price | ## Time windows Every discount has a start date and may have an end date. | Field | Meaning | | - | - | | `effective_from` | When the discount starts. | | `effective_to` | When it ends. A null value means it has no end date. | The endpoint returns only the discounts that are active now. One that has not started yet, or that has already ended, is left out entirely rather than returned as an inactive row. ## Where else the multiplier shows * `GET /v1/pricing` lists entrypoint-wide rows under `contract`. It lists model rows under `model_contract`, by entrypoint and then by model. On Nunchux Optimized models, `applied_at` reads `charge`. * `GET /v1/models` returns `contract_multiplier` for each model. It is the model's own row if it has one, otherwise its entrypoint row. # Errors Source: https://docs.nunchux.ai/errors API error codes, response formats, and retry guidance for the Nunchux API. # Errors ### Validation and content errors returned The Nunchux API uses standard HTTP status codes. All error responses include a JSON body describing what went wrong. ## Client Error Response Format Client errors (4xx) return a JSON body. Auth, rate-limit, and billing errors carry an `error` object; request-validation failures carry a plain `detail` string. | Field | Type | Description | | - | - | - | | `error.code` | string | A machine-readable error code (e.g. invalid_api_key, rpm_limit_exceeded). Use this for conditional logic. | | `error.message` | string | A human-readable description of the error. Display this to end-users. | | `detail` | string | Request-validation failures (unknown model, bad parameters) return this plain string instead of an error object. | ## Client Error Codes ### 400 Bad Request The request is missing required parameters or contains invalid values such as missing prompt, invalid model ID, invalid dimensions. Returned as a plain detail string. ```json theme={"system"} { "detail": "unknown model 'invalid-model'; allowed values: nunchux-qwen-image-2512-lightning, nunchux-flux.2-klein-9b, ..." } ``` > [!WARNING] > > Retry Guide — Do not retry. Fix the request parameters before resending. ### 401 Unauthorized The API key in the X-API-Key header is missing, malformed, unknown, revoked, or expired (codes: missing_api_key, invalid_key_format, invalid_api_key, key_revoked, key_expired). ```json theme={"system"} { "error": { "code": "invalid_api_key", "message": "Invalid or revoked API key." } } ``` > [!WARNING] > > Retry Guide — Do not retry. Check that your API key is correct and active. ### 403 Forbidden The account does not have access to the requested model. Restricted models need an explicit grant. This response carries `detail`, not the error envelope. ```json theme={"system"} { "detail": { "code": "model_not_available", "message": "Model nunchux-flux.2-klein-9b is restricted on this account", "model": "nunchux-flux.2-klein-9b", "entrypoint": "nunchaku" } } ``` > [!WARNING] > > Retry Guide — Do not retry. Use a public model, or contact support to request > access. An account that is not approved to turn content moderation off sent `content_moderation: false`. The request did not run. See [Content moderation](/content-moderation). ```json theme={"system"} { "error": { "code": "content_moderation_not_approved", "message": "This account is not approved to turn content moderation off. Remove content_moderation, or apply for approval." } } ``` > [!WARNING] > > Retry Guide — Do not retry. Remove `content_moderation`, or apply for approval. ### 429 Rate Limit Too many requests in a short period. Code rpm_limit_exceeded for the per-minute cap, concurrent_limit_exceeded for the simultaneous-job cap. Back off and retry. ```json theme={"system"} { "error": { "code": "rpm_limit_exceeded", "message": "Rate limit exceeded. See the rate-limit response headers for your limit and reset time." } } ``` > [!WARNING] > > Retry Guide — Implement exponential backoff. Start with a 1-second delay, then > double on each retry (1s → 2s → 4s → 8s). Cap at 3–5 retries. ### 402 Insufficient Credits Your account does not have enough credits for this request. The response includes your current balance and the cost so you know exactly how many credits to add. > [!NOTE] > > Credit metadata > > The 402 body is the standard error object. `code`, `message` and `request_id` are always present. The credit amounts are not always included. When they are, they ride in `error.details`, with the deprecated `creditsRequired` and `creditsBalance` mirrors alongside. | Field | Type | Description | | - | - | - | | `error.code` | string | Always "insufficient_credits". | | `error.message` | string | A human-readable description of the error. Display this to end-users. | | `error.request_id` | string | Correlation id for this request. Always present. | | `error.details.credits_required` | number | The credits this request needs. Not always included. | | `error.details.credits_balance` | number | Your credit balance. Not always included. | | `error.creditsRequired` | number | Deprecated mirror of error.details.credits_required. | | `error.creditsBalance` | number | Deprecated mirror of error.details.credits_balance. | ```json theme={"system"} { "error": { "code": "insufficient_credits", "message": "Your account does not have enough credits for this request.", "request_id": "", "details": { "credits_required": 0.005, "credits_balance": 0.002 }, "creditsRequired": 0.005, "creditsBalance": 0.002 } } ``` > [!WARNING] > > Retry — Do not retry. Check your credit balance and purchase more credits if > needed. See [Credits & Pricing](/credits-pricing). ## Server Error Response Format Server errors (5xx) return a JSON body with a `detail` string. When the inference backend supplies a typed envelope, an `error` object with a machine-readable `code` rides alongside it. ```json theme={"system"} { "detail": "Inference failed: " } ``` ## Server Error Codes ### 500 Internal Server Error An unexpected error occurred on the server. > [!WARNING] > > Retry Guide — Safe to retry with exponential backoff. Credits are > automatically refunded on failure. ### 502 Bad Gateway The inference service returned no data. The request was processed but no output was generated. > [!WARNING] > > Retry Guide — Safe to retry with exponential backoff. Credits are > automatically refunded on failure. ### 503 Service Unavailable The server is temporarily unavailable. > [!WARNING] > > Retry Guide — Wait a few seconds and retry. ### 504 Gateway Timeout A request exceeded its time budget (code: `engine_timeout`). On an endpoint that takes a source image, fetching that image is the usual cause. > [!WARNING] > > Retry Guide — Safe to retry with exponential backoff. Credits are > automatically refunded on failure. ## Retrying safely Only `429` and the `5xx` family should be retried. Use exponential backoff: start at one second and double on each attempt (1s → 2s → 4s → 8s), capping at 3–5 tries. If a response includes a `Retry-After` header, honor it instead. Never retry a `4xx` other than `429` — the request is malformed and will fail the same way again. ## Asynchronous endpoints Asynchronous partner models return 200 when they accept a job. A job that fails later does not return an HTTP error. The failure appears in the poll response. See [Errors and limits](/partner-models/overview#errors-and-limits) on the Partner models overview, and the model page for the error codes of each provider. ## Credit Safety If an error occurs after credits have been deducted, they are automatically refunded. You will never lose credits due to a server-side failure. # Image-to-image Source: https://docs.nunchux.ai/nunchux-optimized/image-to-image Edit an image, or combine several images, with a text prompt with a Nunchux Optimized model. The edited image is in the response. # Image-to-image Send a source image and a text prompt that describes the edit. Some models also take several source images, for example to put the subject of one image into the scene of another. The response contains the edited image. The request is synchronous. There is no task to poll. ## Models | Model | Model ID | Source images | Use it for | | - | - | - | - | | FLUX.2 Klein 9B Edit | `nunchux-flux.2-klein-9b-edit` | Up to 4 | Edits that must keep the identity of the subject. | | FLUX.2 Klein 4B Edit | `nunchux-flux.2-klein-4b-edit` | Up to 4 | The fastest edits. High-volume edit passes. The output follows the input image. | | Qwen Image Edit 2511 Lightning | `nunchux-qwen-image-edit-2511-lightning` | Up to 3 | Targeted edits: swap elements, change the style, edit text in the image. The recommended editing model. | | Qwen Image Edit 2511 | `nunchux-qwen-image-edit-2511` | Up to 3 | Full-step Qwen Image Edit 2511, in 40 steps, with a guidance control and a negative prompt. Slower than the Lightning model. | | Qwen Image Edit 2509 Lightning | `nunchux-qwen-image-edit-2509-lightning` | Up to 3 | The earlier Qwen Image Edit release, in 8 steps, for work that already depends on it. | | Qwen Image Edit 2509 | `nunchux-qwen-image-edit-2509` | Up to 3 | Full-step Qwen Image Edit 2509, in 40 steps, with a guidance control and a negative prompt. Slower than the Lightning model. | | Qwen Image Edit | `nunchux-qwen-image-edit` | 1 | Full-step Qwen edits, with a guidance control and a negative prompt. Slower than the Lightning model. | | FLUX.2 dev | `nunchux-flux.2-dev` | Up to 6 | Full-step FLUX edits, with a guidance control. The same model as FLUX.2 dev text-to-image. | | FLUX 3 Image Klein Edit | `nunchux-flux.3-image-klein-edit` | Up to 10 | Edits and compositions of many images with the newest FLUX generation, in 16 steps. No guidance or negative prompt. | | FLUX 3 Image Klein Base Edit | `nunchux-flux.3-image-klein-base-edit` | Up to 10 | The undistilled FLUX 3 Image Klein Edit, in 16 to 50 steps, with a guidance control and a negative prompt. Slower than FLUX 3 Image Klein Edit. | | Qwen Image 2.1 Edit | `nunchux-qwen-image-2.1-edit` | Up to 10 | Edits up to 2752x2752, with a negative prompt. | See [Choosing a model](/nunchux-optimized/overview#choosing-a-model) for a comparison, and [Performance tiers](/performance-tiers) for the tiers that each model serves. ## Endpoint ```text theme={"system"} POST https://api.nunchux.com/v1/images/edits ``` ## Request Every request must include your API key and a JSON content type. See [Authentication](/authentication). **X-API-Key** `string` *required* Your API key. **Content-Type** `string` *required* Must be `application/json`. **model** `string` *required* The model that edits the image. Options: `nunchux-flux.2-klein-4b-edit`, `nunchux-flux.2-klein-9b-edit`, `nunchux-qwen-image-edit-2511-lightning`, `nunchux-qwen-image-edit-2511`, `nunchux-qwen-image-edit-2509-lightning`, `nunchux-qwen-image-edit-2509`, `nunchux-qwen-image-edit`, `nunchux-flux.2-dev`, `nunchux-flux.3-image-klein-edit`, `nunchux-flux.3-image-klein-base-edit`, `nunchux-qwen-image-2.1-edit` **url** `string` The source image, as a data URI (for example `data:image/png;base64,...`) or as a public URL. Send the source image in `url` or in `image`, not in both. Supported formats: PNG, JPEG, WebP. Maximum size: 10 MB. Each side must be at least 64 px. The aspect ratio must be no more extreme than 8:1 in either orientation. A remote URL must resolve to a public host. Nunchux does not follow redirects. When you send a data URI, Nunchux keeps a copy of the image so that it appears in your request history for 7 days. **image** `string | array` One source image, or a list of source images. Use a list to send more than one image. Each item follows the same rules as `url`: a data URI or a public URL. You can mix both kinds in one list. The model receives the images in the order of the list. The number of images that each model takes is in the [Models](#models) table. A list with more images than the model takes, or an empty list, returns a 400 with the `invalid_request` code. **prompt** `string` *required* A text description of the edit. Say what to change, add or remove. On Qwen Image 2.1 Edit, the prompt and the source images share 8192 positions. Each prompt token uses one. Each source image uses 64 when it is square, and up to 182 when it is long and narrow, such as 8:1. A request that needs more positions returns a 400 with `error.details.field` set to `prompt`. **tier** `string` (default: radical_speed) The balance of speed and cost. See [Performance tiers](/performance-tiers). Options: `radical_speed`, `radical_value` Qwen Image Edit and FLUX.2 dev have `radical_speed` only. On them, `radical_value` returns a 400. **width** `integer` *required* Output width in pixels. Send it together with `height`. Range: 1 to 8192. On Qwen Image Edit, Qwen Image Edit 2511, Qwen Image Edit 2511 Lightning, Qwen Image Edit 2509, Qwen Image Edit 2509 Lightning and FLUX.2 dev: 256 to 2048, in steps of 16. On FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit: 256 to 4096, in steps of 16. On Radical Value, FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit take at most 4,194,304 pixels (`width` times `height`, the area of 2048x2048), so 4096x1024 works and 2576x1632 returns a 400. On Qwen Image 2.1 Edit: 256 to 2752, in steps of 32. A size that is a multiple of 16 but not of 32, such as 1040, returns a 400 on Qwen Image 2.1 Edit. **height** `integer` *required* Output height in pixels. Send it together with `width`. Range: 1 to 8192. On Qwen Image Edit, Qwen Image Edit 2511, Qwen Image Edit 2511 Lightning, Qwen Image Edit 2509, Qwen Image Edit 2509 Lightning and FLUX.2 dev: 256 to 2048, in steps of 16. On FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit: 256 to 4096, in steps of 16. On Radical Value, FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit take at most 4,194,304 pixels (`width` times `height`, the area of 2048x2048), so 4096x1024 works and 2576x1632 returns a 400. On Qwen Image 2.1 Edit: 256 to 2752, in steps of 32. A size that is a multiple of 16 but not of 32, such as 1040, returns a 400 on Qwen Image 2.1 Edit. **n** `integer` (default: 1) The number of images to generate. Only 1 is supported. **response_format** `string` (default: b64_json) The format of the returned image. Options: `url`, `b64_json` In both formats, Nunchux keeps the generated image for 7 days, so that it appears in your request history. Then Nunchux deletes it. **steps** `integer` Qwen Image Edit, Qwen Image Edit 2511, Qwen Image Edit 2511 Lightning, Qwen Image Edit 2509, Qwen Image Edit 2509 Lightning, FLUX.2 dev, FLUX 3 Image Klein Edit, FLUX 3 Image Klein Base Edit and Qwen Image 2.1 Edit only. The number of denoising steps. Range: 1 to 8 on the two Lightning models, 1 to 16 on FLUX 3 Image Klein Edit, 16 to 50 on FLUX 3 Image Klein Base Edit, 1 to 50 on the others. Default: 8 on the two Lightning models, 16 on FLUX 3 Image Klein Edit, 40 on Qwen Image Edit 2511, Qwen Image Edit 2509 and Qwen Image 2.1 Edit, 50 on the others. More steps give more detail, but take longer. **true_cfg_scale** `number` Qwen Image Edit, Qwen Image Edit 2511, Qwen Image Edit 2509 and Qwen Image 2.1 Edit only. How closely the edit follows the prompt, and how strongly it avoids the `negative_prompt`. Range: 0.0 to 20.0. Default: 4.0 on Qwen Image Edit, Qwen Image Edit 2511 and Qwen Image Edit 2509, 1.0 on Qwen Image 2.1 Edit. On Qwen Image 2.1 Edit, the default 1.0 has no effect. Send a value above 1.0 together with `negative_prompt`. **guidance_scale** `number` (default: 4) FLUX.2 dev and FLUX 3 Image Klein Base Edit only. How closely the edit follows the prompt. Range: 0.0 to 20.0. Default: 4.0. **negative_prompt** `string` Qwen Image Edit, Qwen Image Edit 2511, Qwen Image Edit 2509, Qwen Image 2.1 Edit and FLUX 3 Image Klein Base Edit only. What the edited image must not show. On Qwen Image 2.1 Edit, it takes effect only when you also send `true_cfg_scale` above 1.0. **prompt_expansion** `string` (default: off) FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit only. With `standard`, Nunchux rewrites the prompt into a detailed description of the result before the image renders. It adds about 3 to 4 seconds. The response returns the rewritten prompt as `revised_prompt`. FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit follow a full description much better than a short prompt, so send `standard` unless your prompt already describes the whole result. Options: `off`, `standard` **seed** `integer` The random seed. The same seed with the same parameters gives the same result. **content_moderation** `boolean` (default: true) Whether Nunchux's content filter checks this request. Only accounts approved to turn moderation off may send `false`. Others get a 403. See [Content moderation](/content-moderation). > [!NOTE] > > Dimensions > > * Send `width` and `height` together. A request with only one of them returns a 400. > * Every image-to-image model is priced per megapixel today and charges from the output area. A request with no dimensions returns a 400. The API does not use the source image size or a default size. > * Both values must be integers. The string `"1024"` is rejected, not converted. > * The source image is a reference, not a canvas. The model does not crop or stretch it to `width` and `height`. When the source ratio is different from the output ratio, the model re-frames the content. With several source images, `width` and `height` alone set the output size. > * Smaller source images process faster. Larger output images take longer to generate. A minimal request body: ```json theme={"system"} { "model": "nunchux-qwen-image-edit-2511-lightning", "url": "https://example.com/example.jpg", "prompt": "Transform into a watercolor painting", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" } ``` A request body for Qwen Image 2.1 Edit. Its `width` and `height` are multiples of 32: ```json theme={"system"} { "model": "nunchux-qwen-image-2.1-edit", "url": "https://example.com/example.jpg", "prompt": "Transform into a watercolor painting", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" } ``` A request body for FLUX 3 Image Klein Edit, with prompt expansion. The response returns the rewritten prompt in `data[0].revised_prompt`: ```json theme={"system"} { "model": "nunchux-flux.3-image-klein-edit", "url": "https://example.com/example.jpg", "prompt": "Make it a rainy night", "prompt_expansion": "standard", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" } ``` ## Response The response is JSON. The `data` array contains the edited image, as base64 data or as a URL. **created** `integer` *required* The Unix timestamp of the generation. **data** `array` *required* The generated items. **Item properties** **url** `string` The URL of the image. Returned when `response_format` is `url`. **b64_json** `string` The image as base64 data. Returned when `response_format` is `b64_json`. **revised_prompt** `string` FLUX 3 Image Klein Edit and FLUX 3 Image Klein Base Edit only. The rewritten prompt that the model rendered. Returned when `prompt_expansion` is `standard` and the rewrite succeeds. **model** `string` *required* The model that edited the image. **tier** `string` *required* The tier that served the request: `radical_speed` or `radical_value`. ```json Base64 format theme={"system"} { "created": 1234567890, "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAYAAAB/HSuDAAAACXBIWXMAAA7EAAAOxAGVKw4b..." } ], "model": "nunchux-qwen-image-edit-2511-lightning", "tier": "radical_speed" } ``` ```json URL format theme={"system"} { "created": 1234567890, "data": [ { "url": "https://example.com/edited-image.png" } ], "model": "nunchux-qwen-image-edit-2511-lightning", "tier": "radical_speed" } ``` To save a base64 result from cURL, add this pipe to the command: ```bash theme={"system"} # Replace output.jpg with the file name that you want. | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ## Example ```bash cURL theme={"system"} # The media URL below is a placeholder. Point it at your own publicly # reachable file before running this. curl -X POST https://api.nunchux.com/v1/images/edits \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-qwen-image-edit-2511-lightning", "url": "https://example.com/example.jpg", "prompt": "Transform into a watercolor painting", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ```python Python theme={"system"} # The media URL below is a placeholder. Point it at your own publicly # reachable file before running this. import os import base64 import requests response = requests.post( "https://api.nunchux.com/v1/images/edits", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-qwen-image-edit-2511-lightning", "url": "https://example.com/example.jpg", "prompt": "Transform into a watercolor painting", "tier": "radical_speed", "width": 1024, "height": 1024, }, ) # Decode the base64 image and save it. Change output.jpg to any file name. image_b64 = response.json()["data"][0]["b64_json"] with open("output.jpg", "wb") as f: f.write(base64.b64decode(image_b64)) ``` ```javascript JavaScript theme={"system"} // The media URL below is a placeholder. Point it at your own publicly // reachable file before running this. import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.nunchux.com/v1/images/edits", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-qwen-image-edit-2511-lightning", url: "https://example.com/example.jpg", prompt: "Transform into a watercolor painting", tier: "radical_speed", width: 1024, height: 1024, }), }); const data = await response.json(); // Decode the base64 image and save it. Change output.jpg to any file name. await writeFile("output.jpg", Buffer.from(data.data[0].b64_json, "base64")); ``` ```python Python (OpenAI) theme={"system"} # Replace photo.jpg with the path to your source image. import os import requests from openai import OpenAI client = OpenAI( base_url="https://api.nunchux.com/v1", api_key=os.environ["NUNCHUX_API_KEY"], ) response = client.images.edit( model="nunchux-qwen-image-edit-2511-lightning", image=open("photo.jpg", "rb"), prompt="Transform into a watercolor painting", response_format="url", extra_body={"width": 1024, "height": 1024}, ) # This tab returns a URL. Download it and save it. Change output.jpg to any file name. image_url = response.data[0].url with open("output.jpg", "wb") as f: f.write(requests.get(image_url).content) ``` ## Several source images Send a list in `image`. Say in the prompt what to take from each image. This request puts the person from the first image into the scene of the second: ```bash cURL theme={"system"} # The media URLs below are placeholders. Point them at your own publicly # reachable files before running this. curl -X POST https://api.nunchux.com/v1/images/edits \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-flux.2-klein-9b-edit", "image": [ "https://example.com/person.jpg", "https://example.com/beach.jpg" ], "prompt": "Place the person from the first image on the beach from the second image", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ```python Python (OpenAI) theme={"system"} # Replace person.jpg and beach.jpg with the paths to your source images. import os import requests from openai import OpenAI client = OpenAI( base_url="https://api.nunchux.com/v1", api_key=os.environ["NUNCHUX_API_KEY"], ) response = client.images.edit( model="nunchux-flux.2-klein-9b-edit", image=[open("person.jpg", "rb"), open("beach.jpg", "rb")], prompt="Place the person from the first image on the beach from the second image", response_format="url", extra_body={"width": 1024, "height": 1024}, ) # This tab returns a URL. Download it and save it. Change output.jpg to any file name. image_url = response.data[0].url with open("output.jpg", "wb") as f: f.write(requests.get(image_url).content) ``` > [!NOTE] > > Upload limit with the OpenAI SDK > > The OpenAI SDK uploads the files as a form, with one `image[]` part for each file. A form takes up to 10 image files, so it can send as many images as any model takes. Each file must be PNG, JPEG or WebP, and 10 MB or smaller. ## Tips * Say exactly what to change, add or remove. The models can follow instructions with more than one change. * With several source images, refer to each one by its place in the list, for example "the person from the first image". * Use Qwen Image Edit 2511 Lightning when the edit must keep the identity of the subject, or when it changes text in the image. * Use FLUX.2 Klein 4B Edit for fast, high-volume edit passes. * Use Qwen Image Edit 2511 or Qwen Image Edit when you want more detail than the Lightning model gives and the extra time is acceptable. Qwen Image Edit 2511 takes up to 3 source images. Use `negative_prompt` to keep things out of the edit. * Use Qwen Image Edit 2509 or Qwen Image Edit 2509 Lightning when your work already depends on the 2509 release. For new work, use Qwen Image Edit 2511 or Qwen Image Edit 2511 Lightning. * Use FLUX.2 dev for detailed edits when you already generate with FLUX.2 dev. Steer it with `guidance_scale`. * Use FLUX 3 Image Klein Edit for fast edits, and to combine up to 10 source images. Describe the whole result in the prompt: the subject, the setting, the light and the style, or send `prompt_expansion` set to `standard` to have Nunchux write the description. It takes no guidance and no negative prompt. * Use FLUX 3 Image Klein Base Edit when you want more detail or more control than FLUX 3 Image Klein Edit gives, and the extra time is acceptable. It also takes up to 10 source images. Steer it with `guidance_scale` and `negative_prompt`, and send `prompt_expansion` set to `standard` for a short prompt. * Use Qwen Image 2.1 Edit for edits up to 2752x2752, or with up to 10 source images. Send `width` and `height` in multiples of 32. * Use `radical_speed` when response time is important. Use `radical_value` for large batches where cost per image is more important. Qwen Image Edit and FLUX.2 dev have `radical_speed` only. * Send smaller source images for faster processing. ## Errors and limits | Status | Code | Cause | | - | - | - | | 400 | none | A required field is missing, the model ID is not valid, or a value is not valid. The body is a plain `detail` string. | | 400 | `invalid_request` | The model does not offer the `tier` you sent, for example `radical_value` on Qwen Image Edit. `error.details.reason` is `tier_not_available`. | | 400 | `invalid_request` | The request sends more source images than the model takes, or an empty list. `error.details.field` is `image`. With too many images, `error.details.reason` is `too_many_images` and `error.details.limit` is the model's cap. | | 400 | `invalid_request` | The model does not take a field you sent, or does not take its value. For example: `guidance_scale` or `negative_prompt` on FLUX 3 Image Klein Edit, a `steps` value outside 16 to 50 on FLUX 3 Image Klein Base Edit, a `prompt_expansion` mode other than `off` or `standard`, `guidance_scale` on Qwen Image 2.1 Edit, or a size the model does not render, such as 2784x2784 or 1040x1040 on Qwen Image 2.1 Edit. `error.details.field` names the field, and `error.details.reason` is `field_not_accepted`. | | 400 | `engine_error` | The model cannot render the request, or a source image is rejected: the URL cannot be fetched, the data URI cannot be decoded, or the image is outside the size and ratio limits. | | 403 | `model_not_available` | Your account does not have access to this model. | | 504 | `engine_timeout` | Nunchux could not fetch the source image in time. Make sure that the URL is reachable and fast, or send the image as a data URI. | > [!NOTE] > > Refused requests > > * Nunchux charges only after a successful generation. A refused request is never billed. > * Do not branch on a dimension-specific code. A refused size, field or image list returns `invalid_request`, and `error.details.field` names the field. `engine_error` means the model could not render the request, or a source image was rejected. For authentication, credit and rate-limit errors, see [Error codes](/errors). Every request counts toward the requests-per-minute cap of your plan. See [Rate limits](/rate-limits). # Image-to-video Source: https://docs.nunchux.ai/nunchux-optimized/image-to-video Animate a still image into a video clip with LTX. The clip is in the response. # Image-to-video Send one image and a text prompt that describes the motion. The image becomes the first frame of the clip. The response contains the generated video clip. The request is synchronous. There is no task to poll. A clip is 1 to 8 seconds long, at 1080p or 720p, with an optional soundtrack. ## Models | Model | Model ID | Use it for | | - | - | - | | LTX 2.5 | `nunchux-ltx-2.5-video` | New work. The newer release, with the same controls as LTX 2.3. | | LTX 2.3 | `nunchux-ltx-2.3-video` | Continuity with clips that you already made with LTX 2.3. | Both models also serve [Text-to-video](/nunchux-optimized/text-to-video). See [Choosing a model](/nunchux-optimized/overview#choosing-a-model). ## Endpoint ```text theme={"system"} POST https://api.nunchux.com/v1/video/animations ``` The path `/v1/videos/animations` is an alias. It gives the same result and the same billing. ## Request Every request must include your API key and a JSON content type. See [Authentication](/authentication). **X-API-Key** `string` *required* Your API key. **Content-Type** `string` *required* Must be `application/json`. **model** `string` *required* The model that generates the clip. Options: `nunchux-ltx-2.5-video`, `nunchux-ltx-2.3-video` **prompt** `string` *required* A text description of the motion. Describe what moves, the camera movement and the light. Do not describe again what the image already shows. **messages** `array` *required* The input image. Send one message with one `image_url` part. The model accepts one image. **properties** **role** `string` *required* Must be `user`. **content** `array` *required* The parts of the message. **properties** **type** `string` *required* `image_url` for the image part. **image_url.url** `string` *required* The image, as a data URI (for example `data:image/jpeg;base64,...`) or as a public `https` URL. Use a PNG or JPEG image. The clip keeps the framing of the image. You can also send the image as a top-level `image_url` string. When you send a data URI, Nunchux keeps a copy of the image so that it appears in your request history for 7 days. **width** `integer` (default: 1920) Output width in pixels. Send it together with `height`. The size selects the tier, 1080p or 720p. 1080p costs more per second. Options: `1920` (1080p), `1280` (720p) **height** `integer` (default: 1080) Output height in pixels. Send it together with `width`. Options: `1080` (1080p), `720` (720p) **duration** `number` (default: 6) The clip length in seconds. Range: 1 to 8. The model renders at 24 frames per second, so the length of the clip can differ from your value by a fraction of a second. The response gives the length of the clip. **extra** `object` Model options. **properties** **audio** `boolean` (default: false) When `true`, the model generates a soundtrack with the picture. Describe the sound in the prompt. **seed** `integer` The random seed. When you do not send a seed, the model selects one and returns it in the response. The same seed with the same parameters gives the same result. **content_moderation** `boolean` (default: true) Whether Nunchux's content filter checks this request. Only accounts approved to turn moderation off may send `false`. Others get a 403. See [Content moderation](/content-moderation). **n** `integer` (default: 1) The number of clips to generate. Only 1 is supported. **response_format** `string` (default: b64_json) The format of the returned clip. Options: `b64_json`, `url` In `url` format, Nunchux keeps the generated clip for 7 days, so that it appears in your request history. Then Nunchux deletes it. In `b64_json` format, Nunchux also tries to keep a copy for your request history, but it skips the copy when the service is busy. Save the clip from the response if you need to keep it. > [!NOTE] > > Unsupported fields > > LTX does not accept `steps`, `guidance_scale`, `negative_prompt` or `num_frames`. A request that contains one of them returns a 400. A minimal request body: ```json theme={"system"} { "model": "nunchux-ltx-2.3-video", "prompt": "The scene comes to life with gentle motion", "width": 1280, "height": 720, "duration": 6, "extra": { "audio": false }, "response_format": "b64_json", "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://example.com/first-frame.jpg" } } ] } ] } ``` ## Response The response is JSON. The `data` array contains one MP4 clip, as base64 data or as a URL. **created** `integer` *required* The Unix timestamp of the generation. **model** `string` *required* The model that generated the clip. **tier** `string` *required* Always `radical_speed`. This field does not show the LTX tier. The `width` and `height` of the clip show it. **seed** `integer` *required* The seed of the clip. Send it again to get the same result. **data** `array` *required* The generated clip. **Item properties** **b64_json** `string` The MP4 clip as base64 data. Returned when `response_format` is `b64_json`. **url** `string` The URL of the MP4 clip. Returned when `response_format` is `url`. **width** `integer` The width of the clip in pixels. **height** `integer` The height of the clip in pixels. **duration** `number` The length of the clip in seconds. **frames** `integer` The number of frames in the clip. **frame_rate** `integer` The frame rate of the clip. ```json theme={"system"} { "created": 1234567890, "model": "nunchux-ltx-2.3-video", "tier": "radical_speed", "seed": 1873420651, "data": [ { "b64_json": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQ...", "width": 1280, "height": 720, "duration": 6.0417, "frames": 145, "frame_rate": 24 } ] } ``` A base64 clip is large. A 6 second 1080p clip can be more than 10 MB of base64 data. Use `response_format: "url"` when you do not need the data in the response. ## Example This example reads a local JPEG file and sends it as a data URI. A clip takes some time to render. Set the timeout of your HTTP client to 120 seconds. ```bash cURL theme={"system"} # Encode input.jpg as base64 on one line. IMG_B64=$(base64 < input.jpg | tr -d '\n') curl -X POST https://api.nunchux.com/v1/video/animations \ --max-time 120 \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-ltx-2.3-video", "prompt": "The scene comes to life with gentle motion", "width": 1280, "height": 720, "duration": 6, "extra": {"audio": false}, "response_format": "b64_json", "messages": [{ "role": "user", "content": [ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,'"$IMG_B64"'"}} ] }] }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.mp4 ``` ```python Python theme={"system"} import os import base64 import requests with open("input.jpg", "rb") as f: image_uri = "data:image/jpeg;base64," + base64.b64encode(f.read()).decode() response = requests.post( "https://api.nunchux.com/v1/video/animations", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-ltx-2.3-video", "prompt": "The scene comes to life with gentle motion", "width": 1280, "height": 720, "duration": 6, "extra": {"audio": False}, "response_format": "b64_json", "messages": [ { "role": "user", "content": [{"type": "image_url", "image_url": {"url": image_uri}}], } ], }, timeout=120, ) response.raise_for_status() # Decode the base64 clip and save it. Change output.mp4 to any file name. clip_b64 = response.json()["data"][0]["b64_json"] with open("output.mp4", "wb") as f: f.write(base64.b64decode(clip_b64)) ``` ```javascript JavaScript theme={"system"} import { readFile, writeFile } from "node:fs/promises"; const imageUri = "data:image/jpeg;base64," + (await readFile("input.jpg")).toString("base64"); const response = await fetch("https://api.nunchux.com/v1/video/animations", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-ltx-2.3-video", prompt: "The scene comes to life with gentle motion", width: 1280, height: 720, duration: 6, extra: { audio: false }, response_format: "b64_json", messages: [ { role: "user", content: [{ type: "image_url", image_url: { url: imageUri } }], }, ], }), signal: AbortSignal.timeout(120_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); const data = await response.json(); // Decode the base64 clip and save it. Change output.mp4 to any file name. await writeFile("output.mp4", Buffer.from(data.data[0].b64_json, "base64")); ``` ## Tips * Write the motion, not the image. Say what moves, how the camera moves, and how the light changes. * Use an image with the framing that you want in the clip. The clip keeps the framing of the image. * When `extra.audio` is `true`, describe the sound in the prompt. * Start at 1080p and 6 seconds. Use 720p for faster and lower-cost previews. * Keep the `seed` when you like a result. Then change one parameter at a time. ## Errors and limits | Status | Code | Cause | | - | - | - | | 400 | none | `model` is missing or not valid, or a size value is not valid. The body is a plain `detail` string. | | 400 | `invalid_request` | The request sets `tier` to a value other than `radical_speed`. On LTX, `width` and `height` select the tier. Do not send the `tier` field. | | 400 | `unsupported_response_format` | `response_format` is not `b64_json` or `url`. | | 400 | `engine_error` | The model cannot render the request, for example a size, a duration, an image that it cannot read, more than one image, or a field that it does not accept. | | 422 | `request_too_large` | The requested size is larger than 1920x1080. `details` gives the requested value and the maximum. | | 502 | `output_too_large` | The clip is too large to return. You are not charged. Request a shorter clip or a smaller size. | | 504 | none | The clip did not complete in 120 seconds. Send the request again. | A clip is billed per second of output video, at the rate of its tier: 1080p costs more per second than 720p. See the [pricing page](https://nunchux.ai/pricing) for current rates. Nunchux charges only for a successful clip. A request that fails is never billed. Every request counts toward the requests-per-minute cap of your plan. A request also holds one simultaneous-jobs slot until the response returns. See [Rate limits](/rate-limits). For authentication and credit errors, see [Error codes](/errors). # MiniMax H3 Fast Source: https://docs.nunchux.ai/nunchux-optimized/minimax-h3-fast Generate a video clip with its own soundtrack from a prompt, from a first and last frame, or from reference images, clips and audio. The clip is in the response. # MiniMax H3 Fast MiniMax H3 Fast is MiniMax H3 on the Nunchux engine. It generates a video clip and its soundtrack together, in one request. The request is synchronous. There is no task to poll. Two model IDs serve it. They share one request shape, and the `refs` list carries the inputs: | Model | Model ID | Task | Inputs in `refs` | | - | - | - | - | | MiniMax H3 Fast | `nunchux-minimax-h3-fast-fl2va` | Text-to-video, or a clip that starts or ends on your frames | None, or a first frame, a last frame, or both | | MiniMax H3 Fast | `nunchux-minimax-h3-fast-ref2va` | Reference-to-video | Reference images, reference clips and audio tracks | Both models have the Radical Speed and Radical Value tiers. A clip is 4 to 15 seconds long, with a short edge of 480 or 768 pixels. For MiniMax's own H3 API, with its asynchronous task flow and 2K output, see [MiniMax H3](/partner-models/minimax). ## Endpoint ```text theme={"system"} POST https://api.nunchux.com/v1/videos/generations ``` The older path `/v1/video/generations` still works, with the same result and the same billing, but it is deprecated. Use `/v1/videos/generations` in new code. ## Request Every request must include your API key and a JSON content type. See [Authentication](/authentication). **X-API-Key** `string` *required* Your API key. **Content-Type** `string` *required* Must be `application/json`. **model** `string` *required* The model that generates the clip. Options: `nunchux-minimax-h3-fast-fl2va`, `nunchux-minimax-h3-fast-ref2va` **prompt** `string` *required* A text description of the clip. Describe the shot, what changes during the clip, and the sound. With references, name them by their order: Image 1, Video 1, Audio 1. **tier** `string` (default: radical_speed) The balance of speed and cost. See [Performance tiers](/performance-tiers). Options: `radical_speed`, `radical_value` **duration** `number` (default: 5.1667) The clip length in seconds. Range: 4 to 15. The model renders at 24 frames per second on a fixed frame grid, so the clip can run up to two-thirds of a second longer than your value. A request for 4 seconds returns a 4.46 second clip. The response gives the length of the clip. **refs** `array` The input media, in order. Each item names its role and a public `https` URL. On `nunchux-minimax-h3-fast-fl2va`, send no `refs` for text-to-video. See [Inputs](#inputs) for the roles each model takes. **Item properties** **role** `string` *required* What the input is for. Options: `first_frame`, `last_frame`, `reference_image`, `reference_video`, `reference_audio` **url** `string` *required* A public `https` URL of the file. An `http` URL returns a 400. **extra** `object` The shape of the clip. **properties** **short_edge** `integer` (default: 768) The short edge of the clip in pixels. 768 costs more per second than 480. Options: `480`, `768` **aspect_ratio** `string` (default: 16:9) The shape of the clip. The long edge follows the ratio, rounded to a multiple of 32, and the clip stays under about one megapixel. At 16:9, 480 gives 864x480 and 768 gives 1344x768. At 21:9, 768 gives 1536x672. Options: `21:9`, `16:9`, `4:3`, `1:1`, `3:4`, `9:16` **prompt_expansion** `string` (default: off) With any mode other than `off`, the prompt is rewritten into a detailed shot description before the clip renders. The rewriter sees your frames, images and clips. `fast` adds a few seconds. `standard`, `balanced` and `quality` give fuller rewrites and take longer. The response returns the rewritten prompt as `revised_prompt`. Options: `off`, `fast`, `standard`, `balanced`, `quality` **seed** `integer` The random seed. When you do not send a seed, the model selects one and returns it in the response. The same seed with the same parameters gives the same result. **content_moderation** `boolean` (default: true) Whether Nunchux's content filter checks this request. Only accounts approved to turn moderation off may send `false`. Others get a 403. See [Content moderation](/content-moderation). **n** `integer` (default: 1) The number of clips to generate. Only 1 is supported. **response_format** `string` (default: b64_json) The format of the returned clip. Options: `b64_json`, `url` In `url` format, Nunchux keeps the generated clip for 7 days, so that it appears in your request history. Then Nunchux deletes it. Save the clip from the response if you need to keep it. > [!NOTE] > > Unsupported fields > > MiniMax H3 Fast does not accept `width`, `height`, `steps`, `guidance_scale` or `negative_prompt`. Set the shape with `extra.short_edge` and `extra.aspect_ratio`. A request that contains one of them returns a 400. ## Inputs Each model takes its own roles in `refs`. A role that the model does not take returns a 400. | Model ID | Role | Limit | | - | - | - | | `nunchux-minimax-h3-fast-fl2va` | `first_frame` | 1 image. The clip starts on it. | | `nunchux-minimax-h3-fast-fl2va` | `last_frame` | 1 image. The clip ends on it. | | `nunchux-minimax-h3-fast-ref2va` | `reference_image` | Up to 9 images | | `nunchux-minimax-h3-fast-ref2va` | `reference_video` | Up to 3 clips, 2 to 15 seconds each, 15 seconds in all | | `nunchux-minimax-h3-fast-ref2va` | `reference_audio` | Up to 3 audio tracks | `nunchux-minimax-h3-fast-fl2va` takes a first frame, a last frame, both, or neither. With neither, it generates the clip from the prompt alone. `nunchux-minimax-h3-fast-ref2va` needs at least one reference. A request with no `refs` returns a 400. In the prompt, name each reference by its role and its position in `refs`: the first `reference_image` is Image 1, the first `reference_video` is Video 1, and the first `reference_audio` is Audio 1. The files must meet these limits: * Images: up to 30 MB, each side 256 to 5760 pixels, and a width-to-height ratio from 0.4 to 2.5. * Clips: up to 50 MB, each side 256 to 5760 pixels, a width-to-height ratio from 0.4 to 2.5, and 23.976 to 60 frames per second. Send MP4 or MOV, so that Nunchux can read the clip length for billing. * Audio: up to 15 MB. A minimal text-to-video body: ```json theme={"system"} { "model": "nunchux-minimax-h3-fast-fl2va", "prompt": "A paper boat drifts down a rain-filled gutter at dusk, the patter of rain and a distant tram bell", "duration": 6, "extra": { "short_edge": 480, "aspect_ratio": "16:9" }, "response_format": "url" } ``` A body that starts and ends the clip on your frames: ```json theme={"system"} { "model": "nunchux-minimax-h3-fast-fl2va", "prompt": "The flower opens slowly in the morning light, birdsong in the background", "duration": 6, "refs": [ { "role": "first_frame", "url": "https://example.com/bud.png" }, { "role": "last_frame", "url": "https://example.com/bloom.png" } ], "extra": { "short_edge": 768, "aspect_ratio": "1:1" }, "response_format": "url" } ``` A reference-to-video body: ```json theme={"system"} { "model": "nunchux-minimax-h3-fast-ref2va", "prompt": "Reference the camera movement from Video 1, have the character in Image 1 sing, with the vocals matching Audio 1", "duration": 6, "refs": [ { "role": "reference_image", "url": "https://example.com/singer.png" }, { "role": "reference_video", "url": "https://example.com/camera-move.mp4" }, { "role": "reference_audio", "url": "https://example.com/vocals.mp3" } ], "extra": { "short_edge": 480, "aspect_ratio": "16:9" }, "prompt_expansion": "fast", "response_format": "url" } ``` ## Response The response is JSON. The `data` array contains one MP4 clip, with its soundtrack, as base64 data or as a URL. **created** `integer` *required* The Unix timestamp of the generation. **model** `string` *required* The model that generated the clip. **tier** `string` *required* The tier that served the request: `radical_speed` or `radical_value`. **seed** `integer` *required* The seed of the clip. Send it again to get the same result. **prompt_expansion** `object` Returned when `prompt_expansion` is not `off`. `mode` is the mode you sent. `outcome` is `expanded` when the clip rendered from the rewritten prompt. **data** `array` *required* The generated clip. **Item properties** **b64_json** `string` The MP4 clip as base64 data. Returned when `response_format` is `b64_json`. **url** `string` The URL of the MP4 clip. Returned when `response_format` is `url`. **width** `integer` The width of the clip in pixels. **height** `integer` The height of the clip in pixels. **duration** `number` The length of the clip in seconds. **frames** `integer` The number of frames in the clip. **frame_rate** `integer` The frame rate of the clip. **revised_prompt** `string` The rewritten prompt that the model rendered. Returned when `prompt_expansion` is not `off` and the rewrite succeeds. ```json theme={"system"} { "created": 1234567890, "model": "nunchux-minimax-h3-fast-fl2va", "tier": "radical_speed", "seed": 1536904073, "data": [ { "url": "https://...", "width": 864, "height": 480, "duration": 4.4583, "frames": 107, "frame_rate": 24 } ] } ``` ## Example A clip takes some time to render. A 6 second clip at 480 takes about 6 seconds on Radical Speed and about 20 seconds on Radical Value. Set the timeout of your HTTP client to 120 seconds. ```bash cURL theme={"system"} curl -X POST https://api.nunchux.com/v1/videos/generations \ --max-time 120 \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-minimax-h3-fast-fl2va", "prompt": "A paper boat drifts down a rain-filled gutter at dusk, the patter of rain and a distant tram bell", "tier": "radical_speed", "duration": 6, "extra": {"short_edge": 480, "aspect_ratio": "16:9"}, "response_format": "b64_json" }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.mp4 ``` ```python Python theme={"system"} import os import base64 import requests response = requests.post( "https://api.nunchux.com/v1/videos/generations", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-minimax-h3-fast-fl2va", "prompt": "A paper boat drifts down a rain-filled gutter at dusk, the patter of rain and a distant tram bell", "tier": "radical_speed", "duration": 6, "extra": {"short_edge": 480, "aspect_ratio": "16:9"}, "response_format": "b64_json", }, timeout=120, ) response.raise_for_status() # Decode the base64 clip and save it. Change output.mp4 to any file name. clip_b64 = response.json()["data"][0]["b64_json"] with open("output.mp4", "wb") as f: f.write(base64.b64decode(clip_b64)) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.nunchux.com/v1/videos/generations", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-minimax-h3-fast-fl2va", prompt: "A paper boat drifts down a rain-filled gutter at dusk, the patter of rain and a distant tram bell", tier: "radical_speed", duration: 6, extra: { short_edge: 480, aspect_ratio: "16:9" }, response_format: "b64_json", }), signal: AbortSignal.timeout(120_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); const data = await response.json(); // Decode the base64 clip and save it. Change output.mp4 to any file name. await writeFile("output.mp4", Buffer.from(data.data[0].b64_json, "base64")); ``` ## Billing A clip is billed per second of output video, at the rate of its tier and its short edge. 768 costs more per second than 480, and Radical Value costs less than Radical Speed. The billed seconds are the `duration` you send, not the slightly longer clip that returns. Inputs add to the charge only on `nunchux-minimax-h3-fast-ref2va`: * Each reference clip is billed per second of its length, at the same rate as the output. A clip whose length Nunchux cannot read, such as a WebM file, is billed as 15 seconds. * The first 5 reference images are free. Each image after the fifth has a fixed price. * Reference audio is free. First and last frames on `nunchux-minimax-h3-fast-fl2va` are free. See the [pricing page](https://nunchux.ai/pricing) for current rates. Nunchux charges only for a successful clip. A request that fails is never billed. ## Tips * Describe the sound in the prompt as well as the picture. The model generates both. * On `nunchux-minimax-h3-fast-ref2va`, say what each reference is for: the character in Image 1, the camera movement from Video 1, the voice in Audio 1. * Draft at 480 on Radical Speed. Use 768 for the final clip, and Radical Value for large batches. * Use `prompt_expansion` set to `fast` for a short prompt. Use `off` when your prompt already describes the shot in detail. * Keep the `seed` when you like a result. Then change one parameter at a time. ## Errors and limits | Status | Code | Cause | | - | - | - | | 400 | none | `extra.short_edge` has no price, for example 1080. The body is a plain `detail` string that names the priced short edges. | | 400 | `engine_error` | The model cannot render the request, for example a short edge other than 480 or 768, an aspect ratio off the list, a `duration` under 4 or over 15, an unsupported field, `n` above 1, a role the model does not take, too many references, or a reference URL that is not `https`. | Every request counts toward the requests-per-minute cap of your plan. A request also holds one simultaneous-jobs slot until the response returns. See [Rate limits](/rate-limits). For authentication and credit errors, see [Error codes](/errors). # OpenAI Compatibility Source: https://docs.nunchux.ai/nunchux-optimized/openai-compatibility Use the OpenAI Python or JavaScript SDK with the Nunchux API for image generation. # OpenAI Compatibility ### Use the OpenAI SDK with the Nunchux API ## Overview The Nunchux API is compatible with the [OpenAI Python SDK](https://github.com/openai/openai-python). Point the client at the [Nunchux base URL](/nunchux-optimized/overview#endpoints) and use your [Nunchux API key](/authentication). Your existing OpenAI code keeps working. ## Installation Install the OpenAI Python SDK: ```bash theme={"system"} pip install openai ``` ## Client Setup Point the OpenAI client at the Nunchux API by setting the `base_url` and `api_key`. ```python theme={"system"} from openai import OpenAI client = OpenAI( base_url="https://api.nunchux.com/v1", api_key="YOUR_API_KEY", ) ``` The SDK sends your key as an `Authorization: Bearer` header, which the Nunchux API accepts on every endpoint. See [Authentication](/authentication) for details. ## Text-to-Image Generate images from text descriptions using `client.images.generate()`. Nunchux-specific parameters like `tier` and `seed` are passed via `extra_body`. ```python theme={"system"} import base64 from pathlib import Path response = client.images.generate( model="nunchux-flux.2-klein-4b", prompt="A beautiful sunset over mountains", size="1024x1024", response_format="b64_json", n=1, extra_body={ "tier": "radical_speed", "seed": 42, }, ) image_b64 = response.data[0].b64_json Path("output.png").write_bytes(base64.b64decode(image_b64)) ``` ## Image-to-Image Edit and transform existing images using `client.images.edit()`. Pass the source image as a file object opened in binary mode. ```python theme={"system"} response = client.images.edit( model="nunchux-flux.2-klein-4b-edit", image=open("photo.jpg", "rb"), prompt="Transform into a watercolor painting", size="1024x1024", response_format="url", extra_body={ "tier": "radical_speed", }, ) # URL format requested above print(response.data[0].url) ``` ## Nunchux-Specific Parameters The OpenAI SDK does not natively support all Nunchux parameters. Use the `extra_body` argument to pass Nunchux-specific fields. **tier** `string` Performance tier controlling the tradeoff between speed and cost. See [Performance Tiers](/performance-tiers) for details. Options: `radical_speed`, `radical_value` **seed** `integer` Random seed for reproducible generation. Use the same seed with identical parameters for consistent results. **width** `integer` Output width in pixels. Send it together with `height`. The two fields take precedence over the standard `size` argument. Models priced per megapixel require `width` and `height`, or `size`. Range: 1-8192. **height** `integer` Output height in pixels. Send it together with `width`. Models priced per megapixel require `width` and `height`, or `size`. Range: 1-8192. > [!NOTE] > > Sizing > > The examples on this page use `size` because it is the standard OpenAI argument and it works. Elsewhere in these docs you will see `width` and `height`, which are the preferred spelling. The API accepts either form and resolves both to the same dimensions. Pass them through `extra_body` if you want to match the rest of the platform. > > Models priced per megapixel need dimensions. The [pricing page](https://nunchux.ai/pricing) shows each model's unit. Today, every image model except Ideogram 4 is priced per megapixel. The OpenAI SDK sends no `size` unless you set it. On a per-megapixel model, a request with neither `size` nor `width` and `height` returns a 400. ## Using Other SDK Format Nothing about the API is Python-specific. The official [OpenAI Node SDK](https://github.com/openai/openai-node) works against the same base URL and the same key. | | Python | Node | TypeScript | | - | - | - | - | | Base URL | `base_url` | `baseURL` | `baseURL` | | API key | `api_key` | `apiKey` | `apiKey` | | Methods | `client.images.generate()` | `client.images.generate()` | `client.images.generate()` | | Nunchux params | `extra_body={...}` | inline in the request object | inline, assigned to a variable | | Input image | `open("photo.jpg", "rb")` | a stream, or `toFile()` | a stream, or `toFile()` | > [!NOTE] > > TypeScript > > TypeScript refuses undeclared properties in an object literal, but applies that check only to literals. Assign the parameters to a variable first. This rule is TypeScript excess property checking, not an API limit. See the [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/2/objects.html#excess-property-checks) for the full rule. ## Limitations The API speaks the OpenAI image shape, but it is not OpenAI. Two differences matter when you port existing code: 1. `n` must be 1. One image per request. Any other value returns `400`. Send concurrent requests to generate a batch. 2. Errors do not use the OpenAI error shape. See [Error Handling](#error-handling) below. ## Error Handling Two error shapes are in use. Most endpoints return `detail` and `request_id`. Migrated endpoints add a catalog envelope under `error`. ```jsonc theme={"system"} // Rejecting n=4 { "detail": "only n=1 is currently supported for image requests, got n=4", "request_id": "9f3c1e2a4b5d4f6e8a7b9c0d1e2f3a4b" } ``` On `/v1/images/generations`, a non-integer `n` also returns HTTP 400 with a plain `detail` string. The message text depends on the model. This example is from a per-megapixel model: ```jsonc theme={"system"} // Rejecting n="not-a-number" on a per-megapixel model (HTTP 400) { "detail": "n must be a positive integer for per-megapixel billing, got 'not-a-number'", "request_id": "9f3c1e2a4b5d4f6e8a7b9c0d1e2f3a4b" } ``` Neither shape carries OpenAI's `type` or `param`, so `.type` and `.param` on the raised exception are always `None`. Branch on the HTTP status code, not on the error body. `request_id` is present on both shapes. Quote it when you contact support. It is how we find your request. See [Errors](/errors) for the full code catalog. ## Supported models Every Nunchux Optimized image model works with the OpenAI SDK. See the [models table](/nunchux-optimized/overview#models) for the model IDs, and [Text-to-image](/nunchux-optimized/text-to-image) and [Image-to-image](/nunchux-optimized/image-to-image) for every request field. # Overview Source: https://docs.nunchux.ai/nunchux-optimized/overview Models optimized by Nunchux, served through Nunchux's own endpoints. One request returns the output. # Nunchux Optimized models Nunchux Optimized models run on Nunchux's proprietary Model Optimizer and Inference Engine. You call them through Nunchux's own endpoints. Every request is synchronous: you send one POST, and the image or the video clip is in the response. There is no task to poll. All Nunchux Optimized models accept the same request shape. The `model` field selects the model. On the FLUX, Qwen, HiDream O1, Z-Image Turbo, Krea 2 Turbo and MiniMax H3 Fast models, the `tier` field selects the tier: Radical Speed or Radical Value. FLUX.1 dev, FLUX.2 dev, Qwen Image and Qwen Image Edit have Radical Speed only. FLUX.2 dev Flash has Radical Value only. Ideogram 4 has three other tiers, Turbo, Balanced and Quality. On Ideogram 4, the `extra.rendering_speed` field selects the tier. The LTX models have two other tiers, 720p (1280x720) and 1080p (1920x1080). On LTX, the output size (`width` and `height`) selects the tier. ## Models ### Image | Model | Model ID | Task | Tiers | | - | - | - | - | | FLUX.2 Klein 4B | `nunchux-flux.2-klein-4b` | Text-to-image | Radical Speed, Radical Value | | FLUX.2 Klein 9B | `nunchux-flux.2-klein-9b` | Text-to-image | Radical Speed, Radical Value | | FLUX.1 Schnell | `nunchux-flux.1-schnell` | Text-to-image | Radical Speed, Radical Value | | FLUX.1 dev | `nunchux-flux.1-dev` | Text-to-image | Radical Speed | | FLUX.2 dev | `nunchux-flux.2-dev` | Text-to-image, image-to-image | Radical Speed | | FLUX.2 dev Flash | `nunchux-flux.2-dev-flash` | Text-to-image | Radical Value | | FLUX 3 Image Klein | `nunchux-flux.3-image-klein` | Text-to-image | Radical Speed, Radical Value | | FLUX 3 Image Klein Base | `nunchux-flux.3-image-klein-base` | Text-to-image | Radical Speed, Radical Value | | Qwen Image | `nunchux-qwen-image` | Text-to-image | Radical Speed | | Qwen Image 2512 Lightning | `nunchux-qwen-image-2512-lightning` | Text-to-image | Radical Speed, Radical Value | | Qwen Image 2512 | `nunchux-qwen-image-2512` | Text-to-image | Radical Speed, Radical Value | | Qwen Image 2.1 | `nunchux-qwen-image-2.1` | Text-to-image | Radical Speed, Radical Value | | FLUX.2 Klein 4B Edit | `nunchux-flux.2-klein-4b-edit` | Image-to-image | Radical Speed, Radical Value | | FLUX.2 Klein 9B Edit | `nunchux-flux.2-klein-9b-edit` | Image-to-image | Radical Speed, Radical Value | | FLUX 3 Image Klein Edit | `nunchux-flux.3-image-klein-edit` | Image-to-image | Radical Speed, Radical Value | | FLUX 3 Image Klein Base Edit | `nunchux-flux.3-image-klein-base-edit` | Image-to-image | Radical Speed, Radical Value | | Qwen Image Edit | `nunchux-qwen-image-edit` | Image-to-image | Radical Speed | | Qwen Image Edit 2511 Lightning | `nunchux-qwen-image-edit-2511-lightning` | Image-to-image | Radical Speed, Radical Value | | Qwen Image Edit 2511 | `nunchux-qwen-image-edit-2511` | Image-to-image | Radical Speed, Radical Value | | Qwen Image Edit 2509 Lightning | `nunchux-qwen-image-edit-2509-lightning` | Image-to-image | Radical Speed, Radical Value | | Qwen Image Edit 2509 | `nunchux-qwen-image-edit-2509` | Image-to-image | Radical Speed, Radical Value | | Qwen Image 2.1 Edit | `nunchux-qwen-image-2.1-edit` | Image-to-image | Radical Speed, Radical Value | | HiDream O1 | `nunchux-hidream-o1-image` | Text-to-image | Radical Speed, Radical Value | | HiDream O1 Flash | `nunchux-hidream-o1-image-flash` | Text-to-image | Radical Speed, Radical Value | | Ideogram 4 | `nunchux-ideogram-4` | Text-to-image | Turbo, Balanced, Quality | | Z-Image Turbo | `nunchux-z-image-turbo` | Text-to-image | Radical Speed, Radical Value | | Krea 2 Turbo | `nunchux-krea-2-turbo` | Text-to-image | Radical Speed, Radical Value | > [!NOTE] > > Since November 3, 2026, `nunchux-qwen-image-2512`, `nunchux-qwen-image-edit-2511` and `nunchux-qwen-image-edit-2509` select the full models. Before that date, these IDs selected the Lightning models. The full models take more steps, so they are slower, and their Radical Speed price is higher. See the [pricing page](https://nunchux.ai/pricing). To use the Lightning models, send the `-lightning` IDs. ### Video | Model | Model ID | Tasks | Tiers | | - | - | - | - | | LTX 2.5 | `nunchux-ltx-2.5-video` | Text-to-video, image-to-video | 720p, 1080p | | LTX 2.3 | `nunchux-ltx-2.3-video` | Text-to-video, image-to-video | 720p, 1080p | | MiniMax H3 Fast | `nunchux-minimax-h3-fast-fl2va` | Text-to-video, first and last frame to video | Radical Speed, Radical Value | | MiniMax H3 Fast | `nunchux-minimax-h3-fast-ref2va` | Reference-to-video | Radical Speed, Radical Value | Text-to-image models go to the [Text-to-image](/nunchux-optimized/text-to-image) endpoint. Image-to-image models go to the [Image-to-image](/nunchux-optimized/image-to-image) endpoint. The LTX models go to the [Text-to-video](/nunchux-optimized/text-to-video) and [Image-to-video](/nunchux-optimized/image-to-video) endpoints. MiniMax H3 Fast has its own page, [MiniMax H3 Fast](/nunchux-optimized/minimax-h3-fast), on the text-to-video endpoint. ## Choosing a model FLUX.2 Klein 9B or 4B. The 9B models give higher quality, stronger text rendering, and better results on complex prompts. The 4B models are faster. Use 9B for production output. Use 4B when speed matters more than detail. FLUX or Qwen. FLUX Klein is faster. Qwen Image renders text best, in English and in Chinese, and suits typography and layout work. Qwen Image Edit 2511 Lightning is the recommended editing model when the edit must keep the identity of the subject. HiDream O1. It makes large, photographic images, up to four megapixels, with fine texture in skin, fabric and surfaces. It takes more time per image than FLUX and Qwen. It has a guidance control. HiDream O1 Flash. A distilled HiDream O1 with the same twelve sizes. It is faster, and it takes no guidance and no negative prompt. FLUX.1 dev or FLUX.2 dev. The full-step FLUX models. They take more steps than FLUX.2 Klein, for more detail, and they have a guidance control. FLUX.2 dev is the newer model. FLUX.1 dev also takes a negative prompt, together with `true_cfg_scale`. FLUX.2 dev Flash. A distilled FLUX.2 dev with the same sizes. It returns an image in about a second. It takes no guidance and no negative prompt, and it has Radical Value only. Qwen Image, Qwen Image 2512, Qwen Image Edit, Qwen Image Edit 2511 and Qwen Image Edit 2509. The full-step Qwen models. They take more steps than the Lightning models, for more detail, and they have a guidance control and a negative prompt. Qwen Image 2512, Qwen Image Edit 2511 and Qwen Image Edit 2509 have both tiers. Qwen Image Edit 2511 and Qwen Image Edit 2509 take up to 3 source images. Qwen Image Edit 2509 and its Lightning model are the earlier release; use them when your work already depends on them. FLUX 3 Image Klein and FLUX 3 Image Klein Edit. The newest FLUX generation. They render in 16 steps, up to 4096x4096 (on Radical Value, at most 4,194,304 pixels, for example 2048x2048 or 4096x1024), and the edit model takes up to 10 source images. They take no guidance and no negative prompt, so write a full description of the scene in the prompt. You can instead send `prompt_expansion` set to `standard`, and Nunchux writes the description. FLUX 3 Image Klein Base and FLUX 3 Image Klein Base Edit. The undistilled FLUX 3 Klein models. They take 16 to 50 steps (default 50), a guidance control and a negative prompt, so they give more control and are slower. They render the same sizes, the edit model takes up to 10 source images, and they also take `prompt_expansion`. Qwen Image 2.1 and Qwen Image 2.1 Edit. They render up to 2752x2752, in sizes that are multiples of 32, and the edit model takes up to 10 source images. They take a negative prompt, which takes effect with `true_cfg_scale` above 1.0. Ideogram 4. It renders the words in a prompt legibly, for posters, labels and covers. It takes more time per image than FLUX and Qwen. For Chinese text, use Qwen Image. Z-Image Turbo. A step-distilled model that makes photographic images in 8 steps, so it returns quickly. It takes no guidance and no negative prompt, so put everything in the prompt. Krea 2 Turbo. A step-distilled model that makes photographic images in 8 steps, from 1024x1024 up to 2048x2048. Like Z-Image Turbo, it takes no guidance and no negative prompt. FLUX.1 Schnell. The earlier FLUX generation. It stays available for work that already depends on it. LTX 2.5 or 2.3. LTX 2.5 is the newer release, with the same controls as LTX 2.3. Use LTX 2.3 only for continuity with clips you already made. MiniMax H3 Fast. A clip and its soundtrack in one request, up to 15 seconds. Use it when the clip needs sound, or when it must start or end on your frames, or follow reference images, clips and audio. Use LTX for silent clips at 1080p. ## Endpoints The base URL is `https://api.nunchux.com`. Each page describes one endpoint. | Page | Method and path | | - | - | | [Text-to-image](/nunchux-optimized/text-to-image) | `POST /v1/images/generations` | | [Image-to-image](/nunchux-optimized/image-to-image) | `POST /v1/images/edits` | | [Text-to-video](/nunchux-optimized/text-to-video) | `POST /v1/video/generations` | | [Image-to-video](/nunchux-optimized/image-to-video) | `POST /v1/video/animations` | | [MiniMax H3 Fast](/nunchux-optimized/minimax-h3-fast) | `POST /v1/videos/generations` | The image endpoints also work with the OpenAI SDK. See [OpenAI compatibility](/nunchux-optimized/openai-compatibility). ## How a request works 1. Send a POST with a JSON body to the endpoint. Put your API key in the `X-API-Key` header. See [Authentication](/authentication). 2. Set `model` to a model ID from the tables above. Set `prompt` to the text that describes the output. Image-to-image and image-to-video requests also carry the input image. Then select the tier. Each model uses a different field: * FLUX, Qwen, HiDream O1, Z-Image Turbo and Krea 2 Turbo: set `tier` to `radical_speed` or `radical_value`. * FLUX.1 dev, FLUX.2 dev, Qwen Image and Qwen Image Edit: set `tier` to `radical_speed`. * FLUX.2 dev Flash: set `tier` to `radical_value`. * Ideogram 4: set `extra.rendering_speed` to `turbo`, `balanced` or `quality`. Do not send `steps`. * LTX: set the size with `width` and `height`. The size selects 720p or 1080p. * MiniMax H3 Fast: set `tier` to `radical_speed` or `radical_value`, and the size with `extra.short_edge` and `extra.aspect_ratio`. Do not send `tier` to Ideogram 4 or LTX. 3. Read the output from the response. Images return as base64 data or as a URL, selected by `response_format`. The video endpoint pages describe the video response. Each endpoint page lists every field and shows a full example. ## Billing Each image request is billed on its tier. Radical Speed gives the lowest latency. Radical Value gives the lowest cost per output. Ideogram 4 bills a fixed price per image, at the rate of its tier: Turbo costs the least and Quality the most. Each LTX request is billed per second of output video, at the rate of its tier: 1080p costs more per second than 720p. Each MiniMax H3 Fast request is billed per second of output video, at the rate of its tier and its short edge, and its reference clips and images can add to the charge. Nunchux charges only for successful requests. When a request fails after the credits are deducted, Nunchux refunds them. See [Performance tiers](/performance-tiers) for the tier comparison and [Credits & pricing](/credits-pricing) for how credits work. ## Errors and limits A failed request returns an HTTP error status with a JSON body that names the error. See [Error codes](/errors) for the codes and the retry guidance. Every request counts toward the requests-per-minute cap of your plan. See [Rate limits](/rate-limits). # Text-to-image Source: https://docs.nunchux.ai/nunchux-optimized/text-to-image Generate an image from a text prompt with a Nunchux Optimized model. The image is in the response. # Text-to-image Send a text prompt, and the response contains the generated image. The request is synchronous. There is no task to poll. ## Models | Model | Model ID | Use it for | | - | - | - | | FLUX.2 Klein 9B | `nunchux-flux.2-klein-9b` | Production output. Strong prompt adherence and clean text. | | FLUX.2 Klein 4B | `nunchux-flux.2-klein-4b` | The fastest output. Fast iteration and batch jobs. | | FLUX.2 dev | `nunchux-flux.2-dev` | More detail than Klein, in more steps. Has a guidance control. | | FLUX.2 dev Flash | `nunchux-flux.2-dev-flash` | FLUX.2 dev's detail in about a second. No guidance or negative prompt. | | FLUX.1 dev | `nunchux-flux.1-dev` | The earlier full-step FLUX model. Has a guidance control. | | FLUX 3 Image Klein | `nunchux-flux.3-image-klein` | The newest FLUX generation, in 16 steps, up to 4096x4096. No guidance or negative prompt. | | FLUX 3 Image Klein Base | `nunchux-flux.3-image-klein-base` | The undistilled FLUX 3 Image Klein, in 16 to 50 steps, with a guidance control and a negative prompt. Slower than FLUX 3 Image Klein. | | FLUX.1 Schnell | `nunchux-flux.1-schnell` | The earlier FLUX generation, for work that already depends on it. | | Qwen Image | `nunchux-qwen-image` | Text in the image, with more detail than Lightning, in more steps. | | Qwen Image 2512 Lightning | `nunchux-qwen-image-2512-lightning` | The best text rendering, in English and Chinese. Typography and layout. | | Qwen Image 2512 | `nunchux-qwen-image-2512` | More detail than Qwen Image 2512 Lightning, in 50 steps. Has a guidance control and a negative prompt. | | Qwen Image 2.1 | `nunchux-qwen-image-2.1` | Images up to 2752x2752, with a negative prompt. | | HiDream O1 | `nunchux-hidream-o1-image` | Large, photographic images up to four megapixels. Slower than FLUX and Qwen. | | HiDream O1 Flash | `nunchux-hidream-o1-image-flash` | HiDream O1's sizes, faster. No guidance or negative prompt. | | Ideogram 4 | `nunchux-ideogram-4` | Legible words in the image: posters, labels and covers. Slower than FLUX and Qwen. | | Z-Image Turbo | `nunchux-z-image-turbo` | Fast photographic images in 8 steps. No guidance or negative prompt. | | Krea 2 Turbo | `nunchux-krea-2-turbo` | Fast photographic images in 8 steps, up to 2048x2048. No guidance or negative prompt. | See [Choosing a model](/nunchux-optimized/overview#choosing-a-model) for a comparison, and [Performance tiers](/performance-tiers) for the tiers that each model serves. ## Endpoint ```text theme={"system"} POST https://api.nunchux.com/v1/images/generations ``` ## Request Every request must include your API key and a JSON content type. See [Authentication](/authentication). **X-API-Key** `string` *required* Your API key. **Content-Type** `string` *required* Must be `application/json`. **model** `string` *required* The model that generates the image. Options: `nunchux-flux.2-klein-4b`, `nunchux-flux.2-klein-9b`, `nunchux-flux.1-schnell`, `nunchux-flux.1-dev`, `nunchux-flux.2-dev`, `nunchux-flux.2-dev-flash`, `nunchux-flux.3-image-klein`, `nunchux-flux.3-image-klein-base`, `nunchux-qwen-image`, `nunchux-qwen-image-2512-lightning`, `nunchux-qwen-image-2512`, `nunchux-qwen-image-2.1`, `nunchux-hidream-o1-image`, `nunchux-hidream-o1-image-flash`, `nunchux-ideogram-4`, `nunchux-z-image-turbo`, `nunchux-krea-2-turbo` **prompt** `string` *required* A text description of the image. Specific, descriptive prompts give better results. On Qwen Image 2.1, the prompt can use up to 8192 tokens. A longer prompt returns a 400 with `error.details.field` set to `prompt`. **tier** `string` (default: radical_speed) The balance of speed and cost. See [Performance tiers](/performance-tiers). Options: `radical_speed`, `radical_value` FLUX.1 dev, FLUX.2 dev and Qwen Image have `radical_speed` only. On these models, `radical_value` returns a 400. FLUX.2 dev Flash has `radical_value` only. Send `"tier": "radical_value"`. A request without `tier` uses `radical_speed`, so it returns a 400. Do not send this field to Ideogram 4. On Ideogram 4, `extra.rendering_speed` selects the tier. **width** `integer` Output width in pixels. Send it together with `height`. Required on models priced per megapixel. Today, that is every model except Ideogram 4, which uses 1024x1024 when you send no dimensions. Range: 1 to 8192. On Ideogram 4: 1024 to 2048, in steps of 16. On Z-Image Turbo: 256 to 2048, in steps of 16. On Krea 2 Turbo: 1024 to 2048, in steps of 16. On FLUX.1 dev: 256 to 2048, in steps of 32. On FLUX.2 dev, FLUX.2 dev Flash, Qwen Image and Qwen Image 2512: 256 to 2048, in steps of 16. On FLUX 3 Image Klein and FLUX 3 Image Klein Base: 256 to 4096, in steps of 16. On Radical Value, FLUX 3 Image Klein and FLUX 3 Image Klein Base take at most 4,194,304 pixels (`width` times `height`, the area of 2048x2048), so 4096x1024 works and 2576x1632 returns a 400. On Qwen Image 2.1: 256 to 2752, in steps of 32. On HiDream O1 and HiDream O1 Flash: one of the sizes listed under Dimensions below. **height** `integer` Output height in pixels. Send it together with `width`. Required on models priced per megapixel. Today, that is every model except Ideogram 4, which uses 1024x1024 when you send no dimensions. Range: 1 to 8192. On Ideogram 4: 1024 to 2048, in steps of 16. On Z-Image Turbo: 256 to 2048, in steps of 16. On Krea 2 Turbo: 1024 to 2048, in steps of 16. On FLUX.1 dev: 256 to 2048, in steps of 32. On FLUX.2 dev, FLUX.2 dev Flash, Qwen Image and Qwen Image 2512: 256 to 2048, in steps of 16. On FLUX 3 Image Klein and FLUX 3 Image Klein Base: 256 to 4096, in steps of 16. On Radical Value, FLUX 3 Image Klein and FLUX 3 Image Klein Base take at most 4,194,304 pixels (`width` times `height`, the area of 2048x2048), so 4096x1024 works and 2576x1632 returns a 400. On Qwen Image 2.1: 256 to 2752, in steps of 32. On HiDream O1 and HiDream O1 Flash: one of the sizes listed under Dimensions below. **steps** `integer` HiDream O1, HiDream O1 Flash, FLUX.1 dev, FLUX.2 dev, FLUX.2 dev Flash, FLUX 3 Image Klein, FLUX 3 Image Klein Base, Qwen Image, Qwen Image 2512, Qwen Image 2.1, Z-Image Turbo and Krea 2 Turbo only. The number of denoising steps. Range: 1 to 16 on Z-Image Turbo and FLUX 3 Image Klein, 1 to 8 on Krea 2 Turbo, 12 to 50 on FLUX.2 dev Flash, 16 to 50 on FLUX 3 Image Klein Base, 1 to 50 on the others. Default: 28 on FLUX.1 dev, 40 on Qwen Image 2.1, 16 on FLUX 3 Image Klein, 8 on Z-Image Turbo and Krea 2 Turbo, 50 on the others. More steps give more detail, but take longer. On FLUX.2 dev Flash, the step count does not change the image or the time. The model is distilled, and every count it accepts runs the same schedule. It accepts `steps` so that a FLUX.2 dev request also works on it. Do not send this field to Ideogram 4: it returns a 400. On Ideogram 4, `extra.rendering_speed` selects the tier. **true_cfg_scale** `number` HiDream O1, Qwen Image, Qwen Image 2512, Qwen Image 2.1 and FLUX.1 dev only. How closely the image follows the prompt. Range: 0.0 to 20.0. Default: 5.0 on HiDream O1, 4.0 on Qwen Image and Qwen Image 2512, 1.0 on Qwen Image 2.1, off on FLUX.1 dev. Higher values follow the prompt more closely. Lower values give the model more freedom. On Qwen Image, Qwen Image 2512, Qwen Image 2.1 and FLUX.1 dev, it also sets how strongly the image avoids the `negative_prompt`. On FLUX.1 dev, send it with `negative_prompt`, at a value above 1.0. The model then renders a second pass for the negative prompt, so the request takes longer. Without it, FLUX.1 dev ignores `negative_prompt`. On Qwen Image 2.1, the default 1.0 has no effect. Send a value above 1.0 together with `negative_prompt`. **guidance_scale** `number` FLUX.1 dev, FLUX.2 dev and FLUX 3 Image Klein Base only. How closely the image follows the prompt. Range: 0.0 to 20.0. Default: 3.5 on FLUX.1 dev, 4.0 on FLUX.2 dev and FLUX 3 Image Klein Base. **negative_prompt** `string` Qwen Image, Qwen Image 2512, Qwen Image 2.1, FLUX.1 dev and FLUX 3 Image Klein Base only. What the image must not show. On FLUX.1 dev and Qwen Image 2.1, it takes effect only when you also send `true_cfg_scale` above 1.0. **prompt_expansion** `string` (default: off) Ideogram 4, FLUX 3 Image Klein and FLUX 3 Image Klein Base only. With any mode other than `off`, Nunchux rewrites the prompt into a detailed scene description before the image renders. On Ideogram 4, `fast` adds a few seconds. `standard`, `balanced` and `quality` take longer: up to about 40, 45 and 55 seconds. If the rewrite fails, the image renders from your prompt, and the response has no `revised_prompt`. On FLUX 3 Image Klein and FLUX 3 Image Klein Base, `standard` is the only mode, and it adds about 3 to 4 seconds. The response returns the rewritten prompt as `revised_prompt`. FLUX 3 Image Klein and FLUX 3 Image Klein Base follow a full description of the scene much better than a short prompt, so send `standard` unless your prompt already describes the subject, the setting, the light and the style. Options: `off`, `fast`, `standard`, `balanced`, `quality`. On FLUX 3 Image Klein and FLUX 3 Image Klein Base: `off`, `standard`. **extra** `object` Model options. **properties** **rendering_speed** `string` (default: quality) Ideogram 4 only. Selects the tier. `turbo` is the fastest and costs the least, but gives less detail. `quality` gives the most detail. A request without it renders and is billed as Quality. Options: `turbo`, `balanced`, `quality` **n** `integer` (default: 1) The number of images to generate. Only 1 is supported. **response_format** `string` (default: b64_json) The format of the returned image. Options: `url`, `b64_json` In both formats, Nunchux keeps the generated image for 7 days, so that it appears in your request history. Then Nunchux deletes it. **seed** `integer` The random seed. The same seed with the same parameters gives the same result. **content_moderation** `boolean` (default: true) Whether Nunchux's content filter checks this request. Only accounts approved to turn moderation off may send `false`. Others get a 403. See [Content moderation](/content-moderation). > [!NOTE] > > Dimensions > > * Send `width` and `height` together. A request with only one of them returns a 400. > * Models priced per megapixel charge from the output area, so they require `width` and `height`. A request with no dimensions returns a 400. The API does not choose a default size for these models. The [pricing page](https://nunchux.ai/pricing) shows each model's unit. Today, every text-to-image model except Ideogram 4 is priced per megapixel. > * Both values must be integers. The string `"1024"` is rejected, not converted. > * Larger images take longer to generate. > * HiDream O1 and HiDream O1 Flash render these sizes: 1024x1024, 2048x2048, 2304x1728, 1728x2304, 2560x1440, 1440x2560, 2496x1664, 1664x2496, 3104x1312, 1312x3104, 2304x1792, 1792x2304. On HiDream O1 Flash, another size is not refused: the image comes back at the closest of these sizes, by aspect ratio first, which can be larger than you asked for. A request for 1536x1024 returns 2496x1664. Send one of the listed sizes to get the size you ask for. A minimal request body: ```json theme={"system"} { "model": "nunchux-qwen-image-2512-lightning", "tier": "radical_speed", "prompt": "A beautiful sunset over mountains", "width": 1024, "height": 1024, "response_format": "b64_json", "seed": 42 } ``` A request body for Qwen Image 2.1, with a negative prompt: ```json theme={"system"} { "model": "nunchux-qwen-image-2.1", "tier": "radical_speed", "prompt": "A bookshop window at dusk with a hand-painted sign that reads \"OPEN LATE\"", "negative_prompt": "blurry, low contrast", "true_cfg_scale": 4.0, "width": 1024, "height": 1024, "response_format": "b64_json", "seed": 42 } ``` A request body for FLUX 3 Image Klein, with prompt expansion. The response returns the rewritten prompt in `data[0].revised_prompt`: ```json theme={"system"} { "model": "nunchux-flux.3-image-klein", "tier": "radical_speed", "prompt": "A red bicycle leaning on a brick wall", "prompt_expansion": "standard", "width": 1024, "height": 1024, "response_format": "b64_json", "seed": 42 } ``` ## Response The response is JSON. The `data` array contains the image, as base64 data or as a URL. **created** `integer` *required* The Unix timestamp of the generation. **data** `array` *required* The generated items. **Item properties** **url** `string` The URL of the image. Returned when `response_format` is `url`. **b64_json** `string` The image as base64 data. Returned when `response_format` is `b64_json`. **revised_prompt** `string` Ideogram 4, FLUX 3 Image Klein and FLUX 3 Image Klein Base only. The rewritten prompt that the model rendered. Returned when `prompt_expansion` is not `off` and the rewrite succeeds. To make the same image again, send it as `prompt` with `prompt_expansion` set to `off`, the same `seed` and the same size. On FLUX 3 Image Klein, also send the same `steps`. On FLUX 3 Image Klein Base, also send the same `steps`, `guidance_scale` and `negative_prompt`. On Ideogram 4, also send the same `extra.rendering_speed`. **model** `string` *required* The model that generated the image. **tier** `string` *required* The tier that served the request: `radical_speed` or `radical_value`. On Ideogram 4 this field is always `radical_speed` and does not show the Turbo, Balanced or Quality tier. The `extra.rendering_speed` you sent selects that tier. ```json Base64 format theme={"system"} { "created": 1234567890, "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAYAAAB/HSuDAAAACXBIWXMAAA7EAAAOxAGVKw4b..." } ], "model": "nunchux-qwen-image-2512-lightning", "tier": "radical_speed" } ``` ```json URL format theme={"system"} { "created": 1234567890, "data": [ { "url": "https://example.com/generated-image.png" } ], "model": "nunchux-qwen-image-2512-lightning", "tier": "radical_speed" } ``` To save a base64 result from cURL, add this pipe to the command: ```bash theme={"system"} # Replace output.jpg with the file name that you want. | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ## Example ```bash cURL theme={"system"} curl -X POST https://api.nunchux.com/v1/images/generations \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-flux.2-klein-9b", "tier": "radical_speed", "prompt": "cozy coffee shop interior with vintage furniture", "width": 1024, "height": 1024, "response_format": "b64_json", "seed": 42 }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ```python Python theme={"system"} import os import base64 import requests response = requests.post( "https://api.nunchux.com/v1/images/generations", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-flux.2-klein-9b", "tier": "radical_speed", "prompt": "cozy coffee shop interior with vintage furniture", "width": 1024, "height": 1024, "response_format": "b64_json", "seed": 42, }, ) # Decode the base64 image and save it. Change output.jpg to any file name. image_b64 = response.json()["data"][0]["b64_json"] with open("output.jpg", "wb") as f: f.write(base64.b64decode(image_b64)) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.nunchux.com/v1/images/generations", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-flux.2-klein-9b", tier: "radical_speed", prompt: "cozy coffee shop interior with vintage furniture", width: 1024, height: 1024, response_format: "b64_json", seed: 42, }), }); const data = await response.json(); // Decode the base64 image and save it. Change output.jpg to any file name. await writeFile("output.jpg", Buffer.from(data.data[0].b64_json, "base64")); ``` ```python Python (OpenAI) theme={"system"} import os import base64 from openai import OpenAI client = OpenAI( base_url="https://api.nunchux.com/v1", api_key=os.environ["NUNCHUX_API_KEY"], ) # The OpenAI SDK has no width/height parameter. Send them in `extra_body`, # which the SDK merges into the request body. response = client.images.generate( model="nunchux-flux.2-klein-9b", prompt="cozy coffee shop interior with vintage furniture", n=1, response_format="b64_json", extra_body={"width": 1024, "height": 1024}, ) # Decode the base64 image and save it. Change output.jpg to any file name. image_b64 = response.data[0].b64_json with open("output.jpg", "wb") as f: f.write(base64.b64decode(image_b64)) ``` ## Tips * Write detailed prompts. Include the style, lighting, composition, colors, materials and atmosphere. * Use FLUX.2 Klein 9B for production output. Use FLUX.2 Klein 4B when speed is more important than detail. * Use Qwen Image when the image must contain text, and for Chinese text. Use Ideogram 4 when the words must be legible on a poster, a label or a cover. Put the exact words in quotes or capitals, and say where they go. * Use Qwen Image 2512 when you want more detail than Qwen Image 2512 Lightning gives and the extra time is acceptable. Use `negative_prompt` to keep things out of the image. * Use HiDream O1 for large, photographic images. Describe the light and the materials. A larger size costs more, because the price is per megapixel. * Use HiDream O1 Flash for HiDream O1's large sizes in less time. Put everything in the prompt: it takes no guidance and no negative prompt. * Use FLUX.2 dev Flash to try many prompts quickly at FLUX.2 dev's detail. Send `tier` as `radical_value`. To get a different image, change the `seed`, not `steps`. Put everything in the prompt: it takes no guidance and no negative prompt. * Use FLUX.2 dev or FLUX.1 dev when you want more detail than FLUX.2 Klein gives, and the extra time is acceptable. Steer them with `guidance_scale`. On FLUX.1 dev, to keep things out of the image, send `negative_prompt` with `true_cfg_scale` above 1.0, at the cost of a second pass. * Use FLUX 3 Image Klein for fast output from the newest FLUX generation. Write a full description of the scene: the subject, the setting, the light, the composition and the style. A short prompt gives a generic image. To have Nunchux write the description from a short prompt, send `prompt_expansion` set to `standard`. Keep the default 16 steps. It takes no guidance and no negative prompt. * Use FLUX 3 Image Klein Base when you want more detail or more control than FLUX 3 Image Klein gives, and the extra time is acceptable. Steer it with `guidance_scale` and `negative_prompt`. Send `prompt_expansion` set to `standard` for a short prompt. * Use Qwen Image 2.1 for images up to 2752x2752. Send `width` and `height` in multiples of 32. To keep things out of the image, send `negative_prompt` with `true_cfg_scale` above 1.0. * Use Z-Image Turbo for fast photographic images. It is step-distilled: keep the default 8 steps, and describe what you want in the prompt, because it takes no guidance and no negative prompt. * Use Krea 2 Turbo for fast photographic images at larger sizes, up to 2048x2048. Each side must be at least 1024. Keep the default 8 steps, and leave out guidance and the negative prompt. The same prompt and seed give a close result, but not always an identical image. * On Ideogram 4, draft with `extra.rendering_speed` set to `turbo`. Use `quality` for the final image. * On FLUX.2 Klein, FLUX 3 Image Klein, FLUX 3 Image Klein Base, Qwen Image 2512, Qwen Image 2512 Lightning, Qwen Image 2.1, HiDream O1, HiDream O1 Flash, Z-Image Turbo and Krea 2 Turbo, use `radical_speed` when response time is important. Use `radical_value` for large batches where cost per image is more important. * Keep the `seed` when you like a result. Then change one parameter at a time. ## Errors and limits | Status | Code | Cause | | - | - | - | | 400 | none | A required field is missing, the model ID is not valid, or a value is not valid. The body is a plain `detail` string. | | 400 | `invalid_request` | The model does not offer the `tier` you sent, for example `radical_value` on FLUX.1 dev, or `radical_speed` on FLUX.2 dev Flash. `error.details.reason` is `tier_not_available`. | | 400 | `invalid_request` | The model does not take a field you sent, or does not take its value: a size outside the model's range or off its grid, a `steps` value out of range, or a field the model does not take. For example: `guidance_scale` on Qwen Image and Qwen Image 2.1; `prompt_expansion` on Qwen Image 2.1; `true_cfg_scale` or `prompt_expansion` on Z-Image Turbo; `guidance_scale` or `negative_prompt` on Krea 2 Turbo and FLUX 3 Image Klein; `guidance_scale`, `true_cfg_scale` or `negative_prompt` on HiDream O1 Flash and FLUX.2 dev Flash; a `steps` value above 16 on FLUX 3 Image Klein, outside 16 to 50 on FLUX 3 Image Klein Base, or outside 12 to 50 on FLUX.2 dev Flash; an area above 4,194,304 pixels on the Radical Value tier of FLUX 3 Image Klein or FLUX 3 Image Klein Base; 1040x1040 on FLUX.1 dev or Qwen Image 2.1. `error.details.field` names the field, and `error.details.reason` is `field_not_accepted`. | | 400 | `engine_error` | The model accepted the request but cannot render it. | | 403 | `model_not_available` | Your account does not have access to this model. | > [!NOTE] > > Refused requests > > * Nunchux charges only after a successful generation. A refused request is never billed. > * Do not branch on a dimension-specific code. A refused size, `steps` value or field returns `invalid_request`, and `error.details.field` names the field. `engine_error` means the model could not render a request it accepted. For authentication, credit and rate-limit errors, see [Error codes](/errors). Every request counts toward the requests-per-minute cap of your plan. See [Rate limits](/rate-limits). # Text-to-video Source: https://docs.nunchux.ai/nunchux-optimized/text-to-video Generate a video clip from a text prompt with LTX. The clip is in the response. # Text-to-video Send a text prompt, and the response contains the generated video clip. The request is synchronous. There is no task to poll. A clip is 1 to 8 seconds long, at 1080p or 720p, with an optional soundtrack. ## Models | Model | Model ID | Use it for | | - | - | - | | LTX 2.5 | `nunchux-ltx-2.5-video` | New work. The newer release, with the same controls as LTX 2.3. | | LTX 2.3 | `nunchux-ltx-2.3-video` | Continuity with clips that you already made with LTX 2.3. | Both models also serve [Image-to-video](/nunchux-optimized/image-to-video). See [Choosing a model](/nunchux-optimized/overview#choosing-a-model). MiniMax H3 Fast also serves text-to-video on this endpoint, with a soundtrack and its own fields. See [MiniMax H3 Fast](/nunchux-optimized/minimax-h3-fast). ## Endpoint ```text theme={"system"} POST https://api.nunchux.com/v1/video/generations ``` The path `/v1/videos/generations` is an alias. It gives the same result and the same billing. ## Request Every request must include your API key and a JSON content type. See [Authentication](/authentication). **X-API-Key** `string` *required* Your API key. **Content-Type** `string` *required* Must be `application/json`. **model** `string` *required* The model that generates the clip. Options: `nunchux-ltx-2.5-video`, `nunchux-ltx-2.3-video` **prompt** `string` *required* A text description of the clip. Describe the shot: the subject, the camera movement, the light, and what changes during the clip. **width** `integer` (default: 1920) Output width in pixels. Send it together with `height`. The size selects the tier, 1080p or 720p. 1080p costs more per second. Options: `1920` (1080p), `1280` (720p) **height** `integer` (default: 1080) Output height in pixels. Send it together with `width`. Options: `1080` (1080p), `720` (720p) **duration** `number` (default: 6) The clip length in seconds. Range: 1 to 8. The model renders at 24 frames per second, so the length of the clip can differ from your value by a fraction of a second. The response gives the length of the clip. **extra** `object` Model options. **properties** **audio** `boolean` (default: false) When `true`, the model generates a soundtrack with the picture. Describe the sound in the prompt. **seed** `integer` The random seed. When you do not send a seed, the model selects one and returns it in the response. The same seed with the same parameters gives the same result. **content_moderation** `boolean` (default: true) Whether Nunchux's content filter checks this request. Only accounts approved to turn moderation off may send `false`. Others get a 403. See [Content moderation](/content-moderation). **n** `integer` (default: 1) The number of clips to generate. Only 1 is supported. **response_format** `string` (default: b64_json) The format of the returned clip. Options: `b64_json`, `url` In `url` format, Nunchux keeps the generated clip for 7 days, so that it appears in your request history. Then Nunchux deletes it. In `b64_json` format, Nunchux also tries to keep a copy for your request history, but it skips the copy when the service is busy. Save the clip from the response if you need to keep it. > [!NOTE] > > Unsupported fields > > LTX does not accept `steps`, `guidance_scale`, `negative_prompt` or `num_frames`. A request that contains one of them returns a 400. A minimal request body: ```json theme={"system"} { "model": "nunchux-ltx-2.3-video", "prompt": "A golden retriever running on a beach at sunset, cinematic", "width": 1280, "height": 720, "duration": 6, "extra": { "audio": false }, "response_format": "b64_json" } ``` ## Response The response is JSON. The `data` array contains one MP4 clip, as base64 data or as a URL. **created** `integer` *required* The Unix timestamp of the generation. **model** `string` *required* The model that generated the clip. **tier** `string` *required* Always `radical_speed`. This field does not show the LTX tier. The `width` and `height` of the clip show it. **seed** `integer` *required* The seed of the clip. Send it again to get the same result. **data** `array` *required* The generated clip. **Item properties** **b64_json** `string` The MP4 clip as base64 data. Returned when `response_format` is `b64_json`. **url** `string` The URL of the MP4 clip. Returned when `response_format` is `url`. **width** `integer` The width of the clip in pixels. **height** `integer` The height of the clip in pixels. **duration** `number` The length of the clip in seconds. **frames** `integer` The number of frames in the clip. **frame_rate** `integer` The frame rate of the clip. ```json theme={"system"} { "created": 1234567890, "model": "nunchux-ltx-2.3-video", "tier": "radical_speed", "seed": 1873420651, "data": [ { "b64_json": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQ...", "width": 1280, "height": 720, "duration": 6.0417, "frames": 145, "frame_rate": 24 } ] } ``` A base64 clip is large. A 6 second 1080p clip can be more than 10 MB of base64 data. Use `response_format: "url"` when you do not need the data in the response. ## Example A clip takes some time to render. Set the timeout of your HTTP client to 120 seconds. ```bash cURL theme={"system"} curl -X POST https://api.nunchux.com/v1/video/generations \ --max-time 120 \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-ltx-2.3-video", "prompt": "A golden retriever running on a beach at sunset, cinematic", "width": 1280, "height": 720, "duration": 6, "extra": {"audio": false}, "response_format": "b64_json" }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.mp4 ``` ```python Python theme={"system"} import os import base64 import requests response = requests.post( "https://api.nunchux.com/v1/video/generations", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-ltx-2.3-video", "prompt": "A golden retriever running on a beach at sunset, cinematic", "width": 1280, "height": 720, "duration": 6, "extra": {"audio": False}, "response_format": "b64_json", }, timeout=120, ) response.raise_for_status() # Decode the base64 clip and save it. Change output.mp4 to any file name. clip_b64 = response.json()["data"][0]["b64_json"] with open("output.mp4", "wb") as f: f.write(base64.b64decode(clip_b64)) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.nunchux.com/v1/video/generations", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-ltx-2.3-video", prompt: "A golden retriever running on a beach at sunset, cinematic", width: 1280, height: 720, duration: 6, extra: { audio: false }, response_format: "b64_json", }), signal: AbortSignal.timeout(120_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); const data = await response.json(); // Decode the base64 clip and save it. Change output.mp4 to any file name. await writeFile("output.mp4", Buffer.from(data.data[0].b64_json, "base64")); ``` ## Tips * Write the shot, not only the subject. Include the camera movement, the light, and what changes during the clip. * When `extra.audio` is `true`, describe the sound in the prompt. For example: rain on a window, a crowd, or one piano line. * Start at 1080p and 6 seconds. Use 720p for faster and lower-cost previews. * Keep the `seed` when you like a result. Then change one parameter at a time. ## Errors and limits | Status | Code | Cause | | - | - | - | | 400 | none | `model` is missing or not valid, or a size value is not valid. The body is a plain `detail` string. | | 400 | `invalid_request` | The request sets `tier` to a value other than `radical_speed`. On LTX, `width` and `height` select the tier. Do not send the `tier` field. | | 400 | `unsupported_response_format` | `response_format` is not `b64_json` or `url`. | | 400 | `engine_error` | The model cannot render the request, for example a size, a duration or a field that it does not accept. | | 422 | `request_too_large` | The requested size is larger than 1920x1080. `details` gives the requested value and the maximum. | | 502 | `output_too_large` | The clip is too large to return. You are not charged. Request a shorter clip or a smaller size. | | 504 | none | The clip did not complete in 120 seconds. Send the request again. | A clip is billed per second of output video, at the rate of its tier: 1080p costs more per second than 720p. See the [pricing page](https://nunchux.ai/pricing) for current rates. Nunchux charges only for a successful clip. A request that fails is never billed. Every request counts toward the requests-per-minute cap of your plan. A request also holds one simultaneous-jobs slot until the response returns. See [Rate limits](/rate-limits). For authentication and credit errors, see [Error codes](/errors). # Overview Source: https://docs.nunchux.ai/overview Generate images and videos with one API key and one credit balance. # Nunchux docs Nunchux gives you one API for image and video generation. One API key and one credit balance cover every model. The models are in two groups. The groups use different request shapes. > [card] [Nunchux Optimized models](/nunchux-optimized/overview) > > Image and video models that run on Nunchux's proprietary Model Optimizer and Inference Engine. One request returns the output. Performance tiers set the balance of speed and cost. > [card] [Partner models](/partner-models/overview) > > Third-party models from Google, Kling AI, Alibaba Cloud, ByteDance, MiniMax and HeyGen. Each provider keeps its own routes and request shapes. Video jobs are asynchronous. ## Start here 1. Make your first request. See [Quickstart](/quickstart). 2. Learn how to send your API key. See [Authentication](/authentication). 3. Find a model. See the two overviews above. 4. Connect Claude Code, Cursor and other tools to these docs. See [Coding agents](/coding-agents). # HappyHorse Source: https://docs.nunchux.ai/partner-models/happyhorse Alibaba Cloud's HappyHorse video models for text-to-video, image-to-video and reference-to-video, with a soundtrack on every clip. # HappyHorse HappyHorse is Alibaba Cloud's second video model line, beside Wan. Each version generates a clip from a text prompt, from a still image, or from a set of reference images, and always scores the clip itself. Generation is asynchronous. You submit a task, poll it until the status is terminal, then download the clip. The route mirrors Alibaba Cloud's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Sound without a switch. Every clip arrives with a generated soundtrack, so there is no audio decision to make. > * Reference-driven scenes. Up to nine reference images carry a subject into new footage. > * Draft passes. HappyHorse 1.1 sells a 480P tier that 1.0 does not. > * Steady camera work. Tracking shots, slow push-ins and pans, with the motion described in the prompt. ## Models | Model | Model ID | Tasks | Resolution | Duration | Reference images | | - | - | - | - | - | - | | HappyHorse 1.1 | `happyhorse-1.1-t2v`, `happyhorse-1.1-i2v`, `happyhorse-1.1-r2v` | t2v, i2v, r2v | 480P, 720P, 1080P | 3 to 15 s | Up to 9 | | HappyHorse 1.0 | `happyhorse-1.0-t2v`, `happyhorse-1.0-i2v`, `happyhorse-1.0-r2v` | t2v, i2v, r2v | 720P, 1080P | 3 to 15 s | Up to 9 | Durations are whole seconds. Each version has one model ID per task. Both versions take the same request shape. Only the `model` value changes. HappyHorse 1.1 is the current line, and the only one with a 480P tier. Use it for drafts and for the final render. HappyHorse 1.0 is the earlier line at 720P and 1080P. Image-to-video takes a first frame only. There is no end frame. Reference-to-video takes images only. There is no container for a reference clip or a reference track. ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/alibaba/services/aigc/video-generation/video-synthesis` | | Poll | `GET /v1/alibaba/tasks/{task_id}` | HappyHorse shares the two routes and the body shape of [Wan](/partner-models/wan). The tier goes in `parameters.resolution`, and frames and references go in `input.media[]`. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. **model** `string` *required* The model ID from the table above. The ID names both the version and the task. **input** `object` *required* The prompt and the media items. **properties** **prompt** `string` *required* The text prompt. All tasks. Describe the action and the camera movement. On reference-to-video, name a reference by its position in `media[]`: `[Image 1]`, `[Image 2]` and so on, with the brackets. **media** `array` The media items for image-to-video and reference-to-video. Omit it for text-to-video. A first frame and a reference set cannot appear in the same body. **item properties** **type** `string` *required* What the item is. * `first_frame`: the image the clip starts on. Image-to-video. One item. * `reference_image`: a reference image. Reference-to-video. 1 to 9 items. **url** `string` *required* The URL of the image. The provider fetches it, so the URL must be reachable from the internet. **parameters** `object` The generation controls. All tasks read all three fields. **properties** **resolution** `string` (default: 1080P) The output tier. `480P`, `720P` or `1080P` on HappyHorse 1.1. `720P` or `1080P` on HappyHorse 1.0. The default is the most expensive tier, so name the one you want. **duration** `integer` (default: 5) The clip length in whole seconds, 3 to 15. You are billed per second of output. **watermark** `boolean` (default: true) An omitted flag yields a clip with the text Happy Horse in the lower-right corner. Send `false` for a clean frame. There is no audio parameter. The model scores every clip, and no field turns that off. ## Response ### Submit A 200 status means that the provider accepted the task. It does not mean that the clip is ready. **output** `object` *required* **properties** **task_id** `string` *required* The task ID. Poll `GET /v1/alibaba/tasks/{task_id}` with it. **task_status** `string` *required* `PENDING` on a new task. ### Poll **output.task_status** `string` *required* `PENDING` or `RUNNING` while the task runs. `SUCCEEDED`, `FAILED` or `CANCELED` when it ends. Poll until you read one of the three terminal values. **output.video_url** `string` The URL of the clip. Present only when `task_status` is `SUCCEEDED`. The task ID and the URL expire after 24 hours. Download the clip as soon as the task succeeds. **output.code** `string` The failure code. Present when the task failed. **output.message** `string` The failure message. Read it before you resubmit. ## Example Submit, poll, download. Swap the `model` value for the version and task you want. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/alibaba/services/aigc/video-generation/video-synthesis" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "happyhorse-1.1-t2v", "input": { "prompt": "a fox trotting through a snowy forest at dawn" }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.output.task_id' <<<"$SUBMIT") || { echo "no task_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/alibaba/tasks/$TASK" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.output.task_status // ""' <<<"$RESP") case "$STATUS" in SUCCEEDED|FAILED|CANCELED) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATUS" = "SUCCEEDED" ] || { echo "task $STATUS: $(jq -r '.output.message // "no message"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o happyhorse.mp4 "$(jq -r '.output.video_url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/alibaba/services/aigc/video-generation/video-synthesis", headers=HEADERS, json={ "model": "happyhorse-1.1-t2v", "input": {"prompt": "a fox trotting through a snowy forest at dawn"}, "parameters": {"resolution": "720P", "duration": 5, "watermark": False}, }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task = submit.json()["output"]["task_id"] # 2. Poll until the status is terminal delay = 5 for _ in range(90): data = requests.get(f"{BASE}/v1/alibaba/tasks/{task}", headers=HEADERS).json() status = data.get("output", {}).get("task_status", "") if status in ("SUCCEEDED", "FAILED", "CANCELED"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("HappyHorse task did not reach a terminal status") # 3. Check for failure if status != "SUCCEEDED": raise RuntimeError(f"HappyHorse task {status}: {data['output'].get('message')}") # 4. Download with requests.get(data["output"]["video_url"], stream=True, timeout=300) as r: r.raise_for_status() with open("happyhorse.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` To animate a still, add a `first_frame` item to `input.media[]` and send an `-i2v` model ID. To carry a subject into a new scene, add `reference_image` items and send an `-r2v` model ID. A first frame and a reference set are separate tasks. The bodies below replace the submit body in the example. ```json Image-to-video theme={"system"} { "model": "happyhorse-1.1-i2v", "input": { "prompt": "the fox turns and trots toward the camera", "media": [ { "type": "first_frame", "url": "https://example.com/frame.jpg" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ```json Reference-to-video theme={"system"} { "model": "happyhorse-1.1-r2v", "input": { "prompt": "the person from [Image 1] walks through the doorway from [Image 2], slow tracking shot", "media": [ { "type": "reference_image", "url": "https://example.com/ref-1.jpg" }, { "type": "reference_image", "url": "https://example.com/ref-2.jpg" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ## Tips * Say what moves and how the camera follows it. The prompt drives both. * Send `watermark: false` on every request unless you want the mark. The vendor's default adds it. * Send `resolution` and `duration` on every request. The defaults are 1080P and 5 seconds, and 1080P is the most expensive tier. * Draft at 480P on HappyHorse 1.1, then re-run the prompt at the tier and length you need. You are billed per second of output, and 1080P costs more per second than 720P. * Give a reference set images that agree on the subject. Images that disagree pull the result in different directions. * Name the references in the prompt when the set holds different subjects, so each image has a stated role in the shot. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that the provider accepted the task. It does not mean that the task succeeded. A task that fails later ends with `task_status` set to `FAILED` or `CANCELED`, and `output.message` explains why. Read the message before you resubmit. A failed submit returns an HTTP error status. The body carries `code`, `message` and `request_id`. See [Error codes](/errors). A 5xx status or a timeout on submit does not tell you whether the task was created. Never resubmit blindly. If the submit returned a `task_id`, poll it. If it returned nothing, check your credits before you try again. Alibaba Cloud applies these limits to the images you attach: * A first frame on image-to-video: at least 300 pixels on each side, an aspect ratio between 1:2.5 and 2.5:1, JPEG, JPG, PNG or WEBP, up to 20 MB. * A reference image on reference-to-video: at least 400 pixels on the short side, JPEG, JPG, PNG or WEBP, up to 20 MB, one to nine images per request. Every task counts toward the simultaneous-jobs cap of your plan. See [Rate limits](/rate-limits). Rates are per second of output and depend on the tier. See [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # HeyGen Avatar Source: https://docs.nunchux.ai/partner-models/heygen Turn a photo or a HeyGen avatar into a lip-synced talking-avatar video with HeyGen Avatar 4 Photo and Avatar 5 Digital, driven by audio or a script in a chosen voice. # HeyGen Avatar HeyGen Avatar turns a photo, or a HeyGen avatar, into a lip-synced talking-avatar video. You supply the face and a speech source: an audio file that you host, or a script that HeyGen reads in a voice that you choose. The endpoint is asynchronous. Submit the job, poll until the status is terminal, then download the video. The request and response shapes mirror HeyGen's API. ## Models HeyGen offers two engines. They take the same speech sources, share every other field, and have the same price. They differ only in where the face comes from. | Engine | Id | Face input | Speech input | Output | | - | - | - | - | - | | Avatar 4 Photo | `avatar_iv` | A photo that you supply, by public URL or inline as base64 | `audio_url`, or `script` with `voice_id` | Lip-synced MP4 video of the photo | | Avatar 5 Digital | `avatar_v` | A ready-made avatar from HeyGen's avatar catalog (`avatar_id`) | `audio_url`, or `script` with `voice_id` | Lip-synced MP4 video of the avatar | > [!NOTE] > > The endpoint takes no `model` field, so the ids above are not values that you send. The request body selects the engine. `"type": "image"` with an `image` object selects Avatar 4 Photo. `"type": "avatar"` with an `avatar_id` and `"engine": {"type": "avatar_v"}` selects Avatar 5 Digital. Use Avatar 4 Photo when you have a photo of the face that you need. Use Avatar 5 Digital when you want a ready-made look from HeyGen's avatar catalog. Neither engine has a duration control. The clip is as long as the audio or the script. Common uses are presenter clips, narrated explainers, and re-voiced versions of the same face. ## Endpoints All endpoints share the base URL `https://api.nunchux.com`. | Purpose | Method | Path | | - | - | - | | Submit a video | POST | `/v1/heygen/v3/videos` | | Poll a job | GET | `/v1/heygen/v3/videos/{video_id}` | | List voices | GET | `/v1/heygen/v3/voices` | ## Request Send your API key in the `X-API-Key` header (see [Authentication](/authentication)) and set `Content-Type: application/json`. Also send a `User-Agent` header that identifies your application, for example `YourApp/1.0`. A request that keeps the default `User-Agent` of your HTTP client can be rejected. Send one face and one speech source in the body. The face fields select the engine. The speech fields are the same on both engines. **type** `string` *required* Selects the engine. `image` selects Avatar 4 Photo and animates the photo in `image`. `avatar` selects Avatar 5 Digital and animates the avatar in `avatar_id`. Options: `image`, `avatar` **image** `object` Avatar 4 Photo only. The photo to animate. Required when `type` is `image`. **Item properties** **type** `string` *required* `url` for a link that you host, `base64` for inline bytes. Options: `url`, `base64` **url** `string` Required when `image.type` is `url`. Public HTTPS URL of the portrait, hosted by you. **media_type** `string` Required when `image.type` is `base64`. MIME type of the bytes, for example `image/jpeg` or `image/png`. **data** `string` Required when `image.type` is `base64`. The raw base64-encoded image bytes, without a `data:` URI prefix. **avatar_id** `string` Avatar 5 Digital only. The avatar to animate, from HeyGen's avatar catalog. Required when `type` is `avatar`. **engine** `object` Avatar 5 Digital only. Selects the Avatar 5 renderer. Omit it when `type` is `image`, because that body already selects Avatar 4 Photo. **Item properties** **type** `string` *required* Must be `avatar_v`. **audio_url** `string` Both engines. Public HTTPS URL of a speech audio file (WAV or MP3), hosted by you. Send this or `script` with `voice_id`. One speech source is required. **script** `string` Both engines. Text for the avatar to speak. Requires `voice_id`. Use it instead of `audio_url`. **voice_id** `string` Both engines. The voice that reads `script`. Required when `script` is set. List the voices with `GET /v1/heygen/v3/voices`. **resolution** `string` (default: 1080p) Both engines. Output pixel tier: the size, not the shape. Resolution does not change the price or the render time. Options: `720p`, `1080p`, `4k` **aspect_ratio** `string` (default: 16:9) Both engines. Output canvas shape, independent of `resolution`. See [Resolution and aspect ratio](#resolution-and-aspect-ratio). Options: `auto`, `16:9`, `9:16`, `4:5`, `5:4`, `1:1` ### Resolution and aspect ratio `resolution` sets the pixel tier and `aspect_ratio` sets the canvas. The dimensions below apply at `16:9`. At any other ratio, the same tier is fitted to that canvas. Read the shape from `aspect_ratio`, never from the tier name. | Resolution | Dimensions at 16:9 | | - | - | | `720p` | 1280 × 720 | | `1080p` | 1920 × 1080 | | `4k` | 3840 × 2160 | Set `aspect_ratio` explicitly. The default is `16:9`, so a portrait face sent without it comes back inside a landscape frame with bars down both sides. `auto` has a different meaning on each engine. * Avatar 5 Digital: `auto` follows the shape of the avatar. Use it. * Avatar 4 Photo: `auto` does not read your photo. A 1080 × 1920 portrait comes back as 1280 × 720, cropped to the face, with no bars to signal it. Send the canvas nearest to the pixels of your photo: `9:16` for a 1080 × 1920 photo, `4:5` for a 3:4 phone portrait. A mismatched ratio is padded, not reframed. * `1:1` re-canvases every public-catalog avatar, since those are all landscape or portrait. A private or custom avatar can differ. ### Avatar 4 Photo, photo and audio ```bash theme={"system"} # The media URLs below are placeholders. Point them at your own publicly # reachable files before you run this. curl https://api.nunchux.com/v1/heygen/v3/videos \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "type": "image", "image": { "type": "url", "url": "https://example.com/example-1080x1920.jpg" }, "audio_url": "https://example.com/example.mp3", "resolution": "1080p", "aspect_ratio": "9:16" }' ``` ### Avatar 4 Photo, inline base64 photo ```bash theme={"system"} # The media URL below is a placeholder. Point it at your own publicly # reachable file before you run this. # 1. Encode the photo (raw base64, no "data:" prefix) IMG=$(base64 -w0 portrait.jpg) # 2. Submit curl https://api.nunchux.com/v1/heygen/v3/videos \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "type": "image", "image": { "type": "base64", "media_type": "image/jpeg", "data": "'"$IMG"'" }, "audio_url": "https://example.com/example.mp3", "resolution": "1080p", "aspect_ratio": "9:16" }' ``` ### Avatar 5 Digital, catalog avatar and script ```bash theme={"system"} curl https://api.nunchux.com/v1/heygen/v3/videos \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "type": "avatar", "avatar_id": "your_avatar_id", "engine": { "type": "avatar_v" }, "script": "Hi! Here is a quick walkthrough of what we shipped this week.", "voice_id": "en_us_female_01", "resolution": "1080p", "aspect_ratio": "auto" }' ``` ## Voices When you drive from a `script`, choose a `voice_id` from the voices endpoint. ```bash theme={"system"} curl https://api.nunchux.com/v1/heygen/v3/voices \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0" ``` The response lists each voice with its language and gender. ```json theme={"system"} { "data": { "voices": [ { "voice_id": "en_us_female_01", "language": "English", "gender": "female" }, { "voice_id": "en_us_male_01", "language": "English", "gender": "male" } ] } } ``` ## Response Submit returns a `video_id`. Poll it until `status` is `completed` or `failed`. Then download `video_url`. ### Submit **data** `object` *required* The submitted job. **Item properties** **video_id** `string` *required* The job handle. It is an opaque, variable-length token of about 230 characters. Store it as an unbounded string and send it verbatim on the poll path. **status** `string` *required* The initial job state: `waiting` or `pending` while the job is queued. **output_format** `string` *required* Always `mp4`. ```json theme={"system"} { "data": { "video_id": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1byI6IjNmOWMyYTdlODFiNGQ2MDUiLCJ2IjoiN2QxZTlmMmM0YjhhNGUwZjljM2IyYTFkNmU1ZjRjM2IiLCJtIjoidmlkZW8iLCJleHAiOjE3NTY2OTU2MDAsImlhdCI6MTc1NjA5MDgwMH0.vYKUo0L4vIUnsO4HNHxI5lPoDaYX7gY_dwslw3nWGoI", "status": "waiting", "output_format": "mp4" } } ``` ### Poll **data** `object` *required* The job status. **Item properties** **id** `string` *required* The job handle, echoed back. **status** `string` *required* `waiting` or `pending` while the job is queued, then `processing`, then `completed` or `failed`. Only `completed` and `failed` are terminal. Treat any other value as still running and keep polling. **duration** `number` Output length in seconds. Present when `status` is `completed`. This is the number of output-seconds that you are billed for. **video_url** `string` URL of the output video. Present when `status` is `completed`. The URL expires within hours, so download it promptly. ```json theme={"system"} { "data": { "id": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1byI6IjNmOWMyYTdlODFiNGQ2MDUiLCJ2IjoiN2QxZTlmMmM0YjhhNGUwZjljM2IyYTFkNmU1ZjRjM2IiLCJtIjoidmlkZW8iLCJleHAiOjE3NTY2OTU2MDAsImlhdCI6MTc1NjA5MDgwMH0.vYKUo0L4vIUnsO4HNHxI5lPoDaYX7gY_dwslw3nWGoI", "status": "completed", "duration": 7.02, "video_url": "https://resource.heygen.ai/video/...mp4" } } ``` ## Example Submit, poll, then download. The example uses Avatar 4 Photo with a hosted photo and a hosted audio file. For Avatar 5 Digital, send `"type": "avatar"` with an `avatar_id` and `"engine": {"type": "avatar_v"}` instead of the `image` object. To drive from text, send `script` and `voice_id` instead of `audio_url`. ```bash cURL theme={"system"} # The media URLs below are placeholders. Point them at your own publicly # reachable files before you run this. BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/heygen/v3/videos" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "type": "image", "image": { "type": "url", "url": "https://example.com/example-1080x1920.jpg" }, "audio_url": "https://example.com/example.mp3", "resolution": "1080p", "aspect_ratio": "9:16" }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } VIDEO_ID=$(jq -er '.data.video_id' <<<"$SUBMIT") || { echo "no video id in: $SUBMIT" >&2; exit 1; } # 2. Poll until status is completed or failed DELAY=10 for _ in $(seq 1 60); do RESP=$(curl -sS "$BASE/v1/heygen/v3/videos/$VIDEO_ID" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.data.status' <<<"$RESP") case "$STATUS" in completed|failed) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Stop on failure [ "$STATUS" = "completed" ] || { echo "not completed ($STATUS): $(jq -c '.data' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o avatar.mp4 "$(jq -r '.data.video_url' <<<"$RESP")" ``` ```python Python theme={"system"} # The media URLs below are placeholders. Point them at your own publicly # reachable files before you run this. # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/heygen/v3/videos", headers=HEADERS, json={ "type": "image", "image": {"type": "url", "url": "https://example.com/example-1080x1920.jpg"}, "audio_url": "https://example.com/example.mp3", "resolution": "1080p", "aspect_ratio": "9:16", }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") video_id = submit.json()["data"]["video_id"] # 2. Poll until status is completed or failed delay = 10 for _ in range(60): data = requests.get(f"{BASE}/v1/heygen/v3/videos/{video_id}", headers=HEADERS).json()["data"] if data["status"] in ("completed", "failed"): break time.sleep(delay) delay = min(delay * 2, 30) # 3. Stop on failure if data["status"] != "completed": raise RuntimeError(f"HeyGen job not completed ({data['status']}): {data}") # 4. Download with requests.get(data["video_url"], stream=True, timeout=300) as r: r.raise_for_status() with open("avatar.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` ```javascript JavaScript theme={"system"} // The media URLs below are placeholders. Point them at your own publicly // reachable files before you run this. import { writeFile } from "node:fs/promises"; const BASE = "https://api.nunchux.com"; const HEADERS = { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // 1. Submit const submitRes = await fetch(`${BASE}/v1/heygen/v3/videos`, { method: "POST", headers: HEADERS, body: JSON.stringify({ type: "image", image: { type: "url", url: "https://example.com/example-1080x1920.jpg" }, audio_url: "https://example.com/example.mp3", resolution: "1080p", aspect_ratio: "9:16", }), }); if (!submitRes.ok) throw new Error(`submit failed: HTTP ${submitRes.status} ${await submitRes.text()}`); const videoId = (await submitRes.json()).data.video_id; // 2. Poll until status is completed or failed let data; let delay = 10_000; for (let i = 0; i < 60; i++) { data = ( await fetch(`${BASE}/v1/heygen/v3/videos/${videoId}`, { headers: HEADERS }).then((r) => r.json() ) ).data; if (data.status === "completed" || data.status === "failed") break; await sleep(delay); delay = Math.min(delay * 2, 30_000); } // 3. Stop on failure if (data?.status !== "completed") { throw new Error(`HeyGen job not completed (${data?.status}): ${JSON.stringify(data)}`); } // 4. Download const res = await fetch(data.video_url); if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`); await writeFile("avatar.mp4", Buffer.from(await res.arrayBuffer())); ``` ## Tips * Start from a strong face. On Avatar 4 Photo, send a clear, front-facing portrait with the face well lit and unobstructed. On Avatar 5 Digital, pick the `avatar_id` whose look fits the message. * You host the inputs. There is no upload endpoint. HeyGen downloads a URL during the job, not at submit, so the URL must stay publicly reachable until the job completes. An inline base64 photo needs no hosting. * Match the speech source to the job. Point `audio_url` at polished narration that you host. Use `script` with `voice_id` for fast iterations, for language swaps, and when you have nowhere to host an audio file. * Write scripts in natural, spoken phrasing. It lip-syncs better than dense written prose. * Set `resolution` explicitly. The default is `1080p`. * Set `aspect_ratio` explicitly. On Avatar 4 Photo, send the canvas nearest to the pixels of your photo. On Avatar 5 Digital, send `auto`. See [Resolution and aspect ratio](#resolution-and-aspect-ratio). * Poll every 10 s at first, then back off to 30 s. Polls are free and take no job slot. Render time scales with clip length, so allow 10 minutes or more and set your client timeout to match. * Branch on `failed`. It is terminal, and the body carries the reason. * Download the video as soon as `status` is `completed`. The URL expires within hours. * Store `video_id` as an unbounded string. It is about 230 characters long, and you must send it verbatim on the poll path. * A 5xx or a timeout on submit does not tell you whether the job was created. Do not resubmit blindly, because a second job that completes is billed too. If the submit returned a `video_id`, poll it. If it returned nothing, wait, then read your credit balance before you submit again. ## Errors and limits * A 200 on submit means that HeyGen accepted the job. It does not mean that the job succeeded. A failure appears later as `failed` in the poll response, with the reason in the body. * A failed job is never charged. * `resolution` accepts `720p`, `1080p` and `4k`. Any other value returns 400 with the code `unsupported_resolution`. Nothing is charged. * A submit with no face (`image` when `type` is `image`, `avatar_id` when `type` is `avatar`), with no speech source, or with `script` but no `voice_id` returns 400. * A `video_id` is scoped to your account. Poll only a handle that your own submit returned. A handle that belongs to another account returns 409. * Neither engine has a duration control. The clip is as long as the audio or the script. A URL that HeyGen cannot download fails the submit at once with 400 and the code `invalid_parameter`. Host the file publicly, or send the photo inline as base64. ```json theme={"system"} { "error": { "code": "invalid_parameter", "message": "Invalid URL in files[0]: Could not download the file. Ensure the URL is publicly accessible.", "doc_url": "https://developers.heygen.com/docs/error-codes#invalid-parameter" } } ``` The general error contract, the rate limits and the credit rules apply to every endpoint. See [Errors](/errors), [Rate limits](/rate-limits), [Credits and pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Kling Source: https://docs.nunchux.ai/partner-models/kling Kling V3 and Kling V3 Omni video generation with your Nunchux key: text-to-video, image-to-video, omni video and motion control. # Kling Kling is Kuaishou's video generation model family. Every Kling endpoint is asynchronous: submit a job, poll it until it reaches a terminal status, then download the output. The routes mirror Kling's own API, so the request bodies, response shapes and error codes follow Kling's documentation. You call them with your Nunchux API key and need no Kling account. ## Models | Model | Model ID | Tasks | Modes/resolution | Duration | | - | - | - | - | - | | Kling V3 | `kling-v3` | Text-to-video, image-to-video, motion control | `std`, `pro`, `4k` (motion control: `std`, `pro`) | 3 to 15 s (motion control: follows the reference video) | | Kling V3 Omni | `kling-v3-omni` | Omni video | `std`, `pro`, `4k` | 3 to 10 s (storyboard: up to 30 s) | `std` is the standard tier. It is the fastest and the most economical. `pro` gives sharper detail and stronger motion. `4k` gives 4K-resolution output. Higher tiers take longer. Start with `kling-v3`. It supports the `std`, `pro` and `4k` modes. Both models can add native audio with the `sound` field in [Common fields](#common-fields). Use `kling-v3-omni` on the [omni video](#omni-video) endpoint for multi-reference or storyboard work. For cost-sensitive jobs, use `std`. It is the cheapest per second. ## Endpoints | Capability | Route | | - | - | | [Text-to-video](#text-to-video) | `POST /v1/klingai/videos/text2video` | | [Image-to-video](#image-to-video) | `POST /v1/klingai/videos/image2video` | | [Omni video](#omni-video) | `POST /v1/klingai/videos/omni-video` | | [Motion control](#motion-control) | `POST /v1/klingai/videos/motion-control` | | [Poll a task](#poll-a-task) | `GET /v1/klingai/videos/{capability}/{task_id}` | The base URL is `https://api.nunchux.com`. Each submit returns a `task_id` immediately. Poll the same capability that you submitted to, with the `task_id` appended to the route. ## Common fields Send your API key in the `X-API-Key` header (see [Authentication](/authentication)). Send `Content-Type: application/json` on every submit. Send a `User-Agent` header that identifies your application, such as `YourApp/1.0`. The request fields below appear on more than one endpoint. **model_name** `string` *required* The model to generate with. See [Models](#models). Defaults to `kling-v3` on text-to-video, image-to-video and motion control. Defaults to `kling-v3-omni` on omni video. Options: `kling-v3` on text-to-video, image-to-video and motion control. `kling-v3-omni` on omni video. **mode** `string` (default: std) Quality and speed tier. Higher tiers take longer. Motion control accepts `std` and `pro` only. Options: `std`, `pro`, `4k` **prompt** `string` *required* Description of the video to generate. Max 2500 characters. On image-to-video, describe the motion or the transformation. On omni video, refer to an input with a placeholder such as `<<>>`. Not sent on motion control. Ignored in [storyboard mode](#storyboard-mode). **negative_prompt** `string` What to exclude from the video. Max 2500 characters. Text-to-video and image-to-video only. **duration** `string` (default: 5) Output length in seconds, sent as a string. Billed per second. Common values are `"5"` and `"10"`. Not sent on motion control, where the output length follows the reference video. Ignored in [storyboard mode](#storyboard-mode). Range: 3-15 on text-to-video and image-to-video. 3-10 on omni video. **sound** `string` (default: off) Native audio generation. Off by default, so a clip is silent unless you send `on`. Text-to-video, image-to-video and omni video. In `std` and `pro`, a clip with sound bills at a higher per-second rate. On `kling-v3` in `4k` mode, audio is always included and this flag is ignored. On omni video, `on` cannot be combined with `video_list`; that request returns a 400. Options: `on`, `off` **callback_url** `string` If set, Kling POSTs status updates to this URL, and you do not need to poll. Text-to-video and image-to-video only. ## Text-to-video `POST https://api.nunchux.com/v1/klingai/videos/text2video` Generate a video from a text prompt. Send `model_name` and `prompt`. Every other field is optional and falls back to its default. Use `kling-v3`. **aspect_ratio** `string` (default: 16:9) Output aspect ratio. Options: `16:9`, `9:16`, `1:1` To plan a sequence of shots instead of one prompt, see [Storyboard mode](#storyboard-mode). ```bash cURL theme={"system"} curl https://api.nunchux.com/v1/klingai/videos/text2video \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model_name": "kling-v3", "prompt": "a paper crane unfolding into a real bird, cinematic slow motion", "mode": "std", "duration": "5", "aspect_ratio": "16:9" }' ``` ```python Python theme={"system"} import os, requests resp = requests.post( "https://api.nunchux.com/v1/klingai/videos/text2video", headers={"X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0"}, json={ "model_name": "kling-v3", "prompt": "a paper crane unfolding into a real bird, cinematic slow motion", "mode": "std", "duration": "5", "aspect_ratio": "16:9", }, ) task_id = resp.json()["data"]["task_id"] ``` ```javascript JavaScript theme={"system"} const submit = await fetch("https://api.nunchux.com/v1/klingai/videos/text2video", { method: "POST", headers: { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }, body: JSON.stringify({ model_name: "kling-v3", prompt: "a paper crane unfolding into a real bird, cinematic slow motion", mode: "std", duration: "5", aspect_ratio: "16:9", }), }).then((r) => r.json()); const taskId = submit.data.task_id; ``` ## Image-to-video `POST https://api.nunchux.com/v1/klingai/videos/image2video` Animate a starting image into a video clip. Send `model_name`, `image` and a `prompt` that describes the motion. Use `kling-v3`. **image** `string` *required* The starting frame. Pass a public URL or raw base64, with no `data:image/...;base64,` prefix. Kling rejects the prefixed form with code 1201. ```bash cURL theme={"system"} IMG_B64=$(base64 < input.jpg | tr -d '\n') curl https://api.nunchux.com/v1/klingai/videos/image2video \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d "{ \"model_name\": \"kling-v3\", \"prompt\": \"camera pushes in slowly, subtle ambient motion\", \"mode\": \"pro\", \"duration\": \"5\", \"image\": \"$IMG_B64\" }" ``` ```python Python theme={"system"} import base64, os, requests with open("input.jpg", "rb") as f: img_b64 = base64.b64encode(f.read()).decode() resp = requests.post( "https://api.nunchux.com/v1/klingai/videos/image2video", headers={"X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0"}, json={ "model_name": "kling-v3", "prompt": "camera pushes in slowly, subtle ambient motion", "mode": "pro", "duration": "5", "image": img_b64, }, ) task_id = resp.json()["data"]["task_id"] ``` ```javascript JavaScript theme={"system"} import { readFile } from "node:fs/promises"; const imgB64 = (await readFile("input.jpg")).toString("base64"); const submit = await fetch("https://api.nunchux.com/v1/klingai/videos/image2video", { method: "POST", headers: { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }, body: JSON.stringify({ model_name: "kling-v3", prompt: "camera pushes in slowly, subtle ambient motion", mode: "pro", duration: "5", image: imgB64, }), }).then((r) => r.json()); const taskId = submit.data.task_id; ``` ## Omni video `POST https://api.nunchux.com/v1/klingai/videos/omni-video` Compose one clip from reference images, videos and elements. Use `kling-v3-omni`. At least one of `image_list`, `video_list` or `element_list` must be non-empty. You can send up to 7 reference inputs across the three lists. Refer to an input from the prompt with a 1-indexed placeholder in submission order: `<<>>`, `<<>>`, `<<>>`. **image_list** `array` Reference images. **Item properties** **image_url** `string` *required* Public URL or raw base64 of the reference image, with no `data:image/...;base64,` prefix. **type** `string` Optional sequence anchor. An entry with no type acts as an additional reference. Options: `first_frame`, `end_frame` **video_list** `array` Reference videos to continue or to composite from. **Item properties** **video_url** `string` *required* Public URL of the reference video. **element_list** `array` Reference elements, such as segmented objects or characters, to compose into the video. **aspect_ratio** `string` Output aspect ratio. Required when `image_list` has no `first_frame` entry. Without it, the request returns a 400. Options: `16:9`, `9:16`, `1:1` To plan a sequence of shots, see [Storyboard mode](#storyboard-mode). ```bash cURL theme={"system"} # Placeholder URL: point it at your own publicly reachable file. curl https://api.nunchux.com/v1/klingai/videos/omni-video \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model_name": "kling-v3-omni", "prompt": "<<>> walks through a neon-lit market, cinematic", "mode": "std", "duration": "5", "aspect_ratio": "16:9", "image_list": [{ "image_url": "https://example.com/example.jpg" }] }' ``` ```python Python theme={"system"} # Placeholder URL: point it at your own publicly reachable file. import os, requests resp = requests.post( "https://api.nunchux.com/v1/klingai/videos/omni-video", headers={"X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0"}, json={ "model_name": "kling-v3-omni", "prompt": "<<>> walks through a neon-lit market, cinematic", "mode": "std", "duration": "5", "aspect_ratio": "16:9", "image_list": [{"image_url": "https://example.com/example.jpg"}], }, ) task_id = resp.json()["data"]["task_id"] ``` ```javascript JavaScript theme={"system"} // Placeholder URL: point it at your own publicly reachable file. const submit = await fetch("https://api.nunchux.com/v1/klingai/videos/omni-video", { method: "POST", headers: { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }, body: JSON.stringify({ model_name: "kling-v3-omni", prompt: "<<>> walks through a neon-lit market, cinematic", mode: "std", duration: "5", aspect_ratio: "16:9", image_list: [{ image_url: "https://example.com/example.jpg" }], }), }).then((r) => r.json()); const taskId = submit.data.task_id; ``` ## Motion control `POST https://api.nunchux.com/v1/klingai/videos/motion-control` Drive a still character with the motion of a reference video. Kling transfers the action from the driver clip and preserves the character's identity. Use `kling-v3`. Do not send `prompt` or `duration`. The output length follows the reference video. **image_url** `string` *required* Public URL or raw base64 of the still character to animate, with no `data:image/...;base64,` prefix. **video_url** `string` *required* Public URL of the driver clip whose motion is transferred onto the character. **character_orientation** `string` *required* How the character reference is provided. `image` expects a still image in `image_url` (cap: 10 s). `video` expects a video in `image_url` (cap: 30 s). Options: `image`, `video` **input_video_seconds** `integer` *required* Length of the driver clip in seconds. This value drives per-second billing, so declare it accurately. Range: 1-10. > [!NOTE] > > Billing > > Kling bills per second of generated output. If you under-declare `input_video_seconds`, a follow-up charge is applied after the job completes. If you over-declare, the difference is not refunded automatically. ```bash cURL theme={"system"} # Placeholder URLs: point them at your own publicly reachable files. curl https://api.nunchux.com/v1/klingai/videos/motion-control \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model_name": "kling-v3", "mode": "std", "image_url": "https://example.com/example.jpg", "video_url": "https://example.com/example.mp4", "character_orientation": "image", "input_video_seconds": 5 }' ``` ```python Python theme={"system"} # Placeholder URLs: point them at your own publicly reachable files. import os, requests resp = requests.post( "https://api.nunchux.com/v1/klingai/videos/motion-control", headers={"X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0"}, json={ "model_name": "kling-v3", "mode": "std", "image_url": "https://example.com/example.jpg", "video_url": "https://example.com/example.mp4", "character_orientation": "image", "input_video_seconds": 5, }, ) task_id = resp.json()["data"]["task_id"] ``` ```javascript JavaScript theme={"system"} // Placeholder URLs: point them at your own publicly reachable files. const submit = await fetch("https://api.nunchux.com/v1/klingai/videos/motion-control", { method: "POST", headers: { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }, body: JSON.stringify({ model_name: "kling-v3", mode: "std", image_url: "https://example.com/example.jpg", video_url: "https://example.com/example.mp4", character_orientation: "image", input_video_seconds: 5, }), }).then((r) => r.json()); const taskId = submit.data.task_id; ``` ## Storyboard mode Text-to-video and omni video accept a multi-shot storyboard. Set `multi_shot` to `true` and describe each shot in `multi_prompt`. The top-level `prompt` and `duration` are ignored. The total length is the sum of the per-shot durations. All constraints are validated before billing, so a malformed request returns a 400 with no charge. **multi_shot** `boolean` (default: false) Enable multi-shot storyboard mode. **shot_type** `string` How shots are planned. Required when `multi_shot` is `true`. Options: `customize`, `intelligence` **multi_prompt** `array` Per-shot instructions. Text-to-video accepts up to 6 shots and 15 seconds in total. Omni video caps the total at 30 seconds. **Item properties** **index** `integer` *required* Sequential from 1, with no gaps or duplicates. **prompt** `string` *required* Non-empty description for this shot. **duration** `string` *required* Integer seconds for this shot, sent as a string. Range 1-15 on text-to-video and 1-10 on omni video. ```bash theme={"system"} curl https://api.nunchux.com/v1/klingai/videos/text2video \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model_name": "kling-v3", "mode": "std", "multi_shot": true, "shot_type": "customize", "multi_prompt": [ { "index": 1, "prompt": "wide establishing shot at dawn, fog over a mountain lake", "duration": "5" }, { "index": 2, "prompt": "close-up on a ripple spreading across the water surface", "duration": "5" } ] }' ``` ## Poll a task `GET https://api.nunchux.com/v1/klingai/videos/{capability}/{task_id}` `{capability}` is one of `text2video`, `image2video`, `omni-video` and `motion-control`. Poll the same capability that you submitted to. A `task_id` polled at another capability's route returns 404. Poll every 5 to 10 seconds at first, then back off to 15 to 30 seconds. Polls do not use credits and do not count toward your concurrency limit. `task_status` moves from `submitted` to `processing`, then to `succeed` or `failed`. A task handle expires after 7 days. Output URLs expire within hours, so download the output as soon as the task succeeds. **code** `integer` *required* 0 on success. A non-zero value indicates a Kling error. **message** `string` *required* Human-readable status, such as `SUCCEED`. **data** `object` *required* The task payload. **Item properties** **task_id** `string` *required* The task handle. Poll the same capability that you submitted to with it. **task_status** `string` *required* `submitted`, `processing`, `succeed` or `failed`. **task_status_msg** `string` Explains why a job failed. Show it to your users. **task_result.videos** `array` Present once `task_status` is `succeed`. **Item properties** **url** `string` URL of the output. It expires within hours, so download promptly. **duration** `string` Length of the generated clip in seconds. The submit response has the same shape, with `task_status` set to `submitted`. A poll response when the task has succeeded: ```json theme={"system"} { "code": 0, "message": "SUCCEED", "data": { "task_id": "eyJhbGciOiJIUzI1NiIs...", "task_status": "succeed", "task_result": { "videos": [ { "url": "https://v16-kling-fdl.klingai.com/...", "duration": "5.0" } ] } } } ``` ## Example Submit a text-to-video job, poll it until it reaches a terminal status, then download the clip. ```bash cURL theme={"system"} # 1. Submit SUBMIT=$(curl -sS --fail-with-body https://api.nunchux.com/v1/klingai/videos/text2video \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model_name": "kling-v3", "prompt": "A cinematic drone shot sweeping over snow-capped mountains at sunrise", "mode": "std", "duration": "5", "aspect_ratio": "16:9" }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.data.task_id' <<<"$SUBMIT") || { echo "no task id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the task reaches a terminal status DELAY=5 TERMINAL=0 for _ in $(seq 1 90); do RESP=$(curl -sS https://api.nunchux.com/v1/klingai/videos/text2video/$TASK \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.data.task_status' <<<"$RESP") case "$STATUS" in succeed|failed) TERMINAL=1; break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done [ "$TERMINAL" = 1 ] || { echo "timed out (last status: $STATUS)" >&2; exit 1; } # 3. Check for failure [ "$STATUS" = "succeed" ] || { echo "Kling: status $STATUS, not succeed: $(jq -c '.data.task_status_msg // empty' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o kling.mp4 "$(jq -r '.data.task_result.videos[0].url' <<<"$RESP")" ``` ```python Python theme={"system"} import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "Content-Type": "application/json", "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/klingai/videos/text2video", headers=HEADERS, json={ "model_name": "kling-v3", "prompt": "A cinematic drone shot sweeping over snow-capped mountains at sunrise", "mode": "std", "duration": "5", "aspect_ratio": "16:9", }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task_id = submit.json()["data"]["task_id"] # 2. Poll until the task reaches a terminal status TERMINAL = ("succeed", "failed") delay = 5 for _ in range(90): task = requests.get(f"{BASE}/v1/klingai/videos/text2video/{task_id}", headers=HEADERS).json() if task["data"]["task_status"] in TERMINAL: break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("Kling task did not finish") # 3. Check for failure if task["data"]["task_status"] != "succeed": raise RuntimeError(f"Kling: status {task['data']['task_status']}, not succeed: {task['data'].get('task_status_msg')}") # 4. Download with requests.get(task["data"]["task_result"]["videos"][0]["url"], stream=True, timeout=300) as r: r.raise_for_status() with open("kling.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const BASE = "https://api.nunchux.com"; const HEADERS = { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // 1. Submit const submitRes = await fetch(`${BASE}/v1/klingai/videos/text2video`, { method: "POST", headers: HEADERS, body: JSON.stringify({ model_name: "kling-v3", prompt: "A cinematic drone shot sweeping over snow-capped mountains at sunrise", mode: "std", duration: "5", aspect_ratio: "16:9", }), }); if (!submitRes.ok) throw new Error(`submit failed: HTTP ${submitRes.status} ${await submitRes.text()}`); const taskId = (await submitRes.json()).data.task_id; // 2. Poll until the task reaches a terminal status const TERMINAL = ["succeed", "failed"]; let task; let delay = 5_000; for (let i = 0; i < 90; i++) { task = await fetch(`${BASE}/v1/klingai/videos/text2video/${taskId}`, { headers: HEADERS }).then((r) => r.json() ); if (TERMINAL.includes(task?.data?.task_status)) break; await sleep(delay); delay = Math.min(delay * 2, 30_000); } if (!TERMINAL.includes(task?.data?.task_status)) throw new Error("Kling task did not finish"); // 3. Check for failure if (task.data.task_status !== "succeed") { throw new Error(`Kling: status ${task.data.task_status}, not succeed: ${JSON.stringify(task.data.task_status_msg)}`); } // 4. Download const res = await fetch(task.data.task_result.videos[0].url); if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`); await writeFile("kling.mp4", Buffer.from(await res.arrayBuffer())); ``` ## Tips * Poll; do not busy-wait. Poll every 5 to 10 seconds at first, then back off to 15 to 30 seconds. * Expect text-to-video and image-to-video to finish in 60 to 120 seconds. A `kling-v3` `std` 5-second clip takes about 45 seconds. Motion control and omni video run 2 to 6 minutes, and omni video takes longer with more shots. * Set a client timeout of at least 5 minutes for `std` text-to-video and image-to-video. Use at least 10 minutes for `pro`, `4k`, motion control and omni video. * Download outputs as soon as the task succeeds. Output URLs expire within hours. * Keep prompts concrete and visual. Describe what the camera sees, not abstract concepts. * Use `negative_prompt` to rule out unwanted elements such as blur, text overlays and watermarks. * Set `sound: "on"` to add ambient audio with no post-processing. Omni video clips are silent unless you do. On `kling-v3` in `4k` mode, audio is always included. * Send base64 images as raw bytes with no `data:image/...;base64,` prefix. Public URLs must be reachable by Kling's servers: no auth walls and no localhost. * Use a clear, well-composed starting frame for image-to-video. Kling extends what it sees, so a blurry or cluttered input produces inconsistent motion. * Use a clean, well-lit character image for motion control. Identity preservation is only as good as the source. * Pass a `callback_url` on text-to-video or image-to-video to receive status updates without polling. ## Errors and limits A 200 means that Kling accepted the job and billing started, not that the job succeeded. Do not resubmit after a 200; a second submit creates and bills a second job. Retry only on a network or timeout error that arrives before the submit response. | Response | Meaning | What to do | | - | - | - | | `400` | Invalid request: a bad model name, an unsupported mode or duration, or a missing field. Kling's own 400s can carry a `code`, such as `1201` for a missing `aspect_ratio`. | Read the message and fix the request. A 400 is rejected before billing, so it is never charged, whatever its `code`. | | `401` | Authentication failed, or the task handle expired. | Check your API key and the `task_id`. Task handles expire after 7 days. | | `200` with `code` `1201` | Kling could not read an asset. Usually an `image_url` or `video_url` that is not publicly reachable, or an image sent with a `data:` prefix. | The submit was billed. Fix the asset (public URL or raw base64) and submit again. Open a support ticket for a refund. | | `200` with `task_status` `failed` | The job failed after Kling accepted it. | No action is needed. Credits are refunded automatically. Show `task_status_msg` to your users. | | Other `4xx` or `5xx` | Forwarded from Kling: content moderation, bad parameters or another upstream reason. The response body explains the cause. | Retry only when the cause is transient. | Retry a `5xx` or a transient `429` with backoff. Never retry another `4xx`; the request is invalid as sent. For the general error contract, see [Error codes](/errors). For the concurrency caps and request limits, see [Rate limits](/rate-limits). Every job counts toward your plan's simultaneous-jobs cap; polls do not. Credits are deducted at submit and refunded when a job fails; see [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). Kling-specific limits: * `prompt` and `negative_prompt`: up to 2500 characters. * `duration`: 3 to 15 seconds, or 3 to 10 seconds on omni video. In storyboard mode, text-to-video accepts up to 6 shots and 15 seconds in total, and omni video accepts up to 30 seconds in total. * Omni video: up to 7 reference inputs across `image_list`, `video_list` and `element_list`. * Omni video: `sound: "on"` with a `video_list` returns a 400. * Omni video: `aspect_ratio` is required when `image_list` has no `first_frame` entry. * Motion control: `input_video_seconds` from 1 to 10, and `mode` is `std` or `pro`. * Voice control is not supported on `kling-v3`. Sending `voice_control` or `voice_list` returns a 400. ## Migrating from /v1/video/kling/\* Kling used to live under `/v1/video/kling/*`. It now lives under `/v1/klingai/videos/*`, a faithful mirror of Kling's own API: same request bodies, same response shapes, same error codes. If you call Kling directly today, you can point at us by swapping the base URL and using your Nunchux key as the Bearer token. Existing `/v1/video/kling/*` integrations keep working; migrate when convenient. > [!NOTE] > > Two things that are not a find-and-replace > > * Polling moved from one URL to one per capability. There is no `/v1/klingai/videos/tasks/{task_id}`. Instead of a single `GET /v1/video/kling/tasks/{task_id}`, poll the endpoint you submitted to. For example, a job from `POST /v1/klingai/videos/text2video` is polled at `GET /v1/klingai/videos/text2video/{task_id}`. A shared poll helper needs to carry the submit path through; a `task_id` polled at another capability's URL returns 404. > * One path was renamed beyond the prefix change: `video-effects` → `effects`. The rest keep their trailing segment. | Legacy (superseded) | Current | | - | - | | `POST /v1/video/kling/text2video` | `POST /v1/klingai/videos/text2video` | | `POST /v1/video/kling/image2video` | `POST /v1/klingai/videos/image2video` | | `POST /v1/video/kling/omni-video` | `POST /v1/klingai/videos/omni-video` | | `POST /v1/video/kling/motion-control` | `POST /v1/klingai/videos/motion-control` | | `POST /v1/video/kling/video-effects` | `POST /v1/klingai/videos/effects` | | `POST /v1/video/kling/image-recognize` | `POST /v1/klingai/videos/image-recognize` | | `GET /v1/video/kling/tasks/{task_id}` | `GET /v1/klingai/videos/{capability}/{task_id}` | # MiniMax H3 Source: https://docs.nunchux.ai/partner-models/minimax MiniMax's H3 video model for text-to-video, image-to-video and reference-to-video through one asynchronous endpoint. # MiniMax H3 MiniMax H3 is an omni-modal model that reads text, images, video and audio in one context and generates a video clip. One model ID serves all three tasks. The `content[]` items you send decide which task you get. Generation is asynchronous. You submit a task, poll it until the status is terminal, then download the clip. The route mirrors MiniMax's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Multi-reference scenes. Up to nine reference images, three reference clips and a reference track carry a subject or a style into new footage. > * 2K output. A higher tier than the other partner video models sell. > * Animating a still. A first frame fixes the composition and the prompt drives the motion. > * Longer prompts. The vendor accepts up to 7,000 characters per text item. ## Models | Model | Model ID | Tasks | Resolution | Duration | Reference media | | - | - | - | - | - | - | | MiniMax H3 | `MiniMax-H3` | t2v, i2v, r2v | 768P, 2K | 4 to 15 s | Up to 9 images, 3 clips and 1 audio track | Durations are whole seconds. All three tasks send `MiniMax-H3` as the `model` value. 2K costs more per second than 768P. | Task | Resolution | Duration | Aspect ratio | | - | - | - | - | | Text-to-video | 768P, 2K | 4 to 15 s | Required: 21:9, 16:9, 4:3, 1:1, 3:4 or 9:16 | | Image-to-video | 768P, 2K | 4 to 15 s | Follows the source image | | Reference-to-video | 768P, 2K | 4 to 15 s | Follows the reference set | The `content[]` items select the task. A `text` item alone gives text-to-video. A `first_frame` image item gives image-to-video. `reference_image`, `reference_video` and `reference_audio` items give reference-to-video. A first frame and a reference set cannot appear in the same body. The two use different `role` values, and a body that mixes the role sets is rejected. Pick one task per request. ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/minimax/v2/video_generation` | | Poll | `GET /v1/minimax/v2/query/video_generation/{task_id}` | ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. **model** `string` *required* The model ID: `MiniMax-H3`. **content** `array` *required* The prompt and the media items. Put the `text` item first. Pair each role with its own container: an image rides `image_url`, a clip rides `video_url`, a track rides `audio_url`. A role on the wrong container is accepted without complaint and then does not do what you meant. **item properties** **type** `string` *required* `text` for the prompt. `image_url` for an image. `video_url` for a clip. `audio_url` for a track. **text** `string` The prompt, up to 7,000 characters. Required on a `text` item. All tasks. **role** `string` What a media item is for. * `first_frame`: the image the clip starts on. Image-to-video. One item. * `last_frame`: the image the clip ends on. Image-to-video, optional. One item. * `reference_image`: a reference image. Reference-to-video. Up to 9 items. * `reference_video`: a reference clip. Reference-to-video. Up to 3 items, 2 to 15 seconds each, 15 seconds in total. * `reference_audio`: a reference track. Reference-to-video, optional. One item. **image_url** `object` On an `image_url` item. Holds `url`, the URL of the image. **video_url** `object` On a `video_url` item. Holds `url`, the URL of the clip. **audio_url** `object` On an `audio_url` item. Holds `url`, the URL of the track. **resolution** `string` The output tier: `768P` or `2K`. All tasks. **duration** `integer` *required* The clip length in whole seconds, 4 to 15. All tasks. You are billed per second of output. **ratio** `string` The output shape. Required on a text-only body: `21:9`, `16:9`, `4:3`, `1:1`, `3:4` or `9:16`. `adaptive` is rejected there. Leave it out when the body carries an image, a clip or a track. The output then follows the source. ## Response ### Submit A 200 status means that the provider accepted the task. It does not mean that the clip is ready. **task_id** `string` *required* The task ID. Poll `GET /v1/minimax/v2/query/video_generation/{task_id}` with it. ### Poll **task.status** `string` *required* `queued` or `running` while the task runs. `succeeded`, `failed` or `cancelled` when it ends. Poll until you read one of the three terminal values. **task.content.url** `string` The URL of the clip. Present only when `status` is `succeeded`. The URL is time-limited. Download the clip as soon as the task succeeds. A later poll returns a fresh URL. A task can be polled for 7 days. **task.error** `object` The failure detail. Present when the task did not succeed. Read it before you resubmit. **task.usage** `object` The billed quantities: output seconds, reference-video seconds and the billed image count. ## Example Submit, poll, download. The submit and the poll use different paths. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/minimax/v2/video_generation" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "MiniMax-H3", "content": [ { "type": "text", "text": "a fox trotting through a snowy forest at dawn" } ], "resolution": "768P", "duration": 6, "ratio": "16:9" }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.task_id' <<<"$SUBMIT") || { echo "no task_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/minimax/v2/query/video_generation/$TASK" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.task.status // ""' <<<"$RESP") case "$STATUS" in succeeded|failed|cancelled) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATUS" = "succeeded" ] || { echo "task $STATUS: $(jq -r '.task.error // "no error"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o minimax.mp4 "$(jq -r '.task.content.url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/minimax/v2/video_generation", headers=HEADERS, json={ "model": "MiniMax-H3", "content": [ {"type": "text", "text": "a fox trotting through a snowy forest at dawn"} ], "resolution": "768P", "duration": 6, "ratio": "16:9", }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task = submit.json()["task_id"] # 2. Poll until the status is terminal delay = 5 for _ in range(90): data = requests.get( f"{BASE}/v1/minimax/v2/query/video_generation/{task}", headers=HEADERS ).json() status = data.get("task", {}).get("status", "") if status in ("succeeded", "failed", "cancelled"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("MiniMax task did not reach a terminal status") # 3. Check for failure if status != "succeeded": raise RuntimeError(f"MiniMax task {status}: {data['task'].get('error')}") # 4. Download with requests.get(data["task"]["content"]["url"], stream=True, timeout=300) as r: r.raise_for_status() with open("minimax.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` To animate a still, append an `image_url` item with `role` set to `first_frame` and leave `ratio` out. To carry a subject into a new scene, append `reference_image`, `reference_video` or `reference_audio` items instead, and leave `ratio` out. The bodies below replace the submit body in the example. ```json Image-to-video theme={"system"} { "model": "MiniMax-H3", "content": [ { "type": "text", "text": "the fox turns and trots toward the camera" }, { "type": "image_url", "role": "first_frame", "image_url": { "url": "https://example.com/frame.jpg" } } ], "resolution": "768P", "duration": 6 } ``` ```json Reference-to-video theme={"system"} { "model": "MiniMax-H3", "content": [ { "type": "text", "text": "the subject walks down a rain-soaked street at night, slow tracking shot" }, { "type": "image_url", "role": "reference_image", "image_url": { "url": "https://example.com/ref-1.jpg" } }, { "type": "image_url", "role": "reference_image", "image_url": { "url": "https://example.com/ref-2.jpg" } }, { "type": "video_url", "role": "reference_video", "video_url": { "url": "https://example.com/clip.mp4" } }, { "type": "audio_url", "role": "reference_audio", "audio_url": { "url": "https://example.com/track.mp3" } } ], "resolution": "768P", "duration": 6 } ``` ## Tips * Name a shape on text-to-video. `ratio` is required there, so decide the frame before you run instead of accepting whatever the first attempt gives you. * Give at least one image or one clip on reference-to-video. A reference set describes the subject. The prompt describes the motion. * Keep the reference images consistent in subject and style. Images that disagree pull the result in different directions. * Draft at 768P. 2K costs more per second, so settle the prompt at the lower tier first. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that the provider accepted the task. It does not mean that the task succeeded. A task that fails later ends with `task.status` set to `failed` or `cancelled`, and `task.error` explains why. Read it before you resubmit. A failed submit returns an HTTP error status. See [Error codes](/errors). Two request shapes are rejected: a text-only body without `ratio`, or with `ratio` set to `adaptive`, and a body that mixes the frame roles with the reference roles. A 5xx status or a timeout on submit does not tell you whether the task was created. Never resubmit blindly. If the submit returned a `task_id`, poll it. If it returned nothing, check your credits before you try again. MiniMax applies these limits to the media you attach, and caps the whole set at 12 files: * Images: 256 to 5,760 pixels on each side, JPG, JPEG, PNG, WEBP, HEIC or HEIF, up to 30 MB each * Video: MP4 or MOV, up to 50 MB each, 2 to 15 seconds per clip and 15 seconds in total * Audio: WAV or MP3, up to 15 MB each, 2 to 15 seconds A file you pass by URL is not checked at submit. A file over a cap is refused by the provider after the request was accepted. Reference media changes the charge. Reference video is billed per second at the same rate as the output. The first five reference images are included in the rate, and each image after that adds a charge. Reference audio is free. Every task counts toward the simultaneous-jobs cap of your plan. See [Rate limits](/rate-limits), [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Nano Banana Source: https://docs.nunchux.ai/partner-models/nano-banana Generate and edit images with Google's Nano Banana models in one synchronous call. # Nano Banana Nano Banana is Google's Gemini image model. It generates an image from a text prompt, and it edits images that you send with the prompt. The call is synchronous: one POST returns the finished image in the response body, so there is nothing to poll. The request and response shapes mirror Google's own API. ## Models | Model | Model ID | Tasks | Sizes | Aspect ratios | | - | - | - | - | - | | Nano Banana 2 | `gemini-3.1-flash-image` | Generate, edit | `512`, `1K`, `2K`, `4K` | 14 values, `1:1` to `21:9` | | Nano Banana 2.1 | `gemini-nano-banana-2.1` | Generate, edit | `1K`, `2K`, `4K` | 14 values, `1:1` to `21:9` | | Nano Banana Pro | `gemini-3-pro-image` | Generate, edit | `1K`, `2K`, `4K` | 14 values, `1:1` to `21:9` | | Nano Banana | `gemini-2.5-flash-image` | Generate, edit | `1K` only | 14 values, `1:1` to `21:9` | All four models generate and edit on the same endpoint. A request takes up to 14 reference images on every model. The size is a pixel budget that you set with `image_size`. The shape is a separate axis that you set with `aspect_ratio`. Use Nano Banana 2 for fast everyday generation and edits. It is the default model, and it is the only one that accepts the `512` size. Use Nano Banana 2.1 for the same everyday work when you do not need the `512` size. It is Google's update to Nano Banana 2, and it starts at `1K`. It is a thinking model, so it inserts a `thought` step before the output step in the response. Use Nano Banana Pro when you need the highest fidelity. It starts at `1K`. It is a thinking model, so it inserts a `thought` step before the output step in the response. Nano Banana (`gemini-2.5-flash-image`) is the original Nano Banana, the model before Nano Banana 2. It has one size, `1K`, and no size control. It returns PNG rather than JPEG. > [!WARNING] > > Google shuts down `gemini-2.5-flash-image` on March 15, 2027, and names `gemini-3.1-flash-lite-image` as its replacement. Nunchux stops serving it one to two weeks before that date. `gemini-3.1-flash-lite-image` is not available on Nunchux yet, so plan a move to Nano Banana 2 or Nano Banana 2.1. ## Endpoints The base URL is `https://api.nunchux.com`. | Step | Method | Path | | - | - | - | | Generate or edit | `POST` | `/v1/google/v1beta/interactions` | There is no poll route. The image is in the response. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. Send a `User-Agent` header that names your application, for example `YourApp/1.0`. The JSON body names the model and an `input` array of content parts. A text-only input generates a new image. Image parts turn the request into an edit. See [Editing](#editing). **model** `string` *required* (default: gemini-3.1-flash-image) The Nano Banana model to run. See the [Models](#models) table. Options: `gemini-3.1-flash-image`, `gemini-nano-banana-2.1`, `gemini-3-pro-image`, `gemini-2.5-flash-image` **input** `array` *required* Ordered content parts. A text-only input generates. Add `{ "type": "image" }` parts (up to 14) and the text becomes an edit instruction across them. Image parts also carry `data` and `mime_type`. See [Editing](#editing). **Item properties** **type** `string` *required* The part kind. Options: `text`, `image` **text** `string` The prompt or the edit instruction. Required on `type: "text"` parts. **response_format** `object` *required* Output controls. A request that omits `response_format` or its `type` is rejected with `no_image_format` or `invalid_response_format`. **Item properties** **type** `string` *required* Must be `"image"`. Options: `image` **image_size** `string` Output resolution, as a pixel budget. `512` is accepted on `gemini-3.1-flash-image` only. Google's documentation calls that tier 0.5K, but `0.5K` is rejected as a value. `gemini-2.5-flash-image` accepts `1K` only: send `1K` or omit the field. Any other size is rejected with `not_priced` before anything is charged. Options: `1K`, `2K`, `4K` **aspect_ratio** `string` Output shape, independent of `image_size`. Omitted on a generation, the output is `1:1` on Nano Banana 2, Nano Banana Pro and the original Nano Banana. On Nano Banana 2.1, set the ratio when the shape matters. Omitted on an edit, the output keeps the shape of the first input image. On the original Nano Banana, a two-image edit with a `1:1` first image and a `16:9` second image came back `16:9`, so set the ratio there when the shape matters. Options: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`, `1:8`, `8:1`, `1:4`, `4:1` > [!NOTE] > > Output size and shape > > * `image_size` is a pixel budget, not a shape. `1K` is 1024×1024 at `1:1`, 1584×672 at `21:9` and 768×1376 at `9:16`. On the original Nano Banana, `1K` is 1024×1024 at `1:1`, 1344×768 at `16:9` and 1536×672 at `21:9`. > * Set `image_size` explicitly. When you omit it, the call is billed at the model's largest tier (`4K`, or `1K` on the original Nano Banana), on generations and on edits. > * The 14 ratios in the list are accepted on every model. `1:1`, `21:9` and `9:16` are the ones that have been run end to end. On the original Nano Banana, `1:8` and `8:1` return a `1:4` and a `4:1` image. > * There is no `auto` value for `aspect_ratio`. To keep the shape of the input on an edit, omit the field. On the original Nano Banana, set it on a multi-image edit. ### Editing Add one or more `{ "type": "image" }` parts to `input`, up to 14. The text part becomes an instruction across all of them. The result is always one new image, not a batch and not a mechanical merge. `image_size` and `aspect_ratio` work exactly as on a generation. **input\[].data** `string` Raw base64 image bytes on `type: "image"` parts, with no `data:` prefix. Images are sent inline. There is no URL form. **input\[].mime_type** `string` The MIME type of the image on `type: "image"` parts, for example `image/png` or `image/jpeg`. ## Response The image comes back in the same response, as base64 bytes: JPEG on Nano Banana 2, Nano Banana 2.1 and Nano Banana Pro, and PNG on the original Nano Banana. **id** `string` *required* Identifier for this interaction. **object** `string` *required* The envelope kind. **model** `string` *required* The model that ran, echoed back. **status** `string` *required* The status of the interaction. It is terminal on arrival. The call is synchronous, so there is no in-progress state to poll for. **created** `integer` *required* Unix timestamp when the interaction was created. **updated** `integer` *required* Unix timestamp of the last update, in practice when the image finished. **service_tier** `string` *required* The service tier the call was served on. **usage** `object` *required* Accounting for the call. **steps** `array` *required* The steps of the interaction. The image is on the first entry whose `content[]` carries a `data` field. **Item properties** **signature** `string` Opaque vendor blob on a step of its own. It can be absent. It is not the image, so skip it. **content** `array` The output parts. Take the first step that has one. A `thought` step can sit ahead of it. **Item properties** **data** `string` Base64-encoded image bytes, JPEG or PNG by model. Decode and save. > [!NOTE] > > Reading the response > > * Select the output step by shape, not by index: the first `steps[]` entry whose `content[]` carries a `data` field. The `signature` step is optional, a thinking model such as Nano Banana 2.1 or Nano Banana Pro inserts a `thought` step ahead of the output, and the original Nano Banana can put a step with a `text` part ahead of the image. > * The bytes are JPEG on Nano Banana 2, Nano Banana 2.1 and Nano Banana Pro, whatever the request asked for. The original Nano Banana returns PNG. Name the file accordingly. > * There is no top-level `data` array and no `b64_json` field. If you port a parser from `/v1/images`, this is the line to change. ```json theme={"system"} { "id": "int_01k9v0f2m8e0", "object": "interaction", "model": "gemini-3.1-flash-image", "status": "completed", "created": 1786636800, "updated": 1786636809, "service_tier": "default", "usage": { "...": "accounting for the call" }, "steps": [ { "signature": "CtwBAdHtim8yq0pQ7f..." }, { "content": [ { "data": "/9j/4AAQSkZJRgABAQAAAQABAAD..." } ] } ] } ``` ## Example ### Generate One POST returns the image inline. The example takes the first `steps[]` content part that has a `data` field and saves it as a JPEG. ```bash cURL theme={"system"} # The image is the first steps[] content part with a data field. There is no # data[].b64_json here, and no fixed index: the step layout varies by model. curl -s https://api.nunchux.com/v1/google/v1beta/interactions \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "gemini-3.1-flash-image", "input": [{ "type": "text", "text": "a nano banana dessert, studio lighting" }], "response_format": { "type": "image", "image_size": "1K", "aspect_ratio": "16:9" } }' | jq -r '[.steps[].content[]? | select(.data)][0].data' | base64 -d > output.jpg ``` ```python Python theme={"system"} # pip install requests import base64, os, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # Synchronous: the image is in the response body, so there is no polling. resp = requests.post( f"{BASE}/v1/google/v1beta/interactions", headers=HEADERS, json={ "model": "gemini-3.1-flash-image", "input": [{"type": "text", "text": "a nano banana dessert, studio lighting"}], "response_format": {"type": "image", "image_size": "1K", "aspect_ratio": "16:9"}, }, ) resp.raise_for_status() # The envelope is {id, status, usage, created, updated, service_tier, steps, ...}, # not data[].b64_json. The steps[] layout varies (the signature step is optional, # thinking models add a thought step), so take the first part that has data. steps = resp.json()["steps"] b64 = next(p["data"] for s in steps for p in s.get("content", []) if p.get("data")) with open("output.jpg", "wb") as f: f.write(base64.b64decode(b64)) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const BASE = "https://api.nunchux.com"; const HEADERS = { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }; // Synchronous: the image is in the response body, so there is no polling. const res = await fetch(`${BASE}/v1/google/v1beta/interactions`, { method: "POST", headers: HEADERS, body: JSON.stringify({ model: "gemini-3.1-flash-image", input: [{ type: "text", text: "a nano banana dessert, studio lighting" }], response_format: { type: "image", image_size: "1K", aspect_ratio: "16:9" }, }), }); if (!res.ok) throw new Error(`request failed: HTTP ${res.status} ${await res.text()}`); const body = await res.json(); // The envelope is { id, status, usage, created, updated, service_tier, steps, ... }, // not data[].b64_json. The steps[] layout varies (the signature step is optional, // thinking models add a thought step), so take the first part that has data. const b64 = body.steps.flatMap((s) => s.content ?? []).find((p) => p.data).data; await writeFile("output.jpg", Buffer.from(b64, "base64")); ``` ### Edit The same call with image parts. The prompt places the person from the first image into the room from the second. Omit `aspect_ratio` to keep the shape of the first input. `image_size` still applies, and it still bills at `4K` when you omit it. ```bash cURL theme={"system"} # Images are sent inline as base64. There is no URL form. PERSON=$(base64 < person.jpg | tr -d '\n') ROOM=$(base64 < room.jpg | tr -d '\n') curl -s https://api.nunchux.com/v1/google/v1beta/interactions \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "gemini-3.1-flash-image", "input": [ { "type": "text", "text": "put the person from the first image into the room from the second, keep the lighting natural" }, { "type": "image", "data": "'"$PERSON"'", "mime_type": "image/jpeg" }, { "type": "image", "data": "'"$ROOM"'", "mime_type": "image/jpeg" } ], "response_format": { "type": "image", "image_size": "2K", "aspect_ratio": "3:4" } }' | jq -r '[.steps[].content[]? | select(.data)][0].data' | base64 -d > output.jpg ``` ```python Python theme={"system"} # pip install requests import base64, os, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } def b64_file(path): with open(path, "rb") as f: return base64.b64encode(f.read()).decode() # Images are sent inline as base64. There is no URL form. resp = requests.post( f"{BASE}/v1/google/v1beta/interactions", headers=HEADERS, json={ "model": "gemini-3.1-flash-image", "input": [ {"type": "text", "text": "put the person from the first image into the room from the second, keep the lighting natural"}, {"type": "image", "data": b64_file("person.jpg"), "mime_type": "image/jpeg"}, {"type": "image", "data": b64_file("room.jpg"), "mime_type": "image/jpeg"}, ], "response_format": {"type": "image", "image_size": "2K", "aspect_ratio": "3:4"}, }, ) resp.raise_for_status() steps = resp.json()["steps"] b64 = next(p["data"] for s in steps for p in s.get("content", []) if p.get("data")) with open("output.jpg", "wb") as f: f.write(base64.b64decode(b64)) ``` ```javascript JavaScript theme={"system"} import { readFile, writeFile } from "node:fs/promises"; const BASE = "https://api.nunchux.com"; const HEADERS = { "X-API-Key": process.env.NUNCHUX_API_KEY, "Content-Type": "application/json", "User-Agent": "YourApp/1.0", }; const b64File = async (path) => (await readFile(path)).toString("base64"); // Images are sent inline as base64. There is no URL form. const res = await fetch(`${BASE}/v1/google/v1beta/interactions`, { method: "POST", headers: HEADERS, body: JSON.stringify({ model: "gemini-3.1-flash-image", input: [ { type: "text", text: "put the person from the first image into the room from the second, keep the lighting natural" }, { type: "image", data: await b64File("person.jpg"), mime_type: "image/jpeg" }, { type: "image", data: await b64File("room.jpg"), mime_type: "image/jpeg" }, ], response_format: { type: "image", image_size: "2K", aspect_ratio: "3:4" }, }), }); if (!res.ok) throw new Error(`request failed: HTTP ${res.status} ${await res.text()}`); const body = await res.json(); const b64 = body.steps.flatMap((s) => s.content ?? []).find((p) => p.data).data; await writeFile("output.jpg", Buffer.from(b64, "base64")); ``` ## Tips * Write the prompt as an instruction. Name what must change and what must stay. * When you send several reference images, say which element comes from which image. * Set `image_size` explicitly. An omitted size is billed at the model's largest tier (`4K`, or `1K` on the original Nano Banana), on edits as well as on generations. * Use a larger `image_size` only when you need the detail. Larger sizes cost more and take longer. * Set `aspect_ratio` when you want a shape other than `1:1`. Size and shape are separate axes. * Use Nano Banana Pro for the highest fidelity. Use Nano Banana 2 for fast everyday work. * Read the image from the first `steps[]` entry that has a `data` part. Do not hardcode a step index. * Decode and save the image on receipt. The response carries the bytes, not a URL. ## Errors and limits * A request takes up to 14 image parts. Images are sent inline as base64, with no URL form. * A request that omits `response_format` or `response_format.type` is rejected with `no_image_format` or `invalid_response_format`. A rejected request is not charged. * `512` is accepted on `gemini-3.1-flash-image` only. `0.5K` is rejected on every model. * `gemini-2.5-flash-image` accepts `1K` only. `512`, `2K` and `4K` are rejected with `not_priced`, and nothing is charged. * Nano Banana is priced per image. The price rises with `image_size`, and an omitted `image_size` bills at the model's largest tier: `4K`, or `1K` on `gemini-2.5-flash-image`. The rates are on the [pricing page](https://nunchux.ai/pricing). See [Credits and pricing](/credits-pricing). * A Nano Banana call counts toward your requests per minute. It does not take a simultaneous-job slot. See [Rate limits](/rate-limits). * A `502` after the request was sent is refunded automatically. It is safe to retry. * A `503` with the code `google_unreachable` means that Google could not be reached before anything was sent. Nothing was charged. Retry with backoff. * A `503` whose message says `google pass-through not enabled` means that the route is not available. Do not retry it in a loop. The full error contract, the retry rules and the per-plan caps are on the [Errors](/errors) and [Rate limits](/rate-limits) pages. How every partner model bills and refunds is on the [Partner models overview](/partner-models/overview). # Overview Source: https://docs.nunchux.ai/partner-models/overview Third-party models served through your Nunchux key. Each provider keeps its own routes, request shapes and job lifecycle. # Partner models Partner models are third-party models that you call with your Nunchux API key. Each provider has its own route family on `api.nunchux.com`. The request and response shapes follow the provider's own API. Code written against the provider works after you change the base URL and the key. One key and one credit balance cover every provider. You do not need an account with the provider. When you call a partner model, Nunchux sends your request, including its prompts and files, to the provider of that model. The provider runs the model on its own infrastructure and processes the request under its own terms. The provider can process the request outside the United States. The table below names the provider of each model. Partner models do not use the Nunchux performance tiers. Each model is priced on its own terms. See the model page. ## Models | Model | Provider | Modality | Tasks | Request type | | - | - | - | - | - | | [Nano Banana 2, Nano Banana 2.1, Nano Banana Pro, Nano Banana](/partner-models/nano-banana) | Google | Image | Text-to-image, image-to-image | Synchronous | | [Qwen Image 3.0, Qwen Image 3.0 Pro](/partner-models/qwen-image) | Alibaba Cloud | Image | Text-to-image, image-to-image | Synchronous | | [Kling V3, Kling V3 Omni](/partner-models/kling) | Kling AI | Video | Text-to-video, image-to-video, omni video, motion control | Asynchronous | | [Wan 3.0, Wan 3.0 Prime, Wan 2.7](/partner-models/wan) | Alibaba Cloud | Video | Text-to-video, image-to-video, reference-to-video | Asynchronous | | [HappyHorse 1.1, HappyHorse 1.0](/partner-models/happyhorse) | Alibaba Cloud | Video | Text-to-video, image-to-video, reference-to-video | Asynchronous | | [Seedance 2.5](/partner-models/seedance) | ByteDance | Video | Text-to-video, image-to-video, reference-to-video | Asynchronous | | [MiniMax H3](/partner-models/minimax) | MiniMax | Video | Text-to-video, image-to-video, reference-to-video | Asynchronous | | [Avatar 4 Photo, Avatar 5 Digital](/partner-models/heygen) | HeyGen | Avatar video | Talking avatar from a photo or a HeyGen avatar | Asynchronous | | [Vidu Q4 preview](/partner-models/vidu) | Vidu | Video | Image-to-video, reference-to-video | Asynchronous | | [Grok Imagine Video 1.5, Grok Imagine Video 1.5 Lite](/partner-models/xai) | xAI | Video | Text-to-video, image-to-video, reference-to-video (1.5 only) | Asynchronous | | [Wonder 4, Wonder 3.5, Bloom 2, Gigapixel High Fidelity 3](/partner-models/topaz) | Topaz Labs | Image | Upscaling and enhancement | Asynchronous | Each model page lists the model IDs to send. ## Choosing a model Text-to-video. Seedance 2.5 and HappyHorse generate a soundtrack with the picture. Wan 3.0 holds one shot for up to 30 seconds. Grok Imagine Video 1.5 renders native 1080p, and Grok Imagine Video 1.5 Lite is the cheapest per second. Kling V3 and MiniMax H3 cover the same task. Image-to-video. Every video family animates a starting image. Wan 2.7 also takes a driving audio track. Wan 3.0 and Wan 2.7 take an optional end frame. Reference-to-video. Wan, HappyHorse, MiniMax H3, Vidu Q4 preview and Grok Imagine Video 1.5 carry a subject from reference images into new footage. Vidu Q4 preview takes up to 15 reference images and Grok Imagine Video 1.5 up to 14, plus up to 3 preset voices. Multi-reference and storyboard. Kling V3 Omni composes one clip from reference images, videos and elements, or a multi-shot sequence. Motion transfer. Kling V3 motion control drives a still character with the motion of a reference video. Talking avatar. HeyGen turns a photo or a HeyGen avatar into a lip-synced video, driven by audio or by a script in a chosen voice. Image generation and editing. Nano Banana and Qwen Image generate and edit images in one synchronous call. Qwen Image returns up to six images per request and edits up to three input images. Upscaling and enhancement. Topaz Labs enlarges an image to the size you ask for and repairs noise, blur and compression on the way. Bloom 2 adds new detail to generated images. ## Endpoints Each family has one submit route. The asynchronous families also have one poll route. | Family | Submit | Poll | | - | - | - | | [Nano Banana](/partner-models/nano-banana) | `POST /v1/google/v1beta/interactions` | None. The image is in the response. | | [Qwen Image](/partner-models/qwen-image) | `POST /v1/alibaba/services/aigc/multimodal-generation/generation` | None. The image URL is in the response. | | [Kling](/partner-models/kling) | `POST /v1/klingai/videos/{capability}` | `GET /v1/klingai/videos/{capability}/{task_id}` | | [Wan](/partner-models/wan), [HappyHorse](/partner-models/happyhorse) | `POST /v1/alibaba/services/aigc/video-generation/video-synthesis` | `GET /v1/alibaba/tasks/{task_id}` | | [Seedance](/partner-models/seedance) | `POST /v1/bytedance/contents/generations/tasks` | `GET /v1/bytedance/contents/generations/tasks/{task_id}` | | [MiniMax](/partner-models/minimax) | `POST /v1/minimax/v2/video_generation` | `GET /v1/minimax/v2/query/video_generation/{task_id}` | | [HeyGen](/partner-models/heygen) | `POST /v1/heygen/v3/videos` | `GET /v1/heygen/v3/videos/{video_id}` | | [Vidu](/partner-models/vidu) | `POST /v1/vidu/video/{capability}` | `GET /v1/vidu/video/{task_id}` | | [Grok Imagine Video](/partner-models/xai) | `POST /v1/xai/videos/generations` | `GET /v1/xai/videos/{request_id}` | | [Topaz Labs](/partner-models/topaz) | `POST /v1/topaz/image/enhance` | `GET /v1/topaz/image/{process_id}` | Kling's `{capability}` is one of `text2video`, `image2video`, `omni-video` and `motion-control`. Poll the same capability that you submitted to. Vidu's `{capability}` is `img2video` or `reference2video`, and its poll path takes no capability. ## How a request works Nano Banana and Qwen Image are synchronous. Send one POST and read the image from the response. Every video family is asynchronous, and so is Topaz Labs. A request has three steps. 1. Submit. Send a POST to the submit route with your API key in the `X-API-Key` header. The response contains a task identifier. A 200 status means that the provider accepted the job. It does not mean that the job is complete. 2. Poll. Send a GET to the poll route with the task identifier. Repeat until the status is terminal. Wait a few seconds between polls. Each provider uses its own status field and its own values. 3. Download. When the status is the success value, the poll response contains the URL of the output. Output URLs expire, some within an hour. Download the output as soon as the job succeeds. | Family | Status field | Success | Failure | | - | - | - | - | | Kling | `task_status` | `succeed` | `failed` | | Wan, HappyHorse | `output.task_status` | `SUCCEEDED` | `FAILED`, `CANCELED` | | Seedance | `status` | `succeeded` | `failed`, `cancelled`, `expired` | | MiniMax | `task.status` | `succeeded` | `failed`, `cancelled` | | HeyGen | `data.status` | `completed` | `failed` | | Vidu | `state` | `success` | `failed` | | Grok Imagine Video | `status` | `done` | `failed` | | Topaz Labs | `status` | `Completed` | `Failed`, `Cancelled` | Any other value means that the job is still running. Keep polling. Each model page shows a full submit, poll and download example. ## Billing Each partner model is priced on its own terms, such as resolution, duration or mode. Each model page says what the model is billed on, and the [pricing page](https://nunchux.ai/pricing) lists the rates. Nunchux deducts the credits when it accepts a job. When the job fails, Nunchux refunds the credits. See [Credits & pricing](/credits-pricing). ## Errors and limits A failed submit returns an HTTP error status. See [Error codes](/errors). A failed job does not return an HTTP error. The submit returns 200, and the failure appears later as the failure status in the poll response. The poll response also carries a message that explains the failure. Read it before you resubmit. When the provider cannot read an input that you referenced, such as an image URL that is not publicly reachable, the submit can return 200 with a provider error code in the body. The submit was billed. Correct the input, then submit again. Every job counts toward the simultaneous-jobs cap of your plan. See [Rate limits](/rate-limits). # Qwen Image Source: https://docs.nunchux.ai/partner-models/qwen-image Generate and edit images with Alibaba Cloud's Qwen Image 3.0 models in one synchronous call. # Qwen Image Qwen Image 3.0 is Alibaba Cloud's image model. It generates an image from a text prompt, and it edits up to three images that you send with the prompt. The call is synchronous: one POST returns the image in the response, so there is nothing to poll. The request and response shapes mirror Alibaba Cloud's own API. > [!NOTE] > > Best for > > * Generating and editing on one endpoint, with one model ID. > * Edits that combine up to three input images. > * Batches. One request returns up to six images. ## Models | Model | Model ID | Tasks | Sizes | Input images | Images per request | | - | - | - | - | - | - | | Qwen Image 3.0 | `qwen-image-3.0` | Generate, edit | `1K`, `2K` | Up to 3 | 1 to 6 | | Qwen Image 3.0 Pro | `qwen-image-3.0-pro` | Generate, edit | `1K`, `2K` | Up to 3 | 1 to 6 | Each model uses one ID for both tasks. The items in the message select the task. A text item alone generates an image. Image items before the text item edit those images. Qwen Image 3.0 Pro is the higher grade of Qwen Image 3.0, with the same request shape and the same limits. It costs more per image. Use Qwen Image 3.0 while you iterate, and Qwen Image 3.0 Pro for the final image. ## Endpoints The base URL is `https://api.nunchux.com`. | Step | Method | Path | | - | - | - | | Generate or edit | `POST` | `/v1/alibaba/services/aigc/multimodal-generation/generation` | There is no poll route. The image is in the response. [Wan](/partner-models/wan) and [HappyHorse](/partner-models/happyhorse) use the same `/v1/alibaba` route family, with an asynchronous video route. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. **model** `string` *required* The model ID from the table above: `qwen-image-3.0` or `qwen-image-3.0-pro`. **input** `object` *required* The prompt and the input images. **properties** **messages** `array` *required* One message, with `role` set to `user`. **message properties** **role** `string` *required* Must be `user`. **content** `array` *required* The input images first, then the prompt. * `{"image": "..."}`: an input image, as a URL or a data URI. Edits only. Up to 3 items. The provider fetches a URL, so it must be reachable from the internet. * `{"text": "..."}`: the prompt. One item, after the images. On an edit, say what must change and what must stay. **parameters** `object` The generation controls. **properties** **size** `string` The output size, as `width*height` in pixels, for example `1328*1328`. The output area selects the price tier. A size up to 2,250,000 pixels is billed at the `1K` tier. A larger size is billed at the `2K` tier. Alibaba Cloud documents sizes from `512*512` to `2048*2048`. If you omit it, the image is `2048*2048` and is billed at the `2K` tier. **n** `integer` (default: 1) The number of images. Range: 1 to 6. Each image is billed. **prompt_extend** `boolean` (default: true) When `true`, Alibaba Cloud rewrites the prompt into a more detailed one before the image renders, and `output.rewrite_status` is `success`. Set it to `false` to render your prompt as written. `output.rewrite_status` is then `not_use`. > [!NOTE] > > Common sizes > > | Shape | `1K` tier | `2K` tier | > | - | - | - | > | 1:1 | `1328*1328` | `2048*2048` | > | 16:9 | `1664*928` | `2048*1152` | > | 9:16 | `928*1664` | `1152*2048` | > | 4:3 | `1472*1104` | `2048*1536` | > | 3:4 | `1104*1472` | `1536*2048` | A minimal request body: ```json theme={"system"} { "model": "qwen-image-3.0", "input": { "messages": [ { "role": "user", "content": [{ "text": "a paper lantern floating over a quiet canal at night" }] } ] }, "parameters": { "size": "1328*1328", "n": 1 } } ``` ## Response The response is Alibaba Cloud's own JSON body. Each image is a URL in `output.choices[].message.content[]`. **output** `object` *required* The result. **properties** **choices** `array` *required* The generated images. **item properties** **message.content\[].image** `string` The URL of the image. It is signed and expires after 24 hours. Download the image as soon as you receive it. **rewrite_status** `string` `success` when Alibaba Cloud rewrote the prompt, `not_use` when `prompt_extend` was `false`. **usage** `object` What the request produced: `output_width`, `output_height`, `output_image_count`, `output_image_type` (the size tier), and `input_image_count`. Nunchux bills from these values. **request_id** `string` *required* Alibaba Cloud's identifier for the request. ```json theme={"system"} { "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [{ "type": "image", "image": "https://" }] } } ], "rewrite_status": "success" }, "usage": { "input_image_count": 0, "input_image_type": "qima_input_1k", "output_height": 1328, "output_image_count": 1, "output_image_type": "qima_output_1k", "output_width": 1328 }, "request_id": "19a65aa2-7483-9dc9-85ab-92f349127856" } ``` ## Example ### Generate ```bash cURL theme={"system"} # Synchronous: one POST returns the image URL. There is no polling. # The URL is at output.choices[0].message.content[0].image and expires after 24 hours. url=$(curl -s https://api.nunchux.com/v1/alibaba/services/aigc/multimodal-generation/generation \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "qwen-image-3.0", "input": { "messages": [ { "role": "user", "content": [{"text": "a paper lantern floating over a quiet canal at night"}] } ] }, "parameters": {"size": "1328*1328", "n": 1} }' | jq -r '.output.choices[0].message.content[0].image') curl -s -o output.png "$url" ``` ```python Python theme={"system"} import os import requests response = requests.post( "https://api.nunchux.com/v1/alibaba/services/aigc/multimodal-generation/generation", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "qwen-image-3.0", "input": { "messages": [ { "role": "user", "content": [{"text": "a paper lantern floating over a quiet canal at night"}], } ] }, "parameters": {"size": "1328*1328", "n": 1}, }, ) # The URL expires after 24 hours, so download the image at once. url = response.json()["output"]["choices"][0]["message"]["content"][0]["image"] with open("output.png", "wb") as f: f.write(requests.get(url).content) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const response = await fetch( "https://api.nunchux.com/v1/alibaba/services/aigc/multimodal-generation/generation", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "qwen-image-3.0", input: { messages: [ { role: "user", content: [{ text: "a paper lantern floating over a quiet canal at night" }], }, ], }, parameters: { size: "1328*1328", n: 1 }, }), } ); const data = await response.json(); // The URL expires after 24 hours, so download the image at once. const url = data.output.choices[0].message.content[0].image; await writeFile("output.png", Buffer.from(await (await fetch(url)).arrayBuffer())); ``` ### Edit Put the input images before the prompt. Replace the example URL with an image that the provider can fetch. ```bash cURL theme={"system"} url=$(curl -s https://api.nunchux.com/v1/alibaba/services/aigc/multimodal-generation/generation \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "qwen-image-3.0-pro", "input": { "messages": [ { "role": "user", "content": [ {"image": "https://example.com/street.png"}, {"text": "make it night and add warm lantern light"} ] } ] }, "parameters": {"size": "1328*1328", "n": 1} }' | jq -r '.output.choices[0].message.content[0].image') curl -s -o output.png "$url" ``` ```python Python theme={"system"} import os import requests response = requests.post( "https://api.nunchux.com/v1/alibaba/services/aigc/multimodal-generation/generation", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "qwen-image-3.0-pro", "input": { "messages": [ { "role": "user", "content": [ {"image": "https://example.com/street.png"}, {"text": "make it night and add warm lantern light"}, ], } ] }, "parameters": {"size": "1328*1328", "n": 1}, }, ) url = response.json()["output"]["choices"][0]["message"]["content"][0]["image"] with open("output.png", "wb") as f: f.write(requests.get(url).content) ``` ## Tips * Set `size` explicitly. An omitted size renders at `2048*2048` and is billed at the `2K` tier. * Keep a size at or under 2,250,000 pixels when `1K` is enough. The common `1K` sizes above all qualify. * Leave `prompt_extend` on for short prompts. Turn it off when the prompt is already detailed, or when you need the exact words rendered. * On an edit, put the images first and the prompt last. When you send several images, say which element comes from which image. * Download each image on receipt. The URL expires after 24 hours. ## Errors and limits * `n` above 6 returns a 400 with the code `invalid_request`. So does a request with more than 3 input images. A refused request is not charged. * An error from Alibaba Cloud returns Alibaba Cloud's own body, with `code`, `message` and `request_id`, for example `InvalidParameter`. The charge is refunded in full. * Qwen Image is priced per output image at the rate of its size tier, plus a small fee per input image. The rates are on the [pricing page](https://nunchux.ai/pricing). Nunchux deducts the credits when it sends the request. When Alibaba Cloud returns fewer images than you asked for, Nunchux refunds the difference. See [Credits and pricing](/credits-pricing). * A Qwen Image call counts toward your requests per minute. It does not take a simultaneous-job slot. See [Rate limits](/rate-limits). The full error contract and the per-plan caps are on the [Errors](/errors) and [Rate limits](/rate-limits) pages. How every partner model bills and refunds is on the [Partner models overview](/partner-models/overview). # Seedance Source: https://docs.nunchux.ai/partner-models/seedance ByteDance's Seedance video model for text-to-video and image-to-video with generated audio. # Seedance Seedance is ByteDance's video model line. Each version generates a clip from a text prompt, from a starting image or from reference media, and can score the clip with generated audio. Generation is asynchronous. You submit a task, poll it until the status is terminal, then download the clip. The route mirrors ByteDance's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Prompt-driven scenes. A usable clip from a written description, with no shoot and no source footage. > * Animating a still. A first frame fixes the composition and the prompt drives the motion. > * Guiding a clip with references. Reference images, a video or audio steer the subject, motion or sound without fixing the first frame. > * Clips with sound. The model generates a track with the picture unless you turn it off. ## Models | Model | Model ID | Tasks | Resolution | Duration | | - | - | - | - | - | | Seedance 2.5 | `dreamina-seedance-2-5-260628` | t2v, i2v, reference-to-video | 480p, 720p | From 4 s | One model ID serves every task. The items in `content[]` select the task. A `text` item alone gives text-to-video. A `text` item plus a `first_frame` image item gives image-to-video. A `text` item plus one or more reference items gives reference-to-video. A request cannot mix first or last frame items with reference items; that request returns a 400. On image-to-video the output shape follows the first frame. Crop the image to the shape you want before you upload it. ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/bytedance/contents/generations/tasks` | | Poll | `GET /v1/bytedance/contents/generations/tasks/{task_id}` | The poll route is the submit route with the task ID appended. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. **model** `string` *required* The model ID: `dreamina-seedance-2-5-260628`. **content** `array` *required* The prompt, plus the first frame on image-to-video or the reference media on reference-to-video. Put the `text` item first. **item properties** **type** `string` *required* `text` for the prompt. `image_url` for an image. `video_url` for a video. `audio_url` for an audio clip. **text** `string` The prompt. Required on a `text` item. All tasks. Describe the subject, the action and the camera move. **role** `string` On a media item. What the item is for. Set `first_frame` on an `image_url` item for the image the clip starts on (image-to-video). Set `reference_image`, `reference_video` or `reference_audio` on an `image_url`, `video_url` or `audio_url` item to guide the clip without fixing its first frame (reference-to-video). **image_url** `object` On an `image_url` item. The image container. **properties** **url** `string` *required* The URL of the image. The provider fetches it, so the URL must be reachable from the internet. **video_url** `object` On a `video_url` item. The video container. **properties** **url** `string` *required* The URL of the video. It must be a web URL that the provider can fetch. A `data:` URI returns a 400. **audio_url** `object` On an `audio_url` item. The audio container. **properties** **url** `string` *required* The URL of the audio clip. The provider fetches it, so the URL must be reachable from the internet. The clip can be up to 30 seconds long. **duration** `integer` The clip length in seconds, as a whole number. All tasks. The minimum is 4. A longer clip uses more video tokens. **resolution** `string` (default: 720p) The output tier: `480p` or `720p`. All tasks. A larger frame uses more video tokens. **generate_audio** `boolean` (default: true) Send `false` for a silent clip. All tasks. The flag is a billing dimension: a clip with sound and a silent clip are priced differently. ## Response ### Submit A 200 status means that the provider accepted the task. It does not mean that the clip is ready. **id** `string` *required* The task ID. Treat it as an opaque string. Poll `GET /v1/bytedance/contents/generations/tasks/{task_id}` with it. ### Poll **status** `string` *required* `queued` or `running` while the task runs. `succeeded`, `failed`, `cancelled` or `expired` when it ends. Poll until you read one of the four terminal values. **content.video_url** `string` The URL of the clip. Present only when `status` is `succeeded`. The URL expires. Download the clip as soon as the task succeeds. **error** `object` The failure detail. Present when the task did not succeed. Read it before you resubmit. **duration** `integer` The clip length in seconds. **ratio** `string` The output aspect ratio, such as `16:9`. **usage.completion_tokens** `integer` The number of video tokens the clip used. Present when `status` is `succeeded`. Seedance is billed by this count, so the cost is known when the task completes. ## Example Submit, poll, download. The submit and the poll use the same path. The poll appends the task ID. ```bash cURL theme={"system"} BASE=https://api.nunchux.com TASKS=$BASE/v1/bytedance/contents/generations/tasks # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$TASKS" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "dreamina-seedance-2-5-260628", "content": [ { "type": "text", "text": "a fox trotting through a snowy forest at dawn" } ], "resolution": "720p", "generate_audio": false }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.id' <<<"$SUBMIT") || { echo "no id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$TASKS/$TASK" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.status // ""' <<<"$RESP") case "$STATUS" in succeeded|failed|cancelled|expired) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATUS" = "succeeded" ] || { echo "task $STATUS: $(jq -r '.error // "no error"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o seedance.mp4 "$(jq -r '.content.video_url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" TASKS = f"{BASE}/v1/bytedance/contents/generations/tasks" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( TASKS, headers=HEADERS, json={ "model": "dreamina-seedance-2-5-260628", "content": [ {"type": "text", "text": "a fox trotting through a snowy forest at dawn"} ], "resolution": "720p", "generate_audio": False, }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task = submit.json()["id"] # 2. Poll until the status is terminal delay = 5 for _ in range(90): data = requests.get(f"{TASKS}/{task}", headers=HEADERS).json() status = data.get("status", "") if status in ("succeeded", "failed", "cancelled", "expired"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("Seedance task did not reach a terminal status") # 3. Check for failure if status != "succeeded": raise RuntimeError(f"Seedance task {status}: {data.get('error')}") # 4. Download with requests.get(data["content"]["video_url"], stream=True, timeout=300) as r: r.raise_for_status() with open("seedance.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` To animate a still, append an item with `type` set to `image_url` and `role` set to `first_frame`, with the image URL under `image_url.url`. The body below replaces the submit body in the example. ```json Image-to-video theme={"system"} { "model": "dreamina-seedance-2-5-260628", "content": [ { "type": "text", "text": "the fox turns and trots toward the camera" }, { "type": "image_url", "role": "first_frame", "image_url": { "url": "https://example.com/frame.jpg" } } ], "resolution": "720p", "generate_audio": false } ``` To guide the clip with references instead, give each reference item a `reference_*` role. The body below uses a reference image and a reference audio clip. Do not add a `first_frame` item to a reference request. ```json Reference-to-video theme={"system"} { "model": "dreamina-seedance-2-5-260628", "content": [ { "type": "text", "text": "the fox from the reference image dances to the music" }, { "type": "image_url", "role": "reference_image", "image_url": { "url": "https://example.com/fox.jpg" } }, { "type": "audio_url", "role": "reference_audio", "audio_url": { "url": "https://example.com/music.mp3" } } ], "resolution": "720p", "duration": 5 } ``` ## Tips * Describe motion and camera, not just the scene. A static description gives the model nothing to animate. * Keep the prompt to one clear action. Busy, multi-event prompts are harder to render cleanly. * Draft at 480p to settle the wording, then re-run the same prompt at 720p. A smaller frame uses fewer video tokens. * Decide about audio before you run. The flag changes the price, so a silent draft is the cheaper way to test a prompt. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that the provider accepted the task. It does not mean that the task succeeded. A task that fails later ends with `status` set to `failed`, `cancelled` or `expired`, and `error` explains why. Read it before you resubmit. A failed submit returns an HTTP error status. See [Error codes](/errors). A 5xx status or a timeout on submit does not tell you whether the task was created. Never resubmit blindly. If the submit returned an `id`, poll it. If it returned nothing, check your credits before you try again. ByteDance applies these limits to each first or last frame image you attach: * 300 to 6,000 pixels on each side * An aspect ratio, width over height, between 0.4 and 2.5 * Under 30 MB per file ByteDance also applies these limits to the content of a request: * First or last frame items cannot be mixed with reference items. * A reference video must be a web URL. A `data:` URI returns a 400. * A reference audio clip can be up to 30 seconds long. * `duration` is 4 seconds or more. Seedance is billed by the number of video tokens the finished clip uses. The charge is known when the task completes, not before it starts. A longer or larger clip uses more tokens, and the audio flag changes the rate. Every task counts toward the simultaneous-jobs cap of your plan. See [Rate limits](/rate-limits), [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Topaz Image Enhance Source: https://docs.nunchux.ai/partner-models/topaz Upscale and enhance images with Topaz Labs Wonder 4, Wonder 3.5, Bloom 2 and Gigapixel High Fidelity 3 through one asynchronous endpoint. # Topaz Image Enhance Topaz Labs makes image models that upscale and enhance a photo or a generated image. You send one source image and the output size you want. Topaz returns the image at that size. One route serves all four models. The request is asynchronous. You submit a job, poll it until the status is terminal, then download the image. The route takes a JSON body. Topaz's own API takes a multipart form, so the field names here are ours where the two differ. > [!NOTE] > > Best for > > * Low-resolution and compressed photos. Wonder 4 and Wonder 3.5 remove noise, blur and compression artifacts while they upscale. > * Generated images. Bloom 2 adds new detail and texture to AI artwork, illustrations and renders. > * Camera originals. Gigapixel High Fidelity 3 enlarges high-quality photos and keeps their look. > * Large output. Each side can be up to 32,000 pixels. ## Models | Model | Model ID | Best on | Character | | - | - | - | - | | Wonder 4 | `topaz-wonder-4` | Any photo, from damaged scans to high resolution | All-in-one enhancement and upscaling. Corrects each region of the image on its own. | | Wonder 3.5 | `topaz-wonder-3.5` | Real-world photos, charts and documents | Generative upscaling with fine detail | | Bloom 2 | `topaz-bloom-2` | AI artwork, illustrations, CG renders | Creative upscaling. Adds new detail. | | Gigapixel High Fidelity 3 | `topaz-gigapixel-high-fidelity-3` | Professional and high-resolution photos | Precise upscaling. Keeps the original structure. | Each model runs with Topaz's default settings. Wonder 3.5 enhances at its high strength. Bloom 2 runs at creativity 3 with its automatic prompt and color preservation on. High Fidelity 3 recovers detail at its default strength. Model settings cannot be changed on this route yet. ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/topaz/image/enhance` | | Poll | `GET /v1/topaz/image/{process_id}` | ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. **model** `string` *required* The model ID: `topaz-wonder-4`, `topaz-wonder-3.5`, `topaz-bloom-2` or `topaz-gigapixel-high-fidelity-3`. **image** `string` *required* The source image. Either a public `https` URL, or a `data:` URI with base64 data of type `image/jpeg`, `image/png` or `image/tiff`. An `http` URL is rejected. **output_width** `integer` *required* The output width in pixels, 1 to 32,000. Required, together with `output_height`. The price follows the output canvas, so the route takes no scale factor and does not derive one side from the other. **output_height** `integer` *required* The output height in pixels, 1 to 32,000. Required, together with `output_width`. **output_format** `string` (default: jpeg) The format of the output image: `jpeg`, `png` or `tiff`. **crop_to_fill** `boolean` (default: false) When the output shape differs from the source shape, `true` crops the output to fill the canvas. `false` letterboxes it. ## Response ### Submit A 200 status means that Topaz accepted the job. It does not mean that the image is ready. **process_id** `string` *required* The job ID. Poll `GET /v1/topaz/image/{process_id}` with it. There is no `handle` field: `process_id` is the value to poll. It works for 7 days. ### Poll **status** `string` *required* `Processing` while the job runs. `Completed`, `Failed` or `Cancelled` when it ends. Poll until you read one of the three terminal values. **download_url** `string` The URL of the output image. Present only when `status` is `Completed`. The URL is time-limited. A later poll returns a fresh URL. **output_width** `integer` *required* The output width you requested. **output_height** `integer` *required* The output height you requested. **output_format** `string` *required* The file type of the output: `jpg`, `png` or `tif`. **credits** `integer` The Topaz credits that the job used. Present once the job is billed. **error** `object` Present when the job did not complete. `error.message` explains why. Read it before you resubmit. ## Example Submit, poll, download. The submit and the poll use different paths. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/topaz/image/enhance" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "topaz-wonder-4", "image": "https://example.com/photo.jpg", "output_width": 3840, "output_height": 2160, "output_format": "png" }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } JOB=$(jq -er '.process_id' <<<"$SUBMIT") || { echo "no process_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=3 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/topaz/image/$JOB" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.status // ""' <<<"$RESP") case "$STATUS" in Completed|Failed|Cancelled) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATUS" = "Completed" ] || { echo "job $STATUS: $(jq -r '.error.message // "no error"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o topaz.png "$(jq -r '.download_url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/topaz/image/enhance", headers=HEADERS, json={ "model": "topaz-wonder-4", "image": "https://example.com/photo.jpg", "output_width": 3840, "output_height": 2160, "output_format": "png", }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") job = submit.json()["process_id"] # 2. Poll until the status is terminal delay = 3 for _ in range(90): data = requests.get(f"{BASE}/v1/topaz/image/{job}", headers=HEADERS).json() status = data.get("status", "") if status in ("Completed", "Failed", "Cancelled"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("Topaz job did not reach a terminal status") # 3. Check for failure if status != "Completed": raise RuntimeError(f"Topaz job {status}: {data.get('error')}") # 4. Download with requests.get(data["download_url"], stream=True, timeout=300) as r: r.raise_for_status() with open("topaz.png", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` ## Tips * Keep the output shape equal to the source shape. A different shape is letterboxed, or cropped with `crop_to_fill`. * Pick the canvas you need, not the largest one. The price grows with the output megapixels. * Use Wonder 4 when you are unsure. Use Bloom 2 only on generated images, because it invents detail. Use High Fidelity 3 on sources that are already sharp. * Poll every 3 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that Topaz accepted the job. It does not mean that the job succeeded. A job that fails later ends with `status` set to `Failed` or `Cancelled`, and `error.message` explains why. Read it before you resubmit. A failed submit returns an HTTP error status. See [Error codes](/errors). These request shapes are rejected with 400 before any charge: | Code | Cause | | - | - | | `invalid_output_width`, `invalid_output_height` | A side is missing, is not an integer, or is outside 1 to 32,000. | | `invalid_image` | The image is missing, is an `http` URL, or is a `data:` URI that is not base64 JPEG, PNG or TIFF. | | `invalid_output_format` | The format is not `jpeg`, `png` or `tiff`. | | `webhook_url_not_supported` | The body carries `webhook_url`. Poll the job instead. | | `invalid_settings` | The body carries a `settings` map with a Topaz model setting, which Topaz names in camelCase. A snake_case name passes this check but has no effect. See [Models](#models). | Topaz can refuse an output size that its model does not support. Wonder 4 takes an output from 1 to 6 times the source size. The refusal comes back as a 4xx on submit with Topaz's own message, or as a `Failed` job. Neither is charged. A 5xx status or a timeout on submit does not tell you whether the job was created. Never resubmit blindly. If the submit returned a `process_id`, poll it. If it returned nothing, check your credits before you try again. Topaz bills in whole credits, by output megapixels. Each model turns a different number of megapixels into one credit, so the same canvas costs more on Bloom 2 than on High Fidelity 3. Nunchux holds the charge for your canvas at submit and settles it to the credits that Topaz reports when the job ends. A failed job is refunded. See the [pricing page](https://nunchux.ai/pricing) for the rates. Every submit counts toward the simultaneous-jobs cap of your plan for six minutes, however fast the job finishes. A job that ends sooner does not give its slot back early, so a burst of short jobs can return 429 `concurrent_limit_exceeded`. Wait and retry with backoff. Separately, at most five Topaz jobs per account can be in progress at once. A sixth returns 429 with the code `too_many_open_tasks`. A job stops counting toward the five when Nunchux settles it, which can be a few seconds after the poll first shows a terminal status, so a submit sent at once can still return 429. See [Rate limits](/rate-limits), [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Vidu Q4 Source: https://docs.nunchux.ai/partner-models/vidu Vidu Q4 preview for image-to-video and reference-to-video, with sound generated with the picture, through one asynchronous route family. # Vidu Q4 Vidu Q4 preview is Vidu's newest video model. It animates a still image, or it carries the subjects of up to 15 reference images into a new scene. It generates dialogue and sound effects with the picture, and it can switch camera angles within one clip. Each task has its own submit path. Generation is asynchronous. You submit a task, poll it until the state is terminal, then download the clip. The route mirrors Vidu's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Animating a still. The image becomes the first frame, and the prompt drives the motion. > * Consistent subjects. Up to 15 reference images keep characters and objects the same across the clip. > * Clips with sound. Speech and sound effects come out with the video in one request. > * Resolution range. From 540p drafts to 4K finals. ## Models | Model | Model ID | Tasks | Resolution | Duration | Images | | - | - | - | - | - | - | | Vidu Q4 preview | `viduq4-preview` | i2v, r2v | 540p, 720p, 1080p, 2K, 4K | 3 to 16 s | 1 (i2v), 1 to 15 (r2v) | Durations are whole seconds. Both tasks send `viduq4-preview` as the `model` value. Text-to-video is not offered on this model: a submit to `text2video` returns 400. | Task | Path | Images | Prompt | Aspect ratio | | - | - | - | - | - | | Image-to-video | `img2video` | Exactly 1 | Optional | Follows the image | | Reference-to-video | `reference2video` | 1 to 15 | Required | `16:9` (default), `9:16`, `1:1`, `4:3` or `3:4` | ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/vidu/video/{capability}` | | Poll | `GET /v1/vidu/video/{task_id}` | `{capability}` is `img2video` or `reference2video`. The poll path is the same for both. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. The route accepts only the fields below. A body with any other top-level field, such as Vidu's `sounds` or `callback_url`, returns 400 before any charge. **model** `string` *required* The model ID: `viduq4-preview`. **images** `string[]` *required* The images. On `img2video`, exactly one: the first frame. On `reference2video`, 1 to 15 reference images. Each item is a public `https` URL or a base64 `data:image/...` URI. Vidu takes PNG, JPEG, JPG and WEBP up to 50 MB each. The whole request body must stay under 20 MB, so pass large images by URL. **prompt** `string` The scene, up to 20,000 characters. Required on `reference2video`. Optional on `img2video`. **duration** `integer` (default: 5) The clip length in whole seconds, 3 to 16. You are billed per second of output. **resolution** `string` (default: 720p) The output tier: `540p`, `720p`, `1080p`, `2K` or `4K`. A higher tier costs more per second. **audio** `boolean` (default: true) Whether the clip carries generated sound: dialogue and sound effects. It defaults to on, and sound adds a surcharge to the task. Send `false` for a silent clip. **aspect_ratio** `string` (default: 16:9) The output shape on `reference2video`: `16:9`, `9:16`, `1:1`, `4:3` or `3:4`. On `img2video`, the clip follows the image. **is_rec** `boolean` On `img2video`, `true` lets Vidu write its own prompt and ignore yours. When you send a `prompt` and leave `is_rec` out, Nunchux sends `false`, so your prompt is used. **seed** `integer` (default: 0) The random seed. `0` picks a random seed. **payload** `string` Free text, up to 4,096 characters, that Vidu stores with the task and does not read. ## Response ### Submit A 200 status means that Vidu accepted the task. It does not mean that the clip is ready. **task_id** `string` *required* The task ID. Poll `GET /v1/vidu/video/{task_id}` with it. It works for 7 days. **state** `string` The task state when it was accepted, such as `created`. ### Poll **state** `string` *required* `processing` while the task runs. `success` or `failed` when it ends. Poll until you read one of the two terminal values. **creations\[].url** `string` The URL of the clip, in `creations[0].url`. Present only when `state` is `success`. The URL is time-limited. Download the clip as soon as the task succeeds. A later poll returns a fresh URL. **credits** `integer` The Vidu credits that the task used. Present once the task is billed. **error** `object` Present when `state` is `failed`. `error.message` explains why. Read it before you resubmit. The poll also echoes `model`, `capability`, `duration` and `resolution`. ## Example Submit, poll, download. The submit path names the task, and the poll path takes the task ID. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/vidu/video/img2video" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "viduq4-preview", "images": ["https://example.com/frame.jpg"], "prompt": "the astronaut waves and the camera rises", "duration": 5, "resolution": "720p", "audio": false }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.task_id' <<<"$SUBMIT") || { echo "no task_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the state is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/vidu/video/$TASK" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATE=$(jq -r '.state // ""' <<<"$RESP") case "$STATE" in success|failed) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATE" = "success" ] || { echo "task $STATE: $(jq -r '.error.message // "no error"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o vidu.mp4 "$(jq -r '.creations[0].url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/vidu/video/img2video", headers=HEADERS, json={ "model": "viduq4-preview", "images": ["https://example.com/frame.jpg"], "prompt": "the astronaut waves and the camera rises", "duration": 5, "resolution": "720p", "audio": False, }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task = submit.json()["task_id"] # 2. Poll until the state is terminal delay = 5 for _ in range(90): data = requests.get(f"{BASE}/v1/vidu/video/{task}", headers=HEADERS).json() state = data.get("state", "") if state in ("success", "failed"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("Vidu task did not reach a terminal state") # 3. Check for failure if state != "success": raise RuntimeError(f"Vidu task {state}: {data.get('error')}") # 4. Download with requests.get(data["creations"][0]["url"], stream=True, timeout=300) as r: r.raise_for_status() with open("vidu.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` To carry subjects into a new scene, submit to `/v1/vidu/video/reference2video` instead, with up to 15 images and a prompt. The body below replaces the submit body in the example. It leaves `audio` out, so the clip has sound and the surcharge applies. ```json Reference-to-video theme={"system"} { "model": "viduq4-preview", "images": [ "https://example.com/character.jpg", "https://example.com/product.jpg", "https://example.com/kitchen.jpg" ], "prompt": "In the kitchen from the third image, the character from the first image picks up the product from the second image and says, 'This one is my favorite.'", "duration": 5, "resolution": "720p", "aspect_ratio": "9:16" } ``` ## Tips * Send `audio: false` unless you want sound. Sound is on by default and costs extra on every task. * Draft at 540p or 720p. 2K and 4K cost several times more per second, so settle the prompt at a lower tier first. * Name each subject in the prompt by the image that shows it, and keep the reference images consistent in style. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that Vidu accepted the task. It does not mean that the task succeeded. A task that fails later ends with `state` set to `failed`, and `error.message` explains why. Read it before you resubmit. A failed submit returns an HTTP error status. See [Error codes](/errors). These request shapes are rejected with 400 before any charge: | Code | Cause | | - | - | | `not_priced` | The path is `text2video` or `start-end2video`. The model does not offer them. | | `invalid_duration` | The duration is not a whole number from 3 to 16. | | `invalid_resolution` | The resolution is not `540p`, `720p`, `1080p`, `2K` or `4K`. | | `invalid_images` | The image count does not fit the task, or an image is not an `https` URL or a base64 `data:image/...` URI. | | `invalid_prompt` | `reference2video` without a prompt. | | `invalid_request` | The body carries a field this route does not accept, such as `sounds`. | | `callback_url_not_supported` | The body carries `callback_url`. Poll the task instead. | | `off_peak_not_supported` | The body sets `off_peak` to `true`. | A 5xx status or a timeout on submit does not tell you whether the task was created. Never resubmit blindly. If the submit returned a `task_id`, poll it. If it returned nothing, check your credits before you try again. Vidu bills per second of output at the chosen resolution. Sound adds a fixed surcharge per task on both image-to-video and reference-to-video. Nunchux holds the charge at submit, with the surcharge unless you sent `audio: false`, and settles it to the credits that Vidu reports when the task ends. A failed task is refunded. See the [pricing page](https://nunchux.ai/pricing) for the rates. Every submit counts toward the simultaneous-jobs cap of your plan for six minutes, however fast the task finishes. A task that ends sooner does not give its slot back early, so a burst of short tasks can return 429 `concurrent_limit_exceeded`. Wait and retry with backoff. Separately, at most five Vidu tasks per account can be in progress at once. A sixth returns 429 with the code `too_many_open_tasks`. A task stops counting toward the five when Nunchux settles it, which can be a few seconds after the poll first shows a terminal status, so a submit sent at once can still return 429. See [Rate limits](/rate-limits), [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Wan Source: https://docs.nunchux.ai/partner-models/wan Alibaba Cloud's Wan video models for text-to-video, image-to-video, reference-to-video and video editing through one asynchronous endpoint. # Wan Wan is Alibaba Cloud's video model line. Each version generates a clip with a soundtrack from a text prompt, from a still image, or from a set of reference images, videos and audio. Wan 2.7 Video Edit restyles a clip you send. Generation is asynchronous. You submit a task, poll it until the status is terminal, then download the clip. The route mirrors Alibaba Cloud's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Longer takes. Wan 3.0 holds a shot for up to 30 seconds in one clip. > * Reference-driven scenes. Reference images, videos and audio carry a subject, a motion or a voice into new footage instead of animating one frame. > * Draft passes. Wan 3.0 and Wan 3.0 Prime sell a 480P tier that the earlier versions do not. > * Speed grades. Wan 3.0 Prime returns the same capabilities sooner than the standard grade. ## Models | Model | Model ID | Tasks | Resolution | Duration | Reference images | | - | - | - | - | - | - | | Wan 3.0 | `wan3.0-video` | t2v, i2v, r2v | 480P, 720P, 1080P | 2 to 30 s | Up to 10 | | Wan 3.0 Prime | `wan3.0-video-prime` | t2v, i2v, r2v | 480P, 720P, 1080P | 2 to 30 s | Up to 10 | | Wan 2.7 | `wan2.7-t2v`, `wan2.7-i2v`, `wan2.7-r2v` | t2v, i2v, r2v | 720P, 1080P | 2 to 15 s | Up to 5 | | Wan 2.7 Video Edit | `wan2.7-videoedit` | video edit | 720P, 1080P | 2 to 10 s | None | Durations are whole seconds. Wan 3.0 and Wan 3.0 Prime use one model ID for all three tasks. The items in `input.media[]` select the task. No media item gives text-to-video. A `first_frame` item gives image-to-video. `reference_image` items give reference-to-video. Wan 2.7 uses one model ID per task. Wan 3.0 gives the longest clips and the widest reference set. Use it when a shot has to develop, or when a subject must carry across a new scene. It takes an optional end frame on image-to-video. Wan 3.0 Prime is the accelerated grade of Wan 3.0. Alibaba Cloud describes it as the high-speed version with capabilities aligned to the standard version. It has the same tasks, tiers, lengths and reference ceiling as Wan 3.0. Use it while you iterate. Wan 2.7 has a shorter ceiling and a smaller reference set. On image-to-video it takes an optional end frame and a driving audio track. Wan 2.7 Video Edit takes one source clip of 2 to 10 seconds and a prompt that says how to change it. Reference videos and the edit source clip are billed by their length as well as the output. See [Billing for video inputs](#billing-for-video-inputs). ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/alibaba/services/aigc/video-generation/video-synthesis` | | Poll | `GET /v1/alibaba/tasks/{task_id}` | [HappyHorse](/partner-models/happyhorse) uses the same two routes and the same body shape. ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. **model** `string` *required* The model ID from the table above. On Wan 3.0 and Wan 3.0 Prime the same ID serves every task. **input** `object` *required* The prompt and the media items. **properties** **prompt** `string` *required* The text prompt. All tasks. Describe what moves and how the camera follows it. On reference-to-video, name a reference by its kind and position in `media[]`: `Image 1`, `Image 2`, `Video 1`, `Audio 1` and so on, with a space and a capital letter. **media** `array` The media items for image-to-video, reference-to-video and video editing. Omit it for text-to-video. A first frame and a reference set cannot appear in the same body. **item properties** **type** `string` *required* What the item is. * `first_frame`: the image the clip starts on. Image-to-video. One item. * `last_frame`: the image the clip ends on. Image-to-video, optional. One item. * `driving_audio`: a WAV or MP3 track for the clip. Wan 2.7 image-to-video only, optional. * `reference_image`: a reference image. Reference-to-video. 1 to 10 items on Wan 3.0 and Wan 3.0 Prime, 1 to 5 items on Wan 2.7. * `reference_video`: a reference clip. Reference-to-video on Wan 3.0, Wan 3.0 Prime and Wan 2.7. Its seconds are billed. See [Billing for video inputs](#billing-for-video-inputs). * `reference_audio`: a reference voice or sound. Reference-to-video on Wan 3.0 and Wan 3.0 Prime. Up to 5 items and 15 seconds in total. Not billed as input. * `video`: the clip to edit. Wan 2.7 Video Edit only, required. One item of 2 to 10 seconds. Its seconds are billed. **url** `string` *required* The URL of the file. The provider fetches it, so the URL must be reachable from the internet. **parameters** `object` The generation controls. All tasks read all three fields. **properties** **resolution** `string` (default: 1080P) The output tier. `480P`, `720P` or `1080P` on Wan 3.0 and Wan 3.0 Prime. `720P` or `1080P` on Wan 2.7. The default is the most expensive tier, so name the one you want. **duration** `integer` (default: 5) The clip length in whole seconds. 2 to 30 on Wan 3.0 and Wan 3.0 Prime. 2 to 15 on Wan 2.7. On Wan 2.7 Video Edit it cuts the source clip to this length, 2 to 10. Omit it to keep the whole clip. You are billed per second of output, plus the input seconds of a reference video or an edit source. **watermark** `boolean` (default: false) Send `true` to burn the vendor's mark into the lower-right corner of every frame. ## Response ### Submit A 200 status means that the provider accepted the task. It does not mean that the clip is ready. **output** `object` *required* **properties** **task_id** `string` *required* The task ID. Poll `GET /v1/alibaba/tasks/{task_id}` with it. **task_status** `string` *required* `PENDING` on a new task. ### Poll **output.task_status** `string` *required* `PENDING` or `RUNNING` while the task runs. `SUCCEEDED`, `FAILED` or `CANCELED` when it ends. Poll until you read one of the three terminal values. **output.video_url** `string` The URL of the clip. Present only when `task_status` is `SUCCEEDED`. The task ID and the URL expire after 24 hours. Download the clip as soon as the task succeeds. **output.code** `string` The failure code. Present when the task failed. **output.message** `string` The failure message. Read it before you resubmit. ## Example Submit, poll, download. Swap the `model` value for the version you want. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/alibaba/services/aigc/video-generation/video-synthesis" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "wan3.0-video", "input": { "prompt": "a fox trotting through a snowy forest at dawn" }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } TASK=$(jq -er '.output.task_id' <<<"$SUBMIT") || { echo "no task_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/alibaba/tasks/$TASK" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.output.task_status // ""' <<<"$RESP") case "$STATUS" in SUCCEEDED|FAILED|CANCELED) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure [ "$STATUS" = "SUCCEEDED" ] || { echo "task $STATUS: $(jq -r '.output.message // "no message"' <<<"$RESP")" >&2; exit 1; } # 4. Download curl -sSL -o wan.mp4 "$(jq -r '.output.video_url' <<<"$RESP")" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/alibaba/services/aigc/video-generation/video-synthesis", headers=HEADERS, json={ "model": "wan3.0-video", "input": {"prompt": "a fox trotting through a snowy forest at dawn"}, "parameters": {"resolution": "720P", "duration": 5, "watermark": False}, }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") task = submit.json()["output"]["task_id"] # 2. Poll until the status is terminal delay = 5 for _ in range(90): data = requests.get(f"{BASE}/v1/alibaba/tasks/{task}", headers=HEADERS).json() status = data.get("output", {}).get("task_status", "") if status in ("SUCCEEDED", "FAILED", "CANCELED"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("Wan task did not reach a terminal status") # 3. Check for failure if status != "SUCCEEDED": raise RuntimeError(f"Wan task {status}: {data['output'].get('message')}") # 4. Download with requests.get(data["output"]["video_url"], stream=True, timeout=300) as r: r.raise_for_status() with open("wan.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` To animate a still, add a `first_frame` item to `input.media[]`. To carry a subject into a new scene, add `reference_image` items instead. A first frame and a reference set are separate tasks. The bodies below replace the submit body in the example. ```json Image-to-video theme={"system"} { "model": "wan3.0-video", "input": { "prompt": "the fox turns and trots toward the camera", "media": [ { "type": "first_frame", "url": "https://example.com/frame.jpg" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ```json Reference-to-video theme={"system"} { "model": "wan3.0-video", "input": { "prompt": "the person from Image 1 walks through the doorway from Image 2, slow tracking shot", "media": [ { "type": "reference_image", "url": "https://example.com/ref-1.jpg" }, { "type": "reference_image", "url": "https://example.com/ref-2.jpg" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ```json Reference video theme={"system"} { "model": "wan3.0-video", "input": { "prompt": "Video 1 dances through a sunlit park, handheld camera", "media": [ { "type": "reference_video", "url": "https://example.com/dance.mp4" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ```json Video edit theme={"system"} { "model": "wan2.7-videoedit", "input": { "prompt": "make the scene look like a watercolor painting", "media": [ { "type": "video", "url": "https://example.com/source.mp4" } ] }, "parameters": { "resolution": "720P", "duration": 5, "watermark": false } } ``` ## Billing for video inputs Wan 3.0, Wan 3.0 Prime, Wan 2.7 reference-to-video and Wan 2.7 Video Edit bill the seconds of video you send as well as the seconds they generate. Both are billed at the per-second rate of the output tier you pick: ```text theme={"system"} charge = (output seconds + billed input seconds) x per-second rate ``` How many input seconds are billed depends on the model: | Model | Billed input seconds | Most per request | | - | - | - | | Wan 3.0, Wan 3.0 Prime | The total length of the reference videos | 15 s, and input plus output can't exceed 30 s | | Wan 2.7 reference-to-video | The reference videos, shared out over a cap | 5 s, however many clips you send | | Wan 2.7 Video Edit | The source clip, up to `duration` | 10 s | Reference images and reference audio are not billed as input. A request without a video input is billed for its output only. For example, a 5-second Wan 3.0 clip at 720P with an 8-second reference video bills 13 seconds: 5 output plus 8 input, at the 720P rate. When you submit, your balance must cover the most the request can cost, which counts the input at the per-request maximum. The charge then settles to the seconds the provider reports, and the poll response shows them in `usage.input_video_duration` and `usage.output_video_duration`. On these models, [`GET /pricing`](/credits-pricing) marks the rows with `input_video_billed: true` and `max_billable_input_video_seconds`. ## Tips * Say what moves and how the camera follows it. The prompt drives both, and motion is what the model has to generate. * Name the sounds you want in the prompt when audio matters. The model scores what it reads. * Send `resolution` and `duration` on every request. The defaults are 1080P and 5 seconds, and 1080P is the most expensive tier. * Draft at 480P on Wan 3.0, then re-run the prompt at the tier and length you need. You are billed per second of output, so a long 1080P draft is the expensive way to test wording. * Match the model to the job. A first frame fixes the composition. A reference set fixes the subject and lets the scene change. * Upload the frame at the tier you intend to render. A small source limits what the model can resolve. * Trim a reference video to the part you need before you send it. Its seconds are billed at the output rate. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that the provider accepted the task. It does not mean that the task succeeded. A task that fails later ends with `task_status` set to `FAILED` or `CANCELED`, and `output.message` explains why. Read the message before you resubmit. A failed submit returns an HTTP error status. The body carries `code`, `message` and `request_id`. See [Error codes](/errors). A 5xx status or a timeout on submit does not tell you whether the task was created. Never resubmit blindly. If the submit returned a `task_id`, poll it. If it returned nothing, check your credits before you try again. Alibaba Cloud applies these limits to each reference image: * 240 to 8,000 pixels on each side * An aspect ratio no wider than 8:1 * JPEG, JPG, PNG, BMP or WEBP. A transparent channel is not supported. * Up to 20 MB per file On Wan 3.0 and Wan 3.0 Prime, a reference video plus the output can't exceed 30 seconds, so a request with a reference video and `duration` 30 returns 400. Every task counts toward the simultaneous-jobs cap of your plan. See [Rate limits](/rate-limits). Rates are per second of output, plus the input seconds of a video input, and depend on the tier. See [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Grok Imagine Video Source: https://docs.nunchux.ai/partner-models/xai xAI's Grok Imagine Video 1.5 and 1.5 Lite for text-to-video, image-to-video and reference-to-video, with sound, through one asynchronous endpoint. # Grok Imagine Video Grok Imagine Video is xAI's video model family. It generates a clip from a prompt, animates a still image, or carries people, objects and voices from references into a new scene. Clips carry a soundtrack with lip-synced speech by default. One route serves every task, and the inputs you send decide which task you get. Generation is asynchronous. You submit a request, poll it until the status is terminal, then download the clip. The route mirrors xAI's own API, so the request and response shapes are the provider's. > [!NOTE] > > Best for > > * Native 1080p. Grok Imagine Video 1.5 renders 1080p text-to-video and image-to-video. > * Low cost per second. Grok Imagine Video 1.5 Lite is the cheapest way to draft a clip. > * Characters that speak. Reference-to-video on 1.5 takes up to 14 reference images and up to 3 preset voices. > * Storyboards. On 1.5, pin the first frame, the last frame and up to 4 frames in between. ## Models | Model | Model ID | Tasks | Resolution | Duration | Reference inputs | | - | - | - | - | - | - | | Grok Imagine Video 1.5 | `grok-imagine-video-1.5` | t2v, i2v, r2v | 480p, 720p, 1080p | 1 to 15 s | Up to 14 images and 3 preset voices | | Grok Imagine Video 1.5 Lite | `grok-imagine-video-1.5-lite` | t2v, i2v | 480p, 720p, 1080p | 1 to 15 s | None | Durations are whole seconds. Lite reaches 1080p by upscaling a 720p render. The fields you send select the task: | Task | Send | Resolution | Models | | - | - | - | - | | Text-to-video | `prompt` alone | 480p, 720p, 1080p | Both | | Image-to-video | `image`, with an optional `prompt` | 480p, 720p, 1080p | Both | | Reference-to-video | `reference_images`, `reference_audios`, or both | 480p, 720p | 1.5 only | | Pinned frames | `last_frame` or `keyframes`, with an optional `image` | 480p, 720p | 1.5 only | On 1.5, `image` combined with references or pins becomes the pinned first frame. ## Endpoints | Step | Route | | - | - | | Submit | `POST /v1/xai/videos/generations` | | Poll | `GET /v1/xai/videos/{request_id}` | ## Request Send your API key in the `X-API-Key` header. See [Authentication](/authentication). Set `Content-Type: application/json`. The examples also send a `User-Agent` header that names your application. The route accepts only the fields below. A body with any other top-level field, such as xAI's `output`, `storage_options` or `user`, returns 400 before any charge. **model** `string` *required* The model ID: `grok-imagine-video-1.5` or `grok-imagine-video-1.5-lite`. **prompt** `string` The scene, up to 20,000 characters. Required on text-to-video. Optional when the body carries an image, a reference or a pinned frame. On reference-to-video, name the references by position: ``, `` and so on for images, `` to `` for voices. When `image` is also set, it takes `` and the reference images start at ``. **duration** `integer` (default: 8) The clip length in whole seconds, 1 to 15. You are billed per second of output. **resolution** `string` (default: 480p) The output tier: `480p`, `720p` or `1080p`. A body with references, `last_frame` or `keyframes` takes `480p` or `720p` only. A higher tier costs more per second. The tier names the frame height only roughly: a 16:9 clip at `1080p` comes out 1920x1088. **aspect_ratio** `string` (default: 16:9) The output shape: `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9` or `5:2`. Image-to-video ignores it and follows the image. **generate_audio** `boolean` (default: true) Whether the clip carries a soundtrack. Send `false` for a silent clip. The price per second is the same either way. **image** `object` The image to animate, or on 1.5 the pinned first frame. Holds `url`: a public `https` URL or a base64 `data:image/...` URI. xAI's `file_id` is rejected. **reference_images** `object[]` Grok Imagine Video 1.5 only. 1 to 14 images that guide the subject, clothing or set without fixing the first frame. Each item holds `url`, as on `image`. **reference_audios** `object[]` Grok Imagine Video 1.5 only. 1 to 3 preset voices. Each item is `{"voice_id": ""}`, such as `eve`. Voice IDs are case-insensitive, and an unknown one returns 400 with the list of voices. Your own audio files are not accepted: an item with `url` returns 400. **last_frame** `object` Grok Imagine Video 1.5 only. The image the clip ends on. Holds `url`, as on `image`. **keyframes** `object[]` Grok Imagine Video 1.5 only. 1 to 4 frames the clip passes through. Each item holds `image` (an object with `url`) and `timestamp_s`, a time in seconds strictly greater than 0 and less than `duration`. xAI snaps the times to a one-third-second grid, so keep two keyframes at least 1/3 s apart. ## Response ### Submit A 200 status means that xAI accepted the request. It does not mean that the clip is ready. **request_id** `string` *required* The request ID. Poll `GET /v1/xai/videos/{request_id}` with it. It works for 7 days. ### Poll **status** `string` *required* `pending` while the clip renders. `done` or `failed` when it ends. Poll until you read one of the two terminal values. **video.url** `string` The URL of the clip. Present when `status` is `done`. The URL is time-limited. Download the clip as soon as the request is done. A later poll returns a fresh URL. It is `null` when xAI's moderation filtered the clip. **video.duration** `number` The length of the clip in seconds, as billed. **video.respect_moderation** `boolean` `false` when xAI's moderation filtered the clip. The request is then `done`, billed, and has no URL. **error** `object` Present when `status` is `failed`. `error.message` explains why. Read it before you resubmit. ## Example Submit, poll, download. The submit and the poll use different paths. ```bash cURL theme={"system"} BASE=https://api.nunchux.com # 1. Submit SUBMIT=$(curl -sS --fail-with-body "$BASE/v1/xai/videos/generations" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "Content-Type: application/json" \ -H "User-Agent: YourApp/1.0" \ -d '{ "model": "grok-imagine-video-1.5", "prompt": "a paper boat drifting down a rain-soaked street at night", "duration": 8, "resolution": "720p", "aspect_ratio": "16:9" }') || { echo "submit failed: $SUBMIT" >&2; exit 1; } REQ=$(jq -er '.request_id' <<<"$SUBMIT") || { echo "no request_id in: $SUBMIT" >&2; exit 1; } # 2. Poll until the status is terminal DELAY=5 for _ in $(seq 1 90); do RESP=$(curl -sS "$BASE/v1/xai/videos/$REQ" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -H "User-Agent: YourApp/1.0") STATUS=$(jq -r '.status // ""' <<<"$RESP") case "$STATUS" in done|failed) break ;; esac sleep "$DELAY"; DELAY=$(( DELAY * 2 > 30 ? 30 : DELAY * 2 )) done # 3. Check for failure and moderation [ "$STATUS" = "done" ] || { echo "request $STATUS: $(jq -r '.error.message // "no error"' <<<"$RESP")" >&2; exit 1; } URL=$(jq -r '.video.url // empty' <<<"$RESP") [ -n "$URL" ] || { echo "filtered by moderation" >&2; exit 1; } # 4. Download curl -sSL -o grok.mp4 "$URL" ``` ```python Python theme={"system"} # pip install requests import os, time, requests BASE = "https://api.nunchux.com" HEADERS = { "X-API-Key": os.environ["NUNCHUX_API_KEY"], "User-Agent": "YourApp/1.0", } # 1. Submit submit = requests.post( f"{BASE}/v1/xai/videos/generations", headers=HEADERS, json={ "model": "grok-imagine-video-1.5", "prompt": "a paper boat drifting down a rain-soaked street at night", "duration": 8, "resolution": "720p", "aspect_ratio": "16:9", }, ) if not submit.ok: raise RuntimeError(f"submit failed: HTTP {submit.status_code} {submit.text}") req = submit.json()["request_id"] # 2. Poll until the status is terminal delay = 5 for _ in range(90): data = requests.get(f"{BASE}/v1/xai/videos/{req}", headers=HEADERS).json() status = data.get("status", "") if status in ("done", "failed"): break time.sleep(delay) delay = min(delay * 2, 30) else: raise TimeoutError("xAI request did not reach a terminal status") # 3. Check for failure and moderation if status != "done": raise RuntimeError(f"xAI request {status}: {data.get('error')}") url = data["video"]["url"] if not url: raise RuntimeError("filtered by moderation") # 4. Download with requests.get(url, stream=True, timeout=300) as r: r.raise_for_status() with open("grok.mp4", "wb") as f: for chunk in r.iter_content(1 << 14): f.write(chunk) ``` The bodies below replace the submit body in the example. Image-to-video works on both models. Reference-to-video and pinned frames need Grok Imagine Video 1.5 and run at 720p or below. ```json Image-to-video theme={"system"} { "model": "grok-imagine-video-1.5-lite", "prompt": "the camera slowly pushes in as the clouds drift past", "image": { "url": "https://example.com/frame.jpg" }, "duration": 6, "resolution": "720p", "generate_audio": false } ``` ```json Reference-to-video theme={"system"} { "model": "grok-imagine-video-1.5", "prompt": "The person from holds up the product from and says, in the voice of , 'Launch day is here.'", "reference_images": [ { "url": "https://example.com/person.jpg" }, { "url": "https://example.com/product.jpg" } ], "reference_audios": [{ "voice_id": "eve" }], "duration": 8, "resolution": "720p", "aspect_ratio": "9:16" } ``` ```json Pinned frames theme={"system"} { "model": "grok-imagine-video-1.5", "prompt": "the camera dollies from the doorway to the window", "image": { "url": "https://example.com/first.jpg" }, "keyframes": [ { "image": { "url": "https://example.com/middle.jpg" }, "timestamp_s": 3 } ], "last_frame": { "url": "https://example.com/last.jpg" }, "duration": 6, "resolution": "720p" } ``` ## Tips * Draft on Grok Imagine Video 1.5 Lite at 480p. It costs a fraction of 1.5 per second. Move to 1.5 or 1080p once the prompt works. * Keep the cast small on reference-to-video. Give each reference one role and a fixed place in the scene. * Check `video.url` before you download. A clip filtered by moderation ends as `done` with no URL. * Poll every 5 seconds at first, then back off to 30 seconds. Polls are free and never use a concurrency slot. ## Errors and limits A 200 status on submit means that xAI accepted the request. It does not mean that the clip succeeded. A request that fails later ends with `status` set to `failed`, and `error.message` explains why. Read it before you resubmit. A clip that xAI's moderation filters ends with `status` set to `done`, `video.url` set to `null` and `video.respect_moderation` set to `false`. It is billed. A failed submit returns an HTTP error status. See [Error codes](/errors). These request shapes are rejected with 400 before any charge: | Code | Cause | | - | - | | `invalid_duration` | The duration is not a whole number from 1 to 15. | | `invalid_resolution` | The resolution is not offered, or is `1080p` on a body with references, `last_frame` or `keyframes`. | | `invalid_prompt` | A text-to-video body without a prompt. | | `unsupported_input` | Lite with `reference_images`, `reference_audios`, `last_frame` or `keyframes`. | | `invalid_image` | An image is not an object with an `https` URL or a base64 `data:image/...` URI. | | `file_id_not_supported` | An image names a `file_id` instead of a `url`. | | `reference_audio_url_not_supported` | A voice reference carries `url` instead of `voice_id`. | | `invalid_keyframes` | More than 4 keyframes, or a `timestamp_s` outside the clip. | | `invalid_request` | The body carries a field this route does not accept. | A 5xx status or a timeout on submit does not tell you whether the request was created. Never resubmit blindly. If the submit returned a `request_id`, poll it. If it returned nothing, check your credits before you try again. xAI bills per second of output at the chosen resolution, plus a fee for each input image: `image`, `last_frame`, each keyframe and each reference image. Preset voices are free. Nunchux holds the charge at submit and settles the seconds to the length xAI reports when the clip is done. The image fee stays. A failed request is refunded. See the [pricing page](https://nunchux.ai/pricing) for the rates. Every submit counts toward the simultaneous-jobs cap of your plan for six minutes, however fast the request finishes. A request that ends sooner does not give its slot back early, so a burst of short requests can return 429 `concurrent_limit_exceeded`. Wait and retry with backoff. Separately, at most five Grok Imagine requests per account can be in progress at once. A sixth returns 429 with the code `too_many_open_tasks`. A request stops counting toward the five when Nunchux settles it, which can be a few seconds after the poll first shows a terminal status, so a submit sent at once can still return 429. See [Rate limits](/rate-limits), [Credits & pricing](/credits-pricing) and the [Partner models overview](/partner-models/overview). # Performance Tiers Source: https://docs.nunchux.ai/performance-tiers Balance speed and cost with the performance tiers of the Nunchux Image API. # Performance Tiers ### Balance speed and cost with performance tiers ## Available Tiers ### Nunchux Optimized models The Radical Speed tier delivers the lowest latency, while Radical Value gives the lowest cost per image. Both tiers run on Nunchux's proprietary Model Optimizer and Inference Engine. Together they give the best tradeoff between speed, cost, and quality on the market. These tiers apply to the FLUX, Qwen, HiDream O1, Z-Image Turbo, Krea 2 Turbo and MiniMax H3 Fast models. FLUX.1 dev, FLUX.2 dev, Qwen Image and Qwen Image Edit have Radical Speed only. FLUX.2 dev Flash has Radical Value only. Ideogram 4 has three other tiers: Turbo, Balanced and Quality. The `extra.rendering_speed` field selects the tier, and the price is per image. The LTX video models have two other tiers, 720p and 1080p. The output size selects the tier, and the price is per second of video. ### Partner models Partner models do not use the Nunchux tiers. Each one prices on its own terms, such as output size, resolution, or mode. See the [pricing page](https://nunchux.ai/pricing) for current per-model rates. ## Tier Comparison | Tier | Speed | Cost | Quality | Use Case | | - | - | - | - | - | | `radical_speed` | Fastest | Low | High | Real-time apps, previews | | `radical_value` | Fast | Lowest | High | High-volume batch, cost-sensitive jobs | > [!TIP] > > What tier should I choose? > > Use Radical Speed if the response time is important. Use Radical Value if cost per image is more important across large batches. ## Send a Tier in a Request Set the `tier` field in your API request: ```bash theme={"system"} curl -X POST https://api.nunchux.com/v1/images/generations \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "nunchux-qwen-image-2512-lightning", "tier": "radical_speed", "prompt": "a beautiful mountain landscape", "width": 1024, "height": 1024 }' ``` ## Tier and Model Combinations Each tier and model combination has a different use. The Qwen model with the Radical Speed tier gives the lowest latency. Use this combination for real-time previews and interactive applications. ```bash theme={"system"} # Fastest generation: Qwen Image 2512 Lightning + radical_speed curl -X POST https://api.nunchux.com/v1/images/generations \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "nunchux-qwen-image-2512-lightning", "tier": "radical_speed", "prompt": "real-time preview render", "width": 1024, "height": 1024 }' ``` A small model such as Klein 4B with the Radical Value tier gives the lowest cost per image. Use this combination for high-volume batch jobs. ```bash theme={"system"} # Lowest cost: Klein 4B + radical_value curl -X POST https://api.nunchux.com/v1/images/generations \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "nunchux-flux.2-klein-4b", "tier": "radical_value", "prompt": "high-volume batch icon design", "width": 1024, "height": 1024 }' ``` > [!NOTE] > > Workflow Recommendations > > * For development and test, use Radical Speed. It has the lowest latency. > * For high-volume batch jobs, use Radical Value. It has the lowest cost per image. > * For production, use Radical Speed if latency is important. Use Radical Value if cost per image is more important. ## Error Handling If you send a tier that a model does not support, the API returns an error. ```json theme={"system"} { "detail": "unknown tier 'turbo'; allowed values: radical_speed, radical_value" } ``` Check the model's page to make sure that it supports the tier you send. See the [Error Handling](/errors) guide for more information. # Redeem a promo code Source: https://docs.nunchux.ai/promo-codes Add free credits to a team's balance with a promo code. # Redeem a promo code ### Add free credits to a team's balance with a promo code. A promo code adds free credits to the balance of one team. You redeem it in the dashboard. There is no API endpoint for it. ## Who can redeem a code The credits go to the team that is active in the dashboard when you redeem the code. You must be an admin of that team. You are always the admin of your own team, listed as "Your team" in the account switcher. On a team where you are a member, ask one of its admins to redeem the code. Members have no Billing & Invoices page. See [Teams](/teams) for what each role can do. ## Redeem a code **1. Pick the team** In the dashboard sidebar, open the account switcher under the logo and select the team that should get the credits. **2. Open Add Credits** Go to [Billing & Invoices](https://nunchux.ai/dashboard/admin/billing) and select Top Up on the Credits card. The Add Credits window opens. **3. Enter the code** Type the code under "Have a promo code?" and select Redeem. The line under the field names the team that gets the credits. Letter case does not matter. When the code works, the field clears and shows how many credits were added and the team's new balance. ## Where the credits show up * The team's balance on the Credits card and in the dashboard's top bar. * A row in the Invoices table on Billing & Invoices, with the description "Promo code credit". * `credits_remaining` from [`GET /v1/credits`](/credits-pricing#checking-your-balance), for every API key billed to the team. Promo credits join the team's balance, and they are spent like credits you paid for. The code itself has an expiry date, after which no one can redeem it. Redeeming a code does not change the team's plan. ## Limits * A team can redeem each code once. If two admins of one team redeem the same code, only the first redemption adds credits. * You can redeem each code once, for one team. You cannot redeem the same code into your own team and into another team. * Different codes add up. A team can redeem several codes. * Each code has its own number of redemptions. Once they are used up, the code stops working. * Tries are limited per person, wrong codes included. After too many, the Redeem button stays disabled for up to a minute. ## Errors When a code does not work, nothing is added, and the code stays in the field so you can fix a typo. The field shows one of these messages. | Message | Meaning | | - | - | | We couldn't find that code. Check it for typos. | No code matches what you typed. | | This code has expired. | The code is past its expiry date. | | This code is no longer available. | The code's redemptions are used up, or the code was switched off. | | \[Team] has already redeemed this code. Each organization can use a code once. | Someone already redeemed this code into the active team. | | You've already redeemed this code for another organization. Each person can use a code once. | You redeemed this code into a different team. | | Too many tries. Try again in \[N] seconds. | You hit the limit on tries. Wait, then try again. | | Only org admins can add credits or change the card. | You are a member of the active team, not an admin. Ask an admin to redeem the code. | | You switched accounts in another tab. Reload this page and try again. | The active team changed after the page loaded. Reload it, and check which team the field names before you redeem. | | We couldn't redeem the code right now. Please try again. | A temporary problem on our side. Nothing was added. Try again. | # QuickStart Source: https://docs.nunchux.ai/quickstart Get started generating images and videos with the Nunchux API in minutes. # Quickstart ### Generate your first image in under 5 minutes. ## 1. Create your API key Before you begin, [sign up](https://nunchux.ai/sign-up) for an account to get an API key. Once you've registered, create an API key from your [dashboard](https://nunchux.ai/dashboard) and set it as an environment variable. ```bash Export an environment variable theme={"system"} export NUNCHUX_API_KEY=xxxxx ``` ## 2. Make your first request Generate your first image with a simple API request and save your result. ```bash cURL theme={"system"} # Replace $NUNCHUX_API_KEY with your API key. # Change output.jpg to the filename you want. curl -X POST https://api.nunchux.com/v1/images/generations \ -H "Content-Type: application/json" \ -H "X-API-Key: $NUNCHUX_API_KEY" \ -d '{ "model": "nunchux-flux.2-klein-4b", "prompt": "A beautiful sunset over mountains", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json" }' | jq -r '.data[0].b64_json // error(.error.message // .detail // tostring)' | base64 -d > output.jpg ``` ```python Python theme={"system"} import base64 import os import requests response = requests.post( "https://api.nunchux.com/v1/images/generations", headers={ "Content-Type": "application/json", "X-API-Key": os.environ["NUNCHUX_API_KEY"], }, json={ "model": "nunchux-flux.2-klein-4b", "prompt": "A beautiful sunset over mountains", "tier": "radical_speed", "width": 1024, "height": 1024, "response_format": "b64_json", }, ) # Decode the base64 image and save it. Change output.jpg to any filename. image_b64 = response.json()["data"][0]["b64_json"] with open("output.jpg", "wb") as f: f.write(base64.b64decode(image_b64)) ``` ```javascript JavaScript theme={"system"} import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.nunchux.com/v1/images/generations", { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": process.env.NUNCHUX_API_KEY, }, body: JSON.stringify({ model: "nunchux-flux.2-klein-4b", prompt: "A beautiful sunset over mountains", tier: "radical_speed", width: 1024, height: 1024, response_format: "b64_json", }), }); const data = await response.json(); // Decode the base64 image and save it. Change output.jpg to any filename. await writeFile("output.jpg", Buffer.from(data.data[0].b64_json, "base64")); ``` Congratulations – you've just made your first call to Nunchux! From here: * [Nunchux Optimized models](/nunchux-optimized/overview): the models in this example, and the video models. * [Partner models](/partner-models/overview): third-party image and video models. * [Performance Tiers](/performance-tiers): what the tier field does, and when to change it. * [Text-to-Image reference](/nunchux-optimized/text-to-image): all parameters and response formats. * [Image-to-Image reference](/nunchux-optimized/image-to-image): edit an input image with a prompt. * [Video](/partner-models/overview): the async submit, poll and download flow that every partner video model uses. # Rate Limits Source: https://docs.nunchux.ai/rate-limits Per-plan caps on requests per minute and simultaneous jobs, which requests count toward each, and how to back off from a 429. # Rate Limits ### Understand and manage how many requests you can run simultaneously on Nunchux ## Plan Limits Every API key bills an account, and the account is on a plan. The plan sets two independent caps: requests per minute, and simultaneous jobs. The caps belong to the account, so every key billed to the same account shares them. On a team, that account is the team. | Plan | Requests per Minute | Simultaneous Jobs | | - | - | - | | Free | 60 | 5 | | Pro | 200 | 10 | | Enterprise | 600 | 20 | An Enterprise account can also have its own caps, which replace the plan caps above. To change your caps, contact us. `GET /v1/credits` always returns the caps that apply to your account. ## Checking Your Caps Read your caps at any time from `GET /v1/credits`, which takes no parameters and returns the account the key bills. On a team key, that is the team. It uses the same API key for [authentication](/authentication) as every other endpoint. ```bash curl theme={"system"} curl https://api.nunchux.com/v1/credits \ -H "X-API-Key: $NUNCHUX_API_KEY" ``` ```python python theme={"system"} import os import requests response = requests.get( 'https://api.nunchux.com/v1/credits', headers={'X-API-Key': os.environ['NUNCHUX_API_KEY']}, timeout=30, ) response.raise_for_status() print(response.json()) ``` A `200` carries the caps that apply to your plan: `rpm_limit` is your requests per minute and `concurrent_limit` is your simultaneous jobs. The same response carries your balance. See [Checking Your Balance](/credits-pricing#checking-your-balance) for every field. The API returns [standard error codes](/errors) with a JSON error body. > [!NOTE] > > Polling > > This poll is free and it never takes a job slot. It still counts toward your requests per minute. ## What Counts Every authenticated request counts toward requests per minute, polls included. Only requests that start a generation take a job slot, and how long they hold it depends on the kind of request. | Request | Requests per Minute | Job slot | | - | - | - | | Async submit: Kling, Seedance, HeyGen | Counts | Takes a slot. A rejected submit does not. | | Synchronous generation: `/v1/images/*`, `/v1/videos/*` | Counts | Holds a slot for the duration of the request. | | Nano Banana: `/v1/google/v1beta/interactions` | Counts | No slot. The call is synchronous and returns in seconds. | | Status polls | Counts | No slot. | | Account reads: `GET /v1/credits`, `GET /v1/discounts`, `GET /v1/heygen/v3/voices` | Counts | No slot. | ## When You Hit a Limit The API returns a `429` for both caps. The error code says which cap you hit. ### Requests per Minute ```json theme={"system"} { "error": { "code": "rpm_limit_exceeded", "message": "Rate limit exceeded. See the rate-limit response headers for your limit and reset time." } } ``` > [!NOTE] > > What to do > > Wait, then retry with exponential backoff: 1s, 2s, 4s, 8s. Cap at five attempts. Spreading submits evenly over the minute avoids it altogether. ### Simultaneous Jobs ```json theme={"system"} { "error": { "code": "concurrent_limit_exceeded", "message": "Concurrent job limit reached. Wait for a running job to finish, then retry." } } ``` > [!NOTE] > > What to do > > Retrying quickly will not help. Wait, poll your running jobs, and submit again once one has completed. The full error contract is on the [Errors](/errors) page. # Teams Source: https://docs.nunchux.ai/teams Create a team, invite members, and switch between teams. # Teams ### Share one balance and one bill with the people you work with. ## How teams work Every Nunchux account is a team. When you sign up, you get your own team, listed as "Your team" in the account switcher. It holds your credits, and you are its admin. A team you create is a separate account. It has its own credit balance, billing, API keys, plan, and [rate limits](/rate-limits). Nothing moves between your own team and a team you create. The dashboard calls a team an organization in some places, such as the ORGANIZATION section of the sidebar and the Organization Settings page. ## Create a team **1. Open the account switcher** In the dashboard sidebar, select the account name under the logo. **2. Select Create team** Give the team a name, then create it. The new team becomes the active team, and the dashboard opens its Organization Settings page. You are its admin. A new team starts with no credits. Before anyone uses it, [add credits](https://nunchux.ai/dashboard/admin/billing) or [redeem a promo code](/promo-codes). ## Invite members **1. Open Members** With the team active, select Members under ORGANIZATION in the sidebar, or go to [Members](https://nunchux.ai/dashboard/admin/members). **2. Send the invite** Select the invite button, enter the person's email address, choose a role, and select Send invite. The person gets an email invitation. Once they accept it, the team appears in their account switcher. Until then, the invitation is listed on the Members page, where an admin can revoke it. ## Roles A team has two roles: Admin and Member. An admin can change a member's role on the Members page. | Action | Admin | Member | | - | - | - | | Use the team in the playground | Yes | Yes | | Create API keys billed to the team | Yes | Yes | | Manage API keys | Every key on the team | Only the keys they created | | Add credits, redeem promo codes, and manage the card and auto top-up | Yes | No | | Invite and remove members, and change roles | Yes | No | | See Members, Member Usage, Billing & Invoices, Team Analytics, and Organization Settings | Yes | No | | Receive billing emails, such as low-balance alerts | Yes | No | Only the person who created a key can rotate it, even on a team where an admin manages every key. ## Switch teams Open the account switcher in the sidebar and select a team. A check marks the active team. The dashboard, the playground, and the keys you create from then on use that team. ## Who pays for usage * A request from the playground or the dashboard bills the active team. * An API key bills the team that was active when the key was created. It keeps billing that team, whoever sends the request and whichever team is active later. The key creation window names the team the key bills. * `GET /v1/credits` with a team's key returns that team's balance and caps. Every key billed to a team shares the team's [rate limits](/rate-limits). Switching teams does not move a key or its usage. To bill a different team, switch to it and create a new key there. ## Remove a member or delete a team An admin removes a member from the Members page. Removing a member revokes every API key they created on the team. A member cannot leave a team on their own; ask an admin to remove you. An admin deletes a team from Organization Settings. Deleting a team cannot be undone: * Any remaining balance is forfeited. It does not move to another team. * Every API key billed to the team stops working. * Every member loses access.