Docs / Task Management
Error Code Reference
A complete list of error codes for failed async tasks with a troubleshooting guide: 8 top-level code enums, detailed upstream.code explanations, and retry strategies.
Overview#
This page is the complete reference of error codes returned when an async task fails, along with a troubleshooting guide. Error codes appear in the error.code field of the task response.
Failures of async tasks (image / video / Suno, etc.) are not returned in the submission response — a successful submission only means the task was queued. The final outcome must be determined by polling status and error via GET /v1/tasks/:id.
Error response format#
When a task fails (status: "failed"), the response contains an error object:
{
"id": "task_xxx",
"object": "image.generation.task",
"status": "failed",
"model": "gpt-image-2",
"progress": 100,
"failed_at": 1778570120,
"error": {
"code": "upstream_error",
"message": "openai returned 400: ...",
"upstream": {
"provider": "openai",
"code": "content_policy_violation",
"message": "your request was flagged ..."
}
}
}| Field | Type | Description |
|---|---|---|
error.code | string | Top-level error code (a stable enum, see the overview below); clients use it for coarse routing |
error.message | string | User-friendly error description (sanitized) |
error.upstream | object | Optional. Native upstream error details; present only for execution-stage failures where the provider received an upstream error |
Error code overview#
There are 8 stable top-level error.code enums, grouped by stage:
Request stage (returned immediately at submission, no polling needed)#
| Code | Meaning | Retry? |
|---|---|---|
invalid_request | Invalid request parameters (missing prompt/model, malformed fields, n out of range, etc.) | Fix the parameters and retry |
model_not_supported | The model is not on the supported list | Switch models and retry |
model_price_error | Model pricing misconfigured (missing price / invalid multiplier) | Contact an administrator |
Query stage#
| Code | Meaning | Retry? |
|---|---|---|
task_not_found | The task ID does not exist or belongs to another caller | Check the ID and retry |
Execution stage (the task was queued but failed in the background; retrieve it by polling)#
| Code | Meaning | Retry? |
|---|---|---|
upstream_error | The upstream returned 4xx (including content violations, parameter errors, etc.) | See the upstream.code details |
upstream_unavailable | Upstream 5xx with retries exhausted | Retry later |
storage_error | Failed to upload the result to cloud storage | Retry later |
internal_error | Gateway internal exception | Retry later / contact support |
Failed tasks automatically refund the prepaid quota.
error.upstream upstream error details#
The top-level error.code is a coarse routing signal. To pin down the cause (for example, distinguishing "content violation" vs "bad image format" vs "rate limit"), read error.upstream.code — it is the provider's native error code and varies by upstream.
| Provider | Source of upstream.code | Examples |
|---|---|---|
| openai | error.code (raw); falls back to error.type when empty | content_policy_violation / invalid_image / rate_limit_exceeded |
| gemini (4xx) | error.status (raw); falls back to http_<code> when empty | INVALID_ARGUMENT / PERMISSION_DENIED / RESOURCE_EXHAUSTED |
| gemini (200 but no image, the entire prompt blocked) | prompt_blocked:<blockReason> | prompt_blocked:OTHER / prompt_blocked:SAFETY |
| gemini (200 but no image, candidate stopped midway) | finish_reason:<finishReason> | finish_reason:SAFETY / finish_reason:PROHIBITED_CONTENT |
Gemini's "200 but no image" case (a successful response that produced no image, usually because the content triggered a safety block) is treated as a 4xx upstream_error and must not be retried — retrying blocked content yields the same result.
Troubleshooting common upstream error codes#
content_policy_violation#
The request content was intercepted by the safety review mechanism — the most common failure cause. Covered scenarios:
| Sub-type | Description | Typical message |
|---|---|---|
| Photorealistic people | Uploading photos containing real human faces | photorealistic people detected |
| Celebrity likeness | Involving celebrities or public figures | celebrity detected in image |
| Copyright/trademark | Involving brand logos, trademarks, or copyrighted characters | third-party content violation |
| Adult/NSFW | Containing nudity or sexually suggestive content | nudity detected |
| Violence/self-harm | Containing violent, gory, or self-harm content | violence content blocked |
How to avoid it: Do not upload photos of real people (use illustration / cartoon styles instead); remove brand logos, trademarks, and IP characters; avoid adult, violent, and other sensitive themes; describe people generically (e.g. "a person") instead of naming specific celebrities.
invalid_image / image_processing_error#
The system could not process the input image. Common causes: the image URL is inaccessible (insufficient permissions, CDN restrictions, expired link); unsupported format (HEIC, AVIF, TIFF); corrupted file; network download failure.
How to handle it: Make sure the image URL is publicly accessible; use standard formats such as JPG / PNG / WebP; switch from the URL method to the file upload endpoint; check that the image is complete and can be opened.
image_dimension_mismatch#
The input image dimensions do not match the request parameters; this is common in image-to-video. For example, aspect_ratio=1280x720 requires a 1280×720 landscape image. Fix: Resize the image to match aspect_ratio, or change aspect_ratio to fit the image.
rate_limit_exceeded / RESOURCE_EXHAUSTED#
The request rate / concurrency limit was exceeded, or upstream resources are temporarily exhausted. Fix: Lower the request rate (an interval of 1-2 seconds between calls is recommended); wait for in-flight tasks to finish before submitting again; retry after waiting 1-5 minutes — the system automatically switches between multiple routes.
Best practices#
Error handling recommendations#
import requests
import time
def poll_task_with_retry(task_id, api_key, max_retries=3):
"""Poll a task with automatic retry."""
headers = {"Authorization": f"Bearer {api_key}"}
for attempt in range(max_retries):
resp = requests.get(
f"https://api.apimax.ai/v1/tasks/{task_id}",
headers=headers
)
data = resp.json()
if data["status"] == "completed":
return data.get("data")
if data["status"] == "failed":
error = data.get("error", {})
code = error.get("code", "internal_error")
message = error.get("message", "")
# Request-stage error — not retryable, the request must be changed
if code in ("invalid_request", "model_not_supported", "model_price_error"):
raise Exception(f"Client error [{code}]: {message}")
# task_not_found — not retryable
if code == "task_not_found":
raise Exception(f"Task not found: {message}")
# Upstream 4xx content violation — not retryable (retrying yields the same result)
upstream_code = error.get("upstream", {}).get("code", "")
if code == "upstream_error" and upstream_code in (
"content_policy_violation", "invalid_image", "image_dimension_mismatch"
):
raise Exception(f"Upstream [{upstream_code}]: {message}")
# Upstream 5xx / storage / internal errors — retryable
if code in ("upstream_unavailable", "storage_error", "internal_error"):
if attempt < max_retries - 1:
time.sleep(2 ** attempt * 5) # 5s, 10s, 20s
continue
raise Exception(f"Retryable error [{code}]: {message}")
raise Exception(f"Error [{code}]: {message}")
# Task is still processing
time.sleep(3)
raise Exception("Max polling attempts exceeded")Retryable vs non-retryable#
| Non-retryable (fix the request) | Retryable (retry later) |
|---|---|
invalid_request — fix the parameters | upstream_unavailable — retry after waiting |
model_not_supported — switch models | storage_error — retry later |
upstream_error (content violation / image problems) — change the content or the image | internal_error — retry later |
task_not_found — check the ID | upstream_error (rate limit / resource exhaustion) — retry after slowing down |
When you hit an unclear error, keep the full task_id and error object and contact support so the issue can be traced.

