跳转到正文
阅读设置
GPT Image

gpt-image-2.6-flare API 开发文档 ​

版本 1.0 · 更新于 2026-11-11

1. 模型与接口概览 ​

请求中的 model 固定为 gpt-image-2.6-flare。支持 1K、2K、4K 文生图和参考图生成,可选择输出质量与 PNG 或 GIF 格式。提交后保存 task_id,再查询状态和产物。

项目说明
模型标识gpt-image-2.6-flare
输出类型图片
输入场景文本、单图参考、多图参考
计费方式按次计费
方法路径成功状态码
POST/api/v1/platform/images/generations202
GET/api/v1/platform/tasks/{task_id}200

模型可用状态、权限、售价和配额以控制台为准。

2. 鉴权与环境配置 ​

请求头是否必填说明
Authorization是使用平台密钥,格式为 Bearer <API_KEY>。
Content-TypePOST 必填application/json
Accept-Language否zh-CN、zh-Hant、en,默认简体中文。

API Key 应保存在服务端环境中。调用前确认账号状态、模型权限、来源 IP、余额和 Key 配额满足要求。

将 API_BASE_URL 设为实际 API 服务根地址。示例已包含完整接口路径。

在 Bash 中设置环境变量。

bash
export API_BASE_URL=""
export API_KEY=""

在 PowerShell 中设置环境变量。

powershell
$env:API_BASE_URL = ""
$env:API_KEY = ""

3. 创建生成任务 ​

POST /api/v1/platform/images/generations

正文使用单个 JSON 对象,参数直接放在顶层。

参数JSON 类型必填说明
modelstring是固定为 gpt-image-2.6-flare
promptstring是非空生成提示词
resolutionstring是输出分辨率档位,支持 1K、2K、4K。
ratiostring是输出宽高比,允许值见下节。
qualitystring否图片质量。auto 自动、low 低、medium 中、high 高。
output_formatstring否输出格式。png PNG 位图、gif GIF 图片。
imagesarray<object>否有序参考图片,元素为 url + role 对象
audios、videosarray<object>否调用本型号时省略。非空数组会触发参数校验错误。

请求正文为最多 65535 字节的顶层 JSON 对象。接口拒绝未知字段、重复 JSON 键和非有限数值。省略 quality 或 output_format 时,平台将该项保持为未传。

已声明字段的 null、空字符串、纯空白和忽略大小写的字符串 null 按未传处理。必填项按缺失处理,0、false、空数组和空对象按字段规则校验。

4. 模型规格与素材要求 ​

参数必填允许值
resolution是1K、2K、4K
ratio是1:1、16:9、9:16、4:3、3:4、3:2、2:3、5:4、4:5、21:9、9:21、1:2、2:1
quality否auto、low、medium、high
output_format否png、gif

省略 images 或传空数组时为文生图,传入一张或多张图时为参考生成。数组顺序会保留,参考图的 role 固定为 reference。

当前公开规格未声明固定参考图数量上限,仍需满足实际模型服务的素材限制与请求正文容量约束。

参数值区分大小写。ratio 使用宽高比字符串,resolution 使用档位字符串。

参考素材对象 ​

字段JSON 类型必填说明
urlstring是可公开读取的 HTTP/HTTPS 文件 URL,建议 HTTPS
rolestring是固定为 reference,表示参考素材

使用模型服务可直接读取的公网文件 URL。签名 URL 的有效期应覆盖排队和素材读取过程。调用时将示例的 example.com 地址换为实际素材地址。

5. 快速开始 ​

以下 cURL 使用 Bash 语法。

bash
curl --request POST "${API_BASE_URL}/api/v1/platform/images/generations" \
  --header "Authorization: Bearer ${API_KEY}" \
  --header "Content-Type: application/json" \
  --header "Accept-Language: zh-CN" \
  --data-raw '{
  "model": "gpt-image-2.6-flare",
  "prompt": "Create a small orange cat on a clean white background with soft studio lighting.",
  "resolution": "2K",
  "ratio": "1:1",
  "quality": "medium",
  "output_format": "png"
}'

受理成功返回 HTTP 202,响应示例如下。

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "gpt-image-2.6-flare",
  "modality": "image",
  "status": "queued",
  "artifacts": [],
  "failure_code": null,
  "failure_reason": null,
  "created_at": "2026-11-11 10:00:00",
  "updated_at": "2026-11-11 10:00:00"
}

HTTP 202 表示平台已受理任务。请保存 task_id,后续使用同一把 API Key 查询。

