Async Tasks
Learn how to use async mode for long-running API requests, query task progress, and retrieve results via task ID.
Try it in Playground
Workflow
Async mode is designed for long-running requests (e.g., image generation, video generation) to avoid HTTP connection timeouts.
1. Send request 2. Get task_id 3. Poll status 4. Get result
┌──────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────┐
│ POST ... │───→│ { id, status │───→│ GET /tasks/ │───→│ status = │
│ async: │ │ "queued" } │ │ {taskId} │ │"completed│
│ true │ └──────────────┘ └──────────────┘ └──────────┘
└──────────┘ ↑ every 3-5s
│ repeatSteps
- Send request — Add
"async": trueto the request body - Get task_id — API returns a task ID with initial status (
queued) - Poll status — Periodically query the task endpoint until status is
completedorfailed - Get result — Once completed, the response contains the generated result (e.g., image URL)
Supported Models
| Capability | Typical Duration | Default Mode | Notes |
|---|---|---|---|
| Image Generation | 10-30 seconds | Async | Most image models use async by default |
| Video Generation | 1-5 minutes | Async | Video generation requires async mode |
| Text Generation | 1-10 seconds | Sync | Usually uses sync or streaming mode |
INFO
Async support depends on the model's syncMode configuration. In the Playground, you can toggle async mode via the switch control.
Submit an Async Request
Add "async": true to the request body to enable async mode:
bash
curl https://open.dieyuyun.com/v1/images/generations \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A cat sitting on a windowsill",
"size": "1024x1024",
"async": true
}'python
import requests
response = requests.post(
"https://open.dieyuyun.com/v1/images/generations",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
json={
"model": "gpt-image-2",
"prompt": "A cat sitting on a windowsill",
"size": "1024x1024",
"async": True,
},
)
print(response.json())javascript
const response = await fetch('https://open.dieyuyun.com/v1/images/generations', {
method: 'POST',
headers: {
Authorization: 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-image-2',
prompt: 'A cat sitting on a windowsill',
size: '1024x1024',
async: true,
}),
})
const data = await response.json()
console.log(data)Async Response Format
json
{
"id": "task_abc123xyz",
"status": "queued",
"progress": 0,
"created_at": "2026-06-05T10:30:00Z",
"request_id": "req_def456"
}| Field | Type | Description |
|---|---|---|
| id | string | Unique task identifier for subsequent queries |
| status | string | Current status: queued / processing |
| progress | int | Progress percentage (0-100) |
| created_at | string | Task creation timestamp |
| request_id | string | Unique request identifier |
Query Task Status
Endpoint
| Item | Value |
|---|---|
| Method | GET |
| Path | /v1/tasks/{taskId} |
| Auth | Bearer Token |
bash
curl https://open.dieyuyun.com/v1/tasks/task_abc123xyz \
-H "Authorization: Bearer YOUR_API_KEY"python
import requests
response = requests.get(
"https://open.dieyuyun.com/v1/tasks/task_abc123xyz",
headers={"Authorization": "Bearer YOUR_API_KEY"},
)
task = response.json()
print(f"Status: {task['status']}, Progress: {task['progress']}%")javascript
const response = await fetch('https://open.dieyuyun.com/v1/tasks/task_abc123xyz', {
headers: { Authorization: 'Bearer YOUR_API_KEY' },
})
const task = await response.json()
console.log(`Status: ${task.status}, Progress: ${task.progress}%`)Response Format
Task in progress:
json
{
"id": "task_abc123xyz",
"status": "processing",
"progress": 60,
"model_code": "gpt-image-2",
"created_at": "2026-06-05T10:30:00Z",
"updated_at": "2026-06-05T10:30:15Z"
}Task completed:
json
{
"id": "task_abc123xyz",
"status": "completed",
"progress": 100,
"model_code": "gpt-image-2",
"result": {
"created": 1749116400,
"data": [
{
"url": "https://cdn.dieyuyun.com/images/xxx.png",
"revised_prompt": "A fluffy orange cat sitting on a sunlit windowsill..."
}
]
},
"usage": {
"input_tokens": 0,
"output_tokens": 1
},
"created_at": "2026-06-05T10:30:00Z",
"completed_at": "2026-06-05T10:30:25Z"
}Task failed:
json
{
"id": "task_abc123xyz",
"status": "failed",
"error_code": "upstream_error",
"error_message": "The upstream provider returned an error",
"created_at": "2026-06-05T10:30:00Z",
"failed_at": "2026-06-05T10:30:10Z"
}Cancel a Task
Endpoint
| Item | Value |
|---|---|
| Method | POST |
| Path | /v1/tasks/{taskId}/cancel |
| Auth | Bearer Token |
bash
curl -X POST https://open.dieyuyun.com/v1/tasks/task_abc123xyz/cancel \
-H "Authorization: Bearer YOUR_API_KEY"python
import requests
response = requests.post(
"https://open.dieyuyun.com/v1/tasks/task_abc123xyz/cancel",
headers={"Authorization": "Bearer YOUR_API_KEY"},
)
print(response.json())javascript
const response = await fetch('https://open.dieyuyun.com/v1/tasks/task_abc123xyz/cancel', {
method: 'POST',
headers: { Authorization: 'Bearer YOUR_API_KEY' },
})
console.log(await response.json())WARNING
Tasks can only be cancelled when in queued or processing status. Completed or failed tasks cannot be cancelled.
Task Status Reference
| Status | Description | Terminal |
|---|---|---|
queued | Task submitted, waiting to be processed | No |
processing | Task is being processed | No |
completed | Task finished successfully, result available | Yes |
failed | Task failed, check error details | Yes |
cancelled | Task was cancelled | Yes |
expired | Task expired (result cleaned up) | Yes |
Complete Polling Example
The following Python example demonstrates the complete async task polling workflow:
python
import time
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://open.dieyuyun.com"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
# 1. Submit async request
response = requests.post(
f"{BASE_URL}/v1/images/generations",
headers=HEADERS,
json={
"model": "gpt-image-2",
"prompt": "A beautiful sunset over the ocean",
"size": "1024x1024",
"async": True,
},
)
task = response.json()
task_id = task["id"]
print(f"Task submitted: {task_id}")
# 2. Poll task status
while True:
status_resp = requests.get(
f"{BASE_URL}/v1/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
)
task = status_resp.json()
status = task["status"]
progress = task.get("progress", 0)
print(f"Status: {status}, Progress: {progress}%")
if status == "completed":
print(f"Result: {task['result']}")
break
elif status in ("failed", "cancelled", "expired"):
print(f"Task ended with status: {status}")
if "error_message" in task:
print(f"Error: {task['error_message']}")
break
time.sleep(3) # Poll every 3 secondsBest Practices
- Reasonable polling interval — Poll every 3-5 seconds. Too frequent polling adds unnecessary load
- Set a timeout — Set a maximum wait time (e.g., 5 minutes) and alert or retry on timeout
- Handle terminal states — Ensure proper handling of
failed,cancelled, andexpiredstates - Use exponential backoff — If status hasn't changed after multiple polls, increase the interval
- Persist task_id — Store the
task_idso you can still query results after service restarts - Retrieve results promptly — Task results have an expiration time; download or store them as soon as they're ready
See Also
- Error Codes — Complete API error code reference
- Rate Limits — API rate limiting and quota management
- API Reference — General API documentation