ideogram-image
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseIdeogram Image
Ideogram 图像
Use the official Developer API directly and treat the checked date below as part of the contract.
直接使用官方 Developer API,并将下方注明的检查日期视为合同的一部分。
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, OpenAPI 3.1 JSON, pricing, API agreement, usage policy, and privacy policy 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 | | 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 |
Do not send to V4 or V3 route-scoped endpoints. Their model identifiers are the route segments and . The legacy accepts , , , , , , or ; it does not expose V3/V4. The generic Describe route accepts , , or . A V3 custom model is addressed by in the form .
modelideogram-v4ideogram-v3ModelEnumV_1V_1_TURBOV_2V_2_TURBOV_2AV_2A_TURBOAUTOV_2V_3V_4custom_model_urimodel/<model_name>/version/<version_name>The official reference explicitly says is legacy and will be removed; migrate it to . 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.
POST /v1/ideogram-v3/edit/v1/ideogram-v3/inpaint| 需求 | 标准路由 | 有效模型/生命周期 |
|---|---|---|
| 新的文本/布局生成 | | Ideogram 4.0;当前旗舰 API 路由 |
| 异步新生成 | | Ideogram 4.0;Webhook 与轮询 |
| V4 图像引导式更改 | | Ideogram 4.0 |
| style reference、character reference、mask 编辑、Reframe、替换背景 | 下方的 | Ideogram 3.0;当前专用路由 |
| 仅基于 prompt 的多图像编辑 | | 当前 instruction-edit 路由;文档公开了 V3 分辨率控制项,但没有请求 model 字段 |
| 由请求体选择模型的旧版生成 | | 参考资料明确标为 legacy;新工作应避免使用 |
不要向 V4 或 V3 的路由限定端点发送 。它们的模型标识符就是路由段 和 。旧版 接受 、、、、、 或 ;它不公开 V3/V4。通用 Describe 路由接受 、 或 。V3 custom model 通过 寻址,格式为 。
modelideogram-v4ideogram-v3ModelEnumV_1V_1_TURBOV_2V_2_TURBOV_2AV_2A_TURBOAUTOV_2V_3V_4custom_model_urimodel/<model_name>/version/<version_name>官方参考文档明确指出, 属于 legacy 并将被移除;应将其迁移到 。Ideogram 没有为 V3 或其余 legacy 路由发布第一方 API 下线日期。应用模型历史显示 0.1 和 0.2 已停用,但它们不是当前 API 请求 ID。不要根据应用历史推断 API 下线时间表。
POST /v1/ideogram-v3/edit/v1/ideogram-v3/inpaintAuthenticate and establish the wire contract
身份验证与建立传输契约
Use base URL . Send the secret only as . API billing/account setup is separate from Ideogram app subscriptions. The full key is shown only once when created.
https://api.ideogram.aiApi-Key: <key>Production heuristic: read the key from , 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.
IDEOGRAM_API_KEYMost current operations use ; 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.
multipart/form-data使用 base URL 。仅以 发送 secret。API 计费/账户设置与 Ideogram 应用订阅彼此独立。完整密钥仅在创建时显示一次。
https://api.ideogram.aiApi-Key: <key>生产环境启发式规则: 从 读取密钥,在日志中对其脱敏,在部署系统中使用 secret manager,并设置连接/读取超时。环境变量名属于客户端约定,并非 Ideogram 定义的名称。
IDEOGRAM_API_KEY当前大多数操作使用 ;应让 HTTP 库自行设置 boundary。V4 Magic Prompt 使用 JSON。所有成功的生成/编辑响应均返回 URL,而不是内嵌图像字节。立即下载每个所需结果:第一方文档说明图像链接会过期,但未公布固定有效期。文档没有提供输出格式选择器;不要根据 URL 后缀承诺 PNG/JPEG。下载后应检查响应头和字节内容。
multipart/form-dataUse only documented operations
仅使用已记录的操作
Current image and vision surface
当前图像与视觉接口
| 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 |
All uploaded image fields above accept JPEG, PNG, or WebP and are limited to 10 MB unless 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.
/v1/editThe OpenAPI also documents custom-model administration: , , , , , and . 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. is 5–30 alphanumeric/space/hyphen characters. Use these operations only for an explicit custom-model task.
GET/POST /datasetsGET /datasets/{dataset_id}POST /datasets/{dataset_id}/upload_assetsPOST /v1/ideogram-v3/train-modelGET /modelsGET /models/{model_id}model_nameLegacy-only documented operations are , , , , and . Preserve them only while migrating; do not invent undocumented , , , or routes.
POST /generate/v1/ideogram-v3/edit/edit/remix/reframev4/editv4/inpaintv4/reframev4/replace-background| 方法和路径 | 必需请求 | 可选请求 | 成功响应结构 |
|---|---|---|---|
| 表单 | | null` |
| 同上的 V4 表单;必须提供 HTTPS Webhook 查询参数 | 同上的 V4 选项 | |
| URL-safe base64 generation ID | 无 | pending/failed 状态或 completed 数据 |
| 表单 | | |
| JSON | | |
| 表单 | | |
| 表单 | 下述 V3 generation/style/reference 字段 | |
| 表单 | | X2 |
| 表单 | Magic Prompt、count、seed、speed、V3 style/reference 字段 | V3 图像响应 |
| 表单 | | V3 图像响应 |
| 表单 | count、seed、speed、preset/palette/style code/reference | V3 图像响应 |
| 表单 | Magic Prompt、count、seed、speed、preset/palette/style code/reference | V3 图像响应 |
| 表单 | 无 | `{created, data:[{url:string |
| 表单 | | 见下述文档歧义 |
| 表单 | count、seed、Magic Prompt、V3 resolution 或 aspect ratio、 | |
| 表单 | 对象字段 | legacy 结构图像响应 |
| 表单 | `describe_model_version:V_2 | V_3 |
除 外,上述所有上传图像字段均接受 JPEG、PNG 或 WebP,大小限制为 10 MB; 最多接受 10 张上传图像,每张不超过 10 MB,或者最多 10 个 Ideogram 图像 URL。V3 style reference 和 character reference 组每组总计限制为 10 MB。V3 API 当前支持一张 character reference 图像;对应的可选灰度 mask 必须与 reference 数量和尺寸一致。
/v1/edit/v1/editOpenAPI 还记录了 custom model 管理操作:、、、、 和 。当前 train route/OpenAPI 合同要求提供 15–100 张数据集图像,而第一方教程称训练可从 10 张开始。除非 Ideogram 解决此冲突,否则至少使用 15 张;在每次 40 美元的训练前进行验证,并记录所使用的实时 schema。 必须为 5–30 个字母数字、空格或连字符字符。仅在明确的 custom model 任务中使用这些操作。
GET/POST /datasetsGET /datasets/{dataset_id}POST /datasets/{dataset_id}/upload_assetsPOST /v1/ideogram-v3/train-modelGET /modelsGET /models/{model_id}model_name仅属于 legacy 的已记录操作为 、、、 和 。仅在迁移期间保留它们;不要杜撰未经文档记录的 、、 或 路由。
POST /generate/v1/ideogram-v3/edit/edit/remix/reframev4/editv4/inpaintv4/reframev4/replace-backgroundExact shared schemas
精确的共享 Schema
V4JsonPromptjson
{
"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 , , and . Require plus for objects; require , literal , and for text. and each are optional. Interpret a bbox as four normalized integers on a 1000×1000 coordinate system. The prose defines four values in ; the published JSON Schema does not encode , , or numeric bounds, so validate them client-side.
high_level_descriptioncompositional_deconstruction.backgroundelementstypedesctypetextdescstyle_descriptionbbox[y_min,x_min,y_max,x_max][0,1000]minItemsmaxItemsV4 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, 3072x1024V4 Magic Prompt aspect ratios are , , , , , , , , , , , , , , , , , .
AUTO1x41x31x29x1610x162x33x44x51x15x44x33x216x1016x92x13x14x1V3 aspect ratios are , , , , , , , , , , , , , , . Do not send V3 with ; the default ratio is . is the exact 69-value enum in the OpenAPI schema; validate against that live enum instead of approximating arbitrary dimensions.
1x33x11x22x19x1616x910x1616x102x33x23x44x34x55x41x1aspect_ratioresolution1x1ResolutionV3V3 is 1–8, default 1. V3 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.
num_imagesseedrendering_speedFLASH|TURBO|DEFAULT|QUALITYDEFAULTFLASHFLASHAUTO|GENERAL|REALISTIC|DESIGN|FICTIONGENERALAUTO|ON|OFFV3 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_PRINTUse one color-palette variant: or . Use 8-character hexadecimal . Do not combine with or .
{"name":"EMBER|FRESH|JUNGLE|MAGIC|MELON|MOSAIC|PASTEL|ULTRAMARINE"}{"members":[{"color_hex":"#RRGGBB","color_weight":0.05..1.0}]}style_codesstyle_codesstyle_reference_imagesstyle_typeCommon 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 and ; require , , and per item , , , . When is false, is empty/null. Polling requires , , and ; only completed responses contain and .
upscaled_resolutionstyle_typecreateddatapromptresolutionis_image_safeseedis_image_safeurlgeneration_idstatus:pending|completed|failedcreatedresponse_type:"url"dataAncillary exact responses: returns using legacy entries; returns ; returns ; returns with exactly one item. The OpenAPI leaves and each formally optional even though normal examples include them, so validate their presence before use.
/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}]}descriptionstextV4JsonPromptjson
{
"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]}
]
}
}必须提供 、 和 。对象必须提供 和 ;文本必须提供 、字面量 和 。 及各个 均为可选。将 bbox 解读为 1000×1000 坐标系中的四个归一化整数 。正文规定四个值位于 ;公开的 JSON Schema 未编码 、 或数值边界,因此应在客户端进行验证。
high_level_descriptioncompositional_deconstruction.backgroundelementstypedesctypetextdescstyle_descriptionbbox[y_min,x_min,y_max,x_max][0,1000]minItemsmaxItemsV4 resolution 仅为:
text
2048x2048, 1440x2880, 2880x1440, 1664x2496, 2496x1664, 1792x2240,
2240x1792, 1440x2560, 2560x1440, 1600x2560, 2560x1600, 1728x2304,
2304x1728, 1296x3168, 3168x1296, 1152x2944, 2944x1152, 1248x3328,
3328x1248, 1280x3072, 3072x1280, 1024x3072, 3072x1024V4 Magic Prompt aspect ratio 为 、、、、、、、、、、、、、、、、、。
AUTO1x41x31x29x1610x162x33x44x51x15x44x33x216x1016x92x13x14x1V3 aspect ratio 为 、、、、、、、、、、、、、、。不要同时发送 V3 和 ;默认比例为 。 是 OpenAPI schema 中精确的 69 值 enum;应对照该实时 enum 进行验证,而不是近似使用任意尺寸。
1x33x11x22x19x1616x910x1616x102x33x23x44x34x55x41x1aspect_ratioresolution1x1ResolutionV3V3 为 1–8,默认值为 1。V3 为 0–2147483647。V4 generate/remix 均不公开 count 或请求 seed;响应会返回 seed。不要根据示例响应数组推断可控的输出数量。
num_imagesseedrendering_speedFLASH|TURBO|DEFAULT|QUALITYDEFAULTFLASHFLASHAUTO|GENERAL|REALISTIC|DESIGN|FICTIONGENERALAUTO|ON|OFFV3 style preset 仅为:
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使用一种 color palette variant: 或 。使用 8 字符十六进制 。不要将 与 或 组合使用。
{"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常见的 V4 成功响应:
json
{"created":"date-time","data":[{"url":"uri or null","prompt":"string","resolution":"ResolutionV4","is_image_safe":true,"seed":12345}],"response_type":"url"}常见的 V3 成功响应会增加可选的 和 ;必须提供 、,且每个条目必须包含 、、、。当 为 false 时, 为空/null。轮询要求提供 、 和 ;只有 completed 响应包含 和 。
upscaled_resolutionstyle_typecreateddatapromptresolutionis_image_safeseedis_image_safeurlgeneration_idstatus:pending|completed|failedcreatedresponse_type:"url"data辅助接口的精确响应: 返回 ,其中使用 legacy 条目; 返回 ; 返回 ; 返回 ,且恰好包含一个条目。OpenAPI 在形式上将 及每个 标为可选,即使正常示例中包含它们,因此使用前应验证其存在。
/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}]}descriptionstextControl text, layout, style, and references
控制文本、布局、风格和参考图
For V4 typography, prefer and place exact copy in a element's ; describe font class, weight, case, color, alignment, and role in ; use bbox for layout. automatically enables Magic Prompt, while bypasses it and is consumed directly. Generate structured JSON first with , or recover it from an image with .
json_prompttype:"text"textdesctext_promptjson_prompt/v1/ideogram-v4/magic-prompt/v1/ideogram-v4/describeNo 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 when appropriate. Use for known aesthetics, style references for visual transfer, a character reference for identity consistency, and Remix for source preservation. Do not claim the V4 Generate route accepts V3 style/character reference fields; it does not in the current OpenAPI.
DESIGNstyle_presetimage_weightFor 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.
对于 V4 typography,优先使用 ,并将准确的文案放入 元素的 中;在 中描述字体类别、字重、大小写、颜色、对齐方式和作用;使用 bbox 控制布局。 会自动启用 Magic Prompt,而 会绕过它并被直接消费。先使用 生成结构化 JSON,或使用 从图像中恢复结构化 JSON。
json_prompttype:"text"textdesctext_promptjson_prompt/v1/ideogram-v4/magic-prompt/v1/ideogram-v4/describe第一方 API schema 没有公布最大 prompt 长度、最大字面文本长度、保证可用的字体目录或准确拼写 SLA。不要自行编造。生产环境启发式规则: 保持关键文案简短,隔离每个文案区域,避免在图像其他位置出现矛盾的视觉文字,渲染多个变体,并使用 OCR 与人工审核验证准确拼写。
对于 V3,在 prompt 中清晰写出要显示的字面文案,并在适用时选择 。使用 选择已知美学,使用 style reference 进行视觉风格迁移,使用 character reference 保持身份一致性,并使用 Remix 保留源图特征。不要声称 V4 Generate 路由接受 V3 style/character reference 字段;当前 OpenAPI 明确不支持。
DESIGNstyle_presetimage_weight对于 inpainting,mask 必须与输入图像尺寸一致,并将可编辑像素标记为黑色。对于 reframe,请指定 V3 resolution,而不是 aspect ratio 字段。对于替换背景,只描述所需的新背景,同时保留前景主体。
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
示例:同步 V4 结构化 typography 与持久化下载
Production intent: create a 1:1 campaign poster whose headline matters more than stylistic randomness. Why this structure: use 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 to test typography while holding fixed, or use first when composition is exploratory.
json_promptdesctext/magic-promptpython
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")生产意图: 创建一张 1:1 营销海报,其中标题的重要性高于风格的随机性。采用此结构的原因: 使用 绕过自动 Magic Prompt 重写,隔离字面文案,并明确放置文案。预期结果: 返回一个或多个安全响应条目,其中包含准确的标题候选和 2048×2048 结果。可能的失败: 文案拼写错误、bbox 拥挤、安全检查后 URL 为 null,或下载链接过期。有意义的变体: 仅修改 以测试 typography,同时保持 不变;或者在探索构图时先使用 。
json_promptdesctext/magic-promptpython
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
示例:带 style reference 的 V3 inpaint
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")生产意图: 只替换选定对象,同时借用已批准的视觉风格。采用此结构的原因: V3 Inpaint 是文档记录的 mask 路由,并接受重复的 style reference part。预期结果: 返回两个候选结果,同时保留黑色 mask 之外的像素。可能的失败: mask 语义反转、尺寸不匹配、可见接缝或风格漂移。有意义的变体: 省略 style reference 以执行中性编辑;当需要保持身份一致性时,添加唯一受支持的 character reference 及与其匹配的灰度 reference mask。
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
示例:提交 V4 异步任务并安全轮询
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: transitions to with downloadable data, or to terminal . 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.
pendingcompletedfailedpython
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}")生产意图: 无需保持 HTTP 连接即可提交工作,即使 Webhook 投递失败也能恢复。采用此结构的原因: 持久化服务器签发的 ID,并将轮询作为有界回退机制。预期结果: 转换为包含可下载数据的 ,或者转换为终态 。可能的失败: Webhook URL 不公开、限流、投递丢失或任务无限期保持 pending。有意义的变体: 让经过验证的 Webhook 首先完成记录,并将轮询作为对账机制,而非主要完成路径。
pendingcompletedfailedpython
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
示例:验证并持久化接受 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 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 204Install , , and for the four Python examples. The web framework must pass the untouched request-body bytes and original headers into ; do not parse and reserialize first.
requestsPillowcryptographyhandle_webhookVerify webhook signatures exactly as specified in the official webhook guide: hash the raw body bytes with SHA-256; join generation ID, user ID, Unix timestamp, and body hash with newlines; verify the lowercase-hex Ed25519 signature against keys from . Never reserialize JSON before hashing. Production heuristic: cache keys, refresh on failure/rotation, reject stale timestamps using a locally chosen tolerance, require header/body ID agreement, and deduplicate deliveries transactionally by .
GET /v1/.well-known/jwks.jsongeneration_id生产意图: 在存储前验证原始投递,拒绝过期或不匹配的请求,并以幂等方式确认重复请求。采用此结构的原因: Ideogram 会对原始字节签名,并且可能重复投递;SQLite 在此代替事务型生产数据库。预期结果: 有效的首次投递仅存储一次并返回 HTTP 204;有效的重复投递同样返回 204,且不会重复处理。可能的失败: 时间戳过期、十六进制格式错误、未知或已轮换的密钥、请求体被重新序列化、generation ID 不匹配或 JSON 无效。有意义的变体: 使用应用程序持久化数据库中的事务型唯一约束替换 SQLite,并在提交后向 worker 队列投递任务。
python
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 204四个 Python 示例需要安装 、 和 。Web 框架必须将未经修改的 request body 字节和原始 headers 传入 ;不要先解析并重新序列化。
requestsPillowcryptographyhandle_webhook严格按照 官方 Webhook 指南验证 Webhook 签名:使用 SHA-256 对原始请求体字节进行哈希;使用换行符连接 generation ID、user ID、Unix timestamp 和 body hash;使用 中的密钥验证小写十六进制 Ed25519 签名。哈希前绝不要重新序列化 JSON。生产环境启发式规则: 缓存密钥,在失败或轮换时刷新,使用本地选择的容差拒绝过期时间戳,要求 header/body ID 一致,并按 以事务方式对投递进行去重。
GET /v1/.well-known/jwks.jsongeneration_idHandle lifecycle, errors, retries, and concurrency
处理生命周期、错误、重试与并发
The default limit is 10 in-flight requests; contact Ideogram for higher-volume access. A limit is concurrency, not a documented requests-per-minute quota.
| 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 |
The OpenAPI leaves most 400/401/429/503 bodies untyped. Parse defensively and log status, request metadata, and a redacted/truncated body. It does not document a guarantee; honor it if actually present, otherwise use full jitter.
Retry-AfterNo request idempotency-key header is documented. Production heuristic: never blindly retry a timed-out synchronous POST because it may have completed and been billed. Prefer V4 async, persist before doing other work, and retry only polling GETs. Ideogram may retry a webhook a limited number of times and delivery is not guaranteed; acknowledge successful duplicate deliveries with 2xx and fall back to polling.
generation_id默认限制为 10 个进行中的请求;如需更高吞吐量,请联系 Ideogram。该限制是并发限制,而不是文档记录的 requests-per-minute 配额。
| 状态 | 已记录含义 | 操作 |
|---|---|---|
| 400 | 输入无效;也包括当前不支持的 speed 组合 | 修复请求;不要原样重试 |
| 401 | 缺少或无效的身份验证 | 停止,修复 secret/账户 |
| 402 | | 充值或更改已批准的计划;不要循环重试 |
| 403 | 在 V3 Remix/Upscale 等已记录路由上禁止访问或未获授权 | 停止;验证账户权益和路由访问权限;不要原样重试 |
| 404 | 未知 async generation ID | 验证已存储的 ID/环境 |
| 422 | prompt 或图像安全检查失败;文档记录的请求体为 | 不要规避;根据政策修改或拒绝 |
| 429 | 请求过多 | 减少进行中的工作,并使用有界的指数退避和 jitter 重试 |
| 503 | | 退避后进行有界重试 |
OpenAPI 没有为大多数 400/401/429/503 响应体指定类型。应防御性地解析,并记录状态、请求元数据以及脱敏/截断后的请求体。文档没有保证提供 ;如果实际存在则遵循该值,否则使用 full jitter。
Retry-After文档没有记录请求 idempotency-key header。生产环境启发式规则: 对超时的同步 POST 绝不盲目重试,因为请求可能已经完成并计费。优先使用 V4 async,在执行其他工作前持久化 ,并且只重试轮询 GET。Ideogram 可能会有限次数地重试 Webhook,且不保证投递成功;对成功的重复投递返回 2xx,并回退到轮询。
generation_idPrice and gate spend
定价与费用控制
Volatile documented prices — page last says revised 2025-08-06; checked 2026-07-09: V4 Turbo/Default/Quality cost $0.03/$0.06/$0.10 per output; V3 Flash/Turbo/Default/Quality cost $0.03/$0.03/$0.06/$0.09; V3 with character reference Turbo/Default/Quality costs $0.10/$0.15/$0.20. Transparent V3 X1 costs $0.04/$0.07/$0.10 for Turbo/Default/Quality; 2X costs $0.16/$0.19/$0.22; 4X costs $0.20/$0.23/$0.26. Instructional edit is $0.20/output, upscale $0.06/input, Describe $0.01/input, Layerize $0.09/input, and self-serve custom-model training $40/run. Confirm the live page before estimating.
The price page also lists pricing-only or incompletely routed capabilities: Gemini generation at $0.20 for 1K/2K and $0.36 for 4K; Topaz upscale at $0.12/$0.24/$0.48 for 2K/4K/8K; Generate + Layerize V3 at $0.12/$0.15/$0.18 for Turbo/Default/Quality; and custom inference at V4 $0.06/$0.12/$0.20 and V3 $0.06/$0.12/$0.18. Do not invent endpoints for these entries. The current public OpenAPI does not expose routes for every pricing-table capability and documents only V3 ; treat them as unresolved until a first-party request schema is available to the target account.
custom_model_uriCompute the upper bound before submission: requested outputs × per-output price, plus reference/upscale/edit premiums. Keep API auto-top-up behavior visible to the operator; setup docs describe configurable threshold/top-up balances and separate API credits.
易变的已记录价格 — 页面最后注明修订于 2025-08-06;检查于 2026-07-09: V4 Turbo/Default/Quality 每个输出分别为 0.03/0.06/0.10 美元;V3 Flash/Turbo/Default/Quality 每个输出分别为 0.03/0.03/0.06/0.09 美元;使用 character reference 的 V3 Turbo/Default/Quality 分别为 0.10/0.15/0.20 美元。Transparent V3 X1 的 Turbo/Default/Quality 分别为 0.04/0.07/0.10 美元;2X 分别为 0.16/0.19/0.22 美元;4X 分别为 0.20/0.23/0.26 美元。Instructional edit 为每个输出 0.20 美元,upscale 为每个输入 0.06 美元,Describe 为每个输入 0.01 美元,Layerize 为每个输入 0.09 美元,self-serve custom model training 为每次运行 40 美元。估算前请确认实时页面。
价格页面还列出仅提供定价或路由不完整的能力:Gemini generation 在 1K/2K 下为 0.20 美元,在 4K 下为 0.36 美元;Topaz upscale 在 2K/4K/8K 下分别为 0.12/0.24/0.48 美元;Generate + Layerize V3 在 Turbo/Default/Quality 下分别为 0.12/0.15/0.18 美元;custom inference 在 V4 下为 0.06/0.12/0.20 美元,在 V3 下为 0.06/0.12/0.18 美元。不要为这些条目杜撰端点。当前公开 OpenAPI 并未为价格表中的每项能力公开路由,并且只记录了 V3 ;在目标账户可用的第一方请求 schema 出现之前,将这些能力视为未解决。
custom_model_uri提交前计算费用上限:请求的输出数量 × 每个输出的价格,再加上 reference/upscale/edit 的附加费用。让操作员能够看到 API 自动充值行为;设置文档说明可配置触发阈值/充值余额,并且 API credits 与应用订阅分离。
Enforce safety, privacy, provenance, and rights
强制执行安全、隐私、来源记录与权利要求
Follow the API agreement and usage policy, not merely . Do not submit unlawful, infringing, non-consensual, privacy-invasive, pornographic, excessively violent, hateful, deceptive, bullying, political-campaigning/lobbying, or harmful/criminal content. Do not bypass filters or rate limits.
is_image_safeObtain rights and consent for every uploaded image, character reference, likeness, trademark, and font/brand asset. Ideogram's general Terms say it does not claim ownership in user input/output and does not restrict commercial use, but the user remains responsible for law and third-party rights; output may be non-unique and no non-infringement warranty is provided. Treat this as operational guidance, not legal advice.
The API agreement requires the Developer Application to identify Ideogram-generated output (for example, “Powered by Ideogram”), display approved Ideogram marks where access is enabled, and link users to the Usage Policy. It prohibits presenting AI output as entirely human-made or as a real photo of a real event. Preserve a provenance record containing provider, endpoint/model route, UTC time, request parameters, returned prompt/seed/resolution, source hashes/rights, output hash, safety result, and human approvals. No C2PA field or downloadable provenance manifest is documented in the current response schema; do not claim one.
API input/output is not used to train the Ideogram model except content flagged for Usage Policy violations may be used to train/improve abuse and safety detection. The broader Privacy Policy says prompts/uploads are collected and gives a purpose-based, non-numeric retention period (“as long as reasonably necessary”). It also permits service providers and international processing. Therefore do not send health data, children's data, secrets, or sensitive personal data without a reviewed lawful basis and required consent. Do not promise zero retention or a fixed deletion window absent an order-specific agreement.
enable_copyright_detection=trueis_image_safe:false应遵循 API 协议和使用政策,而不只是依赖 。不要提交违法、侵权、非自愿、侵犯隐私、色情、过度暴力、仇恨、欺骗、霸凌、政治竞选/游说或有害/犯罪内容。不要绕过过滤器或速率限制。
is_image_safe必须为每张上传图像、character reference、肖像、商标及字体/品牌资产取得权利和同意。Ideogram 的一般条款声明其不对用户输入或输出主张所有权,也不限制商业使用,但用户仍须遵守法律并承担第三方权利责任;输出可能不唯一,且不提供不侵权保证。将其视为操作指导,而非法律建议。
API 协议要求 Developer Application 标明输出由 Ideogram 生成,例如使用“Powered by Ideogram”,在启用访问权限时展示经批准的 Ideogram 标识,并将用户链接到 Usage Policy。它禁止将 AI 输出完全宣称为人工创作,或宣称为真实事件的真实照片。保留来源记录,包括 provider、endpoint/model route、UTC 时间、请求参数、返回的 prompt/seed/resolution、源文件哈希/权利信息、输出哈希、安全检查结果和人工审批。当前响应 schema 没有记录 C2PA 字段或可下载的 provenance manifest;不要声称存在这些内容。
API 输入/输出不会用于训练 Ideogram model,但被标记违反 Usage Policy 的内容可能用于训练/改进滥用与安全检测。更广泛的 Privacy Policy 说明会收集 prompts/uploads,并采用基于目的、非具体数值的保留期限,即“在合理必要的期限内”。它还允许使用服务提供商及进行国际处理。因此,在未经过审查的合法依据和所需同意之前,不要发送健康数据、儿童数据、secret 或敏感个人数据。除非存在特定订单协议,否则不要承诺零保留或固定删除期限。
enable_copyright_detection=trueis_image_safe:falseRun QA and migrate safely
执行 QA 并安全迁移
Before sending:
- Re-fetch the OpenAPI enum for routes, sizes, and presets in release automation.
- Validate file type/size, mask dimensions, count, seed, mutually exclusive fields, and V4 bbox ordering/ranges.
- Require approval for cost, references/likenesses, public distribution, and policy-sensitive prompts.
- Store a redacted canonical request and source hashes before submission.
After receiving:
- Reject missing URLs and unsafe results; download ephemeral URLs immediately.
- Verify MIME signature, pixel dimensions, alpha channel when requested, and cryptographic hash.
- Compare literal typography by OCR and human review; compare reference identity/style without assuming perfect fidelity.
- For edits, diff protected regions; for inpaint, inspect mask seams; for reframe, inspect subject preservation and new edges; for background work, inspect hair/transparency halos.
- Record endpoint, returned prompt, seed, actual resolution, price basis, and review outcome.
Migration map:
- Move and
/v1/ideogram-v3/editmask workflows to/edit; rename/v1/ideogram-v3/inpainttoimage_fileand use black editable regions.image - Move legacy to V4 Generate for new text/layout work or V3 Generate when V3 references/presets/custom models are required.
/generate - Move legacy and
/remixto/reframeor their V3 canonical routes according to required controls./v1/ideogram-v4/remix - Replace legacy /
model/prefixed aspect-ratio enums with route-scoped models and the exact current field names.magic_prompt_option - Canary each migration with frozen prompts/assets, compare dimensions, literal text, style, subject preservation, safety behavior, latency, and cost; never assume seed equivalence across model generations.
发送前:
- 在发布自动化中重新获取路由、尺寸和 preset 的 OpenAPI enum。
- 验证文件类型/大小、mask 尺寸、count、seed、互斥字段以及 V4 bbox 的顺序和范围。
- 对费用、references/肖像、公开分发和 policy-sensitive prompts 要求审批。
- 在提交前存储脱敏的规范化请求和源文件哈希。
接收后:
- 拒绝缺少 URL 或不安全的结果;立即下载临时 URL。
- 验证 MIME 签名、像素尺寸、请求 alpha channel 时的透明通道,以及加密哈希。
- 使用 OCR 和人工审核比较字面 typography;比较 reference 的身份/风格,但不要假设完全一致。
- 对编辑操作比较受保护区域;对 inpaint 检查 mask 接缝;对 reframe 检查主体保留和新边缘;对背景操作检查头发/透明光晕。
- 记录 endpoint、返回的 prompt、seed、实际 resolution、价格依据和审核结果。
迁移映射:
- 将 和
/v1/ideogram-v3/editmask 工作流迁移到/edit;将/v1/ideogram-v3/inpaint重命名为image_file,并使用黑色可编辑区域。image - 对于新的文本/布局工作,将 legacy 迁移到 V4 Generate;当需要 V3 references/presets/custom models 时迁移到 V3 Generate。
/generate - 根据所需控制项,将 legacy 和
/remix迁移到/reframe或对应的 V3 标准路由。/v1/ideogram-v4/remix - 将 legacy /
model/带前缀的 aspect-ratio enum 替换为路由限定 model 和当前准确的字段名称。magic_prompt_option - 使用冻结的 prompts/assets 对每次迁移执行 canary,对比尺寸、字面文本、风格、主体保留、安全行为、延迟和费用;绝不要假设不同 model generation 之间的 seed 等价。
Known first-party ambiguities
已知的第一方文档歧义
- The custom-model tutorial says at least 10 dataset images, while the current train-route/OpenAPI contract says 15–100. Enforce the stricter 15-image minimum and recheck immediately before a paid training run.
- The OpenAPI component says the webhook body mirrors the synchronous response with
WebhookUrl, while the async endpoint schema and dedicated webhook guide userequest_id. Follow the dedicated guide/header contract and require matchinggeneration_id; treatgeneration_idwording as stale until resolved.request_id - The Layerize Text prose and example show with font/position/style data, while the current OpenAPI
text_blocksschema declares onlyLayerizeTextResponse, optionalbase_image_url, andoriginal_image_url. Code to the declared schema and feature-detectseed; do not make it required until Ideogram resolves the mismatch.text_blocks - The API overview V3 quickstart shows a JSON body for a route whose reference/OpenAPI declares multipart form. Follow the route reference/OpenAPI, especially when sending files.
- V4 response examples show multiple data items but the request schema has no ; do not treat example cardinality as a guarantee.
num_images - Pricing describes V4 pricing across several operation classes, while current OpenAPI exposes V4 Generate/Remix but retains V3-only paths for inpaint/reframe/replace-background. Choose by documented route availability, not pricing-table wording.
- Custom model 教程称至少需要 10 张数据集图像,而当前 train route/OpenAPI 合同要求 15–100 张。执行更严格的 15 张最低限制,并在付费训练运行前立即重新检查。
- OpenAPI 组件称 Webhook 请求体镜像同步响应并包含
WebhookUrl,而 async endpoint schema 和专用 Webhook 指南使用request_id。遵循专用指南/header 合同,并要求generation_id匹配;在 Ideogram 解决歧义前,将generation_id表述视为过期信息。request_id - Layerize Text 正文和示例展示了包含字体/位置/样式数据的 ,而当前 OpenAPI
text_blocksschema 仅声明LayerizeTextResponse、可选的base_image_url和original_image_url。应按照已声明的 schema 编码,并对seed进行功能检测;在 Ideogram 解决不匹配之前,不要将其设为必需字段。text_blocks - API overview 的 V3 quickstart 为某个路由展示 JSON 请求体,而其 reference/OpenAPI 声明该路由使用 multipart form。应以路由 reference/OpenAPI 为准,尤其是在发送文件时。
- V4 响应示例展示了多个 data 条目,但请求 schema 没有 ;不要将示例中的数量视为保证。
num_images - 定价页面描述了多个操作类别的 V4 价格,而当前 OpenAPI 公开了 V4 Generate/Remix,却仅为 inpaint/reframe/replace-background 保留 V3 路径。应依据已记录的路由可用性进行选择,而不是依据价格表措辞。