6. 生成场景示例 ​

纯文本生成 ​

json
{
  "model": "gpt-image-2.6-flare",
  "prompt": "Create a small orange cat on a clean white background with soft studio lighting.",
  "resolution": "2K",
  "ratio": "1:1",
  "quality": "medium",
  "output_format": "png"
}

单图参考 ​

json
{
  "model": "gpt-image-2.6-flare",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "2K",
  "ratio": "1:1",
  "quality": "medium",
  "output_format": "png",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    }
  ]
}

多图参考 ​

json
{
  "model": "gpt-image-2.6-flare",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "2K",
  "ratio": "1:1",
  "quality": "medium",
  "output_format": "png",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

images 的元素顺序会保留。

7. 任务响应结构 ​

提交与查询使用同一个顶层对象,不包含 data 包装或 code/msg 信封,也不是SSE流式响应。

字段JSON类型说明
task_idstring平台小写UUID
modelstringgpt-image-2.6-flare
modalitystringimage
statusstringqueued, running, succeeded, failed
artifactsarray<object>完整已交付产物列表。交付前或失败时为空数组。
failure_codestring / null确认失败的稳定代码
failure_reasonstring / null按本次请求语言返回的安全原因
created_at, updated_atstringYYYY-MM-DD HH:mm:ss,字段不含时区偏移

artifacts[] 字段 ​

字段JSON类型说明
artifact_typestring本型号返回 image。
urlstring平台完成交付的资源地址
mime_typestring / null可取得时返回实际MIME
size_bytesinteger / null实际字节数
width, heightinteger / null已知时返回实际像素尺寸
duration_secondsstring / null实际产物时长,单位为秒。有值时为十进制字符串。

output_format 与产物 MIME 的对应关系为 png 对应 image/png、gif 对应 image/gif。

完成交付示例 ​

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "gpt-image-2.6-flare",
  "modality": "image",
  "status": "succeeded",
  "artifacts": [
    {
      "artifact_type": "image",
      "url": "https://example.com/outputs/result.png",
      "mime_type": "image/png",
      "size_bytes": 2073482,
      "width": null,
      "height": null,
      "duration_seconds": null
    }
  ],
  "failure_code": null,
  "failure_reason": null,
  "created_at": "2026-11-11 10:00:00",
  "updated_at": "2026-11-11 10:01:00"
}

可选元数据允许为空。duration_seconds 有值时为十进制字符串。下载产物时,使用响应中的 url,无需附带平台 API Key。

8. 查询任务与状态说明 ​

将提交返回的 task_id 填入 TASK_ID 后查询。

bash
curl --request GET "${API_BASE_URL}/api/v1/platform/tasks/${TASK_ID}" \
  --header "Authorization: Bearer ${API_KEY}" \
  --header "Accept-Language: zh-CN"

GET /api/v1/platform/tasks/{task_id}

路径参数为提交返回的小写 UUID。使用创建任务的同一把 API Key 查询。任务不存在或当前 Key 无权读取时返回 HTTP 404。

status含义客户端处理
queued排队等待提交等待后继续查询
running生成、交付或恢复中,也可能是提交结果尚待确认等待后继续查询,不重复提交
succeeded全部产物完成平台交付停止轮询,读取 artifacts
failed已确认失败停止轮询,读取 failure_code 与 failure_reason

建议每 3 秒查询一次,对等待设置上限。failed 任务的查询仍返回 HTTP 200,客户端应按 status 判断结果。客户端等待超时后可保存 task_id,稍后恢复查询。

9. HTTP 错误与任务失败 ​

HTTP 错误结构 ​

json
{
  "error": {
    "message": "参数 resolution 为必填项",
    "type": "invalid_request_error",
    "code": "invalid_request"
  }
}
HTTPerror.code说明
400invalid_request请求格式或规格错误,或者模型已下架。
401unauthorizedAPI Key 缺失、非法、已停用或已过期。
403access_denied用户、IP、模型权限、余额或 API Key 配额不允许。
404task_not_found任务不存在,或不属于当前用户及创建任务的 API Key。
405invalid_requestHTTP 方法不支持。
413invalid_request原始 JSON 正文超过65535字节。
429rate_limited触发身份限流、RPM 或并发限制。
500generation_configuration_invalid / internal_error配置不可用或平台内部异常。
502upstream_error上游服务错误。已受理任务的异步失败通过任务状态体现。
503no_available_channel / service_unavailable模型维护、没有可用渠道或基础依赖暂不可用。

