Skip to main content

Guide to Asynchronous Task API

Overview

For tasks with long generation times (such as 3D modeling, video generation, long audio synthesis, etc.), the platform provides a dedicated asynchronous task API, enabling you to efficiently handle time-consuming operations without waiting for a response for an extended period.

API Architecture

The asynchronous task API adopts a submit-query model:

  • Submission API: Used to create asynchronous tasks. For example, the submission API for text-to-music generation is /async/music/generations
  • Query API: Unified task status query API https://ai.gitee.com/api/v1/task/<task_id>
  • Task Cancellation API: https://ai.gitee.com/api/v1/task/<task_id>/cancel
  • Quota Query API: https://ai.gitee.com/v1/tasks/available-quota
  • Task Status API: https://ai.gitee.com/v1/task/<task_id>/status
  • Task Record API: https://ai.gitee.com/v1/task/<task_id>

Workflow

  1. Submit Task → Get task_id and query URL
  2. Poll Query → Check task status
  3. Get Results → Download generated files

Complete Example: Music Generation

The following example demonstrates how to generate music using the ACE-Step music large model:

Python Implementation

python
import os
import requests
import base64
from PIL import Image
from io import BytesIO
from requests_toolbelt.multipart.encoder import MultipartEncoder

API_URL = "https://ai.gitee.com/v1/async/music/generations"
headers = {
"Authorization": "Bearer <your token>",
}

def query(payload):
data = {}
for key, value in payload.items():
if value is None:
data[key] = ""
elif isinstance(value, list):
data[key] = ",".join(map(str, value))
elif isinstance(value, bool):
data[key] = str(value).lower()
else:
data[key] = str(value)
multipart_data = MultipartEncoder(fields=data)
headers["Content-Type"] = multipart_data.content_type
response = requests.post(API_URL, headers=headers, data=multipart_data)
return response.json()

output = query({
"model": "ACE-Step-v1-3.5B",
"task": "text2music",
"duration": 60,
"prompt": "pop, synth, drums, guitar, 120 bpm, upbeat, catchy, vibrant, female vocals, polished vocals",
"lyrics": """[Verse]
Neon lights across the sky
Every moment passing by
Your smile catches in my mind
Like a snapshot frozen time
[Chorus]
We're dancing through the night
Under these electric lights
Don't need to think about tomorrow
Just feel this moment right
[Verse]
City pulse beneath our feet
Hearts aligned to steady beat
Take my hand and follow me
Into who we're meant to be
[Bridge]
One life, one chance
One perfect night romance
Our story's just beginning
In this magical dance""",
"infer_steps": 60,
"lora_name": 'None',
"guidance_scale": 15,
"guidance_scale_text": 0,
"guidance_scale_lyric": 0,
"scheduler_type": "euler",
"cfg_type": "apg",
"omega_scale": 10,
"guidance_interval": 0.5,
"guidance_interval_decay": 0,
"min_guidance_scale": 3,
"use_erg_tag": True,
"use_erg_lyric": True,
"use_erg_diffusion": True,
})
query_url = output["urls"]["get"]

while True:
resp = requests.get(query_url, headers=headers).json()
print("task status: ", resp["status"])
if resp["status"] == "failure":
print(resp)
print("task failed")
os._exit(1)
if resp["status"] == "success":
break

file_url = resp["output"]["file_url"]
print('final url ', file_url)
resp = requests.get(file_url)

with open("output.mp3", "wb") as f:
f.write(resp.content)

Key Parameter Explanations

General Parameters

  • model: Name of the model used (e.g., "ACE-Step-v1-3.5B")

Music Generation Parameters

  • task: Task type (e.g., "text2music")
  • duration: Generation duration (seconds)
  • prompt: Music style description
  • lyrics: Lyrics content
  • infer_steps: Inference steps (affects quality and speed)
  • guidance_scale: Guidance strength
  • scheduler_type: Scheduler type

Error Handling

Common Error Types

  1. Authentication Error (401)

    • Check if the API token is correct
    • Confirm that the token is valid and not expired
  2. Parameter Error (400)

    • Verify that all required parameters are complete
    • Check if the parameter format is correct
  3. Task Failure

    • Check the error message returned
    • Adjust parameters and try again

Best Practices

  1. Reasonable Polling Interval: Suggested 5-10 seconds, avoid too frequent requests
  2. Implement Timeout Mechanism: Set a reasonable maximum waiting time
  3. Error Retry: Implement exponential backoff retry for temporary errors
  4. Resource Cleanup: Handle downloaded files promptly to avoid disk space exhaustion
  5. Concurrent Quota Management: Check available quota before submitting tasks to avoid exceeding limits
  6. Task Status Monitoring: Regularly check task status, handle failed tasks promptly
  7. Reasonable Use of Cancellation: Cancel tasks that are no longer needed to release resources

Quota Management Example

bash
# Query available quota
curl -H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/v1/tasks/available-quota

# Cancel unnecessary tasks
curl -X POST \
-H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/api/v1/task/<task_id>/cancel

# Query task status
curl -H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/v1/task/<task_id>/status

Frequently Asked Questions

Q: How long does it take for a task to complete after submission? A: Depending on the task complexity, it usually completes within 1-10 minutes.

Q: Can I cancel a task that is currently running? A: Task cancellation is supported. You can cancel tasks in waiting or in_progress status using the cancellation API https://ai.gitee.com/api/v1/task/<task_id>/cancel.

Q: What is the concurrent quota limit? A: Each account has a concurrent quota limit for asynchronous tasks, including the total number of tasks in waiting and in_progress states. Exceeding the quota will prevent new tasks from being submitted.

Q: How can I query my available quota? A: You can query your available quota using the quota query API https://ai.gitee.com/v1/tasks/available-quota.

Q: How long is the download link valid for? A: Download links are typically valid for 24 hours. Please download and save them promptly.

Q: How do I get detailed information about a task? A: You can get detailed information about a task using the task record API https://ai.gitee.com/v1/task/<task_id>.

Q: How to handle insufficient quota? A: You can handle quota insufficient situations in the following ways: 1) Wait for existing tasks to complete; 2) Cancel unnecessary tasks; 3) Implement task queue management mechanisms.