GPT Image 2 API
The image model gpt-image-2 доступна через Images API только при наличии в каталоге Relay. Нативный протокол Gemini не поддерживается:
- Base URL:
https://relay-llm.ru - Endpoint:
POST /v1/images/generations - Authentication:
Authorization: Bearer YOUR_API_KEY
Query GET /v1/models first to confirm the model is available. Treat the live response as the source of truth for available models and routing.
1. Generate an image
curl "https://relay-llm.ru/v1/images/generations" \
-H "Authorization: Bearer $RELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "IMAGE_MODEL_ID",
"prompt": "An orange cat"
}'
Изображение возвращается в Base64 в data[].b64_json:
{
"data": [
{
"b64_json": "BASE64_IMAGE"
}
]
}
Перебирайте все элементы data и декодируйте b64_json каждого изображения. Не записывайте полный Base64 в журнал.
2. Request parameters
| Field | Common values | Description |
|---|---|---|
model | IMAGE_MODEL_ID | Публичный ID модели из /v1/models |
prompt | Prompt string | Subject, style, composition, text, and constraints |
image | mimeType + Base64 data | Source image when editing |
response_format | b64_json or url | Return image, text, or both |
size | 1:1, 16:9, 9:16, and more | Output aspect ratio |
size | 512, 1K, 2K, 4K | Output resolution, defaults to 1K |
Resolution tiers
The sizes below use 1:1; other aspect ratios produce the corresponding non-square size:
size | 1:1 output | Данные каталога | Recommended for |
|---|---|---|---|
512 | 512 × 512 | Не опубликовано | Previews, drafts, low-cost batch tests |
1K | 1024 × 1024 | Не опубликовано | Default tier, social posts, product shots |
2K | 2048 × 2048 | Не опубликовано | Posters, detail pages, text-heavy images |
4K | 4096 × 4096 | Не опубликовано | High-resolution delivery, print, later cropping |
Supported aspect ratios: 1:1, 1:4, 1:8, 2:3, 3:2, 3:4, 4:1, 4:3, 4:5, 5:4, 8:1, 9:16, 16:9, 21:9.
Use the uppercase 1K, 2K, 4K values in production code. The gateway accepts lowercase 2k in testing, but do not rely on it.
3. Python
pip install requests
import base64
import os
from pathlib import Path
import requests
BASE_URL = "https://relay-llm.ru/v1"
API_KEY = os.environ["RELAY_API_KEY"]
MODEL = "IMAGE_MODEL_ID"
response = requests.post(
f"{BASE_URL}/images/generations",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": MODEL,
"prompt": "An orange cat",
},
timeout=300,
)
response.raise_for_status()
result = response.json()
image_bytes = base64.b64decode(result["data"][0]["b64_json"])
Path("image.png").write_bytes(image_bytes)
4. JavaScript / TypeScript
Node.js 18+ can use fetch directly:
import fs from "node:fs";
const baseURL = "https://relay-llm.ru/v1";
const apiKey = process.env.RELAY_API_KEY;
const model = "IMAGE_MODEL_ID";
const response = await fetch(
`${baseURL}/images/generations`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: model,
prompt: "An orange cat",
}),
signal: AbortSignal.timeout(300_000),
},
);
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
const result = await response.json();
const image = result.data?.[0]?.b64_json;
if (!image) throw new Error("No image part in the response");
fs.writeFileSync("image.png", Buffer.from(image, "base64"));
5. Другой запрос
Измените prompt для следующего запроса генерации:
{
"model": "IMAGE_MODEL_ID",
"prompt": "An orange cat on a blue background"
}
6. Production guidance
- Call
/v1/modelsat startup or on a schedule instead of relying on a static model table, and only surface models present in the live list. - Таймауты и поддерживаемые параметры проверяйте в документации Images API Relay.
- Only retry 429 and recoverable 5xx responses with exponential backoff. A 400 usually means a request or routing problem, so retrying will not help.
- Keep API keys in server-side environment variables or a secrets manager. Never ship them to the browser, store them in a database, or write them to logs.
- Validate the HTTP status,
data,b64_json,url, and the Base64 decoding result. - Cap concurrency, output resolution, reference image count, and daily quota.
7. Common errors
401 / authentication failed
Confirm the header is Authorization: Bearer YOUR_API_KEY, with a complete key and no extra whitespace. If you suspect a leak, delete the key in the console and create a new one immediately.
400 / invalid endpoint format
gpt-image-2 в Relay использует поддерживаемый формат Images по адресу https://relay-llm.ru/v1/images/generations. Адрес шлюза уже содержит /v1; не добавляйте версию повторно.
404 or model not found
Query /v1/models first. If the model is missing from the live list, treat it as not yet enabled on the gateway and stop retrying.
Request succeeds but returns no image
Проверьте массив data в ответе. Каждый элемент data[] должен содержать b64_json. Декодируйте b64_json и сохраните image.png. Не записывайте полный Base64 в журнал.