error.message 为本地化文案,error.type 和 error.code 是稳定标识。参数校验返回 HTTP 400,包括不支持的 quality 或 output_format 值。

异步任务失败 ​

如果任务在受理后失败,查询结果会显示 failed,并提供失败代码和原因。

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "gpt-image-2.6-flare",
  "modality": "image",
  "status": "failed",
  "artifacts": [],
  "failure_code": "upstream_rejected",
  "failure_reason": "生成任务失败,请稍后重试。",
  "created_at": "2026-11-11 10:00:00",
  "updated_at": "2026-11-11 10:01:00"
}

failure_code 表示已确认失败的原因,failure_reason 按本次请求语言返回。非失败状态的失败字段为空。

10. Python 完整调用示例 ​

使用 Python 3.11+ 和 httpx。

bash
python -m pip install httpx

配置 API_BASE_URL 与 API_KEY 后运行。参数值应满足本型号的分辨率、比例和素材要求。

python
import json
import os
import random
import time

import httpx

BASE_URL = os.getenv("API_BASE_URL", "").rstrip("/")
API_KEY = os.getenv("API_KEY", "")
PAYLOAD = {
    "model": "gpt-image-2.6-flare",
    "prompt": "Create a small orange cat on a clean white background with soft studio lighting.",
    "resolution": "2K",
    "ratio": "1:1",
    "quality": "medium",
    "output_format": "png"
}
MAX_WAIT_SECONDS = 1800  # 客户端等待预算,不是服务完成时限。


def main():
    if not BASE_URL or not API_KEY:
        raise RuntimeError("请配置 API_BASE_URL 和 API_KEY。")
    deadline = time.monotonic() + MAX_WAIT_SECONDS
    with httpx.Client(follow_redirects=False) as client:
        def request_json(method, path, content=None):
            attempts = 3 if method == "GET" else 1
            for attempt in range(attempts):
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise TimeoutError("客户端等待结束;任务不会因此被取消。")
                headers = {"Authorization": f"Bearer {API_KEY}",
                           "Accept-Language": "zh-CN"}
                if content is not None:
                    headers["Content-Type"] = "application/json"
                try:
                    response = client.request(method, BASE_URL + path,
                        headers=headers, content=content,
                        timeout=min(30.0, remaining))
                except httpx.TransportError:
                    if method == "POST":
                        raise RuntimeError("提交结果不确定,请勿自动重新提交。") from None
                    if attempt == attempts - 1:
                        raise RuntimeError("查询暂时失败,请保留任务 ID 稍后查询。") from None
                else:
                    if response.status_code == (202 if method == "POST" else 200):
                        try:
                            return response.json()
                        except ValueError:
                            raise RuntimeError("响应无法解析;提交请求请勿自动重发,"
                                               "已有任务 ID 时继续查询。") from None
                    if (method != "GET" or response.status_code not in (429, 500, 502, 503)
                            or attempt == attempts - 1):
                        try:
                            error = response.json().get("error", {})
                        except ValueError:
                            error = {}
                        raise RuntimeError(f"HTTP {response.status_code}; "
                                           f"code={error.get('code')}; "
                                           f"message={error.get('message')}")
                time.sleep(min(2 ** attempt + random.random(),
                               max(0, deadline - time.monotonic())))
            raise RuntimeError("查询重试次数已用完,请保留任务 ID。")

        # 已有任务时,设置 TASK_ID 即可恢复查询,不再创建新任务。
        existing_task_id = os.getenv("TASK_ID", "").strip()
        if existing_task_id:
            task = request_json("GET", f"/api/v1/platform/tasks/{existing_task_id}")
        else:
            body = json.dumps(PAYLOAD, ensure_ascii=False,
                              allow_nan=False).encode("utf-8")
            task = request_json("POST", "/api/v1/platform/images/generations", body)
        task_id = task["task_id"]
        print("task_id:", task_id, flush=True)  # 立即保存到业务记录中。
        while True:
            status = task["status"]
            if status == "succeeded":
                for artifact in task["artifacts"]:
                    print(artifact["artifact_type"], artifact["url"])
                return
            if status == "failed":
                raise RuntimeError(f"{task_id}: {task['failure_code']}; "
                                   f"{task['failure_reason']}")
            if status not in ("queued", "running"):
                raise RuntimeError(f"未知任务状态:{status}")
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(f"任务 {task_id} 尚未完成,请稍后继续查询。")
            time.sleep(min(3.0, remaining))
            task = request_json("GET", f"/api/v1/platform/tasks/{task_id}")


