Skip to content

异步图片生成

异步接口先提交任务再查询结果,适合大图、长耗时、或需要轮询状态的场景。

💡 和同步接口的区别

同步 /v1/images/generations异步 /async/images/generations
返回格式data URL(base64 内联)真实图片链接
超时容易超时(60s+)不会超时
适用场景快速调用大图、批量、需要状态跟踪

接口地址

POST https://foxapi.chat/async/images/generations    # 文生图(JSON)
POST https://foxapi.chat/async/images/edits          # 图片编辑(multipart/form-data)
GET  https://foxapi.chat/task/{task_id}              # 查询任务状态

⚠️ 格式区别

  • 文生图 /async/images/generations 使用 JSON(Content-Type: application/json)
  • 图片编辑 /async/images/edits 使用 multipart/form-data(因为要上传图片文件)

流程

1. POST /async/images/generations  →  返回 task_id
2. GET  /task/{task_id}            →  轮询直到 status=completed
3. 从 result.data[0].url 获取图片链接

文生图(异步)

curl

bash
# 1. 提交任务(JSON 格式)
curl https://foxapi.chat/async/images/generations \
  -H "Authorization: Bearer sk-你的Key" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-image-2","prompt":"一只橘猫在阳光下打盹","size":"1024x1024"}'

# 返回: {"status":"pending","task_id":"xxxx"}

# 2. 查询状态
curl https://foxapi.chat/task/xxxx

Python

python
import time
import requests

API_BASE = "https://foxapi.chat"
HEADERS = {"Authorization": "Bearer sk-你的Key"}

# 1. 提交任务(JSON)
resp = requests.post(
    f"{API_BASE}/async/images/generations",
    headers={**HEADERS, "Content-Type": "application/json"},
    json={
        "model": "gpt-image-2",
        "prompt": "一只橘猫在阳光下打盹",
        "size": "1024x1024",
    },
)
task = resp.json()
task_id = task["task_id"]
print(f"任务已提交: {task_id}")

# 2. 轮询结果
while True:
    time.sleep(5)
    result = requests.get(f"{API_BASE}/task/{task_id}", headers=HEADERS).json()
    status = result["status"]
    print(f"状态: {status}, 耗时: {result.get('elapsed', 0)}s")

    if status == "completed":
        url = result["result"]["data"][0]["url"]
        print(f"图片链接: {url}")
        break
    elif status == "failed":
        print(f"失败: {result.get('error', '未知错误')}")
        break

Node.js

javascript
const API_BASE = 'https://foxapi.chat';
const HEADERS = {
  Authorization: 'Bearer sk-你的Key',
  'Content-Type': 'application/json',
};

// 1. 提交任务(JSON)
const submitResp = await fetch(`${API_BASE}/async/images/generations`, {
  method: 'POST',
  headers: HEADERS,
  body: JSON.stringify({
    model: 'gpt-image-2',
    prompt: '一只橘猫在阳光下打盹',
    size: '1024x1024',
  }),
});
const { task_id } = await submitResp.json();
console.log(`任务已提交: ${task_id}`);

// 2. 轮询结果
while (true) {
  await new Promise(r => setTimeout(r, 5000));
  const result = await fetch(`${API_BASE}/task/${task_id}`, {
    headers: { Authorization: 'Bearer sk-你的Key' },
  }).then(r => r.json());

  console.log(`状态: ${result.status}, 耗时: ${result.elapsed}s`);

  if (result.status === 'completed') {
    console.log(`图片链接: ${result.result.data[0].url}`);
    break;
  } else if (result.status === 'failed') {
    console.log(`失败: ${result.error}`);
    break;
  }
}

PHP

php
<?php
$apiBase = 'https://foxapi.chat';
$apiKey  = 'sk-你的Key';

// 1. 提交任务(JSON)
$ch = curl_init("$apiBase/async/images/generations");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode([
        'model'  => 'gpt-image-2',
        'prompt' => '一只橘猫在阳光下打盹',
        'size'   => '1024x1024',
    ]),
    CURLOPT_HTTPHEADER     => [
        "Authorization: Bearer $apiKey",
        'Content-Type: application/json',
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
$submitResp = json_decode(curl_exec($ch), true);
curl_close($ch);

$taskId = $submitResp['task_id'];
echo "任务已提交: $taskId\n";

// 2. 轮询结果
while (true) {
    sleep(5);
    $ch = curl_init("$apiBase/task/$taskId");
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer $apiKey"],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $result = json_decode(curl_exec($ch), true);
    curl_close($ch);

    echo "状态: {$result['status']}, 耗时: {$result['elapsed']}s\n";

    if ($result['status'] === 'completed') {
        $url = $result['result']['data'][0]['url'];
        echo "图片链接: $url\n";
        file_put_contents('output.png', file_get_contents($url));
        break;
    } elseif ($result['status'] === 'failed') {
        echo "失败: {$result['error']}\n";
        break;
    }
}

图片编辑(异步)

图片编辑使用 multipart/form-data(需要上传图片文件):

bash
# 提交编辑任务
curl https://foxapi.chat/async/images/edits \
  -H "Authorization: Bearer sk-你的Key" \
  -F "model=gpt-image-2" \
  -F "image=@/path/to/reference.png" \
  -F "prompt=把背景改成海边日落"

# 查询结果
curl https://foxapi.chat/task/{task_id}
php
<?php
// PHP 异步编辑(form-data)
$ch = curl_init('https://foxapi.chat/async/images/edits');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => [
        'model'  => 'gpt-image-2',
        'image'  => new CURLFile('/path/to/reference.png'),
        'prompt' => '把背景改成海边日落',
    ],
    CURLOPT_HTTPHEADER     => ["Authorization: Bearer $apiKey"],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
$submitResp = json_decode(curl_exec($ch), true);
curl_close($ch);

$taskId = $submitResp['task_id'];
// 后续轮询同上...

返回格式

提交任务

json
{
  "status": "pending",
  "task_id": "461280aa-c42"
}

查询状态(处理中)

json
{
  "status": "processing",
  "elapsed": 0,
  "task_id": "461280aa-c42"
}

查询状态(完成)

json
{
  "status": "completed",
  "elapsed": 74.1,
  "task_id": "461280aa-c42",
  "result": {
    "data": [
      {
        "url": "https://foxapi.chat/img-cache/xxxx.png",
        "revised_prompt": "..."
      }
    ]
  }
}

查询状态(失败)

json
{
  "status": "failed",
  "elapsed": 10.5,
  "task_id": "461280aa-c42",
  "error": "生成失败的原因"
}

状态说明

status说明
pending任务已提交,等待处理
processing正在生成中
completed生成完成,可从 result.data 获取图片
failed生成失败,查看 error 字段

轮询建议

  • 间隔 5 秒 — 不要太频繁,正常生图需要 30-90 秒
  • 超时 5 分钟 — 超过 5 分钟未完成可以认为失败
  • 任务 ID 有效期 — 完成后的任务结果会保留一段时间,但不保证永久保存

常见问题

返回"无效的请求格式"

文生图接口 /async/images/generations 需要 JSON 格式,不是 form-data。确保请求头包含 Content-Type: application/json,body 是 JSON 字符串。

task_id 不存在

任务 ID 过期或无效,需要重新提交。

一直 processing

生图通常需要 30-90 秒,偶尔可能更长。如果超过 5 分钟还是 processing,可以重新提交。

图片链接打不开

异步接口返回的是 https://foxapi.chat/img-cache/... 格式的链接,可以直接在浏览器打开。如果打不开,可能是图片已过期,重新生成即可。

© 2026 FoxAPI. All rights reserved.