> ## Documentation Index
> Fetch the complete documentation index at: https://docs.yingtu.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# GPT Image 2 VIP 调用示例

> 复制 gpt-image-2-vip 的 quality 生图、幂等异步任务、单图或多图输入、原生结果解析和非法值处理。

## 生成一张 medium 方图

```javascript theme={"system"}
import fs from "node:fs";

const response = await fetch("https://api.yingtu.ai/v1/images/generations", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.YINGTU_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-image-2-vip",
    prompt: "深色石材上的银色腕表，克制的摄影棚光线，不要文字",
    size: "1024x1024",
    quality: "medium",
    n: 1,
  }),
});

if (!response.ok) throw new Error(`HTTP ${response.status}`);
const body = await response.json();
const encoded = body.data?.[0]?.b64_json;
if (!encoded) throw new Error("响应中没有图片数据");
fs.writeFileSync("watch.png", Buffer.from(encoded, "base64"));
```

## 异步生成 4K 横图

```python theme={"system"}
import base64
import os
import time
from pathlib import Path

import requests

headers = {
    "Authorization": f"Bearer {os.environ['YINGTU_API_KEY']}",
    "Idempotency-Key": "vip-station-001",
}
submitted = requests.post(
    "https://api.yingtu.ai/v1/images/tasks",
    headers=headers,
    json={
        "model": "gpt-image-2-vip",
        "action": "generate",
        "prompt": "雪山脚下的现代车站，电影感横幅，不要文字",
        "size": "3840x2160",
        "quality": "high",
        "n": 1,
    },
    timeout=30,
)
submitted.raise_for_status()
if submitted.status_code != 202:
    raise RuntimeError(f"异步提交应返回 HTTP 202，实际为 {submitted.status_code}")
task_id = submitted.json()["task_id"]

end_at = time.monotonic() + 300
while time.monotonic() < end_at:
    polled = requests.get(
        f"https://api.yingtu.ai/v1/tasks/{task_id}", headers=headers, timeout=30
    )
    polled.raise_for_status()
    task = polled.json()
    if task["status"] == "completed":
        items = task.get("result", {}).get("data") or []
        encoded = items[0].get("b64_json") if items else None
        if not encoded:
            raise RuntimeError("任务完成但没有返回图片数据")
        Path("station.png").write_bytes(base64.b64decode(encoded))
        break
    if task["status"] in {"failed", "expired"}:
        raise RuntimeError(task.get("error", {}).get("message", "任务失败"))
    time.sleep(3)
else:
    raise TimeoutError("等待任务完成超时")
```

## 上传来源图进行编辑

```python theme={"system"}
import base64
import os
from pathlib import Path

import requests

with open("room.png", "rb") as image:
    response = requests.post(
        "https://api.yingtu.ai/v1/images/edits",
        headers={"Authorization": f"Bearer {os.environ['YINGTU_API_KEY']}"},
        data={
            "model": "gpt-image-2-vip",
            "prompt": "保留家具布局，把墙面换成浅蓝色",
            "size": "2048x2048",
            "quality": "high",
            "n": "1",
        },
        files={"image": ("room.png", image, "image/png")},
        timeout=180,
    )
response.raise_for_status()
body = response.json()
items = body.get("data") or []
encoded = items[0].get("b64_json") if items else None
if not encoded:
    raise RuntimeError("响应中没有图片数据")
Path("room-edited.png").write_bytes(base64.b64decode(encoded))
```

## 用两张参考图提交异步任务

```javascript theme={"system"}
import fs from "node:fs";

const room = fs.readFileSync("room.png").toString("base64");
const style = fs.readFileSync("style.jpg").toString("base64");
const submitted = await fetch("https://api.yingtu.ai/v1/images/tasks", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.YINGTU_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    model: "gpt-image-2-vip",
    action: "edit",
    prompt: "保留家具布局，把墙面换成浅蓝色",
    input_images: [
      { mime_type: "image/png", data: room },
      { mime_type: "image/jpeg", data: style },
    ],
    size: "2048x2048",
    quality: "high",
    n: 1,
  }),
});
if (submitted.status !== 202) throw new Error(`提交失败：${submitted.status}`);
const { task_id } = await submitted.json();
console.log(task_id);
```

每张来源图解码后不超过 20 MiB，全部来源图合计不超过 64 MiB。取得 `task_id` 后复用前面的轮询逻辑，成功图片在 24 小时后过期。

## 发送前校验 quality

只允许 `low`、`medium`、`high`、`auto`。例如 `ultra` 会返回 HTTP 400，不会产生图片费用。

## 在线测试

表单固定使用 `gpt-image-2-vip`，默认 1K 与 low。只有真实交付需要时再提高尺寸或质量。

<Warning>在线测试会按当前价格产生真实 USD 0.05 费用。请使用开发密钥，不要分享带密钥的 cURL。</Warning>


## OpenAPI

````yaml openapi-locales/zh-CN/models/gpt-image-2-vip.json POST /v1/images/generations
openapi: 3.1.0
info:
  title: gpt-image-2-vip API
  version: 1.0.0
  description: 使用 gpt-image-2-vip 生成 GPT Image 图片的模型专属接口。
servers:
  - url: https://api.yingtu.ai
    description: YingTu API
