跳转到正文
阅读设置
生图

图片生成 API 开发文档 ​

版本:1.1 · 更新日期:2026-11-05

按模型查看最新文档

从左侧「生图 → GPT Image / Nano Banana」选择型号,或点击下表中的模型标识,查看该型号的参数和完整调用示例。

1. 接口概览与支持模型 ​

本文介绍平台统一图片生成接口。通过 model 选择模型,提交后获取 task_id,再查询生成状态及产物。

model支持的输入场景计费方式
nano-banana-2.1文本、单图参考、多图参考按次计费
nano-banana-2文本、单图参考、多图参考按次计费
gpt-image-2.6文本、单图参考、多图参考按次计费
gpt-image-2.6-flare文本、单图参考、多图参考按次计费
gpt-image-2.6-sunburst文本、单图参考、多图参考按次计费
gpt-image-2.5文本、单图参考、多图参考按次计费
gpt-image-2文本、单图参考、多图参考按次计费
方法路径成功状态码
POST/api/v1/platform/images/generations202
GET/api/v1/platform/tasks/{task_id}200

模型可用状态、权限和当前售价以控制台为准。本文范围仅包含上表列出的模型。

2. 鉴权与环境配置 ​

请求头是否必填说明
Authorization是Bearer <API_KEY>;使用平台 API Key
Content-TypePOST 必填application/json
Accept-Language否zh-CN、zh-Hant、en;默认简体中文,按首个语言标签协商

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

示例的 API_BASE_URL 特意留空,填写实际服务根地址即可;接口路径已包含 /api/v1/platform,不要重复添加。

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是模型标识,允许值见支持模型表
promptstring是非空生成提示词
resolutionstring是分辨率档位,必须符合所选模型的允许值
ratiostring依模型输出宽高比,必填性和允许值见模型规格
qualitystring否GPT Image 2.6 系列的输出质量,允许值见各型号文档
output_formatstring否GPT Image 2.6 系列的输出格式,允许值见各型号文档
imagesarray<object>否有序参考图片,元素为 url + role 对象
audios、videosarray<object>否保留字段;当前所列模型均不支持非空数组,调用时省略

原始请求正文最多 65535 字节。不增加 data 或 body 包装;未知字段、重复 JSON 键以及非有限数值会被拒绝。未传参数保持未传,平台不补生成默认值。

已声明字段的 null、空字符串、纯空白或忽略大小写的字符串 null 按未传处理:必填项仍会报缺失,可选项保持未传。0、false、空数组和空对象继续按原字段约束校验。

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

modelresolution(必填)ratio 是否必填比例列表
nano-banana-2.11K、2K、4K否A
nano-banana-21K、2K、4K否A
gpt-image-2.61K是B
gpt-image-2.6-flare1K、2K、4K是B
gpt-image-2.6-sunburst1K、2K、4K是B
gpt-image-2.51K是B
gpt-image-21K是B

比例列表 A: 1:1、16:9、9:16、4:3、3:4、3:2、2:3、5:4、4:5、21:9、1:4、4:1、1:8、8:1。

比例列表 B: 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。

上表中的模型都支持文本生成、单图参考和多图参考。不传 images 或传空数组时为文生图;传入一张或多张图片时为参考生成。参考图数组顺序会保留;角色仅支持 reference,不支持首尾帧。参考图片数量支持单张及多张,当前公开规格未声明固定数量上限,仍需满足实际模型服务的素材限制与请求正文容量约束。

参数值区分大小写。ratio 是宽高比,不是像素尺寸;不提交 width、height 或厂商尺寸字段。Nano 系列省略 ratio 时平台不会代为选择默认比例。GPT Image 系列必须同时填写 resolution 与 ratio。

参考素材对象 ​

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

素材服务应允许模型服务直接读取,不依赖浏览器登录态;签名 URL 的有效期应覆盖排队和素材读取过程。不接收 Base64、数据 URI、本地路径、表单文件或内联二进制。文中 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": "nano-banana-2.1",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}'

受理成功返回 HTTP 202:

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

202 表示请求已被本地受理,生成仍可能排队或执行中。立即保存返回的 task_id,后续使用同一把 API Key 查询。不要将 HTTP 202 当作生成完成。

6. 各模型与业务场景示例 ​

nano-banana-2.1:纯文本生成 ​

