> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nika.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Image generation

> Render images inside workflows — local server first, four more providers one line away, every save permit-gated, every asset provenance-carrying.

`nika:image_generate` treats images as workflow citizens: the same declared
`permits:` boundary that gates file writes gates every save, real spend lands
in the run ledger, and provenance is structural — in the manifest beside the
asset *and* inside the PNG itself.

## The five providers

| provider | default model | wire | what to know |
| - | - | - | - |
| `local` | `stablediffusion` | your server's OpenAI-images route | The local inference path. One wire covers LocalAI (`:8080`), Ollama (`:11434`), stable-diffusion.cpp `sd-server` (`:1234`), SGLang Diffusion and vLLM-Omni. Never inferred from `model:` — always explicit. |
| `openai` | `gpt-image-2` | Images API | Exact sizes (`WxH`), native `n`, `background: transparent`, webp/jpeg `compression`. |
| `gemini` | `gemini-3.1-flash-image` | `generateContent` | Aspect-ratio classes; may return an interleaved caption (surfaced as `provider_text`, clamped). |
| `xai` | `grok-imagine-image` | Imagine API | Native aspect ratios + `resolution: 1k\|2k` classes; the `-quality` model tier is the quality knob; **bills exact cost into the run ledger**. |
| `mock` | `mock-image-1` | in-process | Real, decodable, deterministic PNG files — zero network, zero keys. CI runs the whole pipeline offline. |

Keys and the local URL are **engine config, never workflow args**:
`OPENAI_API_KEY` / `GEMINI_API_KEY` / `XAI_API_KEY` (or `NIKA_`-prefixed),
`NIKA_IMAGE_LOCAL_URL` (+ optional `NIKA_IMAGE_LOCAL_API_KEY`). Check what's
wired with `nika doctor` — it prints an `image` line naming the ready
providers.

## Local server quickstart

```bash theme={"system"}
# LocalAI (first-party spec-complete compat route · :8080)
docker run -p 8080:8080 localai/localai:latest

# …or Ollama (macOS · experimental image generation · :11434)
export NIKA_IMAGE_LOCAL_URL=http://localhost:11434

# …or stable-diffusion.cpp's server (:1234)
export NIKA_IMAGE_LOCAL_URL=http://localhost:1234
```

```yaml theme={"system"}
nika: og-hero-sovereign
permits:
  fs: { write: ["./assets/**"] }
  tools: ["nika:image_generate"]
tasks:
  hero:
    invoke:
      tool: "nika:image_generate"
      args:
        provider: local
        model: "x/z-image-turbo"        # model names are server-specific
        prompt: "OG hero — a monarch butterfly over a nebula"
        aspect_ratio: "16:9"
        output_dir: "./assets/og"
```

The engine forces `response_format: b64_json` (LocalAI defaults to URL mode),
refuses url-only answers (**result URLs are never fetched** — that would
reopen the SSRF surface the fixed-endpoint design closed), and gives local
renders a 300s default timeout — CPU diffusion runs minutes, raise
`timeout_ms:` up to 600000 when needed. SD-family servers honor a
`positive | negative` prompt split written directly inside `prompt:`.

## What lands on disk

```
assets/og/
├── hero-local-x-z-image-turbo-0-9ec15c15.png        # sha256-named
└── hero-local-x-z-image-turbo-66a35545.manifest.json
```

The **manifest** carries the resolved request, per-image sha256 + dimensions,
`endpoint_host` (which server actually rendered it), timing, warnings,
`cost_usd`, and your `metadata:` fields — never a credential, by construction.

The **PNG itself** carries a `nika` tEXt chunk (tool, engine version,
provider, model, prompt, seed) — so provenance survives `cp`, the practice
ComfyUI and InvokeAI standardized. Read it back with any PNG tool, for
example `exiftool -a -G1 asset.png | grep -i nika`, or with this
standard-library Python script (no package to install):

```python png-nika.py theme={"system"}
import struct, sys

data = open(sys.argv[1], "rb").read()
pos = 8                                    # skip the 8-byte PNG signature
while pos < len(data):
    length, kind = struct.unpack(">I4s", data[pos:pos + 8])
    if kind == b"tEXt":
        key, _, text = data[pos + 8:pos + 8 + length].partition(b"\0")
        if key == b"nika":
            print(text.decode("utf-8", "replace"))
    pos += 12 + length                     # length + type + data + CRC
```

