图像/OpenAI Images API

通过 OpenAI 兼容 Images API 使用 gpt-image-2 生成和编辑图片。

OpenAI Images API

通过 OpenAI 兼容的 Images API 使用 gpt-image-2 生成和编辑图片。

Base URL: https://api.unigateway.ai/v1

文生图

curl -sS -X POST "https://api.unigateway.ai/v1/images/generations" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A clean product hero image for an AI gateway dashboard."
  }' > response.json

Python

from openai import OpenAI; import base64
client = OpenAI(api_key="<YOUR_UNIGATEWAY_API_KEY>", base_url="https://api.unigateway.ai/v1")
r = client.images.generate(model="gpt-image-2", prompt="A hero image.")
with open("out.png","wb") as f: f.write(base64.b64decode(r.data[0].b64_json))

TypeScript

import OpenAI from "openai"; import fs from "fs";
const c = new OpenAI({ apiKey: process.env.UNIGATEWAY_API_KEY, baseURL: "https://api.unigateway.ai/v1" });
const r = await c.images.generate({ model: "gpt-image-2", prompt: "A hero image." });
fs.writeFileSync("out.png", Buffer.from(r.data[0].b64_json, "base64"));

多图生成

curl -sS -X POST "https://api.unigateway.ai/v1/images/generations" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-image-2","prompt":"Four icons: chat, image, video, search.","n":4,"size":"1024x1024","quality":"medium","output_format":"png"}' > batch.json

参数

参数必填取值说明
modelgpt-image-2
prompt文本
size1024x10241536x10242048x2048autoW×H,16 的倍数,最大 3840,比例 ≤ 3:1
qualitylow / medium / high / auto默认 auto
n1–10
output_formatpng / jpeg / webp默认 png
output_compression0–100仅 jpeg/webp
backgroundopaque / auto
moderationauto / low
streamtrueSSE 流式
partial_images0–3流式中间图片数
userstring终端用户标识

流式生成

启用 stream: true 后,API 以 SSE(Server-Sent Events)逐事件推送,客户端可渐进渲染。

请求

curl -sS -X POST "https://api.unigateway.ai/v1/images/generations" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-image-2","prompt":"A winter landscape.","stream":true,"partial_images":2}'

SSE 事件格式

事件类型字段说明
image_generation.partial_imageb64_json, partial_image_index中间低分辨率图像(数量取决于 partial_images
image_generation.completedb64_json最终完整图像

SSE 原始输出示例:

event: image_generation.partial_image
data: {"created_at":1718000000,"type":"image_generation.partial_image","b64_json":"iVBOR...","partial_image_index":0}

event: image_generation.partial_image
data: {"created_at":1718000000,"type":"image_generation.partial_image","b64_json":"iVBOR...","partial_image_index":1}

event: image_generation.completed
data: {"created_at":1718000000,"type":"image_generation.completed","b64_json":"iVBOR..."}

Python 流式消费

from openai import OpenAI
import base64

client = OpenAI(api_key="<YOUR_UNIGATEWAY_API_KEY>", base_url="https://api.unigateway.ai/v1")

stream = client.images.generate(
    model="gpt-image-2",
    prompt="A winter landscape.",
    stream=True,
    partial_images=2,
)

for event in stream:
    if event.type == "image_generation.partial_image":
        idx = event.partial_image_index
        with open(f"partial_{idx}.png", "wb") as f:
            f.write(base64.b64decode(event.b64_json))
    elif event.type == "image_generation.completed":
        with open("final.png", "wb") as f:
            f.write(base64.b64decode(event.b64_json))

TypeScript 流式消费

import OpenAI from "openai";
import fs from "fs";

const client = new OpenAI({ apiKey: process.env.UNIGATEWAY_API_KEY, baseURL: "https://api.unigateway.ai/v1" });

const stream = await client.images.generate({
  model: "gpt-image-2",
  prompt: "A winter landscape.",
  stream: true,
  partial_images: 2,
});

for await (const event of stream) {
  if (event.type === "image_generation.partial_image") {
    const idx = event.partial_image_index;
    fs.writeFileSync(`partial_${idx}.png`, Buffer.from(event.b64_json, "base64"));
  } else if (event.type === "image_generation.completed") {
    fs.writeFileSync("final.png", Buffer.from(event.b64_json, "base64"));
  }
}

端点兼容性

不同上游端点对流式生成的支持程度不同。仅 OpenAI 官方和 Azure OpenAI 支持真正的 SSE 流式推送(含渐进 partial_image 事件)。其他端点虽然接受 stream:true,但可能在图片完全生成后才一次性返回 JSON,无法实现渐进渲染。

注意:如需真正的流式体验(渐进渲染),请将 gpt-image-2 流式请求路由到支持 SSE 的端点(OpenAI 官方或 Azure OpenAI)。

保存返回

jq -r '.data[0].b64_json' response.json | base64 -D > output.png    # macOS
jq -r '.data[0].b64_json' response.json | base64 --decode > output.png  # Linux

编辑 / 合成 / 重绘

均使用 POST /v1/images/editsmultipart/form-data

单图编辑:

curl -sS -X POST "https://api.unigateway.ai/v1/images/edits" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -F "model=gpt-image-2" -F "image[]=@room.png" \
  -F "prompt=将沙发改为米白色,其余保持不变。" \
  -F "quality=high" -F "size=1024x1024" -F "output_format=png" > edit.json

多参考图合成:

curl -sS -X POST "https://api.unigateway.ai/v1/images/edits" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -F "model=gpt-image-2" \
  -F "image[]=@item1.png" -F "image[]=@item2.png" -F "image[]=@item3.png" \
  -F "prompt=将全部物品合成一张白底产品照。" \
  -F "quality=high" -F "output_format=png" > composite.json

局部重绘:

curl -sS -X POST "https://api.unigateway.ai/v1/images/edits" \
  -H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
  -F "model=gpt-image-2" -F "mask=@mask.png" -F "image[]=@src.png" \
  -F "prompt=在 mask 区域画一只粉色火烈鸟。" > inpaint.json

Mask 要求:尺寸一致、格式相同、≤ 50 MB、含 alpha 通道。

响应格式

{ "created": 1710000000, "data": [{ "b64_json": "..." }] }

常见错误

状态码原因处理
400参数错误检查 promptsizemask
401API Key 无效检查 Authorization
404模型不可用通过 GET /v1/models 确认
429触发限流退避重试
5xx服务异常指数退避

Example request

Run it in your stack

Pick the SDK style that matches your app and copy the snippet directly into your project.

from openai import OpenAI; import base64
client = OpenAI(api_key="<YOUR_UNIGATEWAY_API_KEY>", base_url="https://api.unigateway.ai/v1")
r = client.images.generate(model="gpt-image-2", prompt="A hero image.")
with open("out.png","wb") as f: f.write(base64.b64decode(r.data[0].b64_json))