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

# GPT Image

## gpt-image-1 API

OpenAIs Bildgenerierungs-API `gpt-image-1` bietet sowohl Text-zu-Bild-Generierung als auch text-gestützte Bild-zu-Bild-Bearbeitung.\
Stellen Sie vor der Nutzung sicher, dass Sie das aktuelle OpenAI-Paket installiert haben: `pip install -U openai`.

### Wichtige Hinweise

<Warning>
  * Sobald ein API-Aufruf gesendet wurde, **werden Gebühren unabhängig von Unterbrechungen oder Fehlern** während der Generierung berechnet.
  * Namen lebender Künstler (z. B. „Hayao Miyazaki", „Makoto Shinkai") lösen einen `moderation_blocked`-Fehler aus, **wodurch die Generierung fehlschlägt**. Sie können dies umgehen, indem Sie unverfängliche Begriffe wie „Ghibli" oder „bright modern Japanese anime style" verwenden. Gleiches gilt für Bilder mit freizügiger Kleidung oder anzüglichen Inhalten.
  * Generell ist die Bezugnahme auf einen „Stil" sicherer als das Nennen eines „Künstlers" – „Pixar" wird zum Beispiel unterstützt.
  * Ein zuverlässiger Ansatz ist, verstorbene Künstler oder deren Stile zu verwenden, z. B. „Van Gogh" oder „Mona Lisa".
</Warning>

### Modell und Preisgestaltung

| Modell      | Qualität | 1024x1024 | 1024x1536 | 1536x1024 |
| ----------- | -------- | --------- | --------- | --------- |
| gpt-image-1 | low      | \$0,011   | \$0,016   | \$0,016   |
| gpt-image-1 | medium   | \$0,042   | \$0,063   | \$0,063   |
| gpt-image-1 | high     | \$0,167   | \$0,25    | \$0,25    |

<Info>
  Hinweis: Eingabetext-Token werden separat mit \$5 pro Million Token abgerechnet.
</Info>

### API-Nutzung

**Endpoints**

1. Bildgenerierung: `https://aihubmix.com/v1/images/generations`
2. Bildbearbeitung: `https://aihubmix.com/v1/images/edits`

**Python-Beispiele:**

<CodeGroup>
  ```py Generation (Text-to-Image) theme={null}
  from openai import OpenAI
  import base64
  import os

  client = OpenAI(
      api_key="AIHUBMIX_API_KEY", # Replace with your AIHUBMIX Key "sk-***"
      base_url="https://aihubmix.com/v1"
  )

  prompt = """redesign poster of the movie [Black Swan], 3D cartoon, smooth render, bright tone, 2:3 portrait."""

  result = client.images.generate(
      model="gpt-image-1",
      prompt=prompt,
      n=1, # Number of images to generate, maximum 10
      size="1024x1536", # 1024x1024 (square), 1536x1024 (3:2 landscape), 1024x1536 (2:3 portrait), auto (default) 
      quality="high", # high, medium, low, auto (default)
      moderation="low", # low, auto (default) - requires updated openai package 📍
      background="auto", # transparent, opaque, auto (default)
  )

  print(result.usage)

  # Define file name prefix and save directory
  output_dir = "." # You can specify another directory
  file_prefix = "image_gen"

  # Ensure output directory exists
  os.makedirs(output_dir, exist_ok=True)

  # Iterate through all returned image data
  for i, image_data in enumerate(result.data):
      image_base64 = image_data.b64_json
      if image_base64: # Ensure b64_json is not empty
          image_bytes = base64.b64decode(image_base64)

          # --- Handle filename conflict logic ---
          current_index = i
          while True:
              # Create filename with incremental counter
              file_name = f"{file_prefix}_{current_index}.png"
              file_path = os.path.join(output_dir, file_name) # Build complete file path

              # Check if file exists
              if not os.path.exists(file_path):
                  break # No filename conflict, exit loop

              # Filename conflict, increment counter
              current_index += 1

          # Save image to file using unique file_path
          with open(file_path, "wb") as f:
              f.write(image_bytes)
          print(f"Image saved to: {file_path}")
      else:
          print(f"Image data for index {i} is empty, skipping save.")
  ```

  ```py Editing (Image+Text to Image) theme={null}
  from openai import OpenAI
  import base64
  import os

  client = OpenAI(
      api_key="AIHUBMIX_API_KEY", # Replace with your AIHUBMIX Key "sk-***"
      base_url="https://aihubmix.com/v1"
  )

  prompt = """redesign poster of the movie [Black Swan], 3D cartoon, smooth render, bright tone, 2:3 portrait."""

  result = client.images.edit(
      model="gpt-image-1",
      image=open("yourpath/edit.jpg", "rb"), # For multiple reference images, use a [list,]
      n=2, # Number of images to generate
      prompt=prompt,
      size="1024x1536", # 1024x1024 (square), 1536x1024 (3:2 landscape), 1024x1536 (2:3 portrait), auto (default)
      input_fidelity="high", # "low" as default
      # moderation="low", # editing doesn't support moderation
      quality="high" # high, medium, low, auto (default)
  )

  print(result.usage)

  # Define file name prefix and save directory
  output_dir = "." # You can specify another directory
  file_prefix = "image_edit" # Modify file name prefix

  # Ensure output directory exists
  os.makedirs(output_dir, exist_ok=True)

  # --- Iterate through each image returned by the API ---
  for i, image_item in enumerate(result.data):
      image_base64 = image_item.b64_json
      if image_base64 is None:
          print(f"Warning: Image {i+1} has no base64 data, skipping save.")
          continue # If no b64_json data, skip to next image

      image_bytes = base64.b64decode(image_base64)

      # --- Find non-conflicting filename for current image ---
      current_index = 0 # Start checking from 0, or maintain a globally incrementing index
      while True:
          # Create filename with incremental counter
          file_name = f"{file_prefix}_{current_index}.png"
          file_path = os.path.join(output_dir, file_name) # Build complete file path

          # Check if file exists
          if not os.path.exists(file_path):
              break # No filename conflict, exit inner loop

          # Filename conflict, increment counter
          current_index += 1

      # Save current image to file using unique file_path
      try:
          with open(file_path, "wb") as f:
              f.write(image_bytes)
          print(f"Edited image {i+1} saved to: {file_path}")
      except Exception as e:
          print(f"Error saving image {i+1} ({file_path}): {e}")
  ```
