Images Task 图片任务查询
用于查询图片生成任务的执行状态。由于图片生成采用异步模式,客户端提交生成请求后会获得一个 task_id,需要通过本接口轮询查询,直到任务完成并获取最终图片 URL。
接口地址
GET /api/openai/imagesTask?id={task_id}
请求头 Headers
| 名称 | 是否必须 | 说明 |
|---|
| Authorization | 是 | Bearer API_KEY |
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|
| id | int | 是 | 任务 ID,由 Images Generations 接口返回的 task_id |
请求示例
GET /api/openai/imagesTask?id=15
Authorization: Bearer sk-xxxxxxxx
任务进行中
{
"code": 200,
"msg": "success",
"data": {
"task_id": 15,
"status": "pending"
}
}
{
"code": 200,
"msg": "success",
"data": {
"task_id": 15,
"status": "running"
}
}
任务成功
{
"code": 200,
"msg": "success",
"data": {
"task_id": 15,
"status": "success",
"url": "https://cdn.example.com/images/20260813/xxxx.png",
"quantity": 1,
"cost": 0.40
}
}
任务失败
{
"code": 500,
"msg": "Image generate failed",
"data": {
"task_id": 15,
"status": "failed"
}
}
状态码说明
| 状态 | 说明 | 客户端行为 |
|---|
| pending | 任务已创建,等待执行 | 继续轮询 |
| running | 图片正在生成中 | 继续轮询 |
| success | 生成成功,返回图片 URL | 停止轮询,展示图片 |
| failed | 生成失败 | 停止轮询,提示错误 |
JavaScript 轮询示例
const taskId = 15;
const timer = setInterval(async () => {
try {
const res = await fetch(
`/api/openai/imagesTask?id=${taskId}`,
{
headers: {
Authorization: "Bearer sk-xxxxxxxx",
},
}
);
const result = await res.json();
if (result.code === 200) {
const { status, url, cost } = result.data;
if (status === "success") {
clearInterval(timer);
console.log("图片地址:", url);
console.log("本次消耗:", cost, "元");
displayImage(url);
} else if (status === "failed") {
clearInterval(timer);
console.error("生成失败");
}
} else {
clearInterval(timer);
console.error("查询失败:", result.msg);
}
} catch (err) {
console.error("网络错误:", err);
}
}, 2500);
function displayImage(url) {
const img = document.createElement("img");
img.src = url;
document.body.appendChild(img);
}
建议轮询间隔为 2~3 秒,任务成功或失败后应立即停止轮询,避免不必要的资源消耗。图片生成通常需要 10~60 秒,具体取决于模型复杂度和服务器负载。
完整流程
步骤 1:创建图片生成任务
POST /api/openai/imagesGenerations
{ "model": "wanx2.1-t2i-turbo", "prompt": "..." }
↓
步骤 2:返回任务 ID
{ "code": 200, "data": { "task_id": 15, "status": "pending" } }
↓
步骤 3:轮询任务状态(每 2~3 秒)
GET /api/openai/imagesTask?id=15
↓
running ← 继续轮询
running ← 继续轮询
↓
步骤 4:任务成功
{ "code": 200, "data": { "status": "success", "url": "https://...", "cost": 0.40 } }
↓
步骤 5:获取图片 URL,展示给用户
错误码
| code | 说明 |
|---|
| 400 | 参数错误(如 id 参数缺失或格式错误) |
| 401 | API Key 无效或已过期 |
| 404 | 任务不存在(task_id 无效或已过期) |
| 500 | 图片生成服务内部错误 |
错误返回示例
{ "code": 400, "msg": "Parameter id is required" }
{ "code": 401, "msg": "Invalid API Key" }
{ "code": 404, "msg": "Task not found" }
{ "code": 500, "msg": "Image generate failed" }
注意事项
- task_id 有效期为 24 小时,过期后无法查询
- 建议轮询间隔 2~3 秒,避免过于频繁的请求
- 任务失败不会退还已扣费用,但会退还预扣的余额
- 成功返回的 url 为 CDN 地址,有效期为 7 天