Welcome to the Ainfra MaaS API. This guide helps you connect to the service and start using it quickly.
Introduction
Ainfra MaaS is a unified access platform for AI models. It provides a standardised, OpenAI-compatible interface and supports a wide range of mainstream large language models.
Key features
OpenAI API compatible — switch models without changing your code
Supports mainstream models including DeepSeek, Qwen, GLM and Kimi
Smart routing and load balancing that automatically pick the best channel
Flexible, pay-as-you-go billing
Need help?
If you run into any problem while integrating, contact our team and we will get back to you as quickly as possible.
Authentication
The Ainfra MaaS API authenticates requests with an API key. Include your key in the request headers.
Ainfra MaaS connects to the AI model providers below. Every provider is served through the same OpenAI-compatible interface, so you can switch between models without changing your code.
International
Mistral AI
Mistral Large, Mistral Medium and more
China-based providers
DeepSeek · Recommended
DeepSeek-V3, DeepSeek-R1 and more
Alibaba Tongyi Qianwen (Qwen)
Qwen-Max, Qwen-Plus and more
Alibaba Cloud Bailian
Models on the Alibaba Cloud Bailian platform
Baidu Wenxin Qianfan
ERNIE-Bot family (WebSocket version)
Baidu Wenxin Qianfan V2
ERNIE-Bot family (HTTP V2 version)
iFlytek Spark
SparkDesk family (WebSocket version)
iFlytek Spark V2
SparkDesk family (HTTP version)
Zhipu ChatGLM
GLM-4, GLM-4V and more
Tencent Hunyuan
Hunyuan family
Moonshot AI
moonshot-v1 long-context family
ByteDance Volcano Engine
Doubao model family
Baichuan
Baichuan2-Turbo family
MiniMax
abab model family
360 Zhinao
360GPT family
01.AI
Yi model family
StepFun
Step model family
Open platforms and others
OpenAI-compatible · Recommended
Any OpenAI-format API with a custom base URL
Groq
Ultra-fast inference for Llama and other open-source models
Ollama
Locally deployed open-source model service
SiliconFlow
A range of open-source models
together.ai
Open-source model inference platform
Novita
A range of AI model APIs
Cohere
Command model family
Coze
ByteDance's AI bot platform
Cloudflare Workers AI
AI inference at the Cloudflare edge
DeepL
DeepL translation service
Replicate
Open-source model hosting platform
OpenRouter
Multi-model routing proxy
Proxy
General-purpose proxy channel
Integration notes
One interface format: every provider is called through the OpenAI-compatible /v1/chat/completions endpoint; change the model parameter to switch models.
OpenAI-compatible channel: providers not listed separately can be connected through the "OpenAI-compatible" channel type, with a custom base URL, as long as their API follows the OpenAI format.
Local models: the Ollama channel type connects locally deployed open-source models, so inference can run without data leaving your premises.
Integration examples
Every provider uses the same OpenAI-compatible interface; change the model parameter to switch to a model from a different provider.
Python SDK examples
After installing the official SDK with pip install openai, call each provider's models as follows:
Anthropic Messages format
Models marked Anthropic in the Model Square can also be called with the official Anthropic SDK.
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'sk-xxx', // your Ainfra MaaS API key
baseURL: 'https://modelapi.taikuntech.com/v1',
});
// Works with any connected model
const models = ['deepseek/deepseek-v4-pro', 'qwen/qwen3.8-max', 'z-ai/glm-5.2', 'tk/kimi-k3'];
for (const model of models) {
const response = await client.chat.completions.create({
model,
messages: [{ role: 'user', content: 'Hello' }],
});
console.log(`[${model}] ${response.choices[0].message.content}`);
}
Third-party apps
Any third-party app that supports the OpenAI API works — just configure the API base URL and API key:
Setting
Value
API base URL
https://modelapi.taikuntech.com/v1
API key
Your API key (starts with sk-)
Model
Any supported model name
Common app settings
NextChat: set the endpoint to https://modelapi.taikuntech.com and enter your API key.
LobeChat: in the language-model settings choose the OpenAI-compatible provider, then enter your API key and the endpoint https://modelapi.taikuntech.com/v1.
Cherry Studio: choose the OpenAI-compatible provider type, set the API address to https://modelapi.taikuntech.com and enter your API key.
OpenCat: set the API address to https://modelapi.taikuntech.com and enter your API key.
POST/v1/chat/completions
Chat completions
Creates a chat completion, with streaming or non-streaming responses. OpenAI API compatible, and the most widely used chat interface.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. deepseek/deepseek-v4-pro, qwen/qwen3.8-max, z-ai/glm-5.2
messages
array
Required
List of conversation messages, in chronological order
temperature
number
Optional
Sampling temperature, 0–2, default 1. Lower is more deterministic, higher is more random
max_tokens
integer
Optional
Maximum tokens to generate. Recommended, to control cost and response time
stream
boolean
Optional
Stream the output, default false. When on, incremental data is returned via SSE
top_p
number
Optional
Nucleus sampling, 0–1, default 1. Tune either this or temperature
presence_penalty
number
Optional
Presence penalty, −2 to 2, default 0. Positive values encourage new topics
frequency_penalty
number
Optional
Frequency penalty, −2 to 2, default 0. Positive values reduce repetition
stop
string/array
Optional
Stop sequences; generation stops when the model produces one
n
integer
Optional
Number of replies to generate, default 1
messages structure
Each message has a role and a content field.
JSON
[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hello! How can I help you?"},
{"role": "user", "content": "Please introduce yourself"}
]
Role
Purpose
system
Sets the AI's behaviour and persona
user
Messages or instructions sent by the user
assistant
The AI's earlier replies, used for multi-turn conversations
Response fields
JSON structure of a successful (200) response.
Field
Type
Description
id
string
Unique request ID, format chatcmpl-xxx
object
string
Object type, always chat.completion
model
string
Model actually used
choices
array
List of replies, each with message and finish_reason
What is the difference between streaming and non-streaming requests?
A non-streaming request waits for the model to generate the full response and returns it in one go — good for short outputs. A streaming request (stream=true) returns incremental content in real time over SSE — good for long outputs, and it markedly reduces time to first token.
How do I handle multi-turn conversations?
Pass the conversation history (both user and assistant messages) in order in the messages array; the model replies based on the full context. Keep the context length under control to avoid exceeding the token limit.
What should temperature and top_p be set to?
Adjust one or the other. For deterministic output (such as code generation) set temperature=0; for creative output use 0.7–1.0. top_p is usually fine at 0.9; avoid large changes to both at once.
What does finish_reason = length mean?
The output hit the max_tokens limit and was truncated. Increase max_tokens, or check whether a long prompt is taking up most of the context window.
Why is the model actually used different from the one I requested?
If the requested model is unavailable, the platform may automatically route to an available model in the same family. Check the model field in the response to confirm which model was used.
Best practices
Retries
For 429/500 errors, retry with exponential backoff: wait 1 second the first time, double it each time, up to 60 seconds, with at most 5 retries.
Streaming
For long outputs use stream=true; it significantly improves time to first token (TTFT) and the perceived experience.
Security
Use API keys only on the server side, never in front-end code or client apps. Manage keys through environment variables.
Token control
Set max_tokens sensibly to avoid runaway output and cost, and keep the total length of messages within the model's context limit.
System prompt
Use a system message to define the AI's behaviour and output format; it noticeably improves output quality and consistency.
Model choice
Use lightweight models such as Qwen 3.8 Flash or GLM 5.3 Flash for simple tasks to cut cost; choose stronger models such as DeepSeek-V4-Pro or Qwen3.8-Max for complex reasoning.
POST/v1/messages
Messages (Anthropic format)
Ainfra MaaS natively supports the Anthropic Messages API format and works with the official Anthropic SDK. Models that support it are marked Anthropic under API formats in the Model Square, including DeepSeek-V4-Pro, GLM 5.x, Kimi K3 and Qwen 3.8 Flash.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. z-ai/glm-5.2, deepseek/deepseek-v4-pro
messages
array
Required
List of conversation messages; content may be text or image
max_tokens
integer
Required
Maximum tokens to generate. The Messages format requires this parameter
system
string/array
Optional
System prompt defining the AI's behaviour. Multiple system blocks are supported
temperature
number
Optional
Sampling temperature, 0–1, default 1. Lower is more deterministic
top_p
number
Optional
Nucleus sampling, 0–1. Tune either this or temperature
top_k
integer
Optional
Keep only the K most likely tokens; unlimited by default
stream
boolean
Optional
Stream the output; incremental content is returned via SSE
stop_sequences
array
Optional
Custom stop sequences; generation stops when the model produces one
tools
array
Optional
Tool definitions, enabling tool_use
metadata
object
Optional
Custom metadata, such as user_id for request tracking
Response fields
JSON structure of a successful (200) response.
Field
Type
Description
id
string
Unique message ID, format msg_xxx
type
string
Object type, always message
role
string
Always assistant
model
string
Model actually used
content
array
Reply content; each item has a type (text/tool_use) and its content
content[].type
string
Content type: text or tool_use (tool call)
content[].text
string
Text generated by the AI (when type=text)
stop_reason
string
Why generation stopped: end_turn (normal), max_tokens (hit the limit), stop_sequence (hit a stop sequence), tool_use (requested a tool call)
stop_sequence
string
The stop sequence that was hit (when stop_reason=stop_sequence)
usage.input_tokens
integer
Input tokens
usage.output_tokens
integer
Output tokens
Request examples
Call this endpoint from different languages and SDKs.
The upstream model service is temporarily unavailable
The request payload is too large or timed out
If it persists, contact technical support
FAQ
Should I use the OpenAI-compatible interface or the Anthropic-format interface?
If your code is built on the Anthropic SDK or relies on Messages-format features such as tool_use content blocks, use /v1/messages. If your project is already built on the OpenAI SDK, you can use /v1/chat/completions to keep the code consistent.
Why is max_tokens required?
It is a design requirement of the Messages format, unlike the OpenAI format. Omitting it returns a 400 error. Set a reasonable upper limit for your use case.
How do I pass a system prompt?
In the Messages format, system is a top-level parameter, not part of the messages array. This differs from the OpenAI API, where the system message sits inside messages, so take care to keep them apart.
What should I do when stop_reason is max_tokens?
The output hit the max_tokens limit and was truncated. Increase max_tokens, or tighten the prompt to use fewer input tokens.
Which models support this endpoint?
Models with Anthropic listed under API formats in the Model Square, such as DeepSeek-V4-Pro, Z-AI/GLM 5.2 and 5.3, TK-Kimi K3 and K3.1 Pro, and Qwen 3.8 Flash.
Best practices
Layered system prompts
The Messages format supports multiple system content blocks. Write the persona, format requirements and rules as separate blocks for easier maintenance.
Tool use design
When using tool_use, give each tool a clear name, description and input_schema so the model can pick the right tool more accurately.
Retries
For 429/500 errors, retry with exponential backoff: wait 1 second the first time, double it each time, up to 60 seconds, with at most 5 retries. Check the Retry-After response header.
Streaming
For long outputs, stream mode significantly reduces time to first token (TTFT). The Anthropic SDK's convenient stream method is recommended.
Security
Use API keys only on the server side. The Messages format authenticates with the x-api-key header; never expose it in front-end code.
Multimodal input
Models with image input accept base64-encoded images directly in content, with no separate endpoint. Keep images under 5 MB; JPEG, PNG, GIF and WebP are supported.
POST/v1/completions
Text completions
The classic text-completion interface: given a prompt, the model continues the text. Compatible with the OpenAI Completions API format; suited to code completion, text continuation and similar tasks.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. deepseek/deepseek-v4-pro
prompt
string/array
Required
Prompt text. A single string or an array of strings (several completions sharing context)
max_tokens
integer
Optional
Maximum tokens to generate, default 16. Recommended, to control output length
temperature
number
Optional
Sampling temperature, 0–2, default 1. Lower is more deterministic, higher is more random
top_p
number
Optional
Nucleus sampling, 0–1, default 1. Tune either this or temperature
n
integer
Optional
Number of completions to generate, default 1. Returned together
stream
boolean
Optional
Stream the output, default false. When on, incremental data is returned via SSE
stop
string/array
Optional
Stop sequences; generation stops immediately when the model produces one
presence_penalty
number
Optional
Presence penalty, −2 to 2, default 0. Positive values encourage new topics
frequency_penalty
number
Optional
Frequency penalty, −2 to 2, default 0. Positive values reduce repetition
suffix
string
Optional
Text inserted after the completion. Commonly used for code insertion
echo
boolean
Optional
Include the original prompt in the result, default false
best_of
integer
Optional
Generate best_of results and return the best n. best_of must be greater than n
logprobs
integer
Optional
Return probability information for the logprobs most likely tokens
Response fields
JSON structure of a successful (200) response.
Field
Type
Description
id
string
Unique request ID, format cmpl-xxx
object
string
Object type, always text_completion
model
string
Model actually used
choices
array
List of completions, each with text, index, finish_reason and more
choices[].text
string
Completion text generated by the model
choices[].index
integer
Index of the completion (from 0)
choices[].logprobs
object
Token probability information (requires the logprobs parameter)
The upstream model service is temporarily unavailable
The request payload is too large
If it persists, contact technical support
FAQ
What is the difference between Completions and Chat Completions?
Completions is the classic text-completion interface (prompt in, text out), suited to one-way generation such as code completion and continuation. Chat Completions uses the messages format (multi-role conversation) and is better for dialogue, Q&A and other multi-turn interaction. New projects should prefer Chat Completions.
How do I control the length of the completion?
Limit output length with max_tokens, and combine it with stop sequences (such as '\n\n') so the model stops at a line break.
How do I generate several completions at once?
Set n greater than 1; the choices array in the response will contain several completions. You can also use best_of to have the model generate more candidates and pick the best.
What does finish_reason = length mean?
The output hit the max_tokens limit and was truncated. Increase max_tokens, or shorten the prompt to leave more room for generation.
Which models support the Completions endpoint?
Support varies by model. Most models on the platform are chat models, so Chat Completions is recommended; check a model's API formats in the Model Square.
Best practices
Code completion
Use the suffix parameter for code insertion (fill-in-the-middle): pass the code before the cursor as prompt and the code after it as suffix, and the model generates the code in between.
Low temperature
For deterministic tasks such as code generation, set temperature to 0 or close to it for stable, consistent output.
Using n
When you want several completions, set n=3 and choose the best candidate. Useful for creative work or when you need options.
Prompt design
End the prompt with a clear lead-in (such as a function signature or comment) to help the model understand the context and improve completion quality.
Token control
Set max_tokens sensibly to avoid over-generation. 50–200 tokens is usually enough for code completion; use larger values for long-form text as needed.
Stop sequences
Set sensible stop sequences (such as '\n\n' or '###') so the model stops naturally at the right place instead of rambling on.
POST/v1/responses
Responses API
The Responses API (OpenAI format) is a new-generation conversation interface with more flexible interaction patterns, including built-in tool calling, structured output and web search. It offers a simpler calling experience than Chat Completions.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. tk/kimi-k3, qwen/qwen3.7-plus
input
string/array
Required
User input. A plain text string or an array of messages with multimodal content
instructions
string
Optional
System-level instructions defining the AI's behaviour and output
temperature
number
Optional
Sampling temperature, 0–2, default 1. Lower is more deterministic
max_output_tokens
integer
Optional
Maximum output tokens. Recommended, to control cost
stream
boolean
Optional
Stream the output, default false. When on, an event stream is returned via SSE
top_p
number
Optional
Nucleus sampling, 0–1, default 1. Tune either this or temperature
tools
array
Optional
Available tools: function, web_search_preview, file_search and more
tool_choice
string/object
Optional
Tool-call strategy: auto (default), none, required, or a specific tool
parallel_tool_calls
boolean
Optional
Allow several tools to be called in parallel, default true
text
object
Optional
Text output format; set a json_schema for structured output
previous_response_id
string
Optional
ID of the previous response, for multi-turn context
truncation
string
Optional
Truncation strategy: auto (default) or disabled
Response fields
JSON structure of a successful (200) response.
Field
Type
Description
id
string
Unique response ID, format resp_xxx
object
string
Object type, always response
model
string
Model actually used
output
array
Output items, each with a type field (message, function_call, etc.)
output_text
string
Convenience field returning the text output directly (only when the output type is message)
output[].type
string
Output type: message (text), function_call (tool call), etc.
status
string
Response status: completed, in_progress or failed
usage.input_tokens
integer
Input tokens
usage.output_tokens
integer
Output tokens
usage.total_tokens
integer
Total tokens
Request examples
Call this endpoint from different languages and tools.
{
"id": "resp_xxx",
"object": "response",
"created_at": 1700000000,
"status": "completed",
"model": "tk/kimi-k3",
"output": [
{
"type": "message",
"id": "msg_xxx",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Artificial intelligence (AI) is the science of simulating and extending human intelligence, spanning machine learning, natural language processing and many other fields. It is already widely used in healthcare, finance and everyday life, markedly improving productivity and decision quality. With breakthroughs in deep learning and large models, AI is evolving from an assistive tool into a core driver of social progress."
}
]
}
],
"output_text": "Artificial intelligence (AI) is the science of simulating and extending human intelligence...",
"usage": {
"input_tokens": 15,
"output_tokens": 80,
"total_tokens": 95
}
}
What is the difference between the Responses API and the Chat Completions API?
The Responses API is the newer OpenAI-format interface. It uses input instead of messages and has built-in tool calling and structured output, with no need to handle the tool_calls loop yourself. Chat Completions is more mature and stable with broader ecosystem compatibility. New projects can consider the Responses API first.
How do I get structured output?
Set a json_schema in the text.format parameter and the model will output results that strictly follow the JSON Schema you define. Useful for extracting structured data, such as information extraction and form filling.
How do I use tool calling (function calling)?
Define functions in the tools parameter. The Responses API handles the tool-call loop automatically, without the manual multi-turn management Chat Completions needs. Use tool_choice to control the calling strategy.
How do I keep multi-turn context?
Pass the previous response's id as previous_response_id and the model maintains the conversation context automatically. This is simpler than manually rebuilding the messages history as in Chat Completions.
Which models support the Responses API?
Models with Responses listed under API formats in the Model Square, such as TK-Kimi K3, Qwen3.7-Plus, TK-DeepSeek-V4-Pro and V4-Flash, TK-GLM 5.2 and Z-AI/GLM 5.3.
Best practices
Structured output
When you need structured data, specify a JSON Schema with text.format instead of complex prompt engineering and regex post-processing.
Context management
Use previous_response_id for clean multi-turn conversations; there is no need to manage message history by hand, and the API handles the context window.
Tool-call strategy
Use tool_choice: 'auto' for simple cases and let the model decide; use 'required' to force a call in deterministic cases; set 'none' when no tools are needed to save reasoning time.
Instructions design
Use the instructions parameter to define the AI's behaviour; it supports multiple paragraphs, formatting and personas. Include output-format requirements, behavioural boundaries and domain knowledge.
Streaming
For long responses, use stream=true to show content in real time. The Responses API has richer streaming events (response.created, output_text.delta, response.completed) for precise control of UI state.
Error handling
Handle tool_use failures. When a tool call fails, check that the tools definition and parameter schema are correct, and make sure error branches have a fallback.
POST/v1/images/generations
Wan image generation
Generates high-quality images from text descriptions with Alibaba Cloud's Tongyi Wan models. Supports wan2.7-image-pro, wan2.7-image, wan2.6-t2i and others. Returns image URLs proxied by the platform that can be accessed directly.
Model overview
Supported models and pricing.
Model
Description
Price
wan2.7-image-pro
Wan 2.7 high-quality text-to-image
$0.084 per image
wan2.7-image
Wan 2.7 standard text-to-image
$0.028 per image
wan2.6-t2i
Wan 2.6 text-to-image
$0.028 per image
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. wan2.7-image, wan2.7-image-pro, wan2.6-t2i
prompt
string
Required
Image description, in Chinese or English. More detail gives better results
size
string
Optional
Image size as widthheight, e.g. 10241024, 1280720, 7201280. Default 1024*1024
n
integer
Optional
Number of images, default 1. Each image is billed separately
curl -X POST \
https://modelapi.taikuntech.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "wan2.7-image",
"prompt": "A flower shop with elegant windows and a beautiful wooden door, with flowers on display",
"size": "1280*1280",
"n": 1
}'
Python
from openai import OpenAI
client = OpenAI(
api_key="sk-xxx",
base_url="https://modelapi.taikuntech.com/v1"
)
resp = client.images.generate(
model="wan2.7-image",
prompt="Snow-capped mountains at sunset reflected in a lake, long-exposure photography",
size="1280*720",
n=1
)
print(resp.data[0].url)
wan2.7-image-pro: $0.084 per image · wan2.7-image: $0.028 per image · wan2.6-t2i: $0.028 per image
FAQ
Do image URLs expire?
Returned URLs are proxied by the platform and stay valid for about 24 hours. Download and copy images to your own storage within that time.
What format does the size parameter use?
Width and height separated by an asterisk, e.g. 1280720. 10241024 (square), 720*1280 (portrait) and others are also supported.
What is the difference between wan2.7-image and wan2.7-image-pro?
The pro version produces higher quality with richer detail, for use cases with higher image-quality requirements. The standard version is faster and cheaper.
Best practices
Prompt tips
Describe the image as subject + scene + style + details. Adding lighting, viewpoint and colour tone noticeably improves quality. Chinese and English both work.
Copy images promptly
Returned image URLs have a limited lifetime; download and copy them to your own CDN or object storage before they expire.
Model choice
Choose wan2.7-image-pro when image quality matters most and wan2.7-image for value; both are called in exactly the same way.
Content compliance
Avoid sensitive terms in prompts. If a request is refused under the content policy, the model returns an error.
POST/v1/videos/generations
Video generation
Creates an asynchronous video-generation task, in text-to-video or image-to-video mode. Tasks are processed asynchronously; poll for the result with the task_id.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. bytedance/doubao-seedance-2-0-260128
prompt
string
Required
Video description. Describe the scene, action, viewpoint and lighting in detail. Best kept under about 100 words
async
boolean
Required
Asynchronous mode; must be true. Video generation takes a while, so only asynchronous processing is supported
duration
integer
Optional
Video length in seconds, 5–10, default 5. Longer videos take longer to generate
image
string
Optional
Reference image URL (image-to-video mode). When provided, the model uses the image as the base frame for the video
Request examples
Text-to-video · set duration · image-to-video.
cURL
curl --location --request POST \
'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "A kitten yawns at the camera as lazy afternoon sunlight fills the room",
"async": true
}'
cURL
curl --location --request POST \
'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "Waves crash against rocks with spray flying, aerial view, at sunset",
"duration": 10,
"async": true
}'
cURL
curl --location --request POST \
'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "The scene in the image slowly comes to life as the camera pushes in",
"image": "https://example.com/your-image.jpg",
"async": true
}'
A complete implementation of asynchronous task polling.
Python
import requests
import time
API_KEY = "sk-xxxxxx"
BASE_URL = "https://modelapi.taikuntech.com"# 1. Create a video-generation task
def create_video_task(prompt, duration=5, image=None):
url = f"{BASE_URL}/v1/videos/generations"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": prompt,
"duration": duration,
"async": True
}
if image:
payload["image"] = image
response = requests.post(url, json=payload, headers=headers)
return response.json()
# 2. Query the task status
def get_task_result(task_id):
url = f"{BASE_URL}/v1/videos/{task_id}"
headers = {"Authorization": f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
# 3. Poll until complete
def wait_for_completion(task_id, max_wait=300, interval=5):
elapsed = 0
while elapsed < max_wait:
result = get_task_result(task_id)
status = result.get("task_status")
if status == "succeed":
return result
elif status == "failed":
raise Exception(f"Task failed: {result.get('error')}")
time.sleep(interval)
elapsed += interval
raise Exception("Timed out waiting")
# Usage
if __name__ == "__main__":
task = create_video_task("A kitten running across a sunny meadow")
print(f"Task created: {task['task_id']}")
result = wait_for_completion(task['task_id'])
print(f"Video ready: {result['video_url']}")
Technical limits
Item
Limit
Video length
5–10 seconds
Resolution
1080p (1920×1080)
Frame rate
30 fps
Output format
MP4 (H.264)
Concurrency
Up to 3 tasks processing at once per user
Generation time
Usually 30–120 seconds; complex scenes may take longer
Billing
Pricing unit
Billed by video length at about $0.014 per second.
When you are charged
Quota is deducted only when a task completes successfully; failed tasks are not charged.
Best practices
Polling strategy
Poll every 5 seconds and wait at most 5 minutes. Use exponential backoff: 3 seconds first, then ×1.5 each time, capped at 15 seconds. A webhook callback avoids polling entirely.
Prompt engineering
Describe the video as subject + action + scene + viewpoint + lighting. Use concrete verbs (running, spinning, drifting down) rather than static descriptions, and add a sense of time (gradually, slowly, suddenly) to make the video feel natural.
Copy videos promptly
video_url is valid for about 1 hour. Download the video as soon as the task completes and copy it to your own CDN or object storage. Health-check URLs and retry automatically.
Error handling
Separate recoverable errors (network timeouts) from unrecoverable ones (content violations). Retry network errors with exponential backoff (at most 3 times); return parameter errors straight to the user.
FAQ
What is the difference between text-to-video and image-to-video?
Text-to-video generates a video from a text description alone — good for creative ideas and proofs of concept. Image-to-video takes a still reference image and uses it as the base frame — good for bringing photos to life or extending existing clips. Image-to-video gives higher consistency but needs a suitable base image.
Why asynchronous mode?
Video generation is compute-heavy and usually takes 30–120 seconds. Waiting synchronously holds the HTTP connection open for a long time and easily times out. In asynchronous mode the request returns a task_id immediately, and you can check progress at any time without blocking the client.
How many tasks can I submit at once?
Each user can have at most 3 tasks in pending or processing at the same time. Requests over the limit are queued or rejected. Use a task queue to manage large volumes and stay within the concurrency limit.
Can tasks time out?
The maximum processing time is 5 minutes (300 seconds). Tasks that time out are marked failed and are not charged. Set a sensible max_wait (such as 300 seconds) and show the user a friendly message after a timeout.
Can generated videos be used commercially?
Yes. Videos generated through Ainfra MaaS belong to you and can be used commercially. Note that you must hold the rights to any input images, and generated content must comply with applicable laws and the platform's content policy.
Common error codes
400Bad Request
JSON
{
"error": {
"message": "async must be true",
"type": "invalid_request_error",
"code": "async_required"
}
}
Based on ByteDance's Doubao Seedance 2.0 models, with three modes: text-to-video, image-to-video and asset reference (qasset://). Tasks are processed asynchronously; poll for the result with the task_id.
Overview
What the Seedance 2.0 models can do.
Item
Detail
Model vendor
ByteDance · Volcano Engine
Endpoint
POST /v1/videos/generations
Supported modes
Text-to-video, image-to-video, and asset-reference video (qasset://)
Calling method
Asynchronous only (async: true). Submitting a task returns a task_id; poll GET /v1/videos/{task_id} for the result
Asset reference
Reference virtual-avatar or real-person portrait assets with a qasset:// URI — see the /v1/asset-groups docs
Models
Available Seedance 2.0 models.
Model
Edition
Description
bytedance/doubao-seedance-2-0-260128
Standard
Full Seedance 2.0 standard model; 480p/720p/1080p; text-to-video, image-to-video and asset reference
bytedance/doubao-seedance-2-0-fast-260128
Fast
Seedance 2.0 Fast; faster generation; 480p/720p only
When calling the video-generation endpoint (/v1/videos/generations) and the asset-management endpoints (/v1/asset-groups, /v1/assets), always use the full model name in the model parameter (e.g. bytedance/doubao-seedance-2-0-260128).
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Full model name, e.g. bytedance/doubao-seedance-2-0-260128 or bytedance/doubao-seedance-2-0-fast-260128
prompt
string
Required
Video description. Structure it as subject + action + scene + viewpoint + lighting; best kept under about 100 words
async
boolean
Required
Asynchronous mode; must be true. Only asynchronous processing is supported
duration
integer
Optional
Video length in seconds, 5–10, default 5. Longer videos take longer to generate
resolution
string
Optional
Resolution: 480p, 720p or 1080p. Fast supports 480p/720p only. Default 1080p
image
string
Optional
Image-to-video mode: reference image URL (HTTP/HTTPS), used as the base frame
image_tail
string
Optional
Last-frame image URL. Pass it with image to generate video from first and last frames (some models only)
size
string
Optional
Video size (e.g. 1920x1080). Use either this or resolution; if both are sent, resolution wins
callback_url
string
Optional
Callback address (HTTPS). The platform POSTs a notification here when the task completes, so you don't need to poll
Request examples
Text-to-video · image-to-video · asset reference.
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "A kitten yawns at the camera as lazy afternoon sunlight fills the room",
"duration": 5,
"resolution": "1080p",
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "The scene in the image slowly comes to life as the camera pushes in",
"image": "https://example.com/your-image.jpg",
"duration": 5,
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "A spokesperson faces the camera and introduces the product, smiling, in a high-tech office",
"image": "qasset://qasset-6600000000000000001-1716100000000000",
"duration": 10,
"async": true
}'
Download URL of the generated video, valid for about 1 hour — copy it promptly
finished_at
integer
Task completion time (Unix timestamp, seconds)
Referencing assets
Using qasset:// URIs in video generation.
Assets uploaded through the /v1/asset-groups endpoints that have passed review (status=approved) can be referenced in the image parameter as qasset://qasset-{uid}-{ts} to generate videos featuring the specified virtual avatar or real-person portrait.
Notes:
qasset:// references work only with Seedance 2.0 models
Referenced assets must have status=approved, or the video task fails
Real-person portrait assets (liveness_face) require liveness verification first
Billing
Billing method
Seedance 2.0 is billed by tokens (completion_tokens), with different unit prices per resolution. Fast supports 480p/720p only and costs less.
When you are charged
Quota is deducted only when a task completes successfully; failed tasks are not charged.
Usually 30–120 seconds; complex scenes may take longer
Concurrency
Up to 3 tasks processing at once per user
FAQ
What is the difference between Standard and Fast?
Standard (bytedance/doubao-seedance-2-0-260128) supports 480p, 720p and 1080p with finer image quality — suited to final output. Fast (bytedance/doubao-seedance-2-0-fast-260128) generates faster but supports only 480p and 720p — suited to quick previews and iteration.
How do I use qasset:// asset references?
First call POST /v1/asset-groups to create an asset group, then POST /v1/assets to upload image, video or audio assets. Once an asset is approved (status=approved), pass qasset://qasset-{uid}-{ts} in the image parameter of a video-generation request. See the /v1/asset-groups docs.
Why asynchronous mode?
Video generation is compute-heavy and usually takes 30–120 seconds. Waiting synchronously holds the HTTP connection open and easily times out. In asynchronous mode the request returns a task_id immediately and you can check progress at any time without blocking the client.
How long is video_url valid?
About 1 hour. Download the video as soon as the task completes and copy it to your own CDN or object storage before the URL expires.
POST/v1/videos/generations
Kling v3 video generation
Based on Kuaishou's Kling v3 models, with text-to-video, image-to-video (first and last frames), video editing, motion control, video with audio (audio-video sync), and multi-reference character and style consistency. Choose std, pro or 4k quality with the mode parameter, and use advanced parameters such as camera moves, negative prompts and CFG strength.
Overview
What the Kling v3 models can do.
Item
Detail
Model vendor
Kuaishou · Kling
Endpoint
POST /v1/videos/generations
Supported modes
Text-to-video, image-to-video (first frame / first and last frames), video editing, motion control (replicating motion from a reference video), video with audio (audio-video sync), multi-reference character and style consistency
Quality tiers
std (standard), pro (high quality), 4k (ultra HD)
Calling method
Asynchronous only (async: true). Submitting a task returns a task_id; poll GET /v1/videos/{task_id} for the result
Models
Available Kling models.
Model
Edition
Description
kling-v3
V3 standard
Kling v3 main model: text-to-video, image-to-video, first-and-last-frame and motion control; std/pro/4k quality
kling-v3-omni
V3 Omni
Kling V3 Omni, the all-in-one multimodal edition, unifying text/image-to-video, video editing, and character and style consistency from multiple reference images in a single model. Recommended for complex storytelling and high consistency requirements
kling-v2-6
V2.6
Kling V2.6, with motion control and video with audio (sound and picture together); std/pro quality
kling-v2-6-audio
V2.6 audio
Kling V2.6 model dedicated to video with audio, with specified-voice and default-voice modes
kling-v2-5-turbo
V2.5 Turbo
Kling V2.5 Turbo, balancing performance and cost; suited to batch output
kling-v3-omni vs kling-v3: omni is the all-in-one multimodal edition. It additionally supports video editing (style transfer or content replacement on a source video) and multi-reference consistency (pass several reference images in the elements parameter for consistent characters and style). For plain text-to-video or image-to-video, kling-v3 is enough; for editing or multi-image consistency, use kling-v3-omni.
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. kling-v3, kling-v2-6, kling-v2-6-audio
prompt
string
Required
Video description. Structure it as subject + action + scene + viewpoint + lighting; up to 5,000 English characters or 2,500 Chinese characters
async
boolean
Required
Asynchronous mode; must be true. Only asynchronous processing is supported
Video length in seconds. OpenAI format, a number. v3: 5/10; v2.6: 5/10. Default 5
seconds
string
Optional
Video length in Kling's native format, a string such as "5". Equivalent to duration; if both are sent, duration wins
image
string
Optional
Image-to-video: first-frame image URL. Equivalent to start_image_url in Kling v3 Fal format
image_tail
string
Optional
Image-to-video: last-frame image URL. Pass it with image for first-and-last-frame video (v3 and other supporting models)
start_image_url
string
Optional
Start-frame image URL in Kling v3 Fal format; equivalent to image
end_image_url
string
Optional
End-frame image URL in Kling v3 Fal format; equivalent to image_tail
negative_prompt
string
Optional
Negative prompt describing what you don't want, e.g. "blurry, distorted, low quality"
aspect_ratio
string
Optional
Aspect ratio, e.g. "16:9", "9:16", "1:1", "4:3", "3:4", "21:9"
cfg_scale
number
Optional
CFG guidance strength (0–1). Higher follows the prompt more closely; lower is more creative. 0.5–0.8 recommended
shot_type
string
Optional
Camera move, e.g. "push_in", "pull_out", "pan_left", "pan_right", "zoom_in"
sound
string
Optional
Audio switch: on / off. With on, generates video with audio (model must support it, e.g. kling-v2-6-audio)
voice_ids
array
Optional
List of voice IDs. When set, audio uses the specified voices; otherwise the default voice is used
multi_prompt
array
Optional
Multi-segment prompts (array) describing different shots along the timeline, for complex storytelling
video_url
string
Optional
Motion-control mode: reference video URL; the model replicates the person's body movements and micro-expressions. In video-editing mode, the source video URL
character_orientation
string
Optional
Motion control: character orientation, e.g. "front", "side", "back"
keep_original_sound
boolean
Optional
Motion control: keep the reference video's original audio, true/false
elements
array
Optional
Multi-reference configuration (array, kling-v3-omni only). Pass several reference images with character/style weights for consistent characters and style. Each item has image_url, role (e.g. "character" / "style"), weight and so on
callback_url
string
Optional
Callback address (HTTPS). The platform POSTs a notification here when the task completes, so you don't need to poll
Calling modes
Parameter combinations for the six calling modes.
Mode
Key
How to call
Text-to-video
t2v
Send only prompt + model. Do not send image, image_tail, video_url or elements
Set sound=on. Choose voices with voice_ids; without them the default voice is used (kling-v2-6-audio and similar models only)
Multi-reference consistency
multi-ref
Send an elements array (several reference images + character/style weights) for consistent characters and style. kling-v3-omni only
Request examples
Text-to-video · image-to-video · video editing · motion control · video with audio · multi-reference.
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v3",
"prompt": "A cyberpunk city at night with flickering neon; the camera pushes in from the street to the top of a skyscraper",
"mode": "pro",
"duration": 5,
"aspect_ratio": "16:9",
"cfg_scale": 0.7,
"negative_prompt": "blurry, distorted, low quality",
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v3",
"prompt": "Day slowly turns to night as the city lights come on one by one",
"image": "https://example.com/start-frame.jpg",
"image_tail": "https://example.com/end-frame.jpg",
"mode": "std",
"duration": 10,
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v3-omni",
"prompt": "Convert the video to claymation style, keeping the characters movements the same",
"video_url": "https://example.com/source-video.mp4",
"mode": "pro",
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v2-6",
"prompt": "The person dances following the reference video, keeping the same outfit",
"video_url": "https://example.com/reference-dance.mp4",
"character_orientation": "front",
"mode": "pro",
"duration": 10,
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v2-6-audio",
"prompt": "A girl faces the camera, smiles and says: Hello, welcome to Ainfra MaaS",
"image": "https://example.com/girl-portrait.jpg",
"sound": "on",
"voice_ids": ["voice_zh_female_01"],
"mode": "std",
"duration": 5,
"async": true
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "kling-v3-omni",
"prompt": "The character from the reference images runs along a beach at sunset, keeping the same face and outfit",
"elements": [
{"image_url": "https://example.com/char-1.jpg", "role": "character", "weight": 0.8},
{"image_url": "https://example.com/char-2.jpg", "role": "character", "weight": 0.6},
{"image_url": "https://example.com/style.jpg", "role": "style", "weight": 0.5}
],
"mode": "pro",
"duration": 5,
"async": true
}'
Reference video must be MP4, ≤ 100 MB, ≤ 10 seconds
Generation time
Usually 1–5 minutes; 4k quality or audio may take longer
Concurrency
Up to 3 tasks processing at once per user
FAQ
What is the difference between kling-v3-omni and kling-v3?
Both are Kling V3 models with the same core video generation. kling-v3-omni is the all-in-one multimodal edition and additionally supports (1) video editing: style transfer and content replacement on a source video; and (2) multi-reference consistency: pass several reference images in the elements parameter for consistent characters and style. For plain text-to-video or image-to-video, kling-v3 is enough; for editing or multi-image consistency, use kling-v3-omni.
How do I edit a video?
Use kling-v3-omni and send video_url (the source video) and a prompt with the edit instruction (such as "convert to claymation style" or "replace the background with a beach"). The model keeps the video's main structure and changes the picture as instructed. Note that video_url is the source video in editing mode and the reference video in motion-control mode.
How do I use multi-reference consistency?
Use kling-v3-omni and send an elements array; each item has image_url (reference image), role (character for character consistency, style for style consistency) and weight (0–1). The model generates video that keeps the character's face, outfit or art style consistent with the references — suited to serial storytelling and IP character work.
What quality is used if mode is not sent?
The default is std (standard). For higher quality, pass mode: "pro" or mode: "4k" explicitly (4k on kling-v3 only).
What is the difference between duration and seconds?
Both set the video length in seconds. duration is the OpenAI format (a number) and seconds is Kling's native format (a string). If both are sent, duration wins. We recommend always using duration.
How do image and start_image_url relate?
They are equivalent: both are the first-frame image URL for image-to-video. start_image_url is the Kling v3 Fal field name and image is the OpenAI-compatible field. The platform maps them automatically, so send either one.
How do I generate a first-and-last-frame video?
Send both image (first frame) and image_tail (last frame); the model generates a transition video from the first frame to the last. First-and-last-frame video is available only on supporting models such as kling-v3.
How do I use motion-control mode?
Send video_url (reference video) and a prompt describing the motion; the model replicates the person's body movements and micro-expressions from the reference video. Combine with character_orientation and keep_original_sound as needed. Supported on kling-v2-6 and later.
How do I generate video with audio?
Use an audio-capable model such as kling-v2-6-audio and send sound: "on". Choose voices with voice_ids; otherwise the default voice is used. The video comes with an audio track, naturally synced to the picture.
How should I tune cfg_scale?
cfg_scale controls how strongly the prompt guides generation, from 0 to 1. Higher values follow the prompt more closely; lower values leave more creative room. 0.5–0.8 is recommended; the default is about 0.5.
Which camera moves does shot_type support?
Common types include push_in, pull_out, pan_left, pan_right, tilt_up, tilt_down, zoom_in and static.
How long is the video URL valid?
The download URL of a generated video is valid for about 1 hour. Download it as soon as the task completes and copy it to your own CDN or object storage before the URL expires.
POST/v1/videos/generations
Wan video generation
Based on Alibaba Cloud's Tongyi Wan models, with text-to-video, image-to-video and video editing. Supports synchronous and asynchronous modes; query asynchronous task results with GET /v1/videos/{task_id}.
Model overview
Supported models and capabilities. Prices follow the Model Square.
Model
Type
Description and price
wan2.7-t2v
Text-to-video
Wan 2.7 text-to-video. 720p: $0.083/s, 1080p: $0.139/s
wan2.6-t2v
Text-to-video
Wan 2.6 text-to-video. 720p: $0.083/s, 1080p: $0.139/s
wan2.7-i2v
Image-to-video
Wan 2.7 image-to-video with first frame or first and last frames. 720p: $0.086/s, 1080p: $0.143/s
wan2.6-i2v
Image-to-video
Wan 2.6 image-to-video. 720p: $0.083/s, 1080p: $0.139/s
wan2.6-i2v-flash
Image-to-video
Wan 2.6 Flash, faster. 720p: $0.042/s, 1080p: $0.069/s
wan2.7-videoedit
Video editing
Wan 2.7 video editing: style transfer and content replacement. 720p: $0.086/s, 1080p: $0.143/s
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name, e.g. wan2.7-t2v, wan2.6-i2v-flash
prompt
string
Required
Video or edit description. Describe the scene, action, viewpoint and lighting in detail
image
string
Optional
Image-to-video: first-frame image URL. Video editing: source video URL
image_tail
string
Optional
Last-frame image URL (first-and-last-frame mode on wan2.7-i2v only)
resolution
string
Optional
Resolution: 720P (default) or 1080P
duration
integer
Optional
Video length in seconds. wan2.6 models: 5/10; wan2.7 models: 2–15
async
boolean
Optional
Asynchronous mode. false (default) waits for the result; true returns a task_id immediately
prompt_extend
boolean
Optional
Enable smart prompt rewriting, default true
watermark
boolean
Optional
Add a watermark, default false
negative_prompt
string
Optional
Negative prompt describing what you don't want
seed
integer
Optional
Random seed, for reproducible results
Generation modes
Synchronous vs asynchronous.
Synchronous (default)
The request blocks until the video is ready (1–5 minutes) and returns the video URL directly. Good for simple tests or short videos.
Asynchronous (recommended)
Set async: true and the request returns a task_id immediately. Poll GET /v1/videos/{task_id} for the result without holding the connection. Recommended for production.
curl -X POST \
https://modelapi.taikuntech.com/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "wan2.7-t2v",
"prompt": "A kitten running through flowers on a sunny day",
"resolution": "720P",
"duration": 5
}'
cURL
curl -X POST \
https://modelapi.taikuntech.com/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "wan2.6-i2v-flash",
"prompt": "The camera rises slowly from beneath the sea turtle as it swims leisurely",
"image": "https://example.com/turtle.webp",
"resolution": "720P",
"duration": 5
}'
cURL
curl -X POST \
https://modelapi.taikuntech.com/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "wan2.7-t2v",
"prompt": "Time-lapse of a city at night with light trails from traffic",
"resolution": "1080P",
"duration": 10,
"async": true
}'
Poll every 5–10 seconds. A task_id is valid for 24 hours.
Billing
Billing method
Billed by video length (seconds); prices differ by resolution.
When you are charged
Quota is deducted only when a task completes successfully; failed tasks are not charged.
Best practices
Polling strategy
Poll every 5–10 seconds and wait at most 5 minutes. In production always use async: true to avoid connection timeouts.
Prompt tips
Describe the video as subject + action + scene + viewpoint + lighting. Concrete verbs (running, spinning, drifting down) make the video feel more natural.
Prefer Flash
For speed-sensitive work use wan2.6-i2v-flash: lower cost and faster, at only $0.042 per second for 720p.
Image requirements
JPEG/PNG/BMP/WEBP, 240–8,000 pixels, up to 20 MB, aspect ratio between 1:8 and 8:1.
FAQ
What is the difference between synchronous and asynchronous mode?
Synchronous (default): the request blocks until the video is ready and returns the video URL directly. Asynchronous (async: true): returns a task_id immediately; poll GET /v1/videos/{task_id} for the result. Asynchronous mode is recommended for production.
What are the image requirements for image-to-video?
JPEG, JPG, PNG (no alpha channel), BMP and WEBP. Width and height between 240 and 8,000 pixels, aspect ratio 1:8 to 8:1, file size up to 20 MB. Public HTTP/HTTPS URLs are supported.
Does wan2.7-i2v support first and last frames?
Yes. wan2.7-i2v uses the new protocol and generates video from first and last frames via the image (first frame) and image_tail (last frame) parameters. Other image-to-video models support the first frame only.
How do I use video editing?
Use the wan2.7-videoedit model, pass the source video URL (not an image) in the image parameter, and describe the edit in the prompt (for example, "convert to claymation style").
Can I use images generated on this platform for image-to-video?
Yes. Pass the image URL returned by the text-to-image API straight into the image parameter of image-to-video; the platform handles the URL proxy conversion automatically.
POST/v1/videos/generations
HappyHorse video generation
Based on Alibaba Cloud's HappyHorse 1.1 models, with text-to-video and image-to-video. Audio and video are generated natively together, so videos come with sound. 3–15 second videos at 720p or 1080p. Query asynchronous task results with GET /v1/videos/{task_id}.
HappyHorse 1.1 image-to-video from a first-frame image. 720p: $0.125/s, 1080p: $0.167/s
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name: happyhorse-1.1-t2v (text-to-video) or happyhorse-1.1-i2v (image-to-video)
prompt
string
Required
Video description. 30–60 characters works best; up to 5,000 English characters or 2,500 Chinese characters
image
string
Optional
Required for image-to-video: first-frame image URL. jpeg/jpg/png/bmp/webp, ≤ 20 MB per image
resolution
string
Optional
Resolution: 720P or 1080P, default 720P
duration
integer
Optional
Video length in seconds, an integer from 3 to 15, default 5
async
boolean
Optional
Asynchronous mode. async: true is recommended for HappyHorse and returns a task_id immediately
watermark
boolean
Optional
Add a watermark (bottom right), default true
seed
integer
Optional
Random seed in [0, 2147483647]; fix it to improve reproducibility
Key features
How it differs from the Wan models.
Native audio-video sync
HappyHorse videos come with their own audio track, with no separate audio generation needed. Picture and sound are naturally in sync — suited to short dramas and e-commerce ads.
Multi-shot storytelling
In T2V mode one prompt can plan 6–8 consecutive shots, suited to narrative content.
Flexible length
Any whole number of seconds from 3 to 15, more flexible than the Wan 2.6 models (5 or 10 seconds).
Aspect ratios
Nine aspect ratios: 16:9, 9:16, 1:1, 4:3, 3:4, 4:5, 5:4, 9:21 and 21:9.
curl -X POST \
https://modelapi.taikuntech.com/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "happyhorse-1.1-t2v",
"prompt": "Time-lapse of a city at night with light trails from traffic and flickering neon",
"resolution": "720P",
"duration": 5,
"async": true
}'
cURL
curl -X POST \
https://modelapi.taikuntech.com/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxx" \
-d '{
"model": "happyhorse-1.1-i2v",
"prompt": "The camera slowly pushes in as the sea turtle swims leisurely",
"image": "https://example.com/turtle.webp",
"resolution": "720P",
"duration": 5,
"async": true
}'
Python
import requests
import time
API_KEY = "sk-xxx"
BASE_URL = "https://modelapi.taikuntech.com"# 1. Create the task
resp = requests.post(
f"{BASE_URL}/v1/videos/generations",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
},
json={
"model": "happyhorse-1.1-t2v",
"prompt": "Time-lapse of a city at night with light trails from traffic",
"resolution": "720P",
"duration": 5,
"async": True
}
)
task = resp.json()
print(f"Task created: {task['task_id']}")
# 2. Poll for the result
while True:
result = requests.get(
f"{BASE_URL}/v1/videos/{task['task_id']}",
headers={"Authorization": f"Bearer {API_KEY}"}
).json()
if result["task_status"] == "succeed":
print(f"Video ready: {result['video_result'][0]['url']}")
break
elif result["task_status"] == "failed":
print("Task failed")
break
time.sleep(10)
Create-task response
Field
Type
Description
task_id
string
Unique task ID, valid for 24 hours
task_status
string
Task status: pending (queued), running, succeed (completed) or failed
The returned video URL is proxied by the platform and directly accessible. The video includes a native audio track.
Billing
Billing method
Billed by video length (seconds); prices differ by resolution.
Price per model
720p: about $0.125 per second · 1080p: about $0.167 per second
When you are charged
Quota is deducted only when a task completes successfully; failed tasks are not charged.
Best practices
Polling strategy
Poll every 10 seconds and wait at most 5 minutes. HappyHorse generates video with an audio track, which usually takes 1–5 minutes.
Prompt tips
30–60 characters is optimal. Describe concrete actions, camera moves and sound effects; HappyHorse understands sound descriptions and generates matching audio.
Built-in audio
Unlike the Wan models, HappyHorse videos come with audio, so there's no need to call a separate TTS or audio API — ideal for short dramas, ads and anything that needs voice-over.
Image requirements
jpeg/png/bmp/webp, ≤ 20 MB per image, at least 300 pixels on each side, aspect ratio between 2:5 and 5:2. Image-to-video keeps the original composition and colours.
FAQ
How does HappyHorse differ from the Wan models?
HappyHorse is Alibaba Cloud's new-generation video model. Its standout feature is native audio-video sync: generated videos come with audio, whereas Wan videos are silent. HappyHorse also supports flexible 3–15 second lengths and is priced slightly higher than Wan.
Do the generated videos have sound?
Yes. HappyHorse videos include a native audio track naturally synced with the picture. Describe sound effects in the prompt (such as "waves" or "city bustle") and the model will try to generate matching audio.
What are the image requirements for image-to-video?
jpeg, jpg, png, bmp and webp. Up to 20 MB per image, at least 300 pixels on each side, aspect ratio between 2:5 and 5:2. Public HTTP/HTTPS URLs are supported.
What is the watermark default?
The default is true, which adds a "Happy Horse" watermark in the bottom-right corner. For a video without a watermark, set watermark: false.
Can I use images generated on this platform for image-to-video?
Yes. Pass the image URL returned by the text-to-image API straight into the image parameter; the platform handles the URL proxy conversion automatically.
MiniMax H3 is one model with three API endpoints: video generation (billed per second), Context-IR context understanding (billed per token), and video regeneration (billed per second). It supports text-to-video, image-to-video (first and last frames) and multimodal-reference video, with native 2K output. The native interface matches MiniMax's official API exactly, so clients only need to change the base URL to migrate.
Overview
What MiniMax H3 can do.
Item
Detail
Model vendor
MiniMax
Model name
minimax/minimax-h3 (one model, three endpoints)
Endpoint 1 · Video generation
POST /v2/video_generation — billed per second, native 2K/768p output
Endpoint 2 · Context-IR
POST /v2/h3_context_ir — billed per token; multimodal context understanding that outputs an enhanced prompt
Endpoint 3 · Video regeneration
POST /v2/video_regeneration — billed per second; regenerates a 768p video at 2K
Supported modes
Text-to-video (t2va), image-to-video with first/last/both frames (i2va), multimodal-reference video (r2va: reference images + reference video + reference audio)
Resolution
768P (standard), 2K (native HD output)
Video length
4–15 seconds (integer)
Calling method
Asynchronous. Submitting a task returns a task_id; query GET /v2/video_generation/{task_id} for the result
Models
One model, three endpoints.
MiniMax H3 has a single model, minimax/minimax-h3, exposed through three API endpoints for different purposes and billing. All three use the same model name.
Model
Type
Description
minimax/minimax-h3
Model ID
The single MiniMax H3 model identifier, shared by all three endpoints
The three endpoints
Endpoint
Purpose
Description
/v2/video_generation
Video generation
Text-to-video, image-to-video and multimodal-reference video. Billed per second (2K: $0.116/s, 768p: $0.072/s). Native 2K output
/v2/h3_context_ir
Context-IR
Multimodal context understanding that outputs a structured, enhanced prompt (no video is generated). Billed per token (input: $0.84 per 1M tokens, output: $3.33 per 1M tokens)
/v2/video_regeneration
Video regeneration
Regenerates a previously generated 768p video at 2K. Billed per second (2K pricing: $0.116/s)
Parameters
Request body JSON parameters, Content-Type: application/json.
Parameter
Type
Required
Description
model
string
Required
Model name. Use minimax/minimax-h3 for all three endpoints
content
array
Required
Array of multimodal inputs, typed by type (text/image_url/video_url/audio_url) and labelled by role. See "content: multimodal input" below
resolution
string
Required
Video resolution: 768P (standard) or 2K (native HD)
duration
integer
Required
Video length in seconds, an integer from 4 to 15
ratio
string
Optional
Aspect ratio. Required for text-to-video and cannot be adaptive; always adaptive for image-to-video (set by the input image); optional for multimodal reference, default adaptive. Values: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16
callback_url
string
Optional
Callback address (HTTPS). MiniMax first sends a challenge request to verify it; once verified, it POSTs updates whenever the task status changes
aigc_watermark
boolean
Optional
Add an AIGC watermark to the generated video, default false
content: multimodal input
Array structure and role semantics.
Every request must include one non-empty text item (the prompt is required). Each element is typed by type and labelled by role.
Type
Kind
Description
text
type
Text prompt. At least one non-empty text item is required. Structure it as subject + action + scene + viewpoint + lighting
image_url
type
Image input. JPG/JPEG/PNG/WEBP/HEIC/HEIF, ≤ 30 MB per file, width and height 256–5,760 px, aspect ratio 0.4–2.5
video_url
type
Video input (multimodal reference only). MP4/MOV, H.264/H.265 + AAC/MP3, ≤ 50 MB per file, 2–15 s
audio_url
type
Audio input (multimodal reference only). WAV/MP3, ≤ 15 MB per file, 2–15 s
role labels
Role
Kind
Description
first_frame
role
First-frame image (image-to-video). An image_url with role=first_frame or no role
last_frame
role
Last-frame image (image-to-video). Combine with first_frame for first-and-last-frame video
reference_image
role
Reference image (multimodal reference). Up to 9, for character/style consistency
reference_video
role
Reference video (multimodal reference). Up to 3, for motion/scene reference
reference_audio
role
Reference audio (multimodal reference). Up to 3, for sound-effect/music reference
Mutual exclusion: image-to-video roles (first_frame/last_frame) and multimodal-reference roles (reference_image/reference_video/reference_audio) cannot be mixed. Once any reference_* role appears in content, first_frame/last_frame cannot, and vice versa.
Calling modes
content combinations for the three calling modes.
Mode
Key
How to call
Text-to-video
t2va
content contains only one text item. ratio is required (cannot be adaptive)
Image-to-video
i2va
content contains text + image_url (role=first_frame/last_frame). ratio is always adaptive
Multimodal-reference video
r2va
content contains text plus any combination of reference_image/reference_video/reference_audio. ratio optional, default adaptive
Request examples
Video generation · multimodal reference · Context-IR · video regeneration.
cURL
curl -X POST 'https://modelapi.taikuntech.com/v2/video_generation' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "minimax/minimax-h3",
"content": [
{"type": "text", "text": "An epic space opera: the woman captain stands alone at a vast observation window as the last fleet jumps away"}
],
"resolution": "2K",
"duration": 5,
"ratio": "16:9"
}'
cURL
curl -X POST 'https://modelapi.taikuntech.com/v2/video_generation' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "minimax/minimax-h3",
"content": [
{"type": "text", "text": "Day fades into night as the city lights come on one by one"},
{"type": "image_url", "image_url": {"url": "https://example.com/start-frame.jpg"}, "role": "first_frame"},
{"type": "image_url", "image_url": {"url": "https://example.com/end-frame.jpg"}, "role": "last_frame"}
],
"resolution": "2K",
"duration": 8
}'
Task status: queued, running, succeeded, failed or cancelled
task.content.url
string
Download URL of the generated video (only when status=succeeded)
task.resolution
string
Actual output resolution: 768P or 2K
task.duration
integer
Actual video length (seconds)
task.usage
object
Usage: total_seconds, output_seconds, input_seconds (input video seconds) and input_image_count (number of input images)
task.ratio
string
Actual aspect ratio
task.task_type
string
Task type: generation, h3_context_ir (Context-IR) or regeneration
Exact billing: the platform bills on the actual usage reported in task.usage (output_seconds, input_seconds and input_image_count), not on estimates from the request.
Context-IR response example
When a Context-IR task succeeds, read the enhanced prompt from content.prompt and token usage from usage.
The enhanced prompt output by Context-IR (a structured, semantically rich video description)
task.usage.prompt_tokens
integer
Input tokens (billed at $0.84 per 1M tokens)
task.usage.completion_tokens
integer
Output tokens (billed at $3.33 per 1M tokens)
task.task_type
string
h3_context_ir (marks a Context-IR task)
Billing
Billed on actual usage · one model, three price sets.
The three endpoints are billed differently: video generation and regeneration per second, Context-IR per token. The platform applies the right rule automatically for each endpoint.
768p video output, billed on actual output_seconds (not applicable to regeneration)
Video input (2K output)
$0.116 per second
With 2K output, input reference video is billed on input_seconds
Video input (768p output)
$0.072 per second
With 768p output, input reference video is billed on input_seconds
Image input
$0.029 per image
The first 5 images in each request are free; after that, $0.029 per image
Free allowance: the first 5 input images in each request are free (free_count=5). Text-to-video (no image input) incurs no image charges.
Context-IR (per token)
Endpoint: /v2/h3_context_ir — outputs enhanced prompt text, no video.
Item
Price
Description
Input
$0.84 per 1M tokens
Billed on prompt_tokens (multimodal context-understanding input)
Output
$3.33 per 1M tokens
Billed on completion_tokens (the generated enhanced prompt)
Context-IR returns only the enhanced video prompt and does not create a video task. Use the returned prompt as input to /v2/video_generation to generate the video.
Technical limits
Input media formats and size limits.
Item
Limit
Description
Request body size
≤ 64 MB
Total request body limit. Use public URLs for large files, not Base64
Image formats
JPG/JPEG/PNG/WEBP/HEIC/HEIF
≤ 30 MB per file, width and height 256–5,760 px, aspect ratio 0.4–2.5
Number of images
First frame ≤ 1 / last frame ≤ 1 / reference ≤ 9
At most 1 first_frame, 1 last_frame and 9 reference_image
Video formats
MP4/MOV
H.264/H.265 video + AAC/MP3 audio. ≤ 50 MB per file, 2–15 s, at most 3, total ≤ 15 s
Audio formats
WAV/MP3
≤ 15 MB per file, 2–15 s, at most 3, total ≤ 15 s
Length range
4–15 seconds
duration is an integer from 4 to 15
Resolution
768P / 2K
2K is native HD output with no upscaling post-process
FAQ
How does MiniMax H3 differ from other video models?
MiniMax H3 outputs 2K natively (other models usually need upscaling) and natively supports multimodal-reference video (reference_image + reference_video + reference_audio), combining character, style, motion and sound references. The interface uses a content array for multimodal input, unlike the flat OpenAI field format.
Can ratio be adaptive for text-to-video?
No. For text-to-video (content with only text), ratio is required and cannot be adaptive; choose from 21:9, 16:9, 4:3, 1:1, 3:4 and 9:16. For image-to-video, ratio is set by the input image and is always adaptive.
How is the free image allowance calculated?
The first 5 input images in each request are free (free_count=5); the rest are billed at $0.029 per image. For example, with 8 reference images the first 5 are free and the last 3 are billed, about $0.087 in total.
How do I enable callback notifications?
Set callback_url (an HTTPS address) in the request body. MiniMax first sends a verification request containing a challenge field (echo the challenge back within 3 seconds to verify); after that it POSTs updates whenever the task status changes. Without it, you need to poll.
How does the Context-IR endpoint relate to video generation?
Context-IR (/v2/h3_context_ir) is a multimodal context-understanding endpoint. It does not generate video; it deeply analyses text, image, video and audio input and outputs a structured, enhanced prompt. Using that prompt as the text input to /v2/video_generation gives semantically richer videos. Context-IR is billed per token; video generation per second.
How do I use the video regeneration endpoint?
Video regeneration (/v2/video_regeneration) upgrades a previously generated 768p video to 2K. Pass source_task_id (the task_id of the original generation task) or a content array, and the model regenerates the source video at 2K. It is billed like video generation, on 2K output seconds.
POST/v1/asset-groups · /v1/assets
Seedance 2.0 asset management
Manage virtual-avatar and real-person portrait assets for the Seedance 2.0 models. Once an asset passes review, reference it in video-generation requests with a qasset:// URI.
In the examples below, $BASE_URL is https://modelapi.taikuntech.com.
Real-person groups: after creating the group, poll it (every 2–3 seconds) to get h5_link and byted_token, then guide the user through face verification. h5_link is valid for about 120 seconds.
List groups
GET/v1/asset-groups
Parameter
Type
Required
Description
page
integer
Optional
Page number, default 1
page_size
integer
Optional
Page size, default 20, maximum 100
status
string
Optional
Filter by status: pending/active/failed (real-person groups also have awaiting_auth)
type
string
Optional
Filter by type: aigc/liveness_face
Get or update a group
GETPATCH/v1/asset-groups/:qgroupid
Get group details to poll its status. Real-person groups in the awaiting_auth state return h5_link and byted_token.
After a successful face scan, trigger the verification check; the platform exchanges the one-time byted_token with the provider for the verification result.
Parameter
Type
Required
Description
result_code
string
Required
Face-scan result code; 10000 = success
byted_token
string
Optional
Verification token; leave empty to use the one the platform has stored
One-time token: byted_token can be used only once. Call this endpoint only after a successful face scan (result_code=10000), and only once. A forged result code burns the token and leaves the group unrecoverable.
Upload an asset
POST/v1/assets
Parameter
Type
Required
Description
type
string
Required
Asset type: image/video/audio
url
string
Required
Source file URL; must be publicly accessible
name
string
Required
Asset display name, 1–200 characters
model
string
Required
bytedance/doubao-seedance-2-0-260128
group_id
string
Optional
qgroupid of the group. Required for real-person groups; leave empty for virtual assets to use the default group
Filter by status: pending/reviewing/approved/failed
type
string
Optional
Filter by type: image/video/audio
group_id
string
Optional
Filter by group
Polling: query asset details every 5–10 seconds, with a 10-minute overall timeout. The final states are approved and failed.
Referencing assets
Using qasset:// URIs in video generation.
Once an asset is approved (status=approved), reference it in a video-generation request with qasset://:
cURL
curl -X POST '$BASE_URL/v1/videos/generations' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-xxxxxx' \
-d '{
"model": "bytedance/doubao-seedance-2-0-260128",
"prompt": "The person smiles and waves from the podium",
"image": "qasset://qasset-uid001-1716100100000000000",
"async": true
}'
End-to-end flow
Virtual-avatar flow:
Text
Create group (optional) → Upload asset → Poll review status → approved → Reference via qasset:// → Generate video
Real-person flow:
Text
Create real-person group → Poll for h5_link → User completes face scan → Trigger check (result_code=10000)
→ Group becomes active → Upload asset → Poll review → approved → Reference via qasset://
Notes:
qasset:// references work only with Seedance 2.0 models
Referenced assets must have status=approved, or the video task fails
failed is a final state and cannot be recovered; submit a new asset
Face consistency for real-person groups: assets must show the same person as the verification baseline, with a single face
Supported models
Ainfra MaaS supports a wide range of mainstream large language models. See the Model Square for the full list; popular models from each provider are listed below.
Popular models
DeepSeek-V3
DeepSeek · Best-value choice
DeepSeek-R1
DeepSeek · Deep-reasoning model
Qwen-Max
Alibaba · Qwen flagship
Qwen-Plus
Alibaba · Qwen enhanced edition
GLM-4
Zhipu · Latest ChatGLM
moonshot-v1-128k
Moonshot · Very long context
llama3
Ollama · Meta open-source model (local deployment)
Model names
Model names match those in each provider's official API, for example deepseek/deepseek-v4-pro or z-ai/glm-5.2
ByteDance Volcano Engine (Doubao) uses the inference endpoint name as the model name, e.g. ep-20240608051426-tkxvl
In the Coze channel, the model name is the Bot ID; you can add a bot- prefix
See the Model Square for the models currently available
Billing
Ainfra MaaS is billed pay-as-you-go on the tokens you actually use; each model has its own price.
How billing works
Per-token billing
Billed on the input and output tokens you actually use. Each model has its own unit price.
API key quota
Each API key can have a quota cap. Calls deduct from the quota at the model's price; once it is used up, top up or create a new key.
Model price reference
Reference prices for common models, in US$ per 1M tokens. The Model Square shows the prices that actually apply.
DeepSeek
Model
Input
Output
deepseek-v3
$0.28
$1.11
deepseek-r1
$0.56
$2.22
deepseek-v3.1
$0.56
$1.67
Alibaba Qwen
Model
Input
Output
qwen3-max (≤32K)
$0.83
$3.33
qwen3-max (32K–128K)
$1.39
$5.56
qwen-turbo
$0.042
$0.083
qwen-max
$0.33
$1.33
qwen3.5-397b-a17b (≤128K)
$0.17
$1.00
ByteDance Doubao
Model
Input
Output
doubao-seed-2.0-lite (≤32K)
$0.083
$0.50
doubao-seed-2.0-pro (≤32K)
$0.44
$2.22
doubao-seed-1.6-flash (≤32K)
$0.021
$0.21
doubao-1.5-pro-32k
$0.11
$0.28
doubao-1.5-thinking-pro
$0.56
$2.22
Zhipu GLM
Model
Input
Output
glm-4.5
$0.56
$2.22
glm-4.5-air
$0.28
$1.11
z-ai/glm-4.7
$0.44
$1.74
z-ai/glm-5 (≤32K)
$0.56
$2.50
Other models
Model
Input
Output
kimi-k2 / kimi-k2.5
$0.56
$2.22
MiniMax-M1
$0.56
$2.22
minimax/minimax-m2.5
$0.29
$1.17
xiaomi/mimo-v2-flash
$0.097
$0.29
These prices are for reference only; some models are priced differently depending on context length. See the Model Square for the full model list and current prices.
Volume discounts
Discounts available
Ainfra MaaS offers discounts on model usage. Customers with large volumes can apply for discount tiers based on usage — the more you use, the bigger the discount.
How to apply
To apply for a discount, contact our team. We will put together a discount plan based on your usage and needs.
Rate limits and higher quotas
Low default RPM for new accounts
To keep the platform stable, new accounts start with a low default RPM (requests per minute). If you hit rate-limit errors (HTTP 429), contact our team to have a higher rate quota enabled.
Raising your quotas
After you contact our team, we can adjust the following quotas to fit your business needs: a higher RPM (requests per minute) cap, a higher TPM (tokens per minute) cap, a higher API key quota cap, and model usage discounts.
Error handling
When a request fails, the API returns an HTTP error status and a JSON error body. This page collects the common error codes across all endpoints; each endpoint page lists the causes specific to it.
Error response format
OpenAI-compatible endpoints (/v1/chat/completions, /v1/completions, /v1/responses, /v1/images, /v1/videos and others):
Missing or invalid parameters (model, messages, prompt, input), values out of range, malformed JSON
401
Unauthorized
Invalid or expired API key, missing Authorization or x-api-key header, wrong key format (should start with sk-), insufficient balance or disabled account
404
Not Found
Misspelled or unavailable model name, model doesn't support the endpoint, wrong endpoint path, unknown or expired task_id
413
Content Too Large
Text exceeds the model's token limit, or the request is too large
415
Unsupported Media Type
Content-Type is not application/json, or the body is not valid JSON
429
Rate Limit Exceeded
Request rate or concurrency over the limit, too many concurrent video tasks, or the API key's quota is used up
500
Internal Server Error
The upstream model service is temporarily unavailable, or the request payload is too large or timed out
Error types
type
Typical status
invalid_request_error
400, 401, 404, 413, 415
authentication_error
401 (Anthropic-format endpoint)
not_found_error
404
rate_limit_error
429
server_error
500
Handling errors
Retry with backoff
For 429 and 500 errors, retry with exponential backoff: wait 1 second the first time, double it each time, up to 60 seconds, with at most 5 retries. Respect the Retry-After response header when present.
Don't retry client errors
400, 401, 404, 413 and 415 errors won't succeed on retry. Fix the request, key or parameters and return a clear message to your user.
Separate recoverable errors
Distinguish recoverable errors (network timeouts, rate limits, upstream outages) from unrecoverable ones (invalid parameters, content-policy refusals) and handle each path explicitly.
Raise your limits
If you regularly hit 429 errors, contact our team to raise your RPM, TPM or quota limits.