if __name__ == "__main__":
    main()

11. JavaScript 完整调用示例 ​

使用 Node.js 18+ 的内置 fetch,将代码保存为 .mjs 在服务端运行。环境变量与 Python 示例相同。

javascript
import { setTimeout as sleep } from "node:timers/promises";

const baseUrl = (process.env.API_BASE_URL || "").replace(/\/+$/, "");
const apiKey = process.env.API_KEY || "";
if (!baseUrl || !apiKey) throw new Error("请配置 API_BASE_URL 和 API_KEY。");
const payload = {
  model: "gpt-image-2.6-flare",
  prompt:
    "Create a small orange cat on a clean white background with soft studio lighting.",
  resolution: "2K",
  ratio: "1:1",
  quality: "medium",
  output_format: "png",
};
const deadline = Date.now() + 1800 * 1000; // 客户端等待预算,不是服务完成时限。

async function requestJson(method, path, requestBody) {
  const attempts = method === "GET" ? 3 : 1;
  for (let attempt = 0; attempt < attempts; attempt++) {
    const remaining = deadline - Date.now();
    if (remaining <= 0) throw new Error("客户端等待结束;任务不会因此被取消。");
    const headers = {
      Authorization: `Bearer ${apiKey}`,
      "Accept-Language": "zh-CN",
    };
    if (requestBody !== undefined) headers["Content-Type"] = "application/json";
    let response;
    try {
      response = await fetch(baseUrl + path, {
        method,
        headers,
        body: requestBody,
        redirect: "error",
        signal: AbortSignal.timeout(Math.max(1, Math.min(30000, remaining))),
      });
    } catch {
      if (method === "POST")
        throw new Error("提交结果不确定,请勿自动重新提交。");
      if (attempt === attempts - 1)
        throw new Error("查询暂时失败,请保留任务 ID 稍后查询。");
    }
    if (response) {
      if (response.status === (method === "POST" ? 202 : 200)) {
        try {
          return await response.json();
        } catch {
          throw new Error(
            "响应无法解析;提交请求请勿自动重发,已有任务 ID 时继续查询。",
          );
        }
      }
      if (
        method !== "GET" ||
        ![429, 500, 502, 503].includes(response.status) ||
        attempt === attempts - 1
      ) {
        const data = await response.json().catch(() => ({}));
        throw new Error(
          `HTTP ${response.status}; code=${data.error?.code}; ` +
            `message=${data.error?.message}`,
        );
      }
    }
    await sleep(
      Math.min(
        1000 * (2 ** attempt + Math.random()),
        Math.max(0, deadline - Date.now()),
      ),
    );
  }
  throw new Error("查询重试次数已用完,请保留任务 ID。");
}

// 已有任务时,设置 TASK_ID 即可恢复查询,不再创建新任务。
const existingTaskId = (process.env.TASK_ID || "").trim();
let task = existingTaskId
  ? await requestJson("GET", `/api/v1/platform/tasks/${existingTaskId}`)
  : await requestJson(
      "POST",
      "/api/v1/platform/images/generations",
      JSON.stringify(payload),
    );
const taskId = task.task_id;
console.log("task_id:", taskId); // 立即保存到业务记录中。
while (["queued", "running"].includes(task.status)) {
  const remaining = deadline - Date.now();
  if (remaining <= 0)
    throw new Error(`任务 ${taskId} 尚未完成,请稍后继续查询。`);
  await sleep(Math.min(3000, remaining));
  task = await requestJson("GET", `/api/v1/platform/tasks/${taskId}`);
}
if (task.status === "failed") {
  throw new Error(`${taskId}: ${task.failure_code}; ${task.failure_reason}`);
}
if (task.status !== "succeeded")
  throw new Error(`未知任务状态:${task.status}`);
for (const artifact of task.artifacts)
  console.log(artifact.artifact_type, artifact.url);

12. 常见问题 ​

现象检查方向
任务长期 running可能仍在生成、交付或确认提交结果。保留任务 ID 联系支持。
换Key查询404只能使用创建任务的API Key查询。
参考素材处理失败检查公网可读性、有效期、文件有效性、角色、顺序和模型限制。
元数据为空未知可选元数据保持为空,不从请求宽高或时长推断。
JSON合法仍400/503检查模型拼写,以及是否下架、维护或当前不可用。

13. 接口兼容与版本说明 ​

接口使用平台异步协议。SDK 封装应处理 HTTP 202、任务轮询以及本文所列的响应结构。