इमेज जनरेशन API
BetterToken के OpenAI-संगत API से GPT Image चित्र बनाएं। API Key, Base URL, पैरामीटर, SDK उदाहरण, बिलिंग और त्रुटियां जानें।
POST /v1/images/generations
text-to-image endpoint application/json request body उपयोग करता है। prompt भेजें, HTTP request खुला रखें और उसी response में data[].b64_json की हर generated इमेज पढ़ें।
सही प्रक्रिया चुनें
- टेक्स्ट से image बनाकर result सेव करें: इसी पेज पर रहें।
curlexample से शुरू करें, फिर नीचे इमेज सहेजें मेंdata[]की हर entry decode करें। - मौजूदा image edit करें: image editing API पर एक या अधिक reference images अपलोड करें। सामान्य reference-image edit के लिए mask जरूरी नहीं है; इसे केवल local edit में तभी जोड़ें जब चुना model और size इसका समर्थन करते हों।
- Model चुनें, parameters देखें और budget का अनुमान लगाएं: उपलब्ध Model ID और price model plaza में देखें। पूरा workflow GPT Image 2 guide में है।
curl के साथ त्वरित शुरुआत
https://bettertoken.ai/v1 को Base URL के रूप में उपयोग करें और https://bettertoken.ai/v1/images/generations पर अनुरोध भेजें:
curl --max-time 300 -X POST "https://bettertoken.ai/v1/images/generations" \ -o response.json \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-image-2", "prompt": "A product photo of a green ceramic mug on a studio table", "size": "1024x1024", "n": 1, "response_format": "b64_json", "output_format": "png" }'अनुशंसित मान
ये शुरुआती सुझाव हैं, fixed requirements नहीं। n=1 recommended है; endpoint 1 से 10 तक integer स्वीकार करता है, लेकिन लौटाई गई images की संख्या कम हो सकती है।
{ "model": "gpt-image-2", "n": 1, "response_format": "b64_json", "output_format": "png"}| parameter | क्या भेजें | उद्देश्य |
|---|---|---|
model | gpt-image-2, gpt-image-2.5-flare या gpt-image-2.5-sunburst | उपलब्ध model plaza ID चुनें। वैध ID से model, size या operation उपलब्ध होने की गारंटी नहीं मिलती। |
prompt | text description | जरूरी इमेज वर्णन। subject, style, composition और महत्वपूर्ण constraint शामिल करें। |
size | छोड़ें, auto या 1024x1024 जैसे dimensions | मांगा गया आकार और अनुपात; असली dimensions अलग हो सकते हैं। |
n | 1 से 10 integer | मांगी गई images की अधिकतम संख्या। 1 से शुरू करें; कम images लौट सकती हैं। |
quality | gpt-image-2 के लिए auto, low, medium, high; दोनों 2.5 models xhigh और max भी लेते हैं | वैकल्पिक quality preference। इसे छोड़ने या JSON में null देने पर default उपयोग होता है। parameter स्वीकार होना availability या बेहतर image quality की गारंटी नहीं है। |
response_format | b64_json | हर image को data[].b64_json में base64 लौटाता है। |
output_format | जैसे png | format request है, लौटे file encoding की गारंटी नहीं। सेव करने से पहले bytes से format पहचानें। |
response में n से कम images हो सकती हैं। data[] की हर entry process करें; n=1 recommendation server limit नहीं है।
अनुशंसित आकार
size | अनुपात | उपयोग |
|---|---|---|
auto | Auto | अपने-आप आकार चयन |
1024x1024 | 1:1 | वर्गाकार इमेज, avatar, cover, asset |
1536x1024 | 3:2 | landscape poster, banner, scene |
1024x1536 | 2:3 | portrait mobile cover और poster |
1536x1152 | 4:3 | मानक landscape इमेज, product image, content graphic |
1152x1536 | 3:4 | मानक portrait इमेज, mobile cover, vertical poster |
2048x2048 | 1:1 | high-resolution वर्गाकार इमेज |
2048x1152 | 16:9 | high-resolution landscape इमेज |
3840x2160 | 16:9 | 4K landscape इमेज |
2160x3840 | 9:16 | 4K portrait इमेज |
तालिका सामान्य उदाहरण हैं, बंद सूची नहीं। size छोड़ सकते हैं या auto दें; JSON में size: null auto sizing करता है। Explicit dimensions positive हों और 16 के multiples हों, हर dimension अधिकतम 3840, aspect ratio 3:1 से अधिक नहीं, और कुल pixels 655360 से 8294400 हों। 2080x2080 वैध उदाहरण है। असली dimensions अलग हो सकती हैं; decoded dimensions देखें, जबरन crop न करें।
इमेज सहेजें
सफल response OpenAI-compatible इमेज response स्वरूप का पालन करता है। नीचे की रकम receipt का उदाहरण हैं, fixed prices नहीं:
{ "created": 1710000000, "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUgAA...(truncated)", "revised_prompt": "Optional revised prompt" } ], "bettertoken_image_billing": { "currency": "CNY", "settled_amount": "0.15", "outputs": [ { "index": 0, "width": 1254, "height": 1254, "billing_resolution": "2K", "currency": "CNY", "amount": "0.15" } ] }}data[].b64_json की हर image पढ़ें और revised_prompt जैसे extra fields स्वीकार करें। BetterToken billing root bettertoken_image_billing object में देता है। settled_amount और हर output का amount decimal strings हैं; outputs[].index zero-based है।
output_format format request है, encoding या conversion की guarantee नहीं। bytes से असली format पहचानें और उसी extension से save करें। नीचे के standard-library examples PNG, JPEG और WebP पहचानते हैं।
import base64import jsonfrom pathlib import Path
result = json.loads(Path("response.json").read_text(encoding="utf-8"))for index, item in enumerate(result["data"], start=1): encoded = item["b64_json"] if "," in encoded and "base64" in encoded.split(",", 1)[0]: encoded = encoded.split(",", 1)[1] image_bytes = base64.b64decode(encoded) if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"): extension = "png" elif image_bytes.startswith(b"\xff\xd8\xff"): extension = "jpg" elif image_bytes.startswith(b"RIFF") and image_bytes[8:12] == b"WEBP": extension = "webp" else: raise ValueError("Unsupported image signature") Path(f"output-{index}.{extension}").write_bytes(image_bytes)JavaScript उदाहरण (Node.js)
import { writeFile } from "node:fs/promises";
const response = await fetch("https://bettertoken.ai/v1/images/generations", { method: "POST", headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json", }, body: JSON.stringify({ model: "gpt-image-2", prompt: "A green ceramic mug on a studio table", size: "1024x1024", n: 1, response_format: "b64_json", output_format: "png", }),});
if (!response.ok) { throw new Error(await response.text());}
const result = await response.json();const { data } = result;for (const [index, item] of data.entries()) { const b64Json = item.b64_json.replace(/^data:.*;base64,/, ""); const imageBytes = Buffer.from(b64Json, "base64"); let extension; if (imageBytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) { extension = "png"; } else if (imageBytes[0] === 0xff && imageBytes[1] === 0xd8 && imageBytes[2] === 0xff) { extension = "jpg"; } else if (imageBytes.toString("ascii", 0, 4) === "RIFF" && imageBytes.toString("ascii", 8, 12) === "WEBP") { extension = "webp"; } else { throw new Error("Unsupported image signature"); } await writeFile(`output-${index + 1}.${extension}`, imageBytes);}यदि ऐप को निश्चित PNG, JPEG या WebP एन्कोडिंग चाहिए, तो पहले वास्तविक फ़ॉर्मैट पहचानें और आवश्यकता होने पर चित्र को बदलें। केवल फ़ाइल एक्सटेंशन बदलने से चित्र का फ़ॉर्मैट नहीं बदलता।
वास्तविक लागत देखें
bettertoken_image_billing परिणाम के साथ लौटता है; अलग cost request की जरूरत नहीं है।
| Field | अर्थ |
|---|---|
currency | Settlement currency; यह हमेशा USD या CNY नहीं होती। |
settled_amount | इस request की कुल settled रकम, decimal string। |
requested_resolution | Request से पहचाना गया resolution tier। |
outputs[].index | data[] से जुड़ा zero-based image index। |
outputs[].width, height | Image की वास्तविक चौड़ाई और ऊंचाई, pixels में। |
outputs[].billing_resolution | Image का अंतिम billing tier। |
outputs[].currency, amount | Image की settlement currency और रकम। |
अनुरोधित आकार और billing tier अलग हो सकते हैं: 1024x1024 request से 1254x1254 image मिली है और 2K billing हुई है। Receipt की वास्तविक रकम लें और वर्तमान कीमत model plaza में देखें। दिखाते समय रकम string रखें, गणना में decimal arithmetic करें। Receipt न होना शून्य लागत नहीं है।
from decimal import Decimal
billing = result.get("bettertoken_image_billing")if billing is None: print("Billing receipt unavailable; check your usage records.")else: total = Decimal(billing["settled_amount"]) print(f"Total: {billing['currency']} {total}") for output in billing.get("outputs", []): print( f"Image {output['index'] + 1}: " f"{output['width']}x{output['height']}, " f"{output['billing_resolution']}, " f"{output['currency']} {output['amount']}" )प्रतिक्रिया प्रवाह
यह endpoint synchronous है। POST /images/generations भेजने के बाद server response तक HTTP request खुला रखें। success पर हर image data[].b64_json में delivery और billing details के साथ लौटती है।
endpoint task_id नहीं लौटाता, और कोई अलग status query या result download endpoint नहीं है।
समय सीमा, दोबारा अनुरोध और बिलिंग
HTTP client timeout कई मिनट रखें। timeout, disconnect या अस्पष्ट 5xx यह नहीं बताता कि generation चली या charge हुआ। generation या edit POST अपने-आप दोबारा न भेजें। पहले consumption records या request logs जांचें और लौटे request ID को रखें। Client-generated request ID server idempotency नहीं देता; जानबूझकर resend करने पर नया request और charge हो सकता है।
Reject हुए input, authentication या quota को पहले ठीक करें। 429 पर backoff तभी करें जब request reject होने की पुष्टि हो। हर 5xx या transport error को retry-safe न मानें।
प्रोसेस करने से पहले BetterToken सबसे ऊंचे लागू unit price को n से गुणा करके अधिकतम राशि preauthorize कर सकता है। Delivered 1K image के लिए पर्याप्त balance इस hold के लिए कम पड़ सकता है; ऐसी request 403 और error.code=insufficient_user_quota से reject होती है। अंतिम charge delivered images पर आधारित है। Root bettertoken_image_billing में final settled_amount, currency, हर output का amount, billing_resolution और dimensions होते हैं। रकम decimal strings हैं; images की संख्या n से कम हो सकती है।
त्रुटि प्रबंधन
त्रुटियां सामान्यतः JSON लौटाती हैं। त्रुटि दिखाते समय पहले error.message, फिर message, फिर HTTP status text पढ़ें।
| HTTP status | अर्थ | क्या करें |
|---|---|---|
400 | malformed JSON, missing parameter या असमर्थित size | request body जांचें। अपने-आप retry न करें। |
401 | API Key अनुपस्थित या अमान्य है | Authorization: Bearer YOUR_API_KEY header जांचें। |
402 या 403 | अपर्याप्त quota या balance, balance hold सहित | error.code और account quota/balance जांचें। 403 और error.code=insufficient_user_quota का अर्थ है कि balance preauthorization upper limit से कम हो सकता है। |
429 | rate limit, concurrency limit या व्यस्त upstream | request reject होने की पुष्टि के बाद ही backoff से retry करें। |
5xx | gateway या upstream विफलता | execution और billing अज्ञात हो सकते हैं। resend से पहले logs और consumption जांचें। |
एकीकरण जांचसूची
- Base URL
https://bettertoken.ai/v1है। - हेडर में
Authorization: Bearer sk-...शामिल है। - अनुरोध
application/jsonउपयोग करता है। - इस अनुरोध के लिए उपलब्ध Model ID चुनें:
gpt-image-2,gpt-image-2.5-flareयाgpt-image-2.5-sunburst। response_format=b64_jsonउपयोग करें।output_formatअनुरोधित मान है; सहेजने से पहले बाइट्स से वास्तविक फ़ॉर्मैट पहचानें।nमें1से10तक पूर्णांक दे सकते हैं।1से शुरू करें; लौटे चित्र कम हो सकते हैं।sizeछोड़ सकते हैं,autoदे सकते हैं या मान्य आकार भर सकते हैं। ऊपर की तालिका पूरी सीमित सूची नहीं है।- HTTP क्लाइंट चित्र बनने के लिए कई मिनट तक प्रतीक्षा कर सकता है।
- लॉग और त्रुटि के स्क्रीनशॉट में API Key या पूरा base64 चित्र उजागर नहीं होता।
संबंधित दस्तावेज
/v1/images/generationsप्राधिकरण
Bearer authentication header of the form Bearer <token>, where <token> is your auth token.
बॉडी application/json
GPT Image Model ID. One BetterToken API Key works with all available models.
"gpt-image-2"A detailed description of the image to generate.
"A futuristic AI product poster on a light background, with glass textures, a clean composition, and a premium technology aesthetic."Allowed range: 1–10; start with 1. Fewer images may be delivered than requested. Iterate data[] and use actual-delivery billing.
1Omit or use auto for automatic sizing. For WxH, both dimensions must be positive multiples of 16, each at most 3840, aspect ratio at most 3:1, total pixels 655360–8294400. Examples are not an exhaustive enum; 2080x2080 also meets the geometry rules. Inspect actual decoded dimensions. Valid parameters do not guarantee an available service.
"1024x1024"["auto","1024x1024","2048x2048","2080x2080","3840x2160"]Requested output format; png is recommended, but the response is not guaranteed to have been transcoded to PNG. Detect PNG, JPEG, or WebP from actual bytes before choosing an extension. Convert locally if a specific format is required.
"png"gpt-image-2 accepts auto, low, medium, high. The two 2.5 models also accept xhigh and max. Omit for the model default; JSON null is treated as omitted, while multipart requires a nonempty string. Valid values do not guarantee an available service for every model, size, and editing combination. Acceptance does not guarantee that a higher setting improves image quality.
"auto"प्रतिक्रिया
200BetterToken billing extension. Settlement follows the actual delivered pixels and billing tier, which can differ from the requested tier. Amounts are decimal strings; use the returned values.
OpenAI-compatible image response. Iterate data[] and read each image from b64_json. Fewer images may be delivered than requested.
1710000000Show child attributes
BetterToken billing extension. Settlement follows the actual delivered pixels and billing tier, which can differ from the requested tier. Amounts are decimal strings; use the returned values.
Show child attributes
Settlement currency; do not assume a fixed currency.
Final request amount as a decimal string; use decimal arithmetic for calculations.
Delivered image indices, actual dimensions, billing tiers, and per-image amounts. index is zero-based and corresponds to data[].
Settled amount for this image as a decimal string.
Resolution tier inferred from the request; it may differ from the actual billing tier.
{
"created": 1710000000,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA...(truncated)",
"revised_prompt": "<string>"
}
],
"bettertoken_image_billing": {
"currency": "<string>",
"settled_amount": "<string>",
"outputs": [
{
"index": 0,
"width": 1,
"height": 1,
"billing_resolution": "1K",
"currency": "<string>",
"amount": "<string>"
}
],
"partial": false,
"requested_resolution": "<string>"
}
}400Invalid request format, missing parameters, malformed JSON or multipart data, or invalid dimensions.
Show child attributes
"invalid request""invalid_request_error""invalid_request""insufficient quota"{
"error": {
"message": "invalid request",
"type": "invalid_request_error",
"code": "invalid_request"
},
"message": "insufficient quota"
}401The BetterToken API Key is missing or invalid.
Show child attributes
"invalid request""invalid_request_error""invalid_request""insufficient quota"{
"error": {
"message": "invalid request",
"type": "invalid_request_error",
"code": "invalid_request"
},
"message": "insufficient quota"
}402The account has insufficient credit or balance.
Show child attributes
"invalid request""invalid_request_error""invalid_request""insufficient quota"{
"error": {
"message": "invalid request",
"type": "invalid_request_error",
"code": "invalid_request"
},
"message": "insufficient quota"
}403Insufficient balance or token quota: error.code is insufficient_user_quota. Funds must also cover the reservation of the highest-tier unit price times the image-count upper bound, before actual-delivery settlement. Inspect error.code rather than treating every 403 as an authorization error.
{
"error": {
"code": "insufficient_user_quota",
"message": "Insufficient balance or token quota."
}
}429A rate or concurrency limit was reached, or the upstream service is busy.
Show child attributes
"invalid request""invalid_request_error""invalid_request""insufficient quota"{
"error": {
"message": "invalid request",
"type": "invalid_request_error",
"code": "invalid_request"
},
"message": "insufficient quota"
}500The gateway or upstream service returned an error.
Show child attributes
"invalid request""invalid_request_error""invalid_request""insufficient quota"{
"error": {
"message": "invalid request",
"type": "invalid_request_error",
"code": "invalid_request"
},
"message": "insufficient quota"
}
