Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/gpt-image-2-6-gif.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-module-images": minor
---

`brain image --format gif` makes animated GIFs with the GPT Image 2.6 models, for new images and for edits with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms) set the loop; without them OpenAI applies its defaults of 9 frames at 200 ms. GIF with `--mask` or `--transparent`, GIF on a 2.5 or Gemini model, and frame flags without `--format gif` are refused before any request. OpenAI serves GIF only to organizations with GIF preview access, and a refusal for missing access says so. A dry run reports a GIF's cost as unknown.
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -4078,7 +4078,7 @@ reason through as the refusal body's `error.message` and an additive
`outward_not_approved` (`const refuse`,
`packages/ui-sdk/src/server/provider-relay.ts:386-391`). The OpenAI image
provider no longer appends its account hint to a relay refusal
(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:199-200`).
(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:252-253`).
A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle
section names these causes and what the user can do (`A blocked connection
says why`, `packages/ui-sdk/src/server/system-prompt.ts:167-175`). Since #3246,
Expand Down
2 changes: 1 addition & 1 deletion docs/hosting/paid-cli-provider-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ SDK conversion without adding a public embedding-provider seam.

The image CLI preserves `bytes`, `costIsEstimate`, `costUsd`, `model`, `note`,
`output`, `outputs`, `provider`, `reason` and `renamed`
(`const payload`, `packages/module-images/src/cli.ts:408-420`). Its help example
(`const payload`, `packages/module-images/src/cli.ts:466-477`). Its help example
is abbreviated; it is not the complete machine contract. Internal image raw
usage does not imply that this envelope exposes it.

Expand Down
10 changes: 10 additions & 0 deletions packages/module-images/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ serve at all:
| PNG or WebP | OpenAI | Every Gemini image model serves JPEG only |
| Exact custom pixels | OpenAI | Gemini has fixed ratios; the 2.6 and 2.5 models take any size on a 16px grid up to 3840px, 3:1 and 8.3MP |
| `--complexity` | OpenAI GPT Image 2.6 | Only the 2.6 models take it; it is refused anywhere else |
| Animated GIF (`--format gif`) | OpenAI GPT Image 2.6 | Only the 2.6 models return GIF; it is refused anywhere else |
| Character consistency | Gemini | Narrows to models that claim it; no benchmark picks a winner |
| >6 reference images | Gemini | 10 (Flash) / 14 (Lite) vs OpenAI's practical 8 |
| Watermark-free | OpenAI | Gemini always applies SynthID |
Expand All @@ -57,6 +58,15 @@ it with them is refused. A transparent JPEG, an unknown quality, complexity or
format, a `--size` that is not `WIDTHxHEIGHT`, and a custom size outside
OpenAI's rules are refused before any request.

`--format gif` asks a GPT Image 2.6 model for an animated GIF, for a new image
or an edit with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms)
set its frame count and timing; without them the API uses its own defaults of 9
frames at 200 ms. The frame flags need `--format gif`. A GIF takes no `--mask`
and no `--transparent`, and the 2.5 models and Gemini cannot return one; each of
these is refused before any request. OpenAI serves GIF only to organizations
with GIF preview access, and the refusal says so. A dry run reports a GIF's cost
as unknown, because OpenAI publishes no per-frame token count.

### Retired models

`gpt-image-2` and `gpt-image-1.5` are no longer supported. Naming either in
Expand Down
9 changes: 9 additions & 0 deletions packages/module-images/skills/image-gen/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ only when the user asked for something else.
| More than 6 reference images | Gemini | Up to 10 (Flash) or 14 (Lite); OpenAI's practical ceiling is 8 |
| Output that must carry no watermark | OpenAI | Every Gemini image carries SynthID, with no documented opt-out |
| PNG or WebP output | OpenAI | Every Gemini image model serves JPEG only — verified against the live API, the docs do not say so |
| An animated GIF | `gpt-image-2.6-sunburst` or `-flare` | Only the 2.6 models return GIF |

### The cases worth knowing

Expand Down Expand Up @@ -121,6 +122,14 @@ Without it, the 2.6 models are sent `high`. Lower it only when the user asks,
or when an edit at `high` keeps changing things it should leave alone. The 2.5
models and Gemini do not take it, so naming it with them is refused.

For a moving picture, pass `--format gif`. It works for a new image and for an
edit with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms) set the
loop; leave them out unless the user asks for a length or speed, and the API
uses 9 frames at 200 ms. A GIF cannot take a mask or a transparent background,
and the dry run cannot price it, so say the cost is unknown. If OpenAI answers
that the organization lacks GIF preview access, tell the user that; retrying
will not help.

