ideogram-image — Claude Code skill: what it does, install
ideogram-image is a Claude Code skill for the Ideogram Developer API. It activates for image generation, editing, V4 and V3 integration, and webhook workflows.
MIT 137 installs ★ 252 updated 2026-07-14
npx skills add calesthio/generative-media-skills --skill ideogram-image -a claude-codeWhat ideogram-image does
ideogram-image connects coding agents to the Ideogram Developer API for image generation and editing. It covers remix, inpaint, reframing, background removal, image description, layerization, upscaling, typography-focused layouts, and style or character references.
Requests use https://api.ideogram.ai with Api-Key: <key>. Most operations use multipart/form-data; V4 Magic Prompt uses JSON. Async generation requires an HTTPS webhook URL. The legacy /v1/ideogram-v3/edit route should be migrated to /v1/ideogram-v3/inpaint.
Successful generation calls return image URLs rather than embedded bytes. The URLs expire without a published fixed lifetime, so wanted results need immediate downloading; the key can be read from IDEOGRAM_API_KEY and kept out of logs.
What it helps with
- generate images with readable text and structured layouts
- edit selected image areas with a mask
- reframe an image or replace its background
- connect synchronous and webhook-based generation
- migrate an integration from a legacy Ideogram route
Example prompts for the agent
- Generate an image through Ideogram 4.0 and save the returned result.
- Use the V3 inpaint route with
input.pngandmask.png. - Migrate
/v1/ideogram-v3/editto/v1/ideogram-v3/inpaintand add webhook handling.
How to install ideogram-image
1Skills CLI (Vercel)
npx skills add calesthio/generative-media-skills --skill ideogram-image -a claude-code2Manually: put the files in place
~/.claude/skills/ideogram-image/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/ideogram-image/
1Skills CLI (Vercel)
npx skills add calesthio/generative-media-skills --skill ideogram-image -a codex2Manually: put the files in place
.agents/skills/ideogram-image/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add calesthio/generative-media-skills --skill ideogram-image -a cursor2Manually: put the files in place
.cursor/skills/ideogram-image/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install calesthio/generative-media-skills skills/providers/image-generation/ideogram-image2Manually: put the files in place
.github/skills/ideogram-image/SKILL.md1Skills CLI (Vercel)
npx skills add calesthio/generative-media-skills --skill ideogram-image -a gemini-cli2Platform CLI
gemini skills install https://github.com/calesthio/generative-media-skills --path skills/providers/image-generation/ideogram-imageManually: put the files in place
.devin/skills/ideogram-image/SKILL.mdThe legacy .windsurf/skills/ path still works
Skills CLI (Vercel)
npx skills add calesthio/generative-media-skills --skill ideogram-image -a opencodeClaude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about ideogram-image
How do I install ideogram-image in Claude Code?
Run npx skills add calesthio/generative-media-skills --skill ideogram-image -a claude-code, then use ~/.claude/skills/ideogram-image/SKILL.md.
What does ideogram-image do?
The skill helps integrate the Ideogram Developer API for image generation, remix, inpaint, reframing, background removal, description, and upscaling. It also covers V4, V3, and asynchronous webhook requests.
What does ideogram-image require?
It requires Ideogram API billing setup, a secret API key, and access to https://api.ideogram.ai. The key is sent as Api-Key: <key>; asynchronous generation also requires an HTTPS webhook URL.
Source text
SKILL.md · MIT
---
name: ideogram-image
description: 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.
---
# Ideogram Image
Use the official Developer API directly and treat the checked date below as part of the contract.
## Evidence labels and refresh rule
- **Documented**: stated by an Ideogram first-party page or the official OpenAPI document.
- **Inference**: a conclusion not guaranteed by the published contract.
- **Production heuristic**: operational advice, not an Ideogram promise.
- Treat model availability, endpoint lifecycle, prices, limits, policy, and ephemeral URL lifetime as volatile. Re-check the [documentation index](https://developer.ideogram.ai/llms.txt), [OpenAPI 3.1 JSON](https://developer.ideogram.ai/openapi.json), [pricing](https://ideogram.ai/api-pricing/), [API agreement](https://ideogram.ai/legal/api-tos), [usage policy](https://ideogram.ai/legal/usage-policy), and [privacy policy](https://ideogram.ai/legal/privacy) before a release or quote.
Unless a paragraph says otherwise, API facts below are **Documented — checked 2026-07-09**.
## Select a route, not an invented model string
| Need | Canonical route | Effective model/lifecycle |
|---|---|---|
| New text/layout generation | `POST /v1/ideogram-v4/generate` | Ideogram 4.0; current flagship API route |
| Asynchronous new generation | `POST /v1/ideogram-v4/async/generate` | Ideogram 4.0; webhook plus polling |
| V4 image-guided change | `POST /v1/ideogram-v4/remix` | Ideogram 4.0 |
| Style/character references, mask edit, reframe, replacement background | `/v1/ideogram-v3/*` routes below | Ideogram 3.0; current specialized routes |
| Prompt-only multi-image edit | `POST /v1/edit` | Current instructional-edit route; docs expose V3 resolution controls but no request model field |
| Older body-selected generation | `/generate`, `/edit`, `/remix`, `/reframe` | Explicitly labeled legacy in the reference; avoid for new work |
Do not send `model` to V4 or V3 route-scoped endpoints. Their model identifiers are the route segments `ideogram-v4` and `ideogram-v3`. The legacy `ModelEnum` accepts `V_1`, `V_1_TURBO`, `V_2`, `V_2_TURBO`, `V_2A`, `V_2A_TURBO`, or `AUTO`; it does not expose V3/V4. The generic Describe route accepts `V_2`, `V_3`, or `V_4`. A V3 custom model is addressed by `custom_model_uri` in the form `model/<model_name>/version/<version_name>`.
The official reference explicitly says `POST /v1/ideogram-v3/edit` is legacy and will be removed; migrate it to `/v1/ideogram-v3/inpaint`. No first-party API retirement date is published for V3 or the remaining legacy routes. The app model history says 0.1 and 0.2 are retired, but those are not current API request IDs. Do not infer an API retirement schedule from the app history.
## Authenticate and establish the wire contract
Use base URL `https://api.ideogram.ai`. Send the secret only as `Api-Key: <key>`. API billing/account setup is separate from Ideogram app subscriptions. The full key is shown only once when created.
**Production heuristic:** read the key from `IDEOGRAM_API_KEY`, redact it from logs, use a secret manager in deployed systems, and set connect/read timeouts. The environment-variable name is a client convention, not an Ideogram-defined name.
Most current operations use `multipart/form-data`; let the HTTP library set its boundary. V4 Magic Prompt uses JSON. All successful generation/edit responses return URLs, not embedded image bytes. Download every wanted result immediately: first-party docs say image links expire but do not publish a fixed lifetime. There is no documented output-format selector; do not promise PNG/JPEG from the URL suffix. Inspect response headers/bytes after download.
## Use only documented operations
### Current image and vision surface
| Method and path | Required request | Optional request | Success shape |
|---|---|---|---|
| `POST /v1/ideogram-v4/generate` | exactly one of form `text_prompt:string` or `json_prompt:V4JsonPrompt` | `resolution:ResolutionV4`, `rendering_speed`, `enable_copyright_detection:boolean|null` | `ImageGenerationResponseV4` |
| `POST /v1/ideogram-v4/async/generate?webhook_url=<https-url>` | same V4 form; HTTPS webhook query required | same V4 options | `{generation_id:string}` |
| `GET /v1/generations/{generation_id}` | URL-safe base64 generation ID | none | pending/failed status or completed data |
| `POST /v1/ideogram-v4/remix` | form `image:file`, `text_prompt:string` | `image_weight:1..100`, V4 resolution/speed/copyright detection | `ImageGenerationResponseV4` |
| `POST /v1/ideogram-v4/magic-prompt` | JSON `text_prompt:string` | `aspect_ratio:AspectRatioV4=AUTO` | `{json_prompt:V4JsonPrompt, aspect_ratio}` |
| `POST /v1/ideogram-v4/describe` | form `image_file:file` (JPEG/PNG/WebP, max 10 MB) | `include_bbox:boolean=true` | `{json_prompt:V4JsonPrompt}` |
| `POST /v1/ideogram-v3/generate` | form `prompt:string` | V3 generation/style/reference fields below | `ImageGenerationResponseV3` |
| `POST /v1/ideogram-v3/generate-transparent` | form `prompt:string` | `seed`, `upscale_factor:X1|X2|X4=X1`, `aspect_ratio`, speed except FLASH, Magic Prompt, negative prompt, count | V3 image response |
| `POST /v1/ideogram-v3/inpaint` | form `image:file`, same-sized black/white `mask:file`, `prompt:string` | Magic Prompt, count, seed, speed, V3 style/reference fields | V3 image response |
| `POST /v1/ideogram-v3/remix` | form `image:file`, `prompt:string` | `image_weight=50`, seed, size, speed, Magic Prompt, negative prompt, count, style/reference fields | V3 image response |
| `POST /v1/ideogram-v3/reframe` | form `image:file`, `resolution:ResolutionV3` | count, seed, speed, preset/palette/style code/reference | V3 image response |
| `POST /v1/ideogram-v3/replace-background` | form `image:file`, `prompt:string` | Magic Prompt, count, seed, speed, preset/palette/style code/reference | V3 image response |
| `POST /v1/remove-background` | form `image:file` | none | `{created, data:[{url:string|null,is_image_safe:boolean}]}`; one entry |
| `POST /v1/ideogram-v3/layerize-text` | form `image:file` | `prompt:string`, `seed` | see documentation ambiguity below |
| `POST /v1/edit` | form `prompt:string` plus `images:file[]` or `image_urls:string[]` when editing inputs | count, seed, Magic Prompt, V3 resolution or aspect ratio, `transparent_background=false` | `{created,data:V1EditImageObject[]}` |
| `POST /upscale` | form `image_file:file`, `image_request` JSON object | object fields `prompt`, `resemblance=50`, `detail=50`, `magic_prompt_option`, `num_images=1`, `seed` | legacy-shaped image response |
| `POST /describe` | form `image_file:file` | `describe_model_version:V_2|V_3|V_4=V_3` | `{descriptions:[{text:string}]}` |
All uploaded image fields above accept JPEG, PNG, or WebP and are limited to 10 MB unless `/v1/edit` is used: that route accepts up to 10 uploaded images, each up to 10 MB, or up to 10 Ideogram image URLs. V3 style-reference and character-reference groups have a 10 MB total per group. The V3 API currently supports one character reference image; corresponding optional grayscale masks must match reference count and dimensions.
The OpenAPI also documents custom-model administration: `GET/POST /datasets`, `GET /datasets/{dataset_id}`, `POST /datasets/{dataset_id}/upload_assets`, `POST /v1/ideogram-v3/train-model`, `GET /models`, and `GET /models/{model_id}`. The current train-route/OpenAPI contract requires 15–100 dataset images, while the first-party tutorial says training can start at 10. Use at least 15 unless Ideogram resolves the conflict, validate before the $40 run, and record the live schema used. `model_name` is 5–30 alphanumeric/space/hyphen characters. Use these operations only for an explicit custom-model task.
Legacy-only documented operations are `POST /generate`, `/v1/ideogram-v3/edit`, `/edit`, `/remix`, and `/reframe`. Preserve them only while migrating; do not invent undocumented `v4/edit`, `v4/inpaint`, `v4/reframe`, or `v4/replace-background` routes.
### Exact shared schemas
`V4JsonPrompt`:
```json
{
"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]}
]
}
}
```
Require `high_level_description`, `compositional_deconstruction.background`, and `elements`. Require `type` plus `desc` for objects; require `type`, literal `text`, and `desc` for text. `style_description` and each `bbox` are optional. Interpret a bbox as four normalized integers `[y_min,x_min,y_max,x_max]` on a 1000×1000 coordinate system. The prose defines four values in `[0,1000]`; the published JSON Schema does not encode `minItems`, `maxItems`, or numeric bounds, so validate them client-side.
V4 resolutions are exactly:
```text
2048x2048, 1440x2880, 2880x1440, 1664x2496, 2496x1664, 1792x2240,
2240x1792, 1440x2560, 2560x1440, 1600x2560, 2560x1600, 1728x2304,
2304x1728, 1296x3168, 3168x1296, 1152x2944, 2944x1152, 1248x3328,
3328x1248, 1280x3072, 3072x1280, 1024x3072, 3072x1024
```
V4 Magic Prompt aspect ratios are `AUTO`, `1x4`, `1x3`, `1x2`, `9x16`, `10x16`, `2x3`, `3x4`, `4x5`, `1x1`, `5x4`, `4x3`, `3x2`, `16x10`, `16x9`, `2x1`, `3x1`, `4x1`.
V3 aspect ratios are `1x3`, `3x1`, `1x2`, `2x1`, `9x16`, `16x9`, `10x16`, `16x10`, `2x3`, `3x2`, `3x4`, `4x3`, `4x5`, `5x4`, `1x1`. Do not send V3 `aspect_ratio` with `resolution`; the default ratio is `1x1`. `ResolutionV3` is the exact 69-value enum in the [OpenAPI schema](https://developer.ideogram.ai/openapi.json); validate against that live enum instead of approximating arbitrary dimensions.
V3 `num_images` is 1–8, default 1. V3 `seed` is 0–2147483647. V4 generate/remix expose neither count nor request seed; the response returns a seed. Do not infer a controllable count from example response arrays.
`rendering_speed` is `FLASH|TURBO|DEFAULT|QUALITY`, default `DEFAULT`. **Volatile documented exception:** V4 currently returns 400 for `FLASH`; transparent-background generation also rejects `FLASH`. V3 style type is `AUTO|GENERAL|REALISTIC|DESIGN|FICTION`, default `GENERAL`. V3 Magic Prompt is `AUTO|ON|OFF`.
V3 style presets are exactly:
```text
80S_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
```
Use one color-palette variant: `{"name":"EMBER|FRESH|JUNGLE|MAGIC|MELON|MOSAIC|PASTEL|ULTRAMARINE"}` or `{"members":[{"color_hex":"#RRGGBB","color_weight":0.05..1.0}]}`. Use 8-character hexadecimal `style_codes`. Do not combine `style_codes` with `style_reference_images` or `style_type`.
Common V4 success:
```json
{"created":"date-time","data":[{"url":"uri or null","prompt":"string","resolution":"ResolutionV4","is_image_safe":true,"seed":12345}],"response_type":"url"}
```
Common V3 success adds optional `upscaled_resolution` and `style_type`; require `created`, `data`, and per item `prompt`, `resolution`, `is_image_safe`, `seed`. When `is_image_safe` is false, `url` is empty/null. Polling requires `generation_id`, `status:pending|completed|failed`, and `created`; only completed responses contain `response_type:"url"` and `data`.
Ancillary exact responses: `/upscale` returns `{created, request_id?, data?}` using legacy `ImageObject` entries; `/describe` returns `{descriptions:[{text?:string}]}`; `/v1/ideogram-v4/describe` returns `{json_prompt:V4JsonPrompt}`; `/v1/remove-background` returns `{created,data:[{url?:string|null,is_image_safe:boolean}]}` with exactly one item. The OpenAPI leaves `descriptions` and each `text` formally optional even though normal examples include them, so validate their presence before use.
## Control text, layout, style, and references
For V4 typography, prefer `json_prompt` and place exact copy in a `type:"text"` element's `text`; describe font class, weight, case, color, alignment, and role in `desc`; use bbox for layout. `text_prompt` automatically enables Magic Prompt, while `json_prompt` bypasses it and is consumed directly. Generate structured JSON first with `/v1/ideogram-v4/magic-prompt`, or recover it from an image with `/v1/ideogram-v4/describe`.
No first-party API schema publishes a maximum prompt length, maximum literal-text length, guaranteed font catalog, or exact-spelling SLA. Do not invent one. **Production heuristic:** keep critical copy short, isolate each copy region, avoid contradictory visual text elsewhere, render variants, and verify exact spelling with OCR plus human review.
For V3, put literal display copy clearly in the prompt and choose `DESIGN` when appropriate. Use `style_preset` for known aesthetics, style references for visual transfer, a character reference for identity consistency, and Remix `image_weight` for source preservation. Do not claim the V4 Generate route accepts V3 style/character reference fields; it does not in the current OpenAPI.
For inpainting, make the mask the same dimensions as the input and mark editable pixels black. For reframe, specify a V3 resolution, not an aspect-ratio field. For replacement background, describe only the desired new background while preserving the foreground subject.
## Execute complete examples
The following are **examples**, not a universal client architecture. They make paid calls only when deliberately run with a funded key.
### Example: synchronous V4 structured typography and durable download
**Production intent:** create a 1:1 campaign poster whose headline matters more than stylistic randomness. **Why this structure:** use `json_prompt` to bypass automatic Magic Prompt rewriting, isolate literal copy, and place it explicitly. **Expected result:** one or more safe response items with exact headline candidates and a 2048×2048 result. **Likely failures:** misspelled copy, bbox crowding, null URL after safety checks, or an expiring download. **Meaningful variations:** change only `desc` to test typography while holding `text` fixed, or use `/magic-prompt` first when composition is exploratory.
```python
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"
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")
```
### Example: V3 inpaint with a style reference
**Production intent:** replace only a selected object while borrowing an approved visual style. **Why this structure:** V3 Inpaint is the documented mask route and accepts repeated style-reference parts. **Expected result:** two candidates that preserve pixels outside the black mask. **Likely failures:** inverted mask semantics, dimension mismatch, visible seams, or style drift. **Meaningful variations:** omit the style reference for a neutral edit, or add the single supported character reference plus a matching grayscale reference mask when identity is required.
```python
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")
```
### Example: submit V4 async and poll safely
**Production intent:** submit work without holding an HTTP connection open and recover even if webhook delivery fails. **Why this structure:** persist the server-issued ID and make polling a bounded fallback. **Expected result:** `pending` transitions to `completed` with downloadable data, or to terminal `failed`. **Likely failures:** non-public webhook URL, throttling, dropped delivery, or an indefinitely pending job. **Meaningful variations:** let a verified webhook complete the record first and have polling become reconciliation rather than the primary completion path.
```python
import 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}")
```
### Example: verify and durably accept an Ideogram webhook
**Production intent:** authenticate the raw delivery before storing it, reject stale or mismatched requests, and acknowledge duplicates idempotently. **Why this structure:** Ideogram signs raw bytes and may redeliver; SQLite stands in for a transactional production datastore. **Expected result:** a valid first delivery is stored once and returns HTTP 204; a valid duplicate also returns 204 without duplicate processing. **Likely failures:** stale timestamp, bad hex, unknown/rotated key, body reserialization, mismatched generation ID, or invalid JSON. **Meaningful variation:** replace SQLite with a transactional unique constraint in the application's durable database and queue a worker after commit.
```python
import base64
import hashlib
import json
import sqlite3
import time
import requests
from cryptography.exceptions import InvalidSignat...
© calesthio · MIT · calesthio/generative-media-skills