```text theme={"system"}
$ python3 png-nika.py out/image-mock-mock-image-1-0-a0828e59.png
{"engine":"0.123.0","model":"mock-image-1","prompt":"a blue square","provider":"mock","seed":null,"tool":"nika:image_generate"}
```

## Content credentials (detect-and-preserve)

OpenAI and Google **sign their API bytes** with C2PA Content Credentials —
and C2PA hashes the file's byte ranges, so any pipeline that writes into a
signed render converts valid credentials into *« present but tampered »*.
Nika detects the signals first (PNG `caBX` · JPEG APP11 JUMBF · RIFF
`C2PA` · MP3 GEOB): on signed payloads the `nika` tEXt embed **stands
down** (their signed manifest outranks our informal chunk — a loud
`content_credentials_preserved:` warning says so), and the output +
manifest surface `content_credentials: "c2pa"` plus `watermark_declared`
(SynthID is a provider fact — only the vendor can detect it). Detection
labels only: the wire never says « verified ». With EU AI Act Article 50
in force from **2026-08-02**, preserving machine-readable marks is part of
an operator's compliance surface — no other workflow engine even looks.

## Honesty rules (what the warnings mean)

Every lossy mapping is a **stable, visible warning** — silent degradation is
non-conformant per the spec:

* `count_shortfall:` — the provider returned fewer than `n:` (Ollama's compat
  route ignores `n`, moderation can filter variants).
* `size_conflict:` · `xai_size_class:` · `aspect_remapped:` — your exact size
  was folded to the provider's nearest class, loudly.
* `seed_unsupported:` · `quality_folded:` · `compression_ignored:` — the knob
  doesn't exist on that provider; the arg was dropped, visibly.
* `format_mismatch:` — fires only when you *explicitly* asked for a format
  the provider didn't honor; magic bytes name the real extension either way.

## Real spend in the ledger

xAI bills images in cost ticks — the engine converts them exactly
(`cost_basis: provider_reported`) and the render's cost rides the task line,
the run total, and the manifest:

```
✔  render  invoke · nika:image_generate  5.6s · $0.02
── 1/1 done · $0.02 · elapsed 5.6s ──────────────────
```