</CodeGroup>

Weitere Parameter-Details finden Sie in der [offiziellen OpenAI-Dokumentation](https://platform.openai.com/docs/api-reference/images/create).

### Ausgabebeispiele

<CodeGroup>
  ```json Generation theme={null}
  Usage(input_tokens=150, input_tokens_details=UsageInputTokensDetails(image_tokens=0, text_tokens=150), output_tokens=6240, total_tokens=6390)
  Image saved to: ./image_gen_14.png
  ```

  ```json Editing theme={null}
  Usage(input_tokens=992, input_tokens_details=UsageInputTokensDetails(image_tokens=646, text_tokens=346), output_tokens=12480, total_tokens=13472)
  Edited image 1 saved to: ./image_edit_1.png
  Edited image 2 saved to: ./image_edit_2.png
  ```
</CodeGroup>

### Ablehnungsszenarien

Fehlermeldung bei abgelehntem Request:

```json theme={null}
Error code: 400 - {'error': {'message': 'Your request was rejected as a result of our safety system. Your request may contain content that is not allowed by our safety system.', 'type': 'user_error', 'param': None, 'code': 'moderation_blocked'}}
```

Bei Anforderung von 2–10 Bildern in einer Generierung wird gekennzeichneter Inhalt nicht erzeugt, falls das System eine Richtlinienverletzung erkennt. Dadurch können weniger Bilder erzeugt werden als angefordert; bei Multi-Image-Generierung wird jedoch kein `moderation_blocked`-Fehler ausgelöst.
Daher empfiehlt es sich, potenzielle IP- oder Urheberrechtsprobleme proaktiv zu vermeiden, um Ablehnungen zu minimieren und eine reibungslose Generierung zu gewährleisten.

**✍️ Wichtige Empfehlungen:**

* Vermeiden Sie die direkte Verwendung urheberrechtlich geschützter Figuren, Logos, Promi-Bildnisse usw.
* Nutzen Sie „Stilinspiration", „kreative Neuinterpretation" oder „allgemeine Beschreibungen".
* Wenn Sie bestimmte Elemente referenzieren, prüfen Sie, ob sie gemeinfrei sind.

### Praktische Tipps

<Tip>
  * Unterstützt beliebige Sprachen. Chinesischer Text funktioniert zuverlässig, in jeder Sprache wird das Generieren großer Textmengen jedoch nicht empfohlen.
  * Der Parameter `size` unterstützt nicht das explizite Übergeben von `size="auto"` – auto ist der Standard.
  * Seitenverhältnisse können im Prompt angegeben (2:3, 3:2, 1:1) oder über den Parameter `size` gesetzt werden.
  * Der Parameter `moderation` steuert die Empfindlichkeit; selbst bei „low" können Anfragen abgelehnt werden (z. B. wenn die Venus zu freizügig ist).
  * Der Edits-Endpoint unterstützt den Parameter `moderation` nicht.
  * Eine Kombination aus Textbeschreibungen und Referenzbildern liefert präzisere Ergebnisse.
  * Vorab komprimierte Upload-Bilder erhöhen die Geschwindigkeit.
  * Transparente Hintergründe werden unterstützt (kein manuelles Freistellen nötig) – fügen Sie die Anforderung einfach im Prompt hinzu.
</Tip>
