> ## 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 API examples

> Copy gpt-image-2-vip examples for quality-aware generation, idempotent tasks, one or multiple reference images, native result parsing, and invalid values.

## Generate with a quality tier

```bash theme={"system"}
curl 'https://api.yingtu.ai/v1/images/generations' \
  -H 'Authorization: Bearer YOUR_YINGTU_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gpt-image-2-vip",
    "prompt": "A silver watch on dark stone, controlled studio light, no text",
    "size": "1024x1024",
    "quality": "medium",
    "n": 1
  }' | jq -er '.data[0].b64_json' | base64 --decode > watch.png
```

Use `low` for a smaller output budget, `high` for the largest documented budget, or `auto` to delegate the choice.

## Queue a 4K landscape result

```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-landscape-001",
}
submitted = requests.post(
    "https://api.yingtu.ai/v1/images/tasks",
    headers=headers,
    json={
        "model": "gpt-image-2-vip",
        "action": "generate",
        "prompt": "A glass greenhouse in a snowy forest at dusk, no text",
        "size": "3840x2160",
        "quality": "high",
        "n": 1,
    },
    timeout=30,
)
submitted.raise_for_status()
if submitted.status_code != 202:
    raise RuntimeError(f"Expected HTTP 202, received {submitted.status_code}")
task_id = submitted.json()["task_id"]

deadline = time.monotonic() + 300
while time.monotonic() < deadline:
    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("Completed task did not include image data")
        Path("greenhouse.png").write_bytes(base64.b64decode(encoded))
        break
    if task["status"] in {"failed", "expired"}:
        raise RuntimeError(task.get("error", {}).get("message", "Task failed"))
    time.sleep(3)
else:
    raise TimeoutError("Task deadline exceeded")
```

## Edit a source image

```bash theme={"system"}
curl 'https://api.yingtu.ai/v1/images/edits' \
  -H 'Authorization: Bearer YOUR_YINGTU_API_KEY' \
  -F 'model=gpt-image-2-vip' \
  -F 'image=@product.png;type=image/png' \
  -F 'prompt=Keep the product and replace the background with pale blue' \
  -F 'size=2048x2048' \
  -F 'quality=high' \
  -F 'n=1' > edited-response.json

jq -er '.data[0].b64_json' edited-response.json | base64 --decode > edited.png
```

## Queue a multi-image edit

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

const product = fs.readFileSync("product.png").toString("base64");
const scene = fs.readFileSync("scene.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: "Keep the product and replace the background with pale blue",
    input_images: [
      { mime_type: "image/png", data: product },
      { mime_type: "image/jpeg", data: scene },
    ],
    size: "2048x2048",
    quality: "high",
    n: 1,
  }),
});
if (submitted.status !== 202) throw new Error(`Submit failed: ${submitted.status}`);
const { task_id } = await submitted.json();
console.log(task_id);
```

Each decoded source must not exceed 20 MiB, and all sources together must remain within 64 MiB. Poll with the same terminal-state loop; the successful result expires after 24 hours.

## Reject unknown quality values before sending

Keep a local enum and fail before creating a billable request:

```javascript theme={"system"}
const qualities = new Set(["low", "medium", "high", "auto"]);
if (!qualities.has(input.quality)) throw new TypeError("Unsupported quality");
```

## Test this model online

The embedded operation fixes `gpt-image-2-vip`. It defaults to 1K and `low`; select a larger size or quality only when the real request needs it.

<Warning>
  Try it sends a real USD 0.05 request at the current price. Use a funded development key and keep the generated cURL private.
</Warning>


## OpenAPI

````yaml openapi-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: Model-fixed GPT Image generation for gpt-image-2-vip.
servers:
  - url: https://api.yingtu.ai
    description: YingTu API
security: []
tags:
  - name: Synchronous generation
    description: Wait for a complete Gemini response in one HTTP request.
  - name: Asynchronous tasks
    description: >-
      Submit image work, then retrieve the task until it reaches a terminal
      state.
  - name: GPT Image generation
    description: >-
      Generate GPT Image output synchronously or submit a YingTu task-ID
      generation request.
  - name: GPT Image editing
    description: Edit one source image synchronously with GPT Image.
paths:
  /v1/images/generations:
    post:
      tags:
        - GPT Image generation
      summary: 'Billable request: generate an image with gpt-image-2-vip'
      description: >-
        This sends a real, billable request with the fixed YingTu model ID
        gpt-image-2-vip. Check the current fixed price at
        https://api.yingtu.ai/pricing before sending.
      operationId: generateGptImage_gpt_image_2_vip
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OpenAIImageGenerationRequest'
            examples:
              fixedModel:
                summary: Generate with gpt-image-2-vip
                value:
                  model: gpt-image-2-vip
                  prompt: >-
                    A silver watch on dark stone, controlled studio light, no
                    text.
                  size: 1024x1024
                  quality: low
                  'n': 1
      responses:
        '200':
          description: Complete GPT Image response
          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 generation request
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          $ref: '#/components/schemas/OpenAIImageModelId'
        prompt:
          title: Prompt
          type: string
          minLength: 1
          example: A blue ceramic teapot on a pale table, no text
        size:
          $ref: '#/components/schemas/OpenAIImageSize'
        quality:
          $ref: '#/components/schemas/OpenAIImageQuality'
        'n':
          title: Number of images
          type: integer
          enum:
            - 1
          default: 1
          description: The documented subset returns one image.
    OpenAIImagesResponse:
      title: GPT Image response
      type: object
      required:
        - created
        - data
      properties:
        created:
          type: integer
          format: int64
          description: Unix timestamp in seconds.
        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 model ID
      type: string
      enum:
        - gpt-image-2-vip
      example: gpt-image-2-vip
    OpenAIImageSize:
      title: Output size
      type: string
      enum:
        - 1024x1024
        - 2048x2048
        - 3840x2160
      example: 1024x1024
      description: >-
        Current public presets. Set size explicitly for predictable dimensions;
        the 4K landscape value is 3840x2160.
      x-default: 1024x1024
    OpenAIImageQuality:
      title: Image quality
      type: string
      enum:
        - low
        - medium
        - high
        - auto
      example: low
      description: >-
        Forwarded for both GPT Image routes. The selected upstream determines
        how the requested value affects the result.
      x-default: low
    OpenAIImageData:
      type: object
      required:
        - b64_json
      properties:
        b64_json:
          type: string
          format: byte
          description: Base64-encoded image bytes without a data URL prefix.
          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: Invalid model, field, or parameter value
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: Missing or invalid YingTu API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: >-
        The key is valid but the account lacks balance or access for this
        request
      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: >-
        The selected upstream provider returned a rate, quota, spend, or
        model-capacity limit. For the documented Nano Banana routes, this is the
        official upstream provider and the gateway does not apply a fixed
        platform-side RPM cap. No separate GPT Image gateway RPM or availability
        objective is currently published.
      headers:
        Retry-After:
          description: Seconds to wait before retrying when supplied.
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: The request could not be completed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: YingTu API key.

````