异步任务接口使用指南
概述
对于生成时长较长的任务(如 3D 建模、视频生成、长语音合成等),平台提供了专门的异步任务接口,让您能够高效地处理耗时操作而无需长时间等待响应。
接口架构
异步任务接口采用提交-查询模式:
- 提交接口:用于创建异步任务,例如文本生成音乐的提交接口为
/async/music/generations
- 查询接口:统一的任务状态查询接口
https://ai.gitee.com/api/v1/task/<task_id>
- 任务取消接口:
https://ai.gitee.com/api/v1/task/<task_id>/cancel
- 配额查询接口:
https://ai.gitee.com/v1/tasks/available-quota
- 任务状态接口:
https://ai.gitee.com/v1/task/<task_id>/status
- 任务记录接口:
https://ai.gitee.com/v1/task/<task_id>
工作流程
- 提交任务 → 获取
task_id
和查询 URL - 轮询查询 → 检查任务状态
- 获取结果 → 下载生成的文件
完整示例:音乐生成
以下示例演示如何使用 ACE-Step 音乐大模型生成音乐:
Python 实现
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)
主要参数说明
通用参数
model
: 使用的模型名称(如 "ACE-Step-v1-3.5B")
音乐生成专用参数
task
: 任务类型(如 "text2music")duration
: 生成时长(秒)prompt
: 音乐风格描述lyrics
: 歌词内容infer_steps
: 推理步数(影响质量和速度)guidance_scale
: 引导强度scheduler_type
: 调度器类型
错误处理
常见错误类型
-
认证错误 (401)
- 检查 API 令牌是否正确
- 确认令牌是否有效且未过期
-
参数错误 (400)
- 验证必填参数是否完整
- 检查参数格式是否正确
-
任务失败
- 查看返回的错误信息
- 调整参数重新尝试
最佳实践
- 合理设置轮询间隔:建议 5-10 秒,避免过于频繁的请求
- 实现超时机制:设置合理的最大等待时间
- 错误重试:对临时性错误实现指数退避重试
- 资源清理:及时处理下载的文件,避免占用过多磁盘空间
- 并发配额管理:提交任务前检查可用配额,避免超出限制
- 任务状态监控:定期检查任务状态,及时处理失败任务
- 合理使用取消功能:对于不再需要的任务及时取消,释放资源
配额管理示例
bash
# 查询可用配额
curl -H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/v1/tasks/available-quota
# 取消不需要的任务
curl -X POST \
-H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/api/v1/task/<task_id>/cancel
# 查询任务状态
curl -H "Authorization: Bearer <your_token>" \
https://ai.gitee.com/v1/task/<task_id>/status
常见问题
Q: 任务提交后多久能完成? A: 根据任务复杂度不同 ,通常在 1-10 分钟内完成。
Q: 是否可以取消正在进行的任务?
A: 支持任务取消。使用取消接口 https://ai.gitee.com/api/v1/task/<task_id>/cancel
可以取消 waiting 或 in_progress 状态的任务。
Q: 什么是并发配额限制? A: 每个账号的异步任务有并发配额限制,包括处于 waiting 和 in_progress 状态的任务总数。超过配额将无法提交新任务。
Q: 如何查询我的可用配额?
A: 使用配额查询接口 https://ai.gitee.com/v1/tasks/available-quota
可以查询当前可用的异步任务并发配额。
Q: 下载链接有效期多长? A: 下载链接通常有效期为 24 小时,请及时下载保存。
Q: 如何获取任务的详细信息?
A: 使用任务记录接口 https://ai.gitee.com/v1/task/<task_id>
可以获取任务的完整信息,包括参数、状态、结果等。
Q: 如何处理配额不足的情况? A: 可以通过以下方式处理:1) 等待现有任务完成;2) 取消不需要的任务;3) 实现任务队列管理机制。