OpenAI and Gemini renders are billed from the engine's dated price table
([Cost honesty](https://docs.nika.sh/guides/cost-honesty.md#the-media-price-table)): the token rates
times the usage the response reports (`cost_basis: catalog_rate_x_usage`), or
the price per image times the images when no response reports usage
(`catalog_price_x_images`), with the date of the rates in `cost_as_of`. An
image whose response reports no usage is billed at the dearest row its
request leaves open: `quality: auto` with no `size:` bills `$0.211` on
`gpt-image-2`, never the cheapest `$0.005`, so name the size and quality you
mean. Each response of a Gemini `n:` batch is billed on its own, and a render
that fails after its provider billed (a later request of the batch, a decode,
a save) keeps that spend.

Any invoke tool reporting a top-level `cost_usd` in its structured output is
metered the same way. A call with no price Nika can apply shows `null` —
never an estimate dressed as truth.

Under a cost cap (`--max-cost-usd`, a project `ceiling:` or a beat's
`plafond:`):

* `gpt-image-2` and the Gemini models the table prices
  (`gemini-3.1-flash-image`, `gemini-3-pro-image`, `gemini-2.5-flash-image`,
  `gemini-3.1-flash-lite-image` and `gemini-nano-banana-2.1`) are floored at
  launch, their price per image times `n:`, and billed against the cap.
* `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` have no published price
  per image: they run billed from the usage they report (`METERED` in
  `nika check`), and only a zero cap refuses them.
* xAI images keep their `$0.02` floor per image and the spend xAI reports.
* `gpt-image-1.5`, `gpt-image-1-mini` (which OpenAI shuts down on 2026-12-01)
  and any id the table does not list are refused before any request
  (`NIKA-1709`, or `NIKA-1704` when only the run decides the model): switch to
  `gpt-image-2` or a 2.5 model. Without a cap they run and count as unpriced
  ([Cost honesty](https://docs.nika.sh/guides/cost-honesty.md#paid-media-priced-refused-or-unpriced)).

## Cookbook (each proven end-to-end against live APIs)

**An LLM writes the brief, another provider renders it:**

```yaml theme={"system"}
nika: brief-to-image
model: gemini/gemini-2.5-flash
permits:
  fs: { write: ["./out/**"] }
  tools: ["nika:image_generate"]
tasks:
  brief:
    infer:
      prompt: "Write a vivid one-sentence OG-image brief for a post about local-first AI. Pick the ratio."
      schema:
        type: object
        required: [brief, aspect_ratio]
        properties:
          brief: { type: string }
          aspect_ratio: { type: string, enum: ["1:1", "16:9", "4:3"] }
  render:
    with:
      brief: ${{ tasks.brief.output.brief }}
      ratio: ${{ tasks.brief.output.aspect_ratio }}
    invoke:
      tool: "nika:image_generate"
      args:
        provider: xai
        prompt: "${{ with.brief }}"
        aspect_ratio: "${{ with.ratio }}"
        output_dir: "./out"
```

**Fan out one hero across locales (concurrent, one output dir):**

```yaml theme={"system"}
  hero:
    for_each:
      items: ${{ const.locales }}      # ["fr", "es", "ja"]
      max_parallel: 3
    with: { locale: ${{ item }} }
    invoke:
      tool: "nika:image_generate"
      args:
        provider: mock                   # flip to local/gemini/openai/xai
        prompt: "launch hero, locale ${{ with.locale }}"
        output_dir: "./out"
        filename_prefix: "hero-${{ with.locale }}"
```

**Let an agent decide the arguments** (the model reads the tool definition):

```yaml theme={"system"}
  designer:
    agent:
      prompt: >
        Generate exactly one minimalist butterfly logo using the image tool
        (provider xai, aspect_ratio 1:1, output_dir ./out), then call done
        with the saved path.
      tools: ["nika:image_generate", "nika:done"]
      max_turns: 4
```

**Retry transient failures** (a local server still loading its model):

```yaml theme={"system"}
  render:
    retry:
      max_attempts: 3
      on_codes: ["NIKA-BUILTIN-IMAGE_GENERATE-003"]
    invoke:
      tool: "nika:image_generate"
      args: { provider: local, prompt: "…", output_dir: "./out" }
```

## Why the save is gated

Image bytes land on disk under `permits.fs.write`, the engine verifies
returned MIME types, a provenance manifest records the resolved request,
and result URLs are never fetched (that would reopen SSRF). Local inference
is a first-class provider. The PNG can carry a `nika` tEXt chunk — the
same informal provenance practice ComfyUI and InvokeAI use. The argument
contract is in [builtins](https://docs.nika.sh/reference/builtins.md#media-5) and
`nika catalog --tools`.

## Editing (`mode: edit`)

An input image plus an instruction — the same builtin, one arg away:

```yaml theme={"system"}
  night:
    with:
      src: ${{ tasks.render.output.images[0].path }}   # edit what you generated
    invoke:
      tool: "nika:image_generate"
      args:
        provider: openai            # the first edit wire · gemini/xai/local follow
        mode: edit
        image: ${{ with.src }}
        prompt: "make it night — starry sky"
        output_dir: "./out"
```

The rules mirror generation, inverted where reading demands it:

* **Reads are permit-gated.** Every `image:`/`images:`/`mask:` path is
  enforced against `permits.fs.read` *before* a byte is read — the exact
  mirror of the save boundary. Edit reads what generate writes, so a
  generate→edit chain declares both `read:` and `write:`.
* **`image:` XOR `images:`** — one source or many (capped per provider:
  openai 16 · gemini 14 · xai 3), 20 MB each, magic-byte sniffed.
* **A `mask:` is refused, never dropped**, on providers that edit by
  instruction only (gemini/xai): a silently-ignored mask edits the wrong
  region. openai (and local inpaint) take pixel masks.
* **The provenance chain survives.** The manifest carries `mode: "edit"`
  plus `source_images: [{path, sha256, format}]` — an edited asset records
  exactly what it derived from.

> [!NOTE]
>
> `reference_images:` (compose-from-references) and `save: false` remain
> reserved — refused loudly rather than pretended.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.