图片生成 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/generations | 202 |
| GET | /api/v1/platform/tasks/{task_id} | 200 |
模型可用状态、权限和当前售价以控制台为准。本文范围仅包含上表列出的模型。
2. 鉴权与环境配置
| 请求头 | 是否必填 | 说明 |
|---|---|---|
Authorization | 是 | Bearer <API_KEY>;使用平台 API Key |
Content-Type | POST 必填 | application/json |
Accept-Language | 否 | zh-CN、zh-Hant、en;默认简体中文,按首个语言标签协商 |
API Key 应保存在服务端环境中。调用前确认账号状态、模型权限、来源 IP、余额和 Key 配额满足要求。
示例的 API_BASE_URL 特意留空,填写实际服务根地址即可;接口路径已包含 /api/v1/platform,不要重复添加。
Bash 环境变量:
export API_BASE_URL=""
export API_KEY=""PowerShell 环境变量:
$env:API_BASE_URL = ""
$env:API_KEY = ""3. 创建生成任务:请求参数
POST /api/v1/platform/images/generations
正文使用单个 JSON 对象,参数直接放在顶层。
| 参数 | JSON 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型标识,允许值见支持模型表 |
prompt | string | 是 | 非空生成提示词 |
resolution | string | 是 | 分辨率档位,必须符合所选模型的允许值 |
ratio | string | 依模型 | 输出宽高比,必填性和允许值见模型规格 |
quality | string | 否 | GPT Image 2.6 系列的输出质量,允许值见各型号文档 |
output_format | string | 否 | GPT Image 2.6 系列的输出格式,允许值见各型号文档 |
images | array<object> | 否 | 有序参考图片,元素为 url + role 对象 |
audios、videos | array<object> | 否 | 保留字段;当前所列模型均不支持非空数组,调用时省略 |
原始请求正文最多 65535 字节。不增加 data 或 body 包装;未知字段、重复 JSON 键以及非有限数值会被拒绝。未传参数保持未传,平台不补生成默认值。
已声明字段的 null、空字符串、纯空白或忽略大小写的字符串 null 按未传处理:必填项仍会报缺失,可选项保持未传。0、false、空数组和空对象继续按原字段约束校验。
4. 模型规格与素材要求
| model | resolution(必填) | ratio 是否必填 | 比例列表 |
|---|---|---|---|
nano-banana-2.1 | 1K、2K、4K | 否 | A |
nano-banana-2 | 1K、2K、4K | 否 | A |
gpt-image-2.6 | 1K | 是 | B |
gpt-image-2.6-flare | 1K、2K、4K | 是 | B |
gpt-image-2.6-sunburst | 1K、2K、4K | 是 | B |
gpt-image-2.5 | 1K | 是 | B |
gpt-image-2 | 1K | 是 | 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 类型 | 必填 | 说明 |
|---|---|---|---|
url | string | 是 | 可公开读取的 HTTP/HTTPS 文件 URL,建议 HTTPS |
role | string | 是 | 固定为 reference,表示参考素材 |
素材服务应允许模型服务直接读取,不依赖浏览器登录态;签名 URL 的有效期应覆盖排队和素材读取过程。不接收 Base64、数据 URI、本地路径、表单文件或内联二进制。文中 example.com 地址是占位示例,调用时替换为真实素材。
5. 快速开始
以下 cURL 使用 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:
{
"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:纯文本生成
{
"model": "nano-banana-2.1",
"prompt": "A small orange cat on a clean white background, soft studio lighting.",
"resolution": "1K"
}nano-banana-2.1:多图参考
{
"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:纯文本生成
{
"model": "nano-banana-2",
"prompt": "A small orange cat on a clean white background, soft studio lighting.",
"resolution": "1K"
}nano-banana-2:多图参考
{
"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:纯文本生成
{
"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:多图参考
{
"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:纯文本生成
{
"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:多图参考
{
"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_id | string | 平台小写UUID |
model | string | 平台模型名 |
modality | string | image or video |
status | string | queued, running, succeeded, failed |
artifacts | array<object> | 完整已交付产物;交付前或失败时为空数组 |
failure_code | string / null | 确认失败的稳定代码 |
failure_reason | string / null | 按本次请求语言返回的安全原因 |
created_at, updated_at | string | YYYY-MM-DD HH:mm:ss,字段不含时区偏移 |
artifacts[] 字段
| 字段 | JSON类型 | 说明 |
|---|---|---|
artifact_type | string | image、video、audio、cover;实际输出依型号而定 |
url | string | 平台完成交付的资源地址 |
mime_type | string / null | 可取得时返回实际MIME |
size_bytes | integer / null | 实际字节数 |
width, height | integer / null | 已知时返回实际像素尺寸 |
duration_seconds | string / null | 实际产物秒数,十进制字符串;不复制请求时长 |
完成交付示例
{
"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 后查询:
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 错误结构
{
"error": {
"message": "参数 resolution 为必填项",
"type": "invalid_request_error",
"code": "invalid_request"
}
}| HTTP | error.code | 说明 |
|---|---|---|
| 400 | invalid_request | JSON、必填项、字段类型、规格或未知字段错误;模型已下架。 |
| 401 | unauthorized | API Key 缺失、非法、已停用或已过期。 |
| 403 | access_denied | 用户、IP、模型权限、余额或 API Key 配额不允许。 |
| 404 | task_not_found | 任务不存在,或不属于当前用户及创建任务的 API Key。 |
| 405 | invalid_request | HTTP 方法不支持。 |
| 413 | invalid_request | 原始 JSON 正文超过65535字节。 |
| 429 | rate_limited | 触发身份限流、RPM 或并发限制。 |
| 500 | generation_configuration_invalid / internal_error | 配置不可用或平台内部异常。 |
| 502 | upstream_error | 协议声明的上游错误状态;已受理任务主要通过任务结果表达异步失败。 |
| 503 | no_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:
{
"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:
python -m pip install httpx配置 API_BASE_URL 与 API_KEY 后运行。更换模型时同步核对分辨率、比例和素材要求。
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 示例相同。
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。

