Loading...
Loading...
Generate, remix, edit, inpaint, reframe, background-process, describe, layerize, and upscale images with the Ideogram Developer API. Use when Codex must integrate Ideogram 4.0 or 3.0, render reliable typography or structured layouts, use style or character references, build synchronous or webhook workflows, migrate legacy Ideogram endpoints, or reason about Ideogram API pricing, safety, privacy, and production QA.
npx skill4agent add calesthio/generative-media-skills ideogram-image| Need | Canonical route | Effective model/lifecycle |
|---|---|---|
| New text/layout generation | | Ideogram 4.0; current flagship API route |
| Asynchronous new generation | | Ideogram 4.0; webhook plus polling |
| V4 image-guided change | | Ideogram 4.0 |
| Style/character references, mask edit, reframe, replacement background | | Ideogram 3.0; current specialized routes |
| Prompt-only multi-image edit | | Current instructional-edit route; docs expose V3 resolution controls but no request model field |
| Older body-selected generation | | Explicitly labeled legacy in the reference; avoid for new work |
modelideogram-v4ideogram-v3ModelEnumV_1V_1_TURBOV_2V_2_TURBOV_2AV_2A_TURBOAUTOV_2V_3V_4custom_model_urimodel/<model_name>/version/<version_name>POST /v1/ideogram-v3/edit/v1/ideogram-v3/inpainthttps://api.ideogram.aiApi-Key: <key>IDEOGRAM_API_KEYmultipart/form-data| Method and path | Required request | Optional request | Success shape |
|---|---|---|---|
| exactly one of form | | null` |
| same V4 form; HTTPS webhook query required | same V4 options | |
| URL-safe base64 generation ID | none | pending/failed status or completed data |
| form | | |
| JSON | | |
| form | | |
| form | V3 generation/style/reference fields below | |
| form | | X2 |
| form | Magic Prompt, count, seed, speed, V3 style/reference fields | V3 image response |
| form | | V3 image response |
| form | count, seed, speed, preset/palette/style code/reference | V3 image response |
| form | Magic Prompt, count, seed, speed, preset/palette/style code/reference | V3 image response |
| form | none | `{created, data:[{url:string |
| form | | see documentation ambiguity below |
| form | count, seed, Magic Prompt, V3 resolution or aspect ratio, | |
| form | object fields | legacy-shaped image response |
| form | `describe_model_version:V_2 | V_3 |
/v1/editGET/POST /datasetsGET /datasets/{dataset_id}POST /datasets/{dataset_id}/upload_assetsPOST /v1/ideogram-v3/train-modelGET /modelsGET /models/{model_id}model_namePOST /generate/v1/ideogram-v3/edit/edit/remix/reframev4/editv4/inpaintv4/reframev4/replace-backgroundV4JsonPrompt{
"high_level_description": "required string",
"style_description": {
"aesthetics": "optional string",
"art_style": "optional string",
"lighting": "optional string",
"medium": "optional string",
"photo": "optional string"
},
"compositional_deconstruction": {
"background": "required string",
"elements": [
{"type": "obj", "desc": "required string", "bbox": [0, 0, 1000, 1000]},
{"type": "text", "text": "required literal string", "desc": "required string", "bbox": [0, 0, 1000, 1000]}
]
}
}high_level_descriptioncompositional_deconstruction.backgroundelementstypedesctypetextdescstyle_descriptionbbox[y_min,x_min,y_max,x_max][0,1000]minItemsmaxItems2048x2048, 1440x2880, 2880x1440, 1664x2496, 2496x1664, 1792x2240,
2240x1792, 1440x2560, 2560x1440, 1600x2560, 2560x1600, 1728x2304,
2304x1728, 1296x3168, 3168x1296, 1152x2944, 2944x1152, 1248x3328,
3328x1248, 1280x3072, 3072x1280, 1024x3072, 3072x1024AUTO1x41x31x29x1610x162x33x44x51x15x44x33x216x1016x92x13x14x11x33x11x22x19x1616x910x1616x102x33x23x44x34x55x41x1aspect_ratioresolution1x1ResolutionV3num_imagesseedrendering_speedFLASH|TURBO|DEFAULT|QUALITYDEFAULTFLASHFLASHAUTO|GENERAL|REALISTIC|DESIGN|FICTIONGENERALAUTO|ON|OFF80S_ILLUSTRATION, 90S_NOSTALGIA, ABSTRACT_ORGANIC, ANALOG_NOSTALGIA, ART_BRUT,
ART_DECO, ART_POSTER, AURA, AVANT_GARDE, BAUHAUS, BLUEPRINT, BLURRY_MOTION,
BRIGHT_ART, C4D_CARTOON, CHILDRENS_BOOK, COLLAGE, COLORING_BOOK_I, COLORING_BOOK_II,
CUBISM, DARK_AURA, DOODLE, DOUBLE_EXPOSURE, DRAMATIC_CINEMA, EDITORIAL,
EMOTIONAL_MINIMAL, ETHEREAL_PARTY, EXPIRED_FILM, FLAT_ART, FLAT_VECTOR,
FOREST_REVERIE, GEO_MINIMALIST, GLASS_PRISM, GOLDEN_HOUR, GRAFFITI_I, GRAFFITI_II,
HALFTONE_PRINT, HIGH_CONTRAST, HIPPIE_ERA, ICONIC, JAPANDI_FUSION, JAZZY,
LONG_EXPOSURE, MAGAZINE_EDITORIAL, MINIMAL_ILLUSTRATION, MIXED_MEDIA, MONOCHROME,
NIGHTLIFE, OIL_PAINTING, OLD_CARTOONS, PAINT_GESTURE, POP_ART, RETRO_ETCHING,
RIVIERA_POP, SPOTLIGHT_80S, STYLIZED_RED, SURREAL_COLLAGE, TRAVEL_POSTER,
VINTAGE_GEO, VINTAGE_POSTER, WATERCOLOR, WEIRD, WOODBLOCK_PRINT{"name":"EMBER|FRESH|JUNGLE|MAGIC|MELON|MOSAIC|PASTEL|ULTRAMARINE"}{"members":[{"color_hex":"#RRGGBB","color_weight":0.05..1.0}]}style_codesstyle_codesstyle_reference_imagesstyle_type{"created":"date-time","data":[{"url":"uri or null","prompt":"string","resolution":"ResolutionV4","is_image_safe":true,"seed":12345}],"response_type":"url"}upscaled_resolutionstyle_typecreateddatapromptresolutionis_image_safeseedis_image_safeurlgeneration_idstatus:pending|completed|failedcreatedresponse_type:"url"data/upscale{created, request_id?, data?}ImageObject/describe{descriptions:[{text?:string}]}/v1/ideogram-v4/describe{json_prompt:V4JsonPrompt}/v1/remove-background{created,data:[{url?:string|null,is_image_safe:boolean}]}descriptionstextjson_prompttype:"text"textdesctext_promptjson_prompt/v1/ideogram-v4/magic-prompt/v1/ideogram-v4/describeDESIGNstyle_presetimage_weightjson_promptdesctext/magic-promptimport hashlib
import json
import os
from io import BytesIO
from pathlib import Path
import requests
from PIL import Image
API = "https://api.ideogram.ai"
KEY = os.environ["IDEOGRAM_API_KEY"]
prompt = {
"high_level_description": "A premium square coffee poster with one centered headline.",
"style_description": {"medium": "screen-printed poster", "aesthetics": "minimal, warm"},
"compositional_deconstruction": {
"background": "Flat cream paper with subtle grain.",
"elements": [{
"type": "text",
"text": "MORNING, MADE BOLD",
"desc": "Large centered uppercase condensed black headline",
"bbox": [360, 100, 600, 900],
}],
},
}
with requests.Session() as session:
response = session.post(
f"{API}/v1/ideogram-v4/generate",
headers={"Api-Key": KEY},
files={
"json_prompt": (None, json.dumps(prompt)),
"resolution": (None, "2048x2048"),
"rendering_speed": (None, "TURBO"),
},
timeout=(10, 180),
)
response.raise_for_status()
manifest = {"request": {"json_prompt": prompt, "resolution": "2048x2048",
"rendering_speed": "TURBO"}, "results": []}
signatures = {
"image/png": (b"\x89PNG\r\n\x1a\n", ".png"),
"image/jpeg": (b"\xff\xd8\xff", ".jpg"),
"image/webp": (b"RIFF", ".webp"),
}
for index, item in enumerate(response.json()["data"], start=1):
if not item["is_image_safe"] or not item.get("url"):
raise RuntimeError(f"Ideogram candidate {index} is unusable")
with session.get(item["url"], timeout=(10, 60), stream=True) as download:
download.raise_for_status()
limit = 50 * 1024 * 1024
declared = int(download.headers.get("content-length", "0") or 0)
if declared > limit:
raise RuntimeError("Declared image exceeds local 50 MiB safety limit")
body = bytearray()
for chunk in download.iter_content(1024 * 1024):
body.extend(chunk)
if len(body) > limit:
raise RuntimeError("Streaming image exceeded local 50 MiB safety limit")
raw = bytes(body)
media_type = download.headers.get("content-type", "").split(";", 1)[0].lower()
if media_type not in signatures or not raw.startswith(signatures[media_type][0]):
raise RuntimeError(f"Unexpected image payload: {media_type}")
if media_type == "image/webp" and raw[8:12] != b"WEBP":
raise RuntimeError("RIFF payload is not WebP")
with Image.open(BytesIO(raw)) as decoded:
decoded.verify()
with Image.open(BytesIO(raw)) as decoded:
actual_size = decoded.size
expected_size = tuple(map(int, item["resolution"].lower().split("x")))
if actual_size != expected_size:
raise RuntimeError(f"Expected {expected_size}, decoded {actual_size}")
output = Path(f"poster-{index}{signatures[media_type][1]}")
temporary = output.with_suffix(output.suffix + ".tmp")
temporary.write_bytes(raw)
temporary.replace(output)
manifest["results"].append({**item, "path": str(output),
"download_content_type": media_type,
"sha256": hashlib.sha256(raw).hexdigest()})
Path("poster.metadata.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")import hashlib
import json
import os
from io import BytesIO
from pathlib import Path
import requests
from PIL import Image
API = "https://api.ideogram.ai"
image_path, mask_path, style_path = map(Path, ("input.png", "mask.png", "style.png"))
mime_by_format = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp"}
formats = {}
for path in (image_path, mask_path, style_path):
if path.stat().st_size > 10 * 1024 * 1024:
raise ValueError(f"{path} exceeds 10 MB")
with Image.open(path) as check:
check.verify()
if check.format not in mime_by_format:
raise ValueError(f"Unsupported image format for {path}: {check.format}")
formats[path] = check.format
with Image.open(image_path) as source_check, Image.open(mask_path) as mask_check:
if source_check.size != mask_check.size:
raise ValueError("mask must match input dimensions")
if mask_check.mode not in {"1", "L"}:
raise ValueError("mask must be binary/grayscale")
if set(mask_check.convert("L").getdata()) - {0, 255}:
raise ValueError("mask must contain only black and white pixels")
if style_path.stat().st_size > 10 * 1024 * 1024:
raise ValueError("style-reference group exceeds 10 MB")
with image_path.open("rb") as image, mask_path.open("rb") as mask, style_path.open("rb") as style:
response = requests.post(
f"{API}/v1/ideogram-v3/inpaint",
headers={"Api-Key": os.environ["IDEOGRAM_API_KEY"]},
data={"prompt": "Replace only the black mask region with a red enamel teapot", "num_images": "2", "seed": "42"},
files=[("image", (image_path.name, image, mime_by_format[formats[image_path]])),
("mask", (mask_path.name, mask, mime_by_format[formats[mask_path]])),
("style_reference_images", (style_path.name, style, mime_by_format[formats[style_path]]))],
timeout=(10, 180),
)
response.raise_for_status()
payload = response.json()
manifest = {
"endpoint": "/v1/ideogram-v3/inpaint",
"request": {"prompt": "Replace only the black mask region with a red enamel teapot", "num_images": 2, "seed": 42},
"input_sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (image_path, mask_path, style_path)},
"results": [],
}
for index, item in enumerate(payload["data"], start=1):
if not item["is_image_safe"] or not item.get("url"):
raise RuntimeError(f"Candidate {index} is not usable")
with requests.get(item["url"], timeout=(10, 60), stream=True) as download:
download.raise_for_status()
limit = 50 * 1024 * 1024
declared = int(download.headers.get("content-length", "0") or 0)
if declared > limit:
raise RuntimeError("Declared image exceeds local 50 MiB safety limit")
body = bytearray()
for chunk in download.iter_content(1024 * 1024):
body.extend(chunk)
if len(body) > limit:
raise RuntimeError("Streaming image exceeded local 50 MiB safety limit")
raw = bytes(body)
media_type = download.headers.get("content-type", "").split(";", 1)[0].lower()
signatures = {"image/png": (b"\x89PNG\r\n\x1a\n", ".png"),
"image/jpeg": (b"\xff\xd8\xff", ".jpg"),
"image/webp": (b"RIFF", ".webp")}
if media_type not in signatures or not raw.startswith(signatures[media_type][0]):
raise RuntimeError(f"Unexpected output type: {media_type}")
if media_type == "image/webp" and raw[8:12] != b"WEBP":
raise RuntimeError("RIFF payload is not WebP")
with Image.open(BytesIO(raw)) as decoded:
decoded.verify()
with Image.open(BytesIO(raw)) as decoded:
actual_size = decoded.size
expected_size = tuple(map(int, item["resolution"].lower().split("x")))
if actual_size != expected_size:
raise RuntimeError(f"Expected {expected_size}, decoded {actual_size}")
output = Path(f"inpaint-{index}{signatures[media_type][1]}")
temporary = output.with_suffix(output.suffix + ".tmp")
temporary.write_bytes(raw)
temporary.replace(output)
manifest["results"].append({**item, "path": str(output), "content_type": media_type,
"sha256": hashlib.sha256(raw).hexdigest()})
Path("inpaint.metadata.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")pendingcompletedfailedimport hashlib
import json
import os
import random
import time
from io import BytesIO
from pathlib import Path
import requests
from PIL import Image
API = "https://api.ideogram.ai"
headers = {"Api-Key": os.environ["IDEOGRAM_API_KEY"]}
webhook_url = os.environ["IDEOGRAM_WEBHOOK_URL"]
if not webhook_url.startswith("https://"):
raise ValueError("IDEOGRAM_WEBHOOK_URL must be public HTTPS")
accepted = requests.post(
f"{API}/v1/ideogram-v4/async/generate",
params={"webhook_url": webhook_url},
headers=headers,
files={"text_prompt": (None, "A crisp editorial photograph of a red bicycle")},
timeout=(10, 30),
)
accepted.raise_for_status()
generation_id = accepted.json()["generation_id"]
Path("async.accepted.json").write_text(json.dumps({
"generation_id": generation_id,
"submitted_unix": int(time.time()),
"webhook_url_sha256": hashlib.sha256(webhook_url.encode("utf-8")).hexdigest(),
}, indent=2), encoding="utf-8")
deadline = time.monotonic() + 10 * 60
completed = False
for attempt in range(40):
if time.monotonic() >= deadline:
break
try:
result = requests.get(
f"{API}/v1/generations/{generation_id}", headers=headers, timeout=(10, 30)
)
except (requests.Timeout, requests.ConnectionError):
time.sleep(min(30, 2 ** min(attempt, 5)) + random.random())
continue
if result.status_code == 429:
time.sleep(min(30, 2 ** min(attempt, 5)) + random.random())
continue
if result.status_code in {500, 502, 503, 504}:
time.sleep(min(30, 2 ** min(attempt, 5)) + random.random())
continue
result.raise_for_status()
payload = result.json()
if payload["status"] == "completed":
manifest = {"generation_id": generation_id, "results": []}
for index, item in enumerate(payload["data"], start=1):
if not item["is_image_safe"] or not item.get("url"):
raise RuntimeError(f"Completed candidate {index} is unusable")
with requests.get(item["url"], timeout=(10, 60), stream=True) as download:
download.raise_for_status()
limit = 50 * 1024 * 1024
declared = int(download.headers.get("content-length", "0") or 0)
if declared > limit:
raise RuntimeError("Declared image exceeds local 50 MiB safety limit")
body = bytearray()
for chunk in download.iter_content(1024 * 1024):
body.extend(chunk)
if len(body) > limit:
raise RuntimeError("Streaming image exceeded local 50 MiB safety limit")
raw = bytes(body)
media_type = download.headers.get("content-type", "").split(";", 1)[0].lower()
signatures = {"image/png": (b"\x89PNG\r\n\x1a\n", ".png"),
"image/jpeg": (b"\xff\xd8\xff", ".jpg"),
"image/webp": (b"RIFF", ".webp")}
if media_type not in signatures or not raw.startswith(signatures[media_type][0]):
raise RuntimeError(f"Unexpected output type: {media_type}")
if media_type == "image/webp" and raw[8:12] != b"WEBP":
raise RuntimeError("RIFF payload is not WebP")
with Image.open(BytesIO(raw)) as decoded:
decoded.verify()
with Image.open(BytesIO(raw)) as decoded:
actual_size = decoded.size
expected_size = tuple(map(int, item["resolution"].lower().split("x")))
if actual_size != expected_size:
raise RuntimeError(f"Expected {expected_size}, decoded {actual_size}")
output = Path(f"async-{index}{signatures[media_type][1]}")
temporary = output.with_suffix(output.suffix + ".tmp")
temporary.write_bytes(raw)
temporary.replace(output)
manifest["results"].append({**item, "path": str(output), "content_type": media_type,
"sha256": hashlib.sha256(raw).hexdigest()})
Path("async.metadata.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
completed = True
break
if payload["status"] == "failed":
raise RuntimeError(f"generation failed: {generation_id}")
time.sleep(min(30, 2 ** min(attempt, 5)) + random.random())
if not completed:
raise TimeoutError(f"generation still pending at deadline: {generation_id}")import base64
import hashlib
import json
import sqlite3
import time
import requests
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
JWKS_URL = "https://api.ideogram.ai/v1/.well-known/jwks.json"
H_GENERATION = "X-Ideogram-Webhook-Generation-Id"
H_USER = "X-Ideogram-Webhook-User-Id"
H_TIMESTAMP = "X-Ideogram-Webhook-Timestamp"
H_KEY = "X-Ideogram-Webhook-Key-Id"
H_SIGNATURE = "X-Ideogram-Webhook-Signature"
_JWKS_CACHE = {"keys": None, "expires": 0.0}
def b64url_decode(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
def fetch_jwks(*, force_refresh: bool = False, ttl_seconds: int = 300) -> list[dict]:
now = time.monotonic()
if not force_refresh and _JWKS_CACHE["keys"] is not None and now < _JWKS_CACHE["expires"]:
return _JWKS_CACHE["keys"]
response = requests.get(JWKS_URL, timeout=(5, 15))
response.raise_for_status()
keys = response.json()["keys"]
_JWKS_CACHE.update({"keys": keys, "expires": now + ttl_seconds})
return keys
def verify_with_keys(keys: list[dict], key_hint: str, signature: bytes, message: bytes) -> bool:
ordered = sorted(keys, key=lambda key: 0 if key.get("kid") == key_hint else 1)
for key in ordered:
if key.get("kty") != "OKP" or key.get("crv") != "Ed25519" or not key.get("x"):
continue
try:
Ed25519PublicKey.from_public_bytes(b64url_decode(key["x"])).verify(signature, message)
return True
except (InvalidSignature, ValueError):
continue
return False
def verify_delivery(headers, raw_body: bytes, *, max_age_seconds: int = 300) -> dict:
required = [H_GENERATION, H_USER, H_TIMESTAMP, H_KEY, H_SIGNATURE]
missing = [name for name in required if not headers.get(name)]
if missing:
raise ValueError(f"Missing webhook headers: {missing}")
timestamp = int(headers[H_TIMESTAMP])
if abs(int(time.time()) - timestamp) > max_age_seconds:
raise ValueError("Stale webhook timestamp")
signature_hex = headers[H_SIGNATURE]
if signature_hex != signature_hex.lower():
raise ValueError("Signature must be lowercase hexadecimal")
try:
signature = bytes.fromhex(signature_hex)
except ValueError as exc:
raise ValueError("Invalid signature hexadecimal") from exc
body_hash = hashlib.sha256(raw_body).hexdigest()
message = "\n".join([
headers[H_GENERATION], headers[H_USER], headers[H_TIMESTAMP], body_hash
]).encode("utf-8")
keys = fetch_jwks()
if not verify_with_keys(keys, headers[H_KEY], signature, message):
# Refresh once so key rotation does not require a process restart.
if not verify_with_keys(fetch_jwks(force_refresh=True), headers[H_KEY], signature, message):
raise ValueError("Webhook signature verification failed")
payload = json.loads(raw_body)
if payload.get("generation_id") != headers[H_GENERATION]:
raise ValueError("Header/body generation_id mismatch")
return payload
def handle_webhook(headers, raw_body: bytes, database_path="ideogram-webhooks.sqlite") -> int:
payload = verify_delivery(headers, raw_body)
generation_id = payload["generation_id"]
with sqlite3.connect(database_path) as db:
db.execute("""CREATE TABLE IF NOT EXISTS deliveries (
generation_id TEXT PRIMARY KEY, payload_json TEXT NOT NULL,
received_unix INTEGER NOT NULL, status TEXT NOT NULL
)""")
db.execute(
"INSERT OR IGNORE INTO deliveries VALUES (?, ?, ?, 'received')",
(generation_id, json.dumps(payload, separators=(",", ":")), int(time.time())),
)
# Framework adapter should return this after commit; a worker processes 'received' rows.
return 204requestsPillowcryptographyhandle_webhookGET /v1/.well-known/jwks.jsongeneration_id| Status | Documented meaning | Action |
|---|---|---|
| 400 | invalid input; also current unsupported speed combinations | fix request; do not retry unchanged |
| 401 | missing/invalid authorization | stop, repair secret/account |
| 402 | insufficient credits/quota on | fund or change approved plan; do not loop |
| 403 | forbidden or not authorized on documented routes such as V3 Remix/Upscale | stop; verify account entitlement and route access; do not retry unchanged |
| 404 | unknown async generation ID | verify stored ID/environment |
| 422 | prompt or image safety failure; documented body | do not evade; revise or reject according to policy |
| 429 | too many requests | reduce in-flight work and retry with bounded exponential jitter |
| 503 | temporary service unavailable on selected routes such as | bounded retry after backoff |
Retry-Aftergeneration_idcustom_model_uriis_image_safeenable_copyright_detection=trueis_image_safe:false/v1/ideogram-v3/edit/edit/v1/ideogram-v3/inpaintimage_fileimage/generate/remix/reframe/v1/ideogram-v4/remixmodelmagic_prompt_optionWebhookUrlrequest_idgeneration_idgeneration_idrequest_idtext_blocksLayerizeTextResponsebase_image_urloriginal_image_urlseedtext_blocksnum_images