ideogram-image

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ideogram 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.
  • 已记录:由 Ideogram 第一方页面或官方 OpenAPI 文档明示。
  • 推断:公开合同未作保证的结论。
  • 生产环境启发式规则:操作建议,而非 Ideogram 的承诺。
  • 将模型可用性、端点生命周期、价格、限额、政策以及临时 URL 的存续时间视为易变信息。在发布或报价之前,重新检查 文档索引、OpenAPI 3.1 JSON、定价、API 协议、使用政策 和 隐私政策。
除非段落另有说明,以下 API 事实均为 已记录 — 检查于 2026-07-09。

Select a route, not an invented model string

选择路由,而不是编造模型字符串

NeedCanonical routeEffective 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.
需求标准路由有效模型/生命周期
新的文本/布局生成
POST /v1/ideogram-v4/generate
Ideogram 4.0;当前旗舰 API 路由
异步新生成
POST /v1/ideogram-v4/async/generate
Ideogram 4.0;Webhook 与轮询
V4 图像引导式更改
POST /v1/ideogram-v4/remix
Ideogram 4.0
style reference、character reference、mask 编辑、Reframe、替换背景下方的
/v1/ideogram-v3/*
路由
Ideogram 3.0;当前专用路由
仅基于 prompt 的多图像编辑
POST /v1/edit
当前 instruction-edit 路由;文档公开了 V3 分辨率控制项,但没有请求 model 字段
由请求体选择模型的旧版生成
/generate
、
/edit
、
/remix
、
/reframe
参考资料明确标为 legacy;新工作应避免使用
不要向 V4 或 V3 的路由限定端点发送
model
。它们的模型标识符就是路由段
ideogram-v4
和
ideogram-v3
。旧版
ModelEnum
接受
V_1
、
V_1_TURBO
、
V_2
、
V_2_TURBO
、
V_2A
、
V_2A_TURBO
或
AUTO
;它不公开 V3/V4。通用 Describe 路由接受
V_2
、
V_3
或
V_4
。V3 custom model 通过
custom_model_uri
寻址,格式为
model/<model_name>/version/<version_name>
。
官方参考文档明确指出,
POST /v1/ideogram-v3/edit
属于 legacy 并将被移除;应将其迁移到
/v1/ideogram-v3/inpaint
。Ideogram 没有为 V3 或其余 legacy 路由发布第一方 API 下线日期。应用模型历史显示 0.1 和 0.2 已停用,但它们不是当前 API 请求 ID。不要根据应用历史推断 API 下线时间表。

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.
使用 base URL
https://api.ideogram.ai
。仅以
Api-Key: <key>
发送 secret。API 计费/账户设置与 Ideogram 应用订阅彼此独立。完整密钥仅在创建时显示一次。
生产环境启发式规则: 从
IDEOGRAM_API_KEY
读取密钥,在日志中对其脱敏,在部署系统中使用 secret manager,并设置连接/读取超时。环境变量名属于客户端约定,并非 Ideogram 定义的名称。
当前大多数操作使用
multipart/form-data
;应让 HTTP 库自行设置 boundary。V4 Magic Prompt 使用 JSON。所有成功的生成/编辑响应均返回 URL,而不是内嵌图像字节。立即下载每个所需结果:第一方文档说明图像链接会过期,但未公布固定有效期。文档没有提供输出格式选择器;不要根据 URL 后缀承诺 PNG/JPEG。下载后应检查响应头和字节内容。

Use only documented operations

仅使用已记录的操作

Current image and vision surface

当前图像与视觉接口

Method and pathRequired requestOptional requestSuccess 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`
POST /v1/ideogram-v4/async/generate?webhook_url=<https-url>
same V4 form; HTTPS webhook query requiredsame V4 options
{generation_id:string}
GET /v1/generations/{generation_id}
URL-safe base64 generation IDnonepending/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
POST /v1/ideogram-v3/inpaint
form
image:file
, same-sized black/white
mask:file
,
prompt:string
Magic Prompt, count, seed, speed, V3 style/reference fieldsV3 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/referenceV3 image response
POST /v1/ideogram-v3/replace-background
form
image:file
,
prompt:string
Magic Prompt, count, seed, speed, preset/palette/style code/referenceV3 image response
POST /v1/remove-background
form
image:file
none`{created, data:[{url:string
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_2V_3
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.
方法和路径必需请求可选请求成功响应结构
POST /v1/ideogram-v4/generate
表单
text_prompt:string
或
json_prompt:V4JsonPrompt
中恰好一个
resolution:ResolutionV4
、
rendering_speed
、`enable_copyright_detection:boolean
null`
POST /v1/ideogram-v4/async/generate?webhook_url=<https-url>
同上的 V4 表单;必须提供 HTTPS Webhook 查询参数同上的 V4 选项
{generation_id:string}
GET /v1/generations/{generation_id}
URL-safe base64 generation ID无pending/failed 状态或 completed 数据
POST /v1/ideogram-v4/remix
表单
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
表单
image_file:file
(JPEG/PNG/WebP,最大 10 MB)
include_bbox:boolean=true
{json_prompt:V4JsonPrompt}
POST /v1/ideogram-v3/generate
表单
prompt:string
下述 V3 generation/style/reference 字段
ImageGenerationResponseV3
POST /v1/ideogram-v3/generate-transparent
表单
prompt:string
seed
、`upscale_factor:X1
X2
POST /v1/ideogram-v3/inpaint
表单
image:file
、同尺寸黑白
mask:file
、
prompt:string
Magic Prompt、count、seed、speed、V3 style/reference 字段V3 图像响应
POST /v1/ideogram-v3/remix
表单
image:file
、
prompt:string
image_weight=50
、seed、size、speed、Magic Prompt、negative prompt、count、style/reference 字段
V3 图像响应
POST /v1/ideogram-v3/reframe
表单
image:file
、
resolution:ResolutionV3
count、seed、speed、preset/palette/style code/referenceV3 图像响应
POST /v1/ideogram-v3/replace-background
表单
image:file
、
prompt:string
Magic Prompt、count、seed、speed、preset/palette/style code/referenceV3 图像响应
POST /v1/remove-background
表单
image:file
无`{created, data:[{url:string
POST /v1/ideogram-v3/layerize-text
表单
image:file
prompt:string
、
seed
见下述文档歧义
POST /v1/edit
表单
prompt:string
,编辑输入还需
images:file[]
或
image_urls:string[]
count、seed、Magic Prompt、V3 resolution 或 aspect ratio、
transparent_background=false
{created,data:V1EditImageObject[]}
POST /upscale
表单
image_file:file
、
image_request
JSON 对象
对象字段
prompt
、
resemblance=50
、
detail=50
、
magic_prompt_option
、
num_images=1
、
seed
legacy 结构图像响应
POST /describe
表单
image_file:file
`describe_model_version:V_2V_3
除
/v1/edit
外,上述所有上传图像字段均接受 JPEG、PNG 或 WebP,大小限制为 10 MB;
/v1/edit
最多接受 10 张上传图像,每张不超过 10 MB,或者最多 10 个 Ideogram 图像 URL。V3 style reference 和 character reference 组每组总计限制为 10 MB。V3 API 当前支持一张 character reference 图像;对应的可选灰度 mask 必须与 reference 数量和尺寸一致。
OpenAPI 还记录了 custom model 管理操作:
GET/POST /datasets
、
GET /datasets/{dataset_id}
、
POST /datasets/{dataset_id}/upload_assets
、
POST /v1/ideogram-v3/train-model
、
GET /models
和
GET /models/{model_id}
。当前 train route/OpenAPI 合同要求提供 15–100 张数据集图像,而第一方教程称训练可从 10 张开始。除非 Ideogram 解决此冲突,否则至少使用 15 张;在每次 40 美元的训练前进行验证,并记录所使用的实时 schema。
model_name
必须为 5–30 个字母数字、空格或连字符字符。仅在明确的 custom model 任务中使用这些操作。
仅属于 legacy 的已记录操作为
POST /generate
、
/v1/ideogram-v3/edit
、
/edit
、
/remix
和
/reframe
。仅在迁移期间保留它们;不要杜撰未经文档记录的
v4/edit
、
v4/inpaint
、
v4/reframe
或
v4/replace-background
路由。

Exact shared schemas

精确的共享 Schema

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; 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.
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]}
    ]
  }
}
必须提供
high_level_description
、
compositional_deconstruction.background
和
elements
。对象必须提供
type
和
desc
;文本必须提供
type
、字面量
text
和
desc
。
style_description
及各个
bbox
均为可选。将 bbox 解读为 1000×1000 坐标系中的四个归一化整数
[y_min,x_min,y_max,x_max]
。正文规定四个值位于
[0,1000]
;公开的 JSON Schema 未编码
minItems
、
maxItems
或数值边界,因此应在客户端进行验证。
V4 resolution 仅为:
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 ratio 为
AUTO
、
1x4
、
1x3
、
1x2
、
9x16
、
10x16
、
2x3
、
3x4
、
4x5
、
1x1
、
5x4
、
4x3
、
3x2
、
16x10
、
16x9
、
2x1
、
3x1
、
4x1
。
V3 aspect ratio 为
1x3
、
3x1
、
1x2
、
2x1
、
9x16
、
16x9
、
10x16
、
16x10
、
2x3
、
3x2
、
3x4
、
4x3
、
4x5
、
5x4
、
1x1
。不要同时发送 V3
aspect_ratio
和
resolution
;默认比例为
1x1
。
ResolutionV3
是 OpenAPI schema 中精确的 69 值 enum;应对照该实时 enum 进行验证,而不是近似使用任意尺寸。
V3
num_images
为 1–8,默认值为 1。V3
seed
为 0–2147483647。V4 generate/remix 均不公开 count 或请求 seed;响应会返回 seed。不要根据示例响应数组推断可控的输出数量。
rendering_speed
为
FLASH|TURBO|DEFAULT|QUALITY
,默认值为
DEFAULT
。易变的已记录例外: V4 当前对
FLASH
返回 400;transparent background 生成也拒绝
FLASH
。V3 style type 为
AUTO|GENERAL|REALISTIC|DESIGN|FICTION
,默认值为
GENERAL
。V3 Magic Prompt 为
AUTO|ON|OFF
。
V3 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:
{"name":"EMBER|FRESH|JUNGLE|MAGIC|MELON|MOSAIC|PASTEL|ULTRAMARINE"}
或
{"members":[{"color_hex":"#RRGGBB","color_weight":0.05..1.0}]}
。使用 8 字符十六进制
style_codes
。不要将
style_codes
与
style_reference_images
或
style_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 成功响应会增加可选的
upscaled_resolution
和
style_type
;必须提供
created
、
data
,且每个条目必须包含
prompt
、
resolution
、
is_image_safe
、
seed
。当
is_image_safe
为 false 时,
url
为空/null。轮询要求提供
generation_id
、
status:pending|completed|failed
和
created
;只有 completed 响应包含
response_type:"url"
和
data
。
辅助接口的精确响应:
/upscale
返回
{created, request_id?, data?}
,其中使用 legacy
ImageObject
条目;
/describe
返回
{descriptions:[{text?:string}]}
;
/v1/ideogram-v4/describe
返回
{json_prompt:V4JsonPrompt}
;
/v1/remove-background
返回
{created,data:[{url?:string|null,is_image_safe:boolean}]}
,且恰好包含一个条目。OpenAPI 在形式上将
descriptions
及每个
text
标为可选,即使正常示例中包含它们,因此使用前应验证其存在。

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.
对于 V4 typography,优先使用
json_prompt
,并将准确的文案放入
type:"text"
元素的
text
中;在
desc
中描述字体类别、字重、大小写、颜色、对齐方式和作用;使用 bbox 控制布局。
text_prompt
会自动启用 Magic Prompt,而
json_prompt
会绕过它并被直接消费。先使用
/v1/ideogram-v4/magic-prompt
生成结构化 JSON,或使用
/v1/ideogram-v4/describe
从图像中恢复结构化 JSON。
第一方 API schema 没有公布最大 prompt 长度、最大字面文本长度、保证可用的字体目录或准确拼写 SLA。不要自行编造。生产环境启发式规则: 保持关键文案简短,隔离每个文案区域,避免在图像其他位置出现矛盾的视觉文字,渲染多个变体,并使用 OCR 与人工审核验证准确拼写。
对于 V3,在 prompt 中清晰写出要显示的字面文案,并在适用时选择
DESIGN
。使用
style_preset
选择已知美学,使用 style reference 进行视觉风格迁移,使用 character reference 保持身份一致性,并使用 Remix
image_weight
保留源图特征。不要声称 V4 Generate 路由接受 V3 style/character reference 字段;当前 OpenAPI 明确不支持。
对于 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
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")
生产意图: 创建一张 1:1 营销海报,其中标题的重要性高于风格的随机性。采用此结构的原因: 使用
json_prompt
绕过自动 Magic Prompt 重写,隔离字面文案,并明确放置文案。预期结果: 返回一个或多个安全响应条目,其中包含准确的标题候选和 2048×2048 结果。可能的失败: 文案拼写错误、bbox 拥挤、安全检查后 URL 为 null,或下载链接过期。有意义的变体: 仅修改
desc
以测试 typography,同时保持
text
不变;或者在探索构图时先使用
/magic-prompt
。
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

示例:带 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:
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}")
生产意图: 无需保持 HTTP 连接即可提交工作,即使 Webhook 投递失败也能恢复。采用此结构的原因: 持久化服务器签发的 ID,并将轮询作为有界回退机制。预期结果:
pending
转换为包含可下载数据的
completed
,或者转换为终态
failed
。可能的失败: Webhook URL 不公开、限流、投递丢失或任务无限期保持 pending。有意义的变体: 让经过验证的 Webhook 首先完成记录,并将轮询作为对账机制,而非主要完成路径。
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

示例:验证并持久化接受 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 204
Install
requests
,
Pillow
, and
cryptography
for the four Python examples. The web framework must pass the untouched request-body bytes and original headers into
handle_webhook
; do not parse and reserialize first.
Verify 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
GET /v1/.well-known/jwks.json
. 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
generation_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 示例需要安装
requests
、
Pillow
和
cryptography
。Web 框架必须将未经修改的 request body 字节和原始 headers 传入
handle_webhook
;不要先解析并重新序列化。
严格按照 官方 Webhook 指南验证 Webhook 签名:使用 SHA-256 对原始请求体字节进行哈希;使用换行符连接 generation ID、user ID、Unix timestamp 和 body hash;使用
GET /v1/.well-known/jwks.json
中的密钥验证小写十六进制 Ed25519 签名。哈希前绝不要重新序列化 JSON。生产环境启发式规则: 缓存密钥,在失败或轮换时刷新,使用本地选择的容差拒绝过期时间戳,要求 header/body ID 一致,并按
generation_id
以事务方式对投递进行去重。

Handle 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.
StatusDocumented meaningAction
400invalid input; also current unsupported speed combinationsfix request; do not retry unchanged
401missing/invalid authorizationstop, repair secret/account
402insufficient credits/quota on
/v1/edit
fund or change approved plan; do not loop
403forbidden or not authorized on documented routes such as V3 Remix/Upscalestop; verify account entitlement and route access; do not retry unchanged
404unknown async generation IDverify stored ID/environment
422prompt or image safety failure; documented body
{ "error": "string" }
do not evade; revise or reject according to policy
429too many requestsreduce in-flight work and retry with bounded exponential jitter
503temporary service unavailable on selected routes such as
/v1/edit
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
Retry-After
guarantee; honor it if actually present, otherwise use full jitter.
No 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
generation_id
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.
默认限制为 10 个进行中的请求;如需更高吞吐量,请联系 Ideogram。该限制是并发限制,而不是文档记录的 requests-per-minute 配额。
状态已记录含义操作
400输入无效;也包括当前不支持的 speed 组合修复请求;不要原样重试
401缺少或无效的身份验证停止,修复 secret/账户
402
/v1/edit
的 credits/quota 不足
充值或更改已批准的计划;不要循环重试
403在 V3 Remix/Upscale 等已记录路由上禁止访问或未获授权停止;验证账户权益和路由访问权限;不要原样重试
404未知 async generation ID验证已存储的 ID/环境
422prompt 或图像安全检查失败;文档记录的请求体为
{ "error": "string" }
不要规避;根据政策修改或拒绝
429请求过多减少进行中的工作,并使用有界的指数退避和 jitter 重试
503
/v1/edit
等选定路由暂时不可用
退避后进行有界重试
OpenAPI 没有为大多数 400/401/429/503 响应体指定类型。应防御性地解析,并记录状态、请求元数据以及脱敏/截断后的请求体。文档没有保证提供
Retry-After
;如果实际存在则遵循该值,否则使用 full jitter。
文档没有记录请求 idempotency-key header。生产环境启发式规则: 对超时的同步 POST 绝不盲目重试,因为请求可能已经完成并计费。优先使用 V4 async,在执行其他工作前持久化
generation_id
,并且只重试轮询 GET。Ideogram 可能会有限次数地重试 Webhook,且不保证投递成功;对成功的重复投递返回 2xx,并回退到轮询。

Price 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
custom_model_uri
; treat them as unresolved until a first-party request schema is available to the target account.
Compute 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
custom_model_uri
;在目标账户可用的第一方请求 schema 出现之前,将这些能力视为未解决。
提交前计算费用上限:请求的输出数量 × 每个输出的价格,再加上 reference/upscale/edit 的附加费用。让操作员能够看到 API 自动充值行为;设置文档说明可配置触发阈值/充值余额,并且 API credits 与应用订阅分离。

Enforce safety, privacy, provenance, and rights

强制执行安全、隐私、来源记录与权利要求

Follow the API agreement and usage policy, not merely
is_image_safe
. 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.
Obtain 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=true
opts a V3/V4 request into additional Hive likeness/logo checks unless the organization setting already enables them; it adds latency, and flagged images return
is_image_safe:false
. Treat this as an extra signal, not legal clearance.
应遵循 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=true
会让 V3/V4 请求选择加入额外的 Hive 肖像/Logo 检查,除非组织设置已启用这些检查;它会增加延迟,被标记的图像会返回
is_image_safe:false
。应将其视为额外信号,而不是法律许可。

Run QA and migrate safely

执行 QA 并安全迁移

Before sending:
  1. Re-fetch the OpenAPI enum for routes, sizes, and presets in release automation.
  2. Validate file type/size, mask dimensions, count, seed, mutually exclusive fields, and V4 bbox ordering/ranges.
  3. Require approval for cost, references/likenesses, public distribution, and policy-sensitive prompts.
  4. Store a redacted canonical request and source hashes before submission.
After receiving:
  1. Reject missing URLs and unsafe results; download ephemeral URLs immediately.
  2. Verify MIME signature, pixel dimensions, alpha channel when requested, and cryptographic hash.
  3. Compare literal typography by OCR and human review; compare reference identity/style without assuming perfect fidelity.
  4. 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.
  5. Record endpoint, returned prompt, seed, actual resolution, price basis, and review outcome.
Migration map:
  • Move
    /v1/ideogram-v3/edit
    and
    /edit
    mask workflows to
    /v1/ideogram-v3/inpaint
    ; rename
    image_file
    to
    image
    and use black editable regions.
  • Move legacy
    /generate
    to V4 Generate for new text/layout work or V3 Generate when V3 references/presets/custom models are required.
  • Move legacy
    /remix
    and
    /reframe
    to
    /v1/ideogram-v4/remix
    or their V3 canonical routes according to required controls.
  • Replace legacy
    model
    /
    magic_prompt_option
    /prefixed aspect-ratio enums with route-scoped models and the exact current field names.
  • 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.
发送前:
  1. 在发布自动化中重新获取路由、尺寸和 preset 的 OpenAPI enum。
  2. 验证文件类型/大小、mask 尺寸、count、seed、互斥字段以及 V4 bbox 的顺序和范围。
  3. 对费用、references/肖像、公开分发和 policy-sensitive prompts 要求审批。
  4. 在提交前存储脱敏的规范化请求和源文件哈希。
接收后:
  1. 拒绝缺少 URL 或不安全的结果;立即下载临时 URL。
  2. 验证 MIME 签名、像素尺寸、请求 alpha channel 时的透明通道,以及加密哈希。
  3. 使用 OCR 和人工审核比较字面 typography;比较 reference 的身份/风格,但不要假设完全一致。
  4. 对编辑操作比较受保护区域;对 inpaint 检查 mask 接缝;对 reframe 检查主体保留和新边缘;对背景操作检查头发/透明光晕。
  5. 记录 endpoint、返回的 prompt、seed、实际 resolution、价格依据和审核结果。
迁移映射:
  • 将
    /v1/ideogram-v3/edit
    和
    /edit
    mask 工作流迁移到
    /v1/ideogram-v3/inpaint
    ;将
    image_file
    重命名为
    image
    ,并使用黑色可编辑区域。
  • 对于新的文本/布局工作,将 legacy
    /generate
    迁移到 V4 Generate;当需要 V3 references/presets/custom models 时迁移到 V3 Generate。
  • 根据所需控制项,将 legacy
    /remix
    和
    /reframe
    迁移到
    /v1/ideogram-v4/remix
    或对应的 V3 标准路由。
  • 将 legacy
    model
    /
    magic_prompt_option
    /带前缀的 aspect-ratio enum 替换为路由限定 model 和当前准确的字段名称。
  • 使用冻结的 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
    WebhookUrl
    component says the webhook body mirrors the synchronous response with
    request_id
    , while the async endpoint schema and dedicated webhook guide use
    generation_id
    . Follow the dedicated guide/header contract and require matching
    generation_id
    ; treat
    request_id
    wording as stale until resolved.
  • The Layerize Text prose and example show
    text_blocks
    with font/position/style data, while the current OpenAPI
    LayerizeTextResponse
    schema declares only
    base_image_url
    , optional
    original_image_url
    , and
    seed
    . Code to the declared schema and feature-detect
    text_blocks
    ; do not make it required until Ideogram resolves the mismatch.
  • 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
    num_images
    ; do not treat example cardinality as a guarantee.
  • 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
    WebhookUrl
    组件称 Webhook 请求体镜像同步响应并包含
    request_id
    ,而 async endpoint schema 和专用 Webhook 指南使用
    generation_id
    。遵循专用指南/header 合同,并要求
    generation_id
    匹配;在 Ideogram 解决歧义前,将
    request_id
    表述视为过期信息。
  • Layerize Text 正文和示例展示了包含字体/位置/样式数据的
    text_blocks
    ,而当前 OpenAPI
    LayerizeTextResponse
    schema 仅声明
    base_image_url
    、可选的
    original_image_url
    和
    seed
    。应按照已声明的 schema 编码,并对
    text_blocks
    进行功能检测;在 Ideogram 解决不匹配之前,不要将其设为必需字段。
  • 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 路径。应依据已记录的路由可用性进行选择,而不是依据价格表措辞。

First-party sources

第一方来源