Skip to content

Async Tasks

Learn how to use async mode for long-running API requests, query task progress, and retrieve results via task ID.

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
                                         │ repeat

Steps

  1. Send request — Add "async": true to the request body
  2. Get task_id — API returns a task ID with initial status (queued)
  3. Poll status — Periodically query the task endpoint until status is completed or failed
  4. Get result — Once completed, the response contains the generated result (e.g., image URL)

Supported Models

CapabilityTypical DurationDefault ModeNotes
Image Generation10-30 secondsAsyncMost image models use async by default
Video Generation1-5 minutesAsyncVideo generation requires async mode
Text Generation1-10 secondsSyncUsually 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"
}
FieldTypeDescription
idstringUnique task identifier for subsequent queries
statusstringCurrent status: queued / processing
progressintProgress percentage (0-100)
created_atstringTask creation timestamp
request_idstringUnique request identifier

Query Task Status

Endpoint

ItemValue
MethodGET
Path/v1/tasks/{taskId}
AuthBearer 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

ItemValue
MethodPOST
Path/v1/tasks/{taskId}/cancel
AuthBearer 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

StatusDescriptionTerminal
queuedTask submitted, waiting to be processedNo
processingTask is being processedNo
completedTask finished successfully, result availableYes
failedTask failed, check error detailsYes
cancelledTask was cancelledYes
expiredTask 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 seconds

Best Practices

  1. Reasonable polling interval — Poll every 3-5 seconds. Too frequent polling adds unnecessary load
  2. Set a timeout — Set a maximum wait time (e.g., 5 minutes) and alert or retry on timeout
  3. Handle terminal states — Ensure proper handling of failed, cancelled, and expired states
  4. Use exponential backoff — If status hasn't changed after multiple polls, increase the interval
  5. Persist task_id — Store the task_id so you can still query results after service restarts
  6. Retrieve results promptly — Task results have an expiration time; download or store them as soon as they're ready

See Also