json
{
  "model": "nano-banana-2.1",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K"
}

nano-banana-2.1:多图参考 ​

json
{
  "model": "nano-banana-2.1",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

nano-banana-2:纯文本生成 ​

json
{
  "model": "nano-banana-2",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K"
}

nano-banana-2:多图参考 ​

json
{
  "model": "nano-banana-2",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

gpt-image-2.5:纯文本生成 ​

json
{
  "model": "gpt-image-2.5",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}

gpt-image-2.5:多图参考 ​

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

gpt-image-2:纯文本生成 ​

json
{
  "model": "gpt-image-2",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}

gpt-image-2:多图参考 ​

json
{
  "model": "gpt-image-2",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "ratio": "1:1",
  "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
modelstring平台模型名
modalitystringimage or video
statusstringqueued, running, succeeded, failed
artifactsarray<object>完整已交付产物;交付前或失败时为空数组
failure_codestring / null确认失败的稳定代码
failure_reasonstring / null按本次请求语言返回的安全原因
created_at, updated_atstringYYYY-MM-DD HH:mm:ss,字段不含时区偏移

artifacts[] 字段 ​

字段JSON类型说明
artifact_typestringimage、video、audio、cover;实际输出依型号而定
urlstring平台完成交付的资源地址
mime_typestring / null可取得时返回实际MIME
size_bytesinteger / null实际字节数
width, heightinteger / null已知时返回实际像素尺寸
duration_secondsstring / null实际产物秒数,十进制字符串;不复制请求时长

完成交付示例 ​

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "nano-banana-2.1",
  "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-05 10:00:00",
  "updated_at": "2026-11-05 10:01:00"
}

可选元数据允许为空。响应 duration_seconds 有值时是十进制字符串。输出宽高、时长、图片数量或音轨不从请求参数推断或保证。下载产物资源时,不向资源域名附带平台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也不能读取。任务不存在或不可访问时返回404。查询仍执行鉴权和基础身份限流,但不重新检查模型售卖状态,也不重算该任务价格。

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

以受控间隔轮询,示例为3秒。任务失败时查询仍返回HTTP 200,通过 status 判断。遇到 succeeded 或 failed 停止;对 queued/running 设置有限的客户端等待时间。客户端等待超时不等于任务取消、上游未执行或自动退款。保留任务ID供后续查询和支持排查;长期未解决时联系支持,无限轮询不保证自动恢复。

当前接口未提供任务取消操作或完成回调参数。

9. HTTP 错误与任务失败 ​

HTTP 错误结构 ​

json
{
  "error": {
    "message": "参数 resolution 为必填项",
    "type": "invalid_request_error",
    "code": "invalid_request"
  }
}
HTTPerror.code说明
400invalid_requestJSON、必填项、字段类型、规格或未知字段错误;模型已下架。
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 为稳定标识。错误体不透传上游原始错误,也没有参数详情数组。error.type 取值为 invalid_request_error、authentication_error、permission_error、not_found_error、rate_limit_error、server_error。参数校验用HTTP 400,不使用422。查询任务的业务失败使用响应中的 status 表达;HTTP 参数错误与任务失败应分别处理。

异步任务失败 ​

请求受理后可能稍后失败,此时通过GET查询,不期待原HTTP 202变成502:

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

failure_code 声明值:content_policy、upstream_rejected、internal_error、unknown_error、timeout、cancelled。兼容枚举不代表已提供取消操作或超时自动退款。非失败状态的失败字段为空。

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": "nano-banana-2.1",
    "prompt": "A small orange cat on a clean white background, soft studio lighting.",
    "resolution": "1K",
    "ratio": "1:1"
}
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 完整调用示例 ​

使用支持内置 fetch 的 Node.js 18+,将代码保存为 .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: "nano-banana-2.1",
  prompt:
    "A small orange cat on a clean white background, soft studio lighting.",
  resolution: "1K",
  ratio: "1:1",
};
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;接入SDK封装时需核对HTTP 202、任务轮询及本文响应结构。公共请求体不接收 stream、n、seed、厂商选路字段、自定义存储参数或Webhook/回调参数;未知参数会校验失败。

型号规格基于文档日期的已发布公共规则,可用性、价格和配额可能独立变化。更新接入前核对当前模型页面,并保留在途业务的任务ID。