Browse all docs & guides
On this page
CORE CONCEPTS

Generations Lifecycle

OpenGen processes every media generation as a durable, workspace-private job across eight REST endpoints. Submit once with a persisted Idempotency-Key and optional Prefer wait up to 25 seconds, follow updates via Server-Sent Events or compact status long-polling, recover lost responses via read-only lookup, cancel explicitly, and purge terminal outputs on demand.

Reviewed 2026-12-02
AGENT PROMPT · PASTE INTO YOUR AGENT OR AUTO-READ
Manage generation jobs safely end-to-end using https://opengen.dev/docs/generations:
1. Always inspect the model schema (GET https://opengen.dev/v1/models/{provider}/{model}) and run POST https://opengen.dev/v1/pricing/estimate before confirming maxCostMicros with the user.
2. Persist a unique Idempotency-Key (1–200 chars) and the exact canonical JSON body before calling POST https://opengen.dev/v1/generations (optional Prefer: wait=20 for fast images) or MCP generate(waitMs=20000).
3. On timeout or network drop, NEVER mint a new Idempotency-Key — call read-only GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or MCP job_get({ idempotencyKey }).
4. Follow progress via GET https://opengen.dev/v1/generations/{id}/events (SSE), GET https://opengen.dev/v1/generations/{id}/status?afterRevision=...&waitMs=25000, or webhooks, then fetch fresh signed output links via GET https://opengen.dev/v1/generations/{id} (or job_get).
View raw .md ↗

All 8 generation endpoints

Every endpoint under the generations OpenAPI tag is strictly workspace-private and served with Cache-Control: no-store:

Method & PathOperation IDScopePurpose
POST /v1/generationsmedia.generategenerateSubmit one canonical generation with required Idempotency-Key (1–200 chars) and optional Prefer: wait=N (0–25s). Returns 202 Accepted (or 200 OK if ready inside Prefer: wait) with Location: /v1/generations/{id}
GET /v1/generationsjobs.listreadList workspace generation jobs newest-first. Returns X-Next-Cursor header for pagination; filters: modelId, providerId, deploymentId, endpointRegion, operation, keyId, status, project, since, until, limit (1–100), cursor
GET /v1/generations/lookupjobs.lookupreadRead-only recovery of a job by ?idempotencyKey=<key> when the original submit response was lost. Never creates a job
GET /v1/generations/{id}jobs.getreadRead full job details, billing state, structuredError, and fresh short-lived signed /media output URLs while retained
GET /v1/generations/{id}/statusjobs.statusreadCompact status long-poll (?afterRevision=<64-hex>&waitMs=<0..25000>). Returns { job, changed, timedOut } with 64-hex revision, progress, and timings
GET /v1/generations/{id}/eventsjobs.eventsreadBounded 50-second text/event-stream SSE stream (?afterRevision= or Last-Event-ID header) with 10s heartbeats and clean reconnect cursor
POST /v1/generations/{id}/canceljobs.cancelgenerateImmediately cancels a queued job (200 OK, releases hold) or requests upstream cancellation on a running job (202 Accepted, cancellationState: "requested")
DELETE /v1/generations/{id}/outputsjobs.purgeOutputsgeneratePermanently deletes retained private output bytes on a terminal settled job while preserving job metadata and ledger history

Canonical request envelope

Every generation request uses one consistent envelope across all 54 models and 10 operations:

JSON
{
  "modelId": "openai/gpt-image-2",
  "operation": "text-to-image",
  "input": {
    "prompt": "Minimalist studio photo of a frosted glass carafe on travertine stone",
    "resolution": "1K",
    "aspectRatio": "1:1",
    "quality": "low"
  },
  "billing": "managed",
  "maxCostMicros": 50000,
  "metadata": {
    "project": "catalog-hero",
    "tags": { "env": "staging", "batch": "dec-02" }
  }
}

Optional envelope fields:

  • billing: "managed" (default prepaid workspace credit) or "byok" (encrypted workspace provider key).
  • routeId or routing: pin an exact regional route or declare routing constraints (see Regional Routing & Privacy).
  • maxCostMicros: integer micro-USD ceiling for managed generations (1 USD = 1,000,000 micro-USD).
  • metadata: private project (up to 80 chars) and up to 16 tags (for filtering in GET /v1/generations and cost attribution in GET /v1/analytics).
  • previousJobId: owned completed job UUID for supported continuations (such as Omni video-extend).
  • queueStartDeadlineAt: ISO-8601 UTC deadline after which a still-queued job fails with start_deadline_exceeded before dispatch.
  • webhookUrl and webhookEvents: per-request Ed25519-signed webhook callback (see Webhooks & Ed25519 Verification).

Job status, delivery, and cancellation states

OpenGen tracks execution status, private output delivery, and cancellation independently so callers never confuse upstream completion with downloadable media or confirmed refunds:

Execution status

StatusTerminal?Meaning
queuedNoAdmitted and reserved locally; waiting for worker dispatch
submittingNoWorker is actively submitting to the upstream provider
runningNoUpstream provider accepted the task and is executing
submission-unknownYes (reconciliation)Upstream acceptance could not be confirmed after timeout or transport failure. Reserved funds stay held pending reconciliation — never blind-retry
succeededYesUpstream provider reported completion; inspect deliveryStatus before downloading outputs
failedYesUpstream or admission failure recorded in structuredError
cancelledYesCancellation confirmed

Delivery deliveryStatus

  • pending: worker is downloading, verifying container signatures/SHA-256, and writing outputs into private object storage.
  • available: all output receipts are stored privately and outputs[] contains valid signed URLs.
  • partial: at least one output slot succeeded while another failed (inspect deliveryErrors[]).
  • failed: output capture failed; inspect deliveryErrors[] and structuredError.
  • expired: outputs expired or were explicitly purged via DELETE /v1/generations/{id}/outputs.
  • unverified: legacy/unverified delivery receipt state.

Cancellation cancellationState

  • none: no cancellation requested.
  • requested: upstream cancellation was requested for a running job (POST /v1/generations/{id}/cancel returned 202 Accepted). Reserved credits remain held until polling confirms terminal non-billable cancellation.
  • confirmed: cancellation confirmed (queued jobs transition immediately to status: "cancelled" with 200 OK and hold released).
  • rejected or unsupported: the upstream provider rejected or does not support mid-flight cancellation; the job may finish and settle normally.

Synchronous Prefer: wait, SSE streaming, and compact polling

Choose the waiting strategy that fits your latency profile:

  • **Fast images (Prefer: wait=20)**: Send RFC 7240 Prefer: wait=20 (clamped 0–25s) on POST /v1/generations. If the job reaches a terminal state with non-pending delivery inside the window, OpenGen returns 200 OK with Preference-Applied: wait=20 and populated outputs[]. Otherwise it returns 202 Accepted cleanly so you continue asynchronously.
  • **Server-Sent Events (GET /v1/generations/{id}/events)**: Streams event: status frames carrying id: <64-hex-revision>, : heartbeat comments every 10 seconds, event: done once terminal with non-pending delivery, and event: reconnect with retry: 1000 at the bounded 50-second connection ceiling so EventSource or custom clients reconnect seamlessly using Last-Event-ID. Re-authorizes credentials on every poll tick.
  • **Compact status long-poll (GET /v1/generations/{id}/status)**: Pass afterRevision=<previous-revision>&waitMs=25000 to receive { job, changed, timedOut } without resending full input payloads or re-signing media links until the job finishes.
# Stream live job status via SSE (reconnecting with Last-Event-ID if needed)
curl -N "$OPENGEN_API_URL/v1/generations/$JOB_ID/events" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Accept: text/event-stream"

# Compact status long-poll
curl --fail-with-body \
  "$OPENGEN_API_URL/v1/generations/$JOB_ID/status?waitMs=20000" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

# List recent succeeded video jobs with cursor pagination
curl --fail-with-body -i \
  "$OPENGEN_API_URL/v1/generations?status=succeeded&operation=image-to-video&limit=20" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

Private media delivery, cancellation, and output purging

  • **First-party /media URLs**: Images <= 3.5 MiB stream directly (200 OK) from the OpenGen origin; larger images, videos, and HTTP Range requests return 302 Found to a short-lived private storage URL (<= 300 seconds) stripped of any caller tracking query parameters (such as ?utm_source=...). Re-read GET /v1/generations/{id} (or MCP job_get) to refresh an expired (410 Gone) URL while outputs remain retained.
  • Reusing an output: Pass output.outputIndex (the stable receipt slot, independent of array position) to POST /v1/assets with { "source": "job_output", "sourceJobId": "<jobId>", "outputIndex": 0 } to feed a generated image or video into a downstream edit or video model.
  • Cancelling and purging outputs:
# Request cancellation of an existing job
curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/generations/$JOB_ID/cancel" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

# Permanently purge retained output bytes on a terminal settled job
curl --fail-with-body -X DELETE "$OPENGEN_API_URL/v1/generations/$JOB_ID/outputs" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

Purging requires the job to be terminal and — for succeeded managed jobs — settled (settledMicros !== null). Active delivery leases or unsettled managed jobs return 409 (job_not_terminal, output_purge_pending_settlement, or output_delivery_in_progress). Purging is idempotent and leaves job metadata and billing history intact.