security: []
tags:
  - name: Synchronous generation
    description: 在同一个 HTTP 请求中等待完整 Gemini 响应。
  - name: Asynchronous tasks
    description: 提交图片任务，再查询到任务进入终态。
  - name: GPT Image generation
    description: 同步生成 GPT Image 图片，或提交 YingTu 任务式生图请求。
  - name: GPT Image editing
    description: 使用 GPT Image 同步编辑一张来源图片。
paths:
  /v1/images/generations:
    post:
      tags:
        - GPT Image generation
      summary: 真实计费：使用 gpt-image-2-vip 生成图片
      description: >-
        这会使用固定的 YingTu 模型 ID gpt-image-2-vip 发送真实计费请求。发送前请在
        https://api.yingtu.ai/pricing 查看当前固定价格。
      operationId: generateGptImage_gpt_image_2_vip
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OpenAIImageGenerationRequest'
            examples:
              fixedModel:
                summary: 使用 gpt-image-2-vip 生成图片
                value:
                  model: gpt-image-2-vip
                  prompt: 深色石材上的银色腕表，克制的影棚光线，不要文字。
                  size: 1024x1024
                  quality: low
                  'n': 1
      responses:
        '200':
          description: 完整 GPT Image 响应
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OpenAIImagesResponse'
              example:
                created: 1788307200
                data:
                  - b64_json: iVBORw0KGgo=
                usage:
                  input_tokens: 24
                  output_tokens: 1756
                  total_tokens: 1780
                  input_tokens_details:
                    text_tokens: 24
                    image_tokens: 0
                  output_tokens_details:
                    text_tokens: 0
                    image_tokens: 1756
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/ServerError'
      security:
        - BearerAuth: []
components:
  schemas:
    OpenAIImageGenerationRequest:
      title: GPT Image 生图请求
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          $ref: '#/components/schemas/OpenAIImageModelId'
        prompt:
          title: 提示词
          type: string
          minLength: 1
          example: 浅色桌面上的蓝色陶瓷茶壶，不要文字
        size:
          $ref: '#/components/schemas/OpenAIImageSize'
        quality:
          $ref: '#/components/schemas/OpenAIImageQuality'
        'n':
          title: 图片数量
          type: integer
          enum:
            - 1
          default: 1
          description: 当前文档子集返回一张图片。
    OpenAIImagesResponse:
      title: GPT Image 响应
      type: object
      required:
        - created
        - data
      properties:
        created:
          type: integer
          format: int64
          description: Unix 秒级时间戳。
        data:
          type: array
          minItems: 1
          maxItems: 1
          items:
            $ref: '#/components/schemas/OpenAIImageData'
        size:
          type: string
          description: Output size when returned by the selected GPT Image route.
        quality:
          type: string
          description: Quality value reported by the selected GPT Image route.
        usage:
          $ref: '#/components/schemas/OpenAIImageUsage'
    OpenAIImageModelId:
      title: GPT Image 模型 ID
      type: string
      enum:
        - gpt-image-2-vip
      example: gpt-image-2-vip
    OpenAIImageSize:
      title: 输出尺寸
      type: string
      enum:
        - 1024x1024
        - 2048x2048
        - 3840x2160
      example: 1024x1024
      description: 当前公开支持三档尺寸。请明确传入 size 以获得可预测的像素尺寸；4K 横图使用 3840x2160。
      x-default: 1024x1024
    OpenAIImageQuality:
      title: 图片质量
      type: string
      enum:
        - low
        - medium
        - high
        - auto
      example: low
      description: 两个 GPT Image 接口都会转发该值；实际效果由所选上游决定。
      x-default: low
    OpenAIImageData:
      type: object
      required:
        - b64_json
      properties:
        b64_json:
          type: string
          format: byte
          description: 不带 data URL 前缀的 Base64 图片字节。
          example: iVBORw0KGgo=
    OpenAIImageUsage:
      type: object
      properties:
        input_tokens:
          type: integer
          minimum: 0
        output_tokens:
          type: integer
          minimum: 0
        total_tokens:
          type: integer
          minimum: 0
        input_tokens_details:
          $ref: '#/components/schemas/OpenAIImageTokenDetails'
        output_tokens_details:
          $ref: '#/components/schemas/OpenAIImageTokenDetails'
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          $ref: '#/components/schemas/ErrorObject'
    OpenAIImageTokenDetails:
      type: object
      properties:
        text_tokens:
          type: integer
          minimum: 0
        image_tokens:
          type: integer
          minimum: 0
    ErrorObject:
      type: object
      required:
        - message
        - type
      properties:
        message:
          type: string
        type:
          type: string
          example: invalid_request_error
        param:
          type:
            - string
            - 'null'
        code:
          type:
            - string
            - 'null'
          example: insufficient_user_quota
  responses:
    BadRequest:
      description: 模型、字段或参数值无效
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: YingTu API Key 缺失或无效
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: 密钥有效，但当前账号缺少余额或请求权限
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              message: Insufficient balance for this request
              type: new_api_error
              param: ''
              code: insufficient_user_quota
    RateLimited:
      description: >-
        当前所选上游返回了速率、配额、消费或模型容量限制。对于文档中的 Nano Banana 接口，该限制来自官方上游，网关不设置固定的平台侧 RPM
        上限。目前没有单独公布 GPT Image 的网关 RPM 或可用率目标。
      headers:
        Retry-After:
          description: 响应提供时，表示重试前应等待的秒数。
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: 请求未能完成
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: YingTu API Key。

````