`--draft` takes the cheapest model that fits. `--dry-run` prints the decision
and the price without spending anything — use it when the user is likely to
want a different model, and when a request is large or repeated.
Expand Down
54 changes: 49 additions & 5 deletions packages/module-images/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import { estimateOpenAiOutputCost, openAiRequestQuality, openAiRequestSize } fro
import { isRetiredModel, retiredModelMessage } from "./retired.js";
import { route, type RoutingDecision } from "./routing.js";
import {
GIF_FRAME_COUNT,
GIF_FRAME_DURATION_MS,
IMAGE_COMPLEXITIES,
IMAGE_FORMATS,
IMAGE_QUALITIES,
ImageProviderError,
type ImageComplexity,
Expand All @@ -34,7 +37,15 @@ import {
type ImageRequest,
} from "./types.js";

const FORMATS = ["png", "jpeg", "webp"] as const;
const FORMATS = IMAGE_FORMATS;

/** A whole number within an inclusive range, or why not. */
function wholeInRange(flag: string, raw: string, range: { min: number; max: number }): number | string {
const n = Number(raw);
return /^\d+$/.test(raw) && n >= range.min && n <= range.max
? n
: `${flag} must be a whole number from ${range.min} to ${range.max} (got "${raw}")`;
}

/** A per-image price, or the honest absence of one. */
const price = (usd: number | null) => (usd === null ? "cost unknown" : `~$${usd.toFixed(3)}`);
Expand All @@ -49,8 +60,16 @@ Output:
--scratch Write to the brain's scratch area instead (.brain/scratch/): for a
draft that should not become part of the brain. Never committed;
pruned after 7 days or past 1 GB.
--format png|jpeg|webp Default: whatever the chosen model returns
(every Gemini image model serves JPEG only)
--format png|jpeg|webp|gif
Default: whatever the chosen model returns
(every Gemini image model serves JPEG only). gif is an
animated GIF from GPT Image 2.6 only; it needs GIF preview
access on the OpenAI organization, takes no --mask or
--transparent, and a dry run cannot price it

Animation (--format gif only):
--frames <n> 2-16 frames. Default: the API's, 9
--frame-duration <ms> 20-2000 ms per frame. Default: the API's, 200

Shape (--aspect and --resolution work on every model):
--aspect <W:H> 1:1 2:3 3:2 3:4 4:3 4:5 5:4 9:16 16:9 21:9 on Gemini;
Expand Down Expand Up @@ -221,6 +240,24 @@ export const imageCommand: CommandModule<ImagesConfig> = {
console.error(`--format must be one of ${FORMATS.join(", ")} (got "${format}")`);
return 1;
}
// Frame settings are GIF settings: checked here, before routing or any
// request, so a typo never reaches a paid call (#3783).
const frameFlags = { frames: GIF_FRAME_COUNT, "frame-duration": GIF_FRAME_DURATION_MS } as const;
const frameValues: Partial<Record<keyof typeof frameFlags, number>> = {};
for (const [flag, range] of Object.entries(frameFlags) as [keyof typeof frameFlags, { min: number; max: number }][]) {
const raw = parsed.flags[flag];
if (raw === undefined) continue;
if (format !== "gif") {
console.error(`--${flag} applies to animated GIFs only; add --format gif`);
return 1;
}
const value = wholeInRange(`--${flag}`, String(raw), range);
if (typeof value === "string") {
console.error(value);
return 1;
}
frameValues[flag] = value;
}

let request: ImageRequest;
try {
Expand All @@ -232,6 +269,8 @@ export const imageCommand: CommandModule<ImagesConfig> = {
quality: quality as ImageQuality | undefined,
complexity: complexity as ImageComplexity | undefined,
format: format as ImageRequest["format"],
frames: frameValues.frames,
frameDurationMs: frameValues["frame-duration"],
transparent: parsed.flags.transparent === true,
references: (parsed.repeated.ref ?? []).map((r) => loadImage(ctx.root, r)),
mask: parsed.flags.mask ? loadImage(ctx.root, parsed.flags.mask as string) : undefined,
Expand Down Expand Up @@ -324,8 +363,11 @@ export const imageCommand: CommandModule<ImagesConfig> = {
// The GPT Image models have no card price, but a quality (stated, or the
// max default) and a size have a published output-token count; `auto`
// or an unstated size stays unknown.
// GIF has no published per-frame token count, so it is never priced.
const estimatedCostUsd =
model.provider === "openai"
request.format === "gif"
? null
: model.provider === "openai"
? (estimateOpenAiOutputCost(model.id, openAiRequestQuality(request), openAiRequestSize(request, model.id)) ?? null)
: model.approxCostUsd1K;
const payload = {
Expand All @@ -339,7 +381,9 @@ export const imageCommand: CommandModule<ImagesConfig> = {
if (ctx.json) console.log(JSON.stringify(payload, null, 2));
else {
const cost =
estimatedCostUsd === null && model.provider === "openai"
request.format === "gif"
? "cost unknown — OpenAI publishes no per-frame token count for GIF"
: estimatedCostUsd === null && model.provider === "openai"
? "cost unknown — pass --size or --aspect (and a quality other than auto) to price it"
: price(estimatedCostUsd);
console.log(`Would use ${describe(decision)}`);
Expand Down
42 changes: 35 additions & 7 deletions packages/module-images/src/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ import {
* https://developers.openai.com/api/docs/guides/image-generation
*
* Only the 2.6 pair takes `complexity` (low|medium|high, default high, no
* separate fee). The 2.5 pair is not deprecated upstream and stays
* separate fee) and returns animated GIFs (`output_format: "gif"`, #3783),
* which need GIF preview access on the OpenAI organization. The 2.5 pair is not deprecated upstream and stays
* selectable. gpt-image-2 and gpt-image-1.5 are retired (`../retired.ts`) and
* must not be re-added as a fallback.
*/
Expand All @@ -61,27 +62,32 @@ const GPT_IMAGE = {
// not transfer by name.
strongTextRendering: false,
watermarked: false,
outputFormats: ["png", "jpeg", "webp"],
outputFormats: ["png", "jpeg", "webp"] as ModelCapabilities["outputFormats"],
defaultFormat: "png",
// Billed per token, so there is no single per-image figure to show. A dry
// run with a quality and a size is priced by `estimateOpenAiOutputCost`.
approxCostUsd1K: null,
} satisfies Omit<ModelCapabilities, "id" | "summary" | "complexityControl">;

/** The 2.6 pair adds animated GIF to the shared formats (#3783). */
const GPT_IMAGE_26_FORMATS: ModelCapabilities["outputFormats"] = [...GPT_IMAGE.outputFormats, "gif"];

const MODELS: ModelCapabilities[] = [
{
id: "gpt-image-2.6-sunburst",
summary:
"OpenAI's most capable image model — the default; complexity control, transparency on png/webp, masks, custom sizes, xhigh/max quality, no watermark",
...GPT_IMAGE,
complexityControl: true,
outputFormats: GPT_IMAGE_26_FORMATS,
},
{
id: "gpt-image-2.6-flare",
summary:
"OpenAI's fastest 2.6 model — chosen by --model; same complexity control, transparency, masks, sizes and quality tiers as Sunburst",
...GPT_IMAGE,
complexityControl: true,
outputFormats: GPT_IMAGE_26_FORMATS,
},
{
id: "gpt-image-2.5-sunburst",
Expand Down Expand Up @@ -203,7 +209,7 @@ export function openAiRequestSize(req: ImageRequest, model: string): string | un
);
}

async function readError(res: Response): Promise<never> {
async function readError(res: Response, req: ImageRequest): Promise<never> {
let code: string | undefined;
let message = `${res.status} ${res.statusText}`;
let moderation: string | undefined;
Expand Down Expand Up @@ -231,14 +237,21 @@ async function readError(res: Response): Promise<never> {
const retryable = res.status >= 500 || (res.status === 429 && !(code && billing.has(code)));

const hints: string[] = [];
// GIF output is a preview feature: an organization without access gets a
// 4xx about it, and neither retrying nor the generic hints below help.
const gifAccess =
req.format === "gif" && (res.status === 400 || res.status === 403) && /\bgif\b|preview/i.test(message);
if (gifAccess) {
hints.push("GIF output needs GIF preview access for this model on the OpenAI organization; ask without --format gif meanwhile");
}
if (code === "moderation_blocked") {
hints.push(`refused by moderation${moderation ? ` — ${moderation}` : ""}`);
}
// The host's provider relay refused before contacting OpenAI (#3431): its
// message says why, and the account hint would point the agent elsewhere.
const relayRefusal = code === "brain_provider_refused" || code === "budget_exceeded";
if (res.status === 403 && !relayRefusal) hints.push("region not supported, or the org is not verified");
if (res.status === 400 && /model/i.test(message)) {
if (res.status === 403 && !relayRefusal && !gifAccess) hints.push("region not supported, or the org is not verified");
if (res.status === 400 && /model/i.test(message) && !gifAccess) {
hints.push("GPT-image models require API Organization Verification");
}
if (code && billing.has(code)) hints.push("billing limit — retrying will not help");
Expand Down Expand Up @@ -304,6 +317,16 @@ export const openaiProvider: Provider = {
retryable: false,
});
}
const gif = req.format === "gif";
if (gif && !MODELS.find((m) => m.id === model)?.outputFormats.includes("gif")) {
throw new ImageProviderError(`${model} does not return GIF; the GPT Image 2.6 models do.`, { retryable: false });
}
if (gif && (req.mask || req.transparent)) {
throw new ImageProviderError("GIF output takes no mask and no transparent background.", { retryable: false });
}
if (!gif && (req.frames !== undefined || req.frameDurationMs !== undefined)) {
throw new ImageProviderError("Frame count and frame duration apply to GIF output only.", { retryable: false });
}
const headers = { Authorization: `Bearer ${apiKey}` };
// Without the key, the host's metered relay adds it (#1673).
const send = providerRelayFetch("openai", "OPENAI_API_KEY") ?? fetch;
Expand All @@ -317,6 +340,9 @@ export const openaiProvider: Provider = {
// be explicit so a caller-set default cannot flatten the transparency.
if (req.format) payload.output_format = req.format;
else if (req.transparent) payload.output_format = "png";
// Unset frame settings stay unsent: the API's defaults (9, 200 ms) apply.
if (req.frames !== undefined) payload.frame_count = req.frames;
if (req.frameDurationMs !== undefined) payload.frame_duration_ms = req.frameDurationMs;
if (req.n && req.n > 1) payload.n = req.n;
// `transparent` is only legal on models that support it; routing guarantees that.
if (req.transparent) payload.background = "transparent";
Expand All @@ -326,7 +352,7 @@ export const openaiProvider: Provider = {
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) await readError(res);
if (!res.ok) await readError(res, req);
return decode((await res.json()) as OpenAiImageResponse, model, req);
}

Expand All @@ -342,6 +368,8 @@ export const openaiProvider: Provider = {
if (req.format) form.append("output_format", req.format);
else if (req.transparent) form.append("output_format", "png");
if (req.transparent) form.append("background", "transparent");
if (req.frames !== undefined) form.append("frame_count", String(req.frames));
if (req.frameDurationMs !== undefined) form.append("frame_duration_ms", String(req.frameDurationMs));
for (const [i, ref] of (req.references ?? []).entries()) {
form.append("image[]", new Blob([ref.data as BlobPart], { type: ref.mime }), ref.label ?? `image-${i}.png`);
}
Expand All @@ -350,7 +378,7 @@ export const openaiProvider: Provider = {
}

const res = await send(`${resolveEnv().openaiBaseUrl}/images/edits`, { method: "POST", headers, body: form });
if (!res.ok) await readError(res);
if (!res.ok) await readError(res, req);
return decode((await res.json()) as OpenAiImageResponse, model, req);
},
};
26 changes: 26 additions & 0 deletions packages/module-images/src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,21 @@ export function route(input: RoutingInput): RoutingDecision {
pool = capable;
}

// GPT Image 2.6 GIF output has no masks, and transparency is documented
// for png and webp only (#3783): refuse rather than let the API decide.
if (req.format === "gif" && req.mask) {
return {
kind: "impossible",
reason: "GIF output takes no mask. Drop --mask and describe the change in the prompt, or ask for png or webp.",
};
}
if (req.format === "gif" && req.transparent) {
return {
kind: "impossible",
reason: "A transparent background is documented for png and webp only, not GIF. Drop --transparent, or ask for png or webp.",
};
}

if (req.transparent && req.format === "jpeg") {
return {
kind: "impossible",
Expand All @@ -194,6 +209,17 @@ export function route(input: RoutingInput): RoutingDecision {

if (req.format) {
const supported = byCapability(pool, (m) => m.outputFormats.includes(req.format!));
if (supported.length === 0 && req.format === "gif") {
const named = available.filter((m) => m.outputFormats.includes("gif")).map((m) => m.id);
return {
kind: "impossible",
reason:
`Animated GIF is a GPT Image 2.6 output, and no model in this request returns it` +
`${input.pinnedModel ? ` (${input.pinnedModel} does not)` : ""}. Use ` +
`${named.length ? named.join(" or ") : "gpt-image-2.6-sunburst or gpt-image-2.6-flare (set OPENAI_API_KEY)"}, ` +
`or ask for png, jpeg or webp.`,
};
}
if (supported.length === 0) {
return {
kind: "impossible",
Expand Down
Loading
Loading