# OpenGen Full Documentation > Complete single-source Markdown documentation corpus for OpenGen (https://opengen.dev). Includes every page's `## Agent Prompt` and live `@media-router/catalog` `## Supported Models` tables. --- Source: https://opengen.dev/docs/quickstart.md (Reviewed 2026-12-02) # Quickstart > OpenGen routes image, video, and audio generations across 12 serving providers through one canonical JSON contract. Check gateway liveness, inspect an exact model variant and its published pricing, run a stateless dry-run cost estimate, verify your workspace balance, and submit once with a persisted Idempotency-Key to receive private signed media delivery. ## Agent Prompt ```text Follow https://opengen.dev/docs/quickstart to run a safe, budget-checked OpenGen generation: 1. Check gateway health at GET https://opengen.dev/health and discover models via GET https://opengen.dev/v1/models (or MCP find_models on https://opengen.dev/mcp/readonly with zero auth). 2. Inspect an exact variant such as openai/gpt-image-2 via GET https://opengen.dev/v1/models/openai/gpt-image-2?operation=text-to-image (or MCP get_model). 3. Estimate cost without spending via POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and check balance via GET https://opengen.dev/v1/balance (or MCP balance). 4. Ask the user to confirm the exact model, route, and maxCostMicros spend cap before submitting. 5. Persist a unique Idempotency-Key before calling POST https://opengen.dev/v1/generations with Prefer: wait=20 (or MCP generate with waitMs=20000). Never blind-retry on timeout; recover with GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or job_get({ idempotencyKey }). ``` ## Prerequisites OpenGen exposes a single canonical HTTP API, Streamable HTTP MCP servers (`/mcp` and zero-auth `/mcp/readonly`), and a zero-dependency portable CLI ([`@opengen-dev/cli`](https://www.npmjs.com/package/@opengen-dev/cli) on npm, Node.js `22.12+`). Standalone third-party SDK packages are deferred — use standard `curl`, `fetch`, Python `httpx`, MCP, or the CLI directly. Before submitting paid work, set two environment variables: - `OPENGEN_API_URL`: defaults to `https://opengen.dev` (or your self-hosted gateway origin). - `OPENGEN_API_KEY`: a scoped workspace API key (`og_sk_...`) created in `/app/keys` with `read` and `generate` scopes, or authenticate interactively via `opengen login` (OAuth 2.1 DCR + PKCE). Never send a third-party provider key as an OpenGen Bearer token. > [!NOTE] > **Zero-auth discovery & `$0` dry-run sandbox:** You can browse models (`GET /v1/models`), inspect schemas (`GET /v1/models/{provider}/{model}`), query published rates (`GET /v1/pricing`), run dry-run cost estimates (`POST /v1/pricing/estimate`), and connect to zero-auth **`https://opengen.dev/mcp/readonly`** (`find_models`, `get_model`, `estimate_cost`, `search_docs`) with **no account, no API key, and `$0` spend**. New personal workspaces start with `$0` managed credit (minimum top-up is `$5` USD in `/billing`). Alternatively, store your own encrypted provider key per deployment in `/app/providers` and set `"billing": "byok"` in your request. ## 1. Check gateway liveness and discover models Catalog discovery endpoints are unauthenticated, CORS-enabled (`Access-Control-Allow-Origin: *`), and CDN-cacheable (`Cache-Control: public, max-age=60, s-maxage=300`). By default, `GET /v1/models` returns compact summaries (~25 KB across all 54 catalog variants) without embedded input schemas. Use `GET /v1/models/{provider}/{model}` to fetch one exact variant's full schemas, regional routes, privacy disclosures, deployments, and published pricing in a single call. ```bash tab="cURL" export OPENGEN_API_URL="https://opengen.dev" # Check gateway liveness curl --fail-with-body "$OPENGEN_API_URL/health" # Search compact image model summaries curl --fail-with-body "$OPENGEN_API_URL/v1/models?modality=image&q=gpt-image-2" # Inspect one exact variant, its schemas, routes, privacy disclosures, and pricing curl --fail-with-body \ "$OPENGEN_API_URL/v1/models/openai/gpt-image-2?operation=text-to-image" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const health = await fetch(`${baseUrl}/health`).then((r) => r.json()); const detail = await fetch(`${baseUrl}/v1/models/openai/gpt-image-2?operation=text-to-image`).then( (r) => r.json(), ); console.log(health.status, detail.model.id, detail.routes.length); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(base_url=base_url, timeout=30.0) as client: health = client.get("/health").raise_for_status().json() detail = client.get( "/v1/models/openai/gpt-image-2", params={"operation": "text-to-image"}, ).raise_for_status().json() print(health["status"], detail["model"]["id"], len(detail["routes"])) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "openai/gpt-image-2", "operation": "text-to-image" } } ``` ```bash tab="CLI" npm install --prefix "$HOME/.opengen/cli" @opengen-dev/cli --ignore-scripts --no-audit --no-fund export PATH="$HOME/.opengen/cli/node_modules/.bin:$PATH" export OPENGEN_API_URL="https://opengen.dev" opengen catalog search "gpt-image-2" --modality image opengen catalog get openai/gpt-image-2 ``` For full details on collections, filters, and exact variant identity, see [Models & Catalog](/docs/models-and-catalog). ## 2. Estimate cost and check workspace balance Before spending credit, run a stateless dry-run estimate against `POST /v1/pricing/estimate`. It validates the exact request payload against the canonical schema, computes per-route `estimatedCostMicros` and `recommendedMaxCostMicros` (in integer micro-USD, where `1 USD = 1,000,000 micro-USD`), and reports `workspaceEligibility` when authenticated — without reserving funds or contacting upstream providers. ```bash tab="cURL" curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low" }, "billing": "managed", "maxCostMicros": 50000 }' # Verify available and reserved workspace credit (requires read scope) curl --fail-with-body "$OPENGEN_API_URL/v1/balance" \ -H "Authorization: Bearer $OPENGEN_API_KEY" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const requestBody = { modelId: 'openai/gpt-image-2', operation: 'text-to-image', input: { prompt: 'A brass compass resting on woven linen, soft north-window studio light', resolution: '1K', aspectRatio: '1:1', quality: 'low', }, billing: 'managed', maxCostMicros: 50000, }; const estimate = await fetch(`${baseUrl}/v1/pricing/estimate`, { method: 'POST', headers, body: JSON.stringify(requestBody), }).then((r) => r.json()); const balance = await fetch(`${baseUrl}/v1/balance`, { headers }).then((r) => r.json()); console.log(estimate.recommendedMaxCostMicros, balance.availableMicros); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} payload = { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", }, "billing": "managed", "maxCostMicros": 50000, } with httpx.Client(base_url=base_url, headers=headers, timeout=30.0) as client: estimate = client.post("/v1/pricing/estimate", json=payload).raise_for_status().json() balance = client.get("/v1/balance").raise_for_status().json() print(estimate["recommendedMaxCostMicros"], balance["availableMicros"]) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low" }, "billing": "managed", "maxCostMicros": 50000 } } ``` ```bash tab="CLI" opengen login opengen balance umask 077 rm -f request.json cat <<'EOF' > request.json { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low" }, "billing": "managed", "maxCostMicros": 50000 } EOF chmod 600 request.json opengen pricing estimate --input request.json ``` > [!TIP] > Inspect published list rates across all serving providers for [GPT Image 2](/openai/gpt-image-2) via `GET /v1/pricing?modelId=openai/gpt-image-2` or [Pricing & Analytics](/docs/pricing-and-analytics). Unknown prices always remain `null` or omitted, never `$0`. ## 3. Submit once with an Idempotency-Key Every `POST /v1/generations` call requires a caller-generated `Idempotency-Key` header (1–200 characters). Persist both the key and the exact request payload into a private per-submission file before sending, and refuse to overwrite an existing unresolved submission record so retries never create a second paid job. OpenGen is queue-first (`202 Accepted` by default). For fast image models, add RFC 7240 `Prefer: wait=20` (clamped `0–25` seconds; or MCP `waitMs=20000` / CLI `--wait 20`). If the generation finishes with available private delivery within the wait window, OpenGen returns `200 OK` with signed output URLs in one round-trip; otherwise it returns `202 Accepted` with a `Location: /v1/generations/{id}` header so you can poll or stream updates. ```bash tab="cURL" set -eu umask 077 RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } OPENGEN_IDEMPOTENCY_KEY="quickstart-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" SUBMISSION_JSON="$(cat <<'JSON' | jq --arg key "$OPENGEN_IDEMPOTENCY_KEY" '{ idempotencyKey: $key, payload: . }' { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low" }, "billing": "managed", "maxCostMicros": 50000 } JSON )" # Atomically claim quickstart-submission.json with both key and exact payload (refuses overwrite on rerun) (set -C; printf '%s\n' "$SUBMISSION_JSON" > quickstart-submission.json) jq '.payload' quickstart-submission.json | curl --fail-with-body -i -X POST "$OPENGEN_API_URL/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $OPENGEN_IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data-binary @- ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const payload = { modelId: 'openai/gpt-image-2', operation: 'text-to-image', input: { prompt: 'A brass compass resting on woven linen, soft north-window studio light', resolution: '1K', aspectRatio: '1:1', quality: 'low', }, billing: 'managed', maxCostMicros: 50000, } as const; // Persist idempotencyKey + exact payload exclusively (flag: 'wx' fails if an unresolved record exists). const idempotencyKey = `quickstart-${randomUUID()}`; await writeFile( 'quickstart-submission.json', JSON.stringify({ idempotencyKey, payload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const response = await fetch(`${baseUrl}/v1/generations`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20', }, body: JSON.stringify(payload), }); if (!response.ok) { throw new Error(`Submission failed (${response.status}): ${await response.text()}`); } const job = await response.json(); console.log(response.status, job.id, job.status, job.deliveryStatus); ``` ```python tab="Python" import json import os import uuid import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") payload = { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", }, "billing": "managed", "maxCostMicros": 50000, } # Persist idempotency_key + exact payload exclusively (O_EXCL fails if an unresolved record exists). idempotency_key = f"quickstart-{uuid.uuid4()}" fd = os.open("quickstart-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": payload}, handle, indent=2) with httpx.Client(base_url=base_url, timeout=35.0) as client: response = client.post( "/v1/generations", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": idempotency_key, "Prefer": "wait=20", }, json=payload, ) response.raise_for_status() job = response.json() print(response.status_code, job["id"], job["status"], job["deliveryStatus"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass resting on woven linen, soft north-window studio light", "resolution": "1K", "aspectRatio": "1:1", "quality": "low" }, "billing": "managed", "maxCostMicros": 50000, "idempotencyKey": "quickstart-2026-12-02-compass-01", "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } OPENGEN_IDEMPOTENCY_KEY="quickstart-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" SUBMISSION_JSON="$(jq -n --arg key "$OPENGEN_IDEMPOTENCY_KEY" --slurpfile payload request.json \ '{ idempotencyKey: $key, payload: $payload[0] }')" (set -C; printf '%s\n' "$SUBMISSION_JSON" > quickstart-submission.json) opengen generate --input request.json --idempotency-key "$OPENGEN_IDEMPOTENCY_KEY" --wait 20 ``` > [!WARNING] > If the network disconnects before you receive a job ID, do **not** overwrite `quickstart-submission.json` or generate a new `Idempotency-Key`. Read the saved key from `quickstart-submission.json` and call read-only `GET /v1/generations/lookup?idempotencyKey=...` (or MCP `job_get({ idempotencyKey })` / `opengen job recover --idempotency-key ...`): > > ```bash > IDEMPOTENCY_KEY=$(jq -r '.idempotencyKey' quickstart-submission.json) > curl --fail-with-body -G "$OPENGEN_API_URL/v1/generations/lookup" \ > --data-urlencode "idempotencyKey=$IDEMPOTENCY_KEY" \ > -H "Authorization: Bearer $OPENGEN_API_KEY" > # Or via CLI: > opengen job recover --idempotency-key "$IDEMPOTENCY_KEY" > ``` ## 4. Follow progress and download private output When a request returns `202 Accepted` (or `deliveryStatus: "pending"`), follow status via Server-Sent Events (`GET /v1/generations/{id}/events`), compact long-polling (`GET /v1/generations/{id}/status`), or webhooks (`webhookUrl`), then fetch the full job via `GET /v1/generations/{id}` once `deliveryStatus` is `"available"` or `"partial"`. All user outputs remain private to the owning workspace. Each item in `outputs[]` carries a short-lived, query-free first-party signed URL (`https://opengen.dev/media/v1...`) served with `Cache-Control: private, no-store`, `Referrer-Policy: no-referrer`, and `X-Robots-Tag: noindex, nofollow, noarchive`. If a link expires, re-read `GET /v1/generations/{id}` (or MCP `job_get`) to mint a fresh link while outputs are retained. ```bash tab="cURL" # Read full job and fresh signed download URLs curl --fail-with-body "$OPENGEN_API_URL/v1/generations/$JOB_ID" \ -H "Authorization: Bearer $OPENGEN_API_KEY" # Download the private output file cleanly (follows 302 for videos and >3.5 MiB images) curl --fail -L -o output.png "$SIGNED_OUTPUT_URL" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const jobId: string = job.id; let afterRevision: string | undefined; while (true) { const qs = new URLSearchParams({ waitMs: '20000' }); if (afterRevision) qs.set('afterRevision', afterRevision); const statusRes = await fetch(`${baseUrl}/v1/generations/${jobId}/status?${qs}`, { headers, }); if (!statusRes.ok) { throw new Error(`Status poll failed (${statusRes.status}): ${await statusRes.text()}`); } const { job: status } = await statusRes.json(); afterRevision = status.revision; const stillActive = ['queued', 'submitting', 'running'].includes(status.status) || (status.status === 'succeeded' && status.deliveryStatus === 'pending'); if (!stillActive) break; } const detailRes = await fetch(`${baseUrl}/v1/generations/${jobId}`, { headers }); if (!detailRes.ok) { throw new Error(`Job detail failed (${detailRes.status}): ${await detailRes.text()}`); } const finalJob = await detailRes.json(); console.log(finalJob.status, finalJob.deliveryStatus); if (Array.isArray(finalJob.outputs) && finalJob.outputs.length > 0) { console.log(finalJob.outputs[0].url); } else if (finalJob.structuredError) { console.error(finalJob.structuredError); } ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} job_id = job["id"] with httpx.Client(base_url=base_url, headers=headers, timeout=30.0) as client: after_revision = None while True: params: dict[str, object] = {"waitMs": 20000} if after_revision: params["afterRevision"] = after_revision status = client.get( f"/v1/generations/{job_id}/status", params=params, ).raise_for_status().json()["job"] after_revision = status["revision"] still_active = status["status"] in {"queued", "submitting", "running"} or ( status["status"] == "succeeded" and status["deliveryStatus"] == "pending" ) if not still_active: break final_job = client.get(f"/v1/generations/{job_id}").raise_for_status().json() print(final_job["status"], final_job.get("deliveryStatus")) outputs = final_job.get("outputs") or [] if outputs: print(outputs[0]["url"]) elif final_job.get("structuredError"): print(final_job["structuredError"]) ``` ```json tab="MCP" { "tool": "job_get", "arguments": { "id": "00000000-0000-4000-8000-000000000001", "waitMs": 25000 } } ``` ```bash tab="CLI" opengen job wait "$JOB_ID" opengen job get "$JOB_ID" ``` ## Next steps - Configure workspace API keys, OAuth 2.1 grants, and least-privilege scopes in [Authentication & Scopes](/docs/authentication). - Connect ChatGPT, Claude, Codex, Claude Code, Cursor, or Grok Bot via [MCP Server & Tools](/docs/mcp) and [Agent Clients](/docs/clients). - Upload private images, videos, or audio for editing and video conditioning in [Private Assets](/docs/assets) and [Image-to-Video Guide](/docs/guides/image-to-video). - Explore all 24 public OpenAPI 3.1 endpoints interactively in the [API Reference](/docs/api). --- Source: https://opengen.dev/docs/authentication.md (Reviewed 2026-12-02) # Authentication & Scopes > OpenGen authenticates REST and MCP requests using workspace-scoped API keys (og_sk_), OAuth 2.1 Dynamic Client Registration with S256 PKCE tokens (og_mcp_a_), or HttpOnly browser sessions. Provider API keys are never OpenGen client credentials; BYOK supplier keys are stored encrypted separately per deployment. ## Agent Prompt ```text Verify workspace authentication before running private OpenGen endpoints using https://opengen.dev/docs/authentication: 1. Never accept or send a third-party provider key (such as an OpenAI or fal key) as an OpenGen Authorization Bearer token, and never place tokens in URLs or shell argv. 2. For public discovery (GET https://opengen.dev/v1/models, /v1/pricing, /openapi.json, or https://opengen.dev/mcp/readonly public tools), no token is needed. 3. For private reads (GET https://opengen.dev/v1/balance, /v1/analytics, /v1/generations, /v1/assets), confirm read scope. For paid submissions, uploads, cancellations, or deletions, confirm generate scope and verify budget via POST https://opengen.dev/v1/pricing/estimate before submitting with an Idempotency-Key. 4. When using OAuth on https://opengen.dev/mcp or https://opengen.dev/mcp/readonly, discover metadata at /.well-known/oauth-protected-resource/mcp (or /mcp/readonly) and /.well-known/oauth-authorization-server. ``` ## Authentication methods OpenGen supports three authentication transports, all strictly scoped to a single workspace: | Method | Token or Cookie | Intended Caller | Lifecycle & Revocation | | --------------------------- | ----------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Workspace API key | `Authorization: Bearer og_sk_<64-hex>` | Server backends, CI jobs, scripts, non-OAuth agents | Created in `/app/keys`; supports explicit scopes, expiry, routing policy, and monthly spend cap; revocable anytime | | OAuth 2.1 (DCR + S256 PKCE) | `Authorization: Bearer og_mcp_a_<43-base64url>` | Hosted assistants, coding agents, IDEs, `@opengen-dev/cli` | 1-hour access token TTL; 30-day grant with refresh-token rotation (`og_mcp_r_...`); revocable via `POST /oauth/revoke` or `/app/apps` | | Browser session cookie | `Cookie: og_session=` | OpenGen web console (`/dashboard`, `/playground`, `/billing`) | `HttpOnly`, `SameSite=Lax`, `Secure` on HTTPS, 12-hour TTL; signed in via Google OIDC, GitHub OAuth, or Email OTP | > [!IMPORTANT] > Upstream supplier keys (OpenAI, fal, Alibaba, BytePlus, Replicate, etc.) are **never** OpenGen authentication credentials. For Bring Your Own Key (`"billing": "byok"`), store encrypted supplier keys per regional deployment in `/app/providers`, then call OpenGen with your OpenGen workspace token. ## Scoped workspace API keys Create dedicated least-privilege keys in `/app/keys`. Send the key strictly in the `Authorization` header — never in query strings, request bodies, committed files, or CLI positional arguments. ```bash tab="cURL" # Verify authentication and inspect available/reserved workspace credit curl --fail-with-body "$OPENGEN_API_URL/v1/balance" \ -H "Authorization: Bearer $OPENGEN_API_KEY" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const res = await fetch(`${baseUrl}/v1/balance`, { headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, }, }); if (res.status === 401) { throw new Error('OpenGen API key is missing, expired, or revoked.'); } console.log(await res.json()); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") response = httpx.get( f"{base_url}/v1/balance", headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}, timeout=15.0, ) response.raise_for_status() print(response.json()) ``` ```bash tab="CLI" # Browser PKCE login (recommended for local interactive terminals) opengen login # Or authenticate headless CI via environment variable (overrides saved browser login) export OPENGEN_API_KEY="og_sk_..." opengen status ``` Each workspace API key can optionally bind: - **Expiration (`expiresAt`)**: expired keys immediately fail with `401 unauthorized`. - **Monthly spend cap (`monthlyCapMicros`)**: hard integer micro-USD ceiling per key. - **Governance routing policy (`policyId`)**: restricts allowed models, serving providers, endpoint regions, and per-request `maxCostMicros`. Request-level `routing` parameters can only narrow an attached policy, never broaden it. ## Permission scopes Every workspace credential carries an explicit set of scopes. Requests missing the required scope fail closed with `403 insufficient_scope`. | Scope | Public Developer Endpoints & MCP Tools | Notes | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | _(none — public)_ | `GET /health`, `GET /openapi.json`, `GET /v1/models*`, `GET /v1/collections*`, `GET /v1/routes`, `GET /v1/pricing`, `POST /v1/pricing/estimate`, `GET /.well-known/webhook-jwks.json`, and 4 public tools on `/mcp/readonly` | Unauthenticated catalog GETs are CDN-cached; authenticated calls switch to `Cache-Control: no-store` | | `read` | `GET /v1/balance`, `GET /v1/analytics`, `GET /v1/generations`, `GET /v1/generations/lookup`, `GET /v1/generations/{id}`, `GET /v1/generations/{id}/status`, `GET /v1/generations/{id}/events`, `GET /v1/assets`, and workspace read MCP tools (`balance`, `analytics`, `job_get`, `jobs_list`, `assets_list`) | Safe read-only visibility into workspace balance, jobs, outputs, assets, and analytics | | `generate` | `POST /v1/generations`, `POST /v1/generations/{id}/cancel`, `DELETE /v1/generations/{id}/outputs`, `POST /v1/assets`, `POST /v1/assets/complete`, `DELETE /v1/assets`, and `/mcp` write tools (`generate`, `job_cancel`, `upload_asset`, `upload_attachment`, `delete_asset`, `purge_job_outputs`) | Authorizes spending managed credit or BYOK runs and mutating/purging private media | | `keys:write` | Workspace API key administration (internal console surface) | Never delegated via MCP OAuth | | `policies:write` | Governance routing policy administration | Never delegated via MCP OAuth | | `connections:write` | Encrypted BYOK provider connection administration | Never delegated via MCP OAuth | | `webhooks:write` | Workspace alert configuration (`GET/PUT /v1/alerts/settings`, `GET /v1/alerts`) | Not required for per-request `webhookUrl` on `POST /v1/generations` | | `members:write` | Team membership and role administration | Admin only; never delegated via MCP OAuth | | `feedback:write` | Feedback and catalog request submission | Never delegated via MCP OAuth | > [!NOTE] > OAuth 2.1 grants for MCP and `@opengen-dev/cli` can only request `read` and `generate` (and `/mcp/readonly` grants are strictly restricted to `read`). Administrative `*:write` scopes are never delegated through OAuth. ## OAuth 2.1 with Dynamic Client Registration & PKCE OpenGen implements OAuth 2.1 with Dynamic Client Registration (RFC 7591), S256 PKCE, Protected Resource Metadata (RFC 9728), and Resource Indicators (RFC 8707). OpenGen does not use Client ID Metadata Documents (CIMD). ### Discovery and protocol endpoints - `GET /.well-known/oauth-authorization-server` — authorization server metadata (`issuer`, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`, `revocation_endpoint`, `code_challenge_methods_supported: ["S256"]`, `token_endpoint_auth_methods_supported: ["none"]`). - `GET /.well-known/oauth-protected-resource` and `GET /.well-known/oauth-protected-resource/mcp` — RFC 9728 metadata for full `/mcp` (`scopes_supported: ["read", "generate"]`). - `GET /.well-known/oauth-protected-resource/mcp/readonly` — RFC 9728 metadata for `/mcp/readonly` (`scopes_supported: ["read"]`). - `POST /oauth/register` — public client registration (`1–10` redirect URIs; supports public HTTPS callbacks, RFC 8252 literal HTTP loopback `http://127.0.0.1` / `http://[::1]` with ephemeral positive ports, and exact `http://localhost:/` callbacks). - `GET /oauth/authorize` — browser authorization endpoint requiring `response_type=code` and `code_challenge_method=S256`. - `POST /oauth/token` — exchanges `authorization_code` or rotates `refresh_token` (`1` hour access token TTL, `30` day grant lifetime). - `POST /oauth/revoke` — revokes an access or refresh token (grants can also be revoked individually in `/app/apps`). ### RFC 8707 audience isolation OAuth tokens minted for `/mcp` (`resource: "https://opengen.dev/mcp"`) and tokens minted for `/mcp/readonly` (`resource: "https://opengen.dev/mcp/readonly"`) are strictly audience-isolated. Presenting a `/mcp/readonly` token to `/mcp` — or a `/mcp` token to `/mcp/readonly` — fails with `401` and a `WWW-Authenticate` challenge pointing to the matching `resource_metadata` URL. ## Workspace isolation, CSRF, and caching boundaries - **Expected workspace guard**: On `GET /v1/balance`, callers can send `X-OpenGen-Expected-Workspace: ` to ensure the credential still resolves to the intended paying workspace; mismatches return `409 workspace_changed`. - **CSRF protection**: Cookie-bearing (`og_session`) cross-origin mutations are rejected with `403 origin_denied`. Cookie-free Bearer/public cross-origin `POST` calls on `/mcp`, `/mcp/readonly`, and `/v1/pricing/estimate` are permitted via public CORS (`Access-Control-Allow-Origin: *`, never `Access-Control-Allow-Credentials: true`). - **Private caching**: Every request carrying an `Authorization` header or `og_session` cookie — and every private endpoint under `/v1/generations*`, `/v1/assets*`, `/v1/balance`, `/v1/analytics`, `/mcp`, and `/mcp/readonly` — is served with `Cache-Control: no-store`. ## Related pages - [MCP Server & Tools](/docs/mcp) — connect `/mcp` or zero-auth `/mcp/readonly`. - [Agent Clients](/docs/clients) — client-specific OAuth setup for ChatGPT, Claude, Codex, Claude Code, Cursor, Grok Bot, Hermes Agent, Muse Code, and CLI. - [Errors & Recovery](/docs/errors) — handle `401 unauthorized`, `403 insufficient_scope`, and `403 policy_denied`. --- Source: https://opengen.dev/docs/mcp.md (Reviewed 2026-12-02) # MCP Server & Tools > OpenGen serves two stateless Streamable HTTP MCP endpoints. The /mcp endpoint exposes all 15 read and write tools behind OAuth 2.1 or API key auth, while /mcp/readonly exposes 9 read-only tools including 4 zero-auth public discovery tools (find_models, get_model, estimate_cost, search_docs). Both publish RFC 9728 metadata, CORS headers, and standard Accept compatibility. ## Agent Prompt ```text Connect to OpenGen over Streamable HTTP MCP using https://opengen.dev/docs/mcp: 1. For zero-auth discovery, send JSON-RPC POST requests to https://opengen.dev/mcp/readonly and call find_models, get_model, estimate_cost, or search_docs (or read opengen://skill and opengen://pricing). 2. For private workspace reads and paid generations, connect to https://opengen.dev/mcp with OAuth 2.1 DCR+PKCE (discovered at https://opengen.dev/.well-known/oauth-protected-resource/mcp) or an OpenGen Bearer token. 3. Always call get_model, estimate_cost, and balance before generate. Confirm the exact model, route, and maxCostMicros spend cap with the user, persist an idempotencyKey, and never call generate a second time to recover a timed-out job — use job_get({ idempotencyKey }) instead. 4. When job_get or generate returns private delivery URLs, include clickable Open/Download links alongside expiresAt and the job ID in your response. ``` ## Two Streamable HTTP MCP endpoints OpenGen provides two stateless Streamable HTTP MCP endpoints (`POST` only; `GET` returns `405` with `Allow: POST, OPTIONS`): | Endpoint | Tools | Authentication | RFC 9728 Protected Resource Metadata | | ------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `https://opengen.dev/mcp` | **15 tools** (9 read-only + 6 write/billable) | OAuth 2.1 DCR + PKCE or OpenGen Bearer token (`read`, `generate`) | `https://opengen.dev/.well-known/oauth-protected-resource/mcp` | | `https://opengen.dev/mcp/readonly` | **9 read-only tools** (4 zero-auth public + 5 workspace-read) | **Zero auth** for `initialize`, `tools/list`, `resources/*`, `prompts/*`, `find_models`, `get_model`, `estimate_cost`, `search_docs`; `read` OAuth/Bearer token required for workspace tools | `https://opengen.dev/.well-known/oauth-protected-resource/mcp/readonly` | ### Edge ergonomics: CORS, `Accept`, and SSE progress - **Zero-friction `Accept` handling**: Missing `Accept`, `*/*`, or `application/json` headers are normalized cleanly so plain `curl` and browser `fetch` JSON-RPC calls receive `200 OK` with `application/json` (never spurious `406 Not Acceptable`). Explicitly refusing JSON (such as `Accept: application/json;q=0, text/event-stream`) returns `406`. - **Opt-in SSE progress**: Sending `Accept: application/json, text/event-stream` together with `_meta.progressToken` on `generate` (with `waitMs > 0`) or `job_get` (with `waitMs > 0` or `afterRevision`) streams live `notifications/progress` frames over `text/event-stream` (`Cache-Control: private, no-store, no-transform`, `X-Accel-Buffering: no`). - **Browser & remote CORS**: Both `/mcp` and `/mcp/readonly` return `Access-Control-Allow-Origin: *` (never `Access-Control-Allow-Credentials: true`), `Cache-Control: no-store`, `Vary: Authorization`, and `204` `OPTIONS` preflight responses. ## Zero-auth test against `/mcp/readonly` Any agent, IDE, or HTTP client can inspect OpenGen's catalog, schemas, regional privacy disclosures, published pricing, and docs over `/mcp/readonly` with zero credentials: ```bash tab="cURL" # 1. List all 9 read-only MCP tools with zero auth and plain default Accept curl --fail-with-body -X POST "https://opengen.dev/mcp/readonly" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }' # 2. Run a zero-auth dry-run cost estimate over MCP curl --fail-with-body -X POST "https://opengen.dev/mcp/readonly" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "estimate_cost", "arguments": { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "Studio portrait of a ceramic vase", "resolution": "1K", "quality": "low" } } } }' ``` ```ts tab="TypeScript" const res = await fetch('https://opengen.dev/mcp/readonly', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'find_models', arguments: { modality: 'video', operation: 'image-to-video', inputRole: 'firstFrame' }, }, }), }); const rpc = await res.json(); console.log(rpc.result.structuredContent.models.length); ``` ```python tab="Python" import httpx response = httpx.post( "https://opengen.dev/mcp/readonly", json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "search_docs", "arguments": {"query": "ed25519 webhook signature", "topic": "webhooks"}, }, }, timeout=20.0, ) response.raise_for_status() print(response.json()["result"]["structuredContent"]["docs"][0]["url"]) ``` ```json tab="MCP" { "tool": "find_models", "arguments": { "collection": "image-to-video" } } ``` ```bash tab="CLI" # Equivalent portable CLI discovery (zero auth required for public catalog & pricing) opengen catalog search --modality video --operation image-to-video --input-role firstFrame opengen collections ``` ## Complete MCP tool reference (15 tools) ### Public zero-auth discovery tools (4 — `/mcp/readonly` & `/mcp`) | Tool | Required Auth | Key Arguments | Purpose | | --------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `find_models` | None on `/mcp/readonly` | `query?`, `listCollections?`, `collection?`, `modality?`, `providerId?`, `region?`, `familyId?`, `operation?`, `inputRole?` | Search exact catalog variants or list/inspect the 9 curated factual collections | | `get_model` | None on `/mcp/readonly` | `id`, `operation?` | Single-call inspection of an exact model, alias, series, or route: returns `generationProfiles`, regional routes with `privacyDisclosure`, deployments, and published pricing | | `estimate_cost` | None on `/mcp/readonly` | `modelId`, `operation`, `input`, `billing?`, `routeId?`, `routing?`, `maxCostMicros?` | Stateless dry-run cost estimator (`estimatedCostMicros`, `recommendedMaxCostMicros`, route candidates, plus `workspaceEligibility` when authenticated) | | `search_docs` | None on `/mcp/readonly` | `query`, `topic?`, `limit?` (`1–10`) | Search OpenGen documentation chunks across `quickstart`, `models`, `generation`, `pricing`, `assets`, `webhooks`, `recovery`, `analytics`, `privacy`, and `mcp-cli` | ### Workspace read-only tools (5 — `/mcp/readonly` & `/mcp`) | Tool | Required Scope | Key Arguments | Purpose | | ------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `balance` | `read` | `{}` | Read `availableMicros`, `reservedMicros`, `currency`, `workspaceId`, plus `billingUrl` and `minTopUpUsd` (`5`) when hosted top-ups are active | | `analytics` | `read` | `since?`, `until?`, `modelId?`, `providerId?`, `deploymentId?`, `endpointRegion?`, `operation?`, `keyId?`, `status?`, `project?` | Bounded (max 31-day) workspace usage, spend (`settledMicros`, `heldMicros`, `byKey`, `byTag`), and per-route latency/reliability `cohorts` | | `job_get` | `read` | `id?` **or** `idempotencyKey?`, plus optional `waitMs` (`0–25000`), `afterRevision` | Read, long-poll with live progress, recover a lost submission by `idempotencyKey`, refresh signed output URLs, and attach the inline MCP App preview card | | `jobs_list` | `read` | `status?`, `modelId?`, `providerId?`, `deploymentId?`, `endpointRegion?`, `operation?`, `keyId?`, `project?`, `since?`, `until?`, `limit?`, `cursor?` | List private workspace generation jobs newest-first with `{ data, nextCursor }` pagination | | `assets_list` | `read` | `state?` (default `ready`), `mediaTypePrefix?`, `limit?` (`1–100`), `cursor?` | List private workspace-owned uploaded/imported input assets with cursor pagination | ### Workspace write & billable tools (6 — `/mcp` only) | Tool | Required Scope | Key Arguments | Purpose | | ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `generate` | `generate` | `modelId`, `operation`, `input`, `idempotencyKey`, `billing?`, `routeId?`, `routing?`, `maxCostMicros?`, `metadata?`, `webhookUrl?`, `webhookEvents?`, `waitMs?` (`0–25000`) | Submit one generation once with a persisted `idempotencyKey`; optionally wait up to 25s for fast results + inline MCP App preview | | `job_cancel` | `generate` | `id` | Cancel a queued job immediately (releasing its hold) or request upstream cancellation on a running job (refund not guaranteed until confirmed) | | `upload_asset` | `generate` | `source` (`url` \| `job_output` \| `presign_prepare` \| `presign_complete` \| `base64`), plus source-specific fields | Ingest private workspace input media and obtain a reusable `assetKey` (inline `base64` strictly capped at `64 KiB`; presigned PUT up to `100 MiB`) | | `upload_attachment` | `generate` | `file` (`download_url`, `file_id`, `mime_type?`, `file_name?`), `type` (`image` \| `video` \| `audio`), `idempotencyKey` | Hosted-chat attachment ingestion (`_meta['openai/fileParams']`) via SSRF-safe public HTTPS import without passing file bytes through LLM tokens | | `delete_asset` | `generate` | `key` | Tombstone and delete a workspace-owned input asset key (blocks new admissions while preserving in-flight job pins) | | `purge_job_outputs` | `generate` | `id` | Permanently delete archived output media bytes for a terminal settled job while preserving metadata and accounting history | ## MCP resources, prompts, and interactive preview apps Both `/mcp` and `/mcp/readonly` register five MCP Resources and three guided Prompts: - **Resources**: - `ui://opengen/job-result` (`text/html;profile=mcp-app`) — sandboxed interactive MCP App preview card attached to `generate` and `job_get` responses, displaying first-party signed images, videos, and audio with explicit CSP `resourceDomains`. - `opengen://skill` (`text/markdown`) — safe discovery, estimation, upload, submit, and recovery workflow instructions. - `opengen://llms` (`text/plain`) — compact endpoint and discovery index. - `opengen://pricing` (`application/json`) — full single-source published route pricing table from `@media-router/catalog`. - `opengen://models/{provider}/{model}` (`application/json`) — resource template listing all 54 exact models with schemas, regional routes, privacy disclosures, and pricing. - **Prompts**: `generate-image`, `image-to-video`, and `troubleshoot-job`. > [!TIP] > Not every MCP host renders interactive MCP App cards. Always surface clickable Open/Download URLs alongside `expiresAt` and the job UUID directly in chat text whenever `deliveryStatus` is `"available"` or `"partial"`. ## Supported clients and verification status Client-specific setup guides live under [Agent Clients](/docs/clients). OpenGen distinguishes live-verified integrations from documentation-only configurations: - **Live generation verified** (`openai/gpt-image-2` `1K` `low` + first-party `/media` delivery, reviewed `2026-11-30`): [ChatGPT](/docs/clients/chatgpt) (web), [Claude](/docs/clients/claude) (web), [Grok Bot](/docs/clients/grok-bot) (web), [Codex](/docs/clients/codex) (`codex-cli 0.155.1`), and [OpenGen CLI](/docs/clients/cli) (`@opengen-dev/cli` on [npm](https://www.npmjs.com/package/@opengen-dev/cli)). - **Live OAuth connection verified** (tool/generation turns separately pending): [Claude Code](/docs/clients/claude-code), [Hermes Agent](/docs/clients/hermes), and [Muse Code](/docs/clients/muse). - **Documentation-based (unverified end-to-end)**: [Cursor](/docs/clients/cursor), [OpenClaw](/docs/clients/openclaw), [OpenCode](/docs/clients/opencode), and [pi](/docs/clients/pi). Desktop and mobile apps for hosted assistants remain separately unverified. For raw HTTP integrations outside MCP, see [Quickstart](/docs/quickstart) and [API Reference](/docs/api). --- Source: https://opengen.dev/docs/models-and-catalog.md (Reviewed 2026-12-03) # Models & Catalog > OpenGen catalogs 54 exact image, video, and audio model variants across 33 series, 12 serving providers, and 184 regional routes. Every variant retains its exact execution identity without merging derivatives by name. Discover models via compact GET /v1/models summaries, curated collections, or single-call GET /v1/models/{provider}/{model} detail responses. ## Agent Prompt ```text Discover and inspect exact OpenGen model contracts using https://opengen.dev/docs/models-and-catalog: 1. Search compact model summaries via GET https://opengen.dev/v1/models (filters: q, modality, providerId, region, familyId, operation, inputRole, collection; omit expand=schemas unless bulk schemas are needed) or MCP find_models on https://opengen.dev/mcp/readonly. 2. Inspect one exact variant, its effective generationProfiles (JSON input schema, defaults, bounds), regional routes with privacy disclosures, and published pricing in one call via GET https://opengen.dev/v1/models/{provider}/{model}?operation= (or MCP get_model). 3. Never substitute a derivative or sibling variant by marketing name, and never assume a documented route is live-verified — inspect route.status and call POST https://opengen.dev/v1/pricing/estimate before asking the user to confirm spend and submitting with an Idempotency-Key. ``` ## Exact variant identity and catalog structure OpenGen separates four concepts so execution choices stay explicit and auditable: - **Exact model variant (`modelId`)**: A fixed `/` execution identity (for example `openai/gpt-image-2`, `bytedance/seedance-2.5`, `alibaba/wan-3.0`, or `minimax/h3-max`). OpenGen catalogs **54** exact variants (**7** published with `open-weights`, each retaining its own license). Derivatives and speed tiers (`Fast`, `Flash`, `Lite`, `Mini`, `Turbo`, `Prime`, `Klein`) are never merged by marketing name. Where equivalence is explicitly confirmed — such as `minimax/h3-max` served by MiniMax and fal — legacy aliases (`fal/h3-max`) resolve cleanly without merging distinct derivatives (`fal/h3-max-turbo`, `pika/h3-flex`). - **Model series**: A public grouping of closely related variants for browsing (33 series across 11 model providers — for example [GPT Image 2](/openai/gpt-image-2), [Seedance 2.5](/bytedance/seedance-2.5), [Wan 3.0](/alibaba/wan-3.0), [Kling 4.0](/kling/kling-4.0), [Nano Banana 2](/google/nano-banana-2), [FLUX 3 Image](/bfl/flux-3-image), [MiniMax H3](/minimax/h3), and [GPT-4o mini TTS](/openai/gpt-4o-mini-tts)). - **Regional deployment (`deploymentId`)**: A serving provider's specific API endpoint region and scope (20 deployments across 12 serving providers: Alibaba Cloud, Black Forest Labs, BytePlus, fal, Google, Kling AI, MiniMax, OpenAI, Pika, Replicate, Runway, and xAI). - **Regional route (`routeId`)**: One exact `modelId` served on one `deploymentId` with explicit supported operations, resolutions, durations, single-source pricing, privacy disclosure, and verification status (184 total routes: **19** `live-verified` with scoped `liveVerification` metadata and **165** `documented`). > [!IMPORTANT] > A `documented` catalog listing is **not** a claim of live execution availability or live-verified behavior on `https://opengen.dev`. Check `route.status`, `route.liveVerification`, and `POST /v1/pricing/estimate` (`selectedRouteId`, `candidates[].executable`, and `workspaceEligibility`) before submitting. ## Public catalog endpoints (6 routes) All six endpoints under the `models` OpenAPI tag are unauthenticated, CORS-enabled (`Access-Control-Allow-Origin: *`), and served with `Cache-Control: public, max-age=60, s-maxage=300` (`Vary: Authorization, Cookie`) on unauthenticated `200 OK` responses: | Endpoint | Operation ID | Purpose & Key Query Parameters | | ----------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /v1/models` | `models.list` | Compact list/search of exact variants (~25 KB default without `generationProfiles`). Filters: `q`, `modality` (`image\|video\|audio`), `familyId`, `providerId`, `region`, `operation`, `inputRole`, `collection`, and optional `expand=schemas` to embed full `generationProfiles` | | `GET /v1/models/{provider}/{model}` | `models.get` | **Recommended single-call inspection**: returns `model` (with `generationProfiles`), `series`, `routes` (with `privacyDisclosure`), `pricing`, and `deployments`. Optional `?operation=` narrows schemas, routes, and pricing | | `GET /v1/models/schema` | `models.schema` | Returns one exact `GenerationProfile` (`?modelId=&operation=`), including `commonArguments`, `modelSpecificArguments`, `defaults`, `capabilities`, `inputSchema`, `sources`, `notices`, and validated `examples` | | `GET /v1/collections` | `collections.list` | Lists all 9 curated factual model collections with slugs, factual selection criteria, modalities, and `modelIds` | | `GET /v1/collections/{slug}` | `collections.get` | Returns full collection detail including constituent `models` (with `generationProfiles`), `series`, and privacy-disclosed `routes` | | `GET /v1/routes` | `routes.list` | Lists documented and live-verified regional routes with `privacyDisclosure`, `rates`, `publishedPricing`, and `pricingSource`. Filters: `?modelId=` and `?operation=` | > [!NOTE] > Free-text model search uses REST query param `q` on `GET /v1/models` and MCP `find_models` argument `query`; single-model inspection uses `GET /v1/models/{provider}/{model}` on REST and argument `id` on MCP `get_model`. ### Compact search and single-call inspection ```bash tab="cURL" # Compact filtered search (returns ~25 KB or smaller summaries without JSON Schemas) curl --fail-with-body \ "$OPENGEN_API_URL/v1/models?modality=video&operation=image-to-video&inputRole=firstFrame" # Opt-in bulk schema expansion when needed curl --fail-with-body \ "$OPENGEN_API_URL/v1/models?collection=image-utilities&expand=schemas" # Single-call model inspection (schemas + routes + privacy disclosures + pricing + deployments) curl --fail-with-body \ "$OPENGEN_API_URL/v1/models/bytedance/seedance-2.5?operation=image-to-video" # Exact schema profile only (JSON Schema + defaults + example payload) curl --fail-with-body \ "$OPENGEN_API_URL/v1/models/schema?modelId=bytedance%2Fseedance-2.5&operation=image-to-video" # List regional routes for one model curl --fail-with-body \ "$OPENGEN_API_URL/v1/routes?modelId=alibaba%2Fwan-3.0&operation=text-to-video" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; // 1. Search compact models const list = await fetch( `${baseUrl}/v1/models?modality=video&operation=image-to-video&inputRole=firstFrame`, ).then((r) => r.json()); // 2. Single-call inspection of one variant const detail = await fetch( `${baseUrl}/v1/models/bytedance/seedance-2.5?operation=image-to-video`, ).then((r) => r.json()); console.log(list.data.length, detail.model.generationProfiles[0].capabilities); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(base_url=base_url, timeout=30.0) as client: models = client.get( "/v1/models", params={"modality": "video", "operation": "image-to-video", "inputRole": "firstFrame"}, ).raise_for_status().json() detail = client.get( "/v1/models/bytedance/seedance-2.5", params={"operation": "image-to-video"}, ).raise_for_status().json() print(len(models["data"]), detail["routes"][0]["id"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "bytedance/seedance-2.5", "operation": "image-to-video" } } ``` ```bash tab="CLI" opengen catalog search --modality video --operation image-to-video --input-role firstFrame opengen catalog get bytedance/seedance-2.5 opengen routes --model alibaba/wan-3.0 --operation text-to-video opengen collections image-to-video ``` ## Supported operations and input roles Every generation request declares an exact `operation` from the 10 canonical operations in `@media-router/contracts`. Each operation has a dedicated walkthrough guide with live supported-model tables: | Operation | Modality | Primary Input Roles | Guide | | -------------------- | -------- | --------------------------------------------------------------- | ----------------------------------------------------- | | `text-to-image` | Image | `prompt` | [Text to Image](/docs/guides/text-to-image) | | `image-edit` | Image | `prompt`, `references.image`, optional `mask` | [Image Edit](/docs/guides/image-edit) | | `image-upscale` | Image | `references.image`, `scale` | [Image Upscale](/docs/guides/image-upscale) | | `background-remove` | Image | `references.image` | [Background Remove](/docs/guides/background-remove) | | `text-to-video` | Video | `prompt` | [Text to Video](/docs/guides/text-to-video) | | `image-to-video` | Video | `firstFrame`, optional `lastFrame`, `keyframes` | [Image to Video](/docs/guides/image-to-video) | | `reference-to-video` | Video | `references.image` / `video` / `audio` / `document`, `elements` | [Reference to Video](/docs/guides/reference-to-video) | | `video-edit` | Video | `sourceVideo`, `prompt`, optional `references` / `elements` | [Video Edit](/docs/guides/video-edit) | | `video-extend` | Video | `sourceVideo` or `previousJobId` | [Video Extend](/docs/guides/video-extend) | | `text-to-speech` | Audio | `prompt`, `voice`, `speed` | [Text to Speech](/docs/guides/text-to-speech) | Filter `GET /v1/models` or MCP `find_models` by any of the **11** canonical `inputRole` values: `firstFrame`, `lastFrame`, `keyframes`, `sourceVideo`, `references.image`, `references.video`, `references.audio`, `references.document`, `mask`, `elements`, and `targetAudio`. ## Curated factual collections (9 slugs) Collections are computed deterministically from live catalog metadata via `GET /v1/collections` and `GET /v1/collections/{slug}` (or MCP `find_models({ listCollections: true })` / `find_models({ collection: "" })`): - `fast-image` — Image variants explicitly designated Flash, Klein, Lite, Turbo, or Highspeed. - `image-editing` — Image models supporting `image-edit`. - `image-utilities` — Specialized `image-upscale` and `background-remove` models. - `text-to-video` — Video models supporting `text-to-video`. - `image-to-video` — Video models supporting first-frame, last-frame, or keyframe conditioning. - `audio-enabled-video` — Video models with documented `switchable` or `always-on` synchronized audio. - `reference-consistent-video` — Video models supporting `reference-to-video`. - `text-to-speech` — Audio speech synthesis models supporting `text-to-speech`. - `open-weights` — Exact catalog variants published with open weights (each with its own license). ## Reading `GenerationProfile` and `examples` `GET /v1/models/{provider}/{model}` and `GET /v1/models/schema` return `GenerationProfile` objects containing: - `commonArguments` and `modelSpecificArguments`: exact allowlisted keys for `input`. Unknown or unsupported fields fail fast with `400 invalid_generation` before hitting any provider. - `capabilities`: exact `resolutions`, `aspectRatios`, `duration` (`minimum`, `maximum`, `integer`, `auto`), `references` (`types`, per-type `maximum`, `totalMaximum`), `frames` (`first`, `last`, `lastOnly`, `keyframesMaximum`, `timed`), `frameReferenceMix`, `audio` (`switchable | always-on | unsupported | unverified`), `quality`, and `countMaximum`. - `inputSchema`: JSON Schema for the nested `input` object. - `examples`: ready-to-edit `request`, `generate` envelope, `cli` command, `placeholders` (asset keys to replace after uploading), and `notices`. ## Model-specific connect instructions & `.md` twins Every model series page (`/[provider]/[series]`, such as `/openai/gpt-image-2` or `/bytedance/seedance-2.5`) pairs an above-the-fold **Pricing at a Glance** summary with a single-source `#connect` section generated from `@media-router/docs` and `@media-router/catalog`: - An above-the-fold **Pricing at a Glance** prose lead and `Provider | Unit Price | Cost per 1,000 ... | Region` comparison table sourced strictly from `@media-router/catalog` (with a unified `Checked YYYY-MM-DD` catalog/pricing review date, exact same-`modelId` `Lowest` comparisons, `≈` markers for approximate/token-derived rates, `Unknown` / `—` for unpriced or mixed-unit entries, and explicit separation of higher-priced, unpriced, and other-variant regions). Treat starting rates as catalog list rates rather than executable quotes — confirm exact request cost via `POST /v1/pricing/estimate` or MCP `estimate_cost` (see [Pricing & Analytics](/docs/pricing-and-analytics)). - A copyable **Agent Prompt** box tailored to the selected exact variant and operation (with zero-auth `GET /v1/models/{provider}/{model}` / MCP `get_model`, dry-run `POST /v1/pricing/estimate`, private `/v1/assets` upload when required, and persisted `Idempotency-Key` safety). - Step-by-step connection checklists and synced 5-tab copy-paste examples (`cURL`, `TypeScript`, `Python`, `MCP`, and `CLI`) backed by live `GenerationProfile` schemas. - Direct backlinks to the matching `/docs/guides/` page and core platform docs (`/docs/quickstart`, `/docs/mcp`, `/docs/clients`, `/docs/authentication`, `/docs/generations`, `/docs/regional-routing`, `/docs/pricing-and-analytics`, `/docs/webhooks`, and `/docs/api`). - A full Markdown twin at `/[provider]/[series].md` (and via `Accept: text/markdown`) including `## Pricing at a Glance`, `## Agent Prompt`, and optional `?variant=&operation=` selection. > [!TIP] > Browse the live model directory at [/models](/models), compare providers at [/providers](/providers), or fetch any series page directly as Markdown (for example `https://opengen.dev/openai/gpt-image-2.md` or `https://opengen.dev/openai/gpt-image-2.md?operation=image-edit`). --- Source: https://opengen.dev/docs/regional-routing.md (Reviewed 2026-12-02) # Regional Routing & Privacy > OpenGen keeps endpoint region, inference scope, processing regions, and storage residency strictly distinct. Every catalog route attaches a PublicPrivacyDisclosure where unestablished residency, logs, retention, and Zero Data Retention facts stay null. All user prompts, inputs, and outputs remain workspace-private with no public gallery and on-demand output purging. ## Agent Prompt ```text Apply regional routing and privacy checks before submitting OpenGen generations using https://opengen.dev/docs/regional-routing: 1. Inspect route privacy disclosures via GET https://opengen.dev/v1/models/{provider}/{model} or GET https://opengen.dev/v1/routes (or MCP get_model). Never infer processing residency, storage residency, or Zero Data Retention from endpointRegion or optional provider headers alone — check whether each fact's value is non-null with dated evidence. 2. Constrain execution explicitly with either routeId (exact pinned route) or routing ({ providerIds, deploymentIds, endpointRegions, processingRegions, processingScopes, authorOnly, preference, fallback }). 3. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) with those routing constraints to confirm an eligible route and spend ceiling before asking the user to approve and submitting with an Idempotency-Key. ``` ## Endpoint region is not data residency Many media gateways conflate an API hostname with where inference runs or where assets are stored. OpenGen separates four distinct attributes on every deployment and route: | Field | Meaning | Observed Values in Catalog | | ------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `endpointRegion` | Geographic region where the provider's API HTTP endpoint terminates | `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `us-east-1`, `cn-beijing`, `cn-hongkong`, or `undisclosed` | | `inferenceScope` (`deployment.scope`) | Provider's documented routing scope for that endpoint | `regional`, `mainland-china`, `international`, `global`, or `undisclosed` | | `processingRegions` | Verified regions where model inference actually executes | Array of region codes, or **`null`** when not established | | `storageRegions` | Verified regions where provider-side inputs/outputs are stored | Array of region codes, or **`null`** when not established | > [!WARNING] > Selecting `endpointRegions: ["eu-central-1"]` or `endpointRegions: ["ap-southeast-1"]` routes requests to that documented regional API endpoint, but **does not** establish per-request processing or storage residency unless the provider documents and OpenGen qualifies non-null `processingRegions` / `storageRegions` evidence. ## Public supplier privacy disclosures (`privacyDisclosure`) Every route returned by `GET /v1/routes`, `GET /v1/models/{provider}/{model}`, `GET /v1/collections/{slug}`, and MCP `get_model` includes a `privacyDisclosure` object. Each privacy fact is represented as `{ "value": , "evidence": { "source": "https://...", "checkedAt": "YYYY-MM-DD", "status": "documented" | "live-verified" } | null }`. Whenever a provider has not established a guarantee at the public catalog level, OpenGen sets **`value: null` and `evidence: null`** rather than guessing: - `endpointRegion` and `inferenceScope` (populated when documented, `null` when `undisclosed`) - `processingRegions` and `storageRegions` (`null` unless explicitly qualified) - `payloadHistory` (`"disabled" | "enabled" | null`) - `deploymentLogs` (`"disabled" | "enabled" | null`) - `maxDataRetentionSeconds` (integer seconds or `null`) - `zeroDataRetention` (boolean or `null`) - `controls`: documented opt-in provider controls (`payloadHistoryOptOut`, `outputExpiryControl`, `privateOutputAcl`) - `notes`: plain-language caveats summarizing what is and is not established > [!IMPORTANT] > On `fal` routes, OpenGen documents the provider's `controls` (`X-Fal-Store-IO: 0` for payload history opt-out and `X-Fal-Object-Lifecycle-Preference` for CDN expiry and output ACL), while keeping `deploymentLogs`, `maxDataRetentionSeconds`, and `zeroDataRetention` as `null`. Neither header disables deployment logs or establishes Zero Data Retention (ZDR) or regional residency. ## Request-level routing controls You can control route selection on `POST /v1/pricing/estimate`, `POST /v1/generations`, and MCP `estimate_cost` / `generate` in two ways: 1. **Pin one exact route (`routeId`)**: Pass `"routeId": "alibaba/ap-southeast-1/wan-3.0"` (or another canonical ID from `GET /v1/routes`) to lock execution to that exact deployment and model. 2. **Declarative constraints (`routing`)**: Filter candidate routes and choose ranking and fallback behavior: - `providerIds`: restrict to specific serving providers (e.g., `["alibaba", "byteplus"]`). - `deploymentIds`: restrict to specific regional deployments (e.g., `["alibaba-model-studio-ap-southeast-1"]`). - `endpointRegions`: restrict by API endpoint region (e.g., `["ap-southeast-1", "ap-northeast-1"]`). - `processingRegions`: require qualified processing residency regions (fails with `422 no_executable_route` if no route establishes them). - `processingScopes`: restrict by `deployment.scope` (`"regional"`, `"mainland-china"`, `"international"`, `"global"`, `"undisclosed"`). - `authorOnly`: boolean — when `true`, restrict serving routes strictly to the model creator's own `authorProviderIds` (for example OpenAI for [GPT Image 2](/openai/gpt-image-2) or Alibaba for [Wan 3.0](/alibaba/wan-3.0)). - `fidelity`: `"any"` or `"native"`. - `preference`: `"cost"`, `"speed"`, or `"reliability"`. - `fallback`: boolean — set `false` to prevent automatic failover to another candidate route if the primary route fails before dispatch. ```bash tab="cURL" # Pin Alibaba Model Studio Singapore with no cross-region fallback curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "Slow dolly shot over rain-slicked granite courtyard at dawn", "resolution": "480p", "duration": 5, "aspectRatio": "16:9" }, "routing": { "authorOnly": true, "endpointRegions": ["ap-southeast-1"], "fallback": false, "preference": "cost" } }' ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const estimate = await fetch(`${baseUrl}/v1/pricing/estimate`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ modelId: 'alibaba/wan-3.0', operation: 'text-to-video', input: { prompt: 'Slow dolly shot over rain-slicked granite courtyard at dawn', resolution: '480p', duration: 5, aspectRatio: '16:9', }, routing: { authorOnly: true, endpointRegions: ['ap-southeast-1'], fallback: false, preference: 'cost', }, }), }).then((r) => r.json()); console.log(estimate.selectedRouteId, estimate.candidates); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") response = httpx.post( f"{base_url}/v1/pricing/estimate", headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}, json={ "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "Slow dolly shot over rain-slicked granite courtyard at dawn", "resolution": "480p", "duration": 5, "aspectRatio": "16:9", }, "routing": { "authorOnly": True, "endpointRegions": ["ap-southeast-1"], "fallback": False, "preference": "cost", }, }, timeout=30.0, ) response.raise_for_status() print(response.json()["selectedRouteId"]) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "Slow dolly shot over rain-slicked granite courtyard at dawn", "resolution": "480p", "duration": 5, "aspectRatio": "16:9" }, "routing": { "authorOnly": true, "endpointRegions": ["ap-southeast-1"], "fallback": false, "preference": "cost" } } } ``` ```bash tab="CLI" cat <<'EOF' > regional-request.json { "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "Slow dolly shot over rain-slicked granite courtyard at dawn", "resolution": "480p", "duration": 5, "aspectRatio": "16:9" }, "routing": { "authorOnly": true, "endpointRegions": ["ap-southeast-1"], "fallback": false, "preference": "cost" } } EOF opengen pricing estimate --input regional-request.json ``` ## Workspace governance policies Workspace administrators can attach reusable routing policies (`modelIds`, `modelProviderExceptions`, `authorOnly`, `providerIds`, `deploymentIds`, `endpointRegions`, `processingRegions`, `processingScopes`, `fidelity`, `fallback`, plus `maxCostMicros`) to API keys in `/app/keys`. OAuth grants inherit the intersection of the authorizing credential's policy snapshot and current policy. Request-level routing can only narrow a governance policy — attempting to route outside it returns `403 policy_denied`. ## Workspace privacy and owned media delivery All user generations, prompts, uploaded inputs, outputs, receipts, and metadata are strictly private to the owning workspace: - **No public gallery**: OpenGen has no public generation feed, share/publish operation, visibility toggle, or private-content SEO. - **No leaked provider URLs**: Raw upstream provider output URLs remain internal recovery data (`upstreamId` is always `null` and `storageKey` is stripped on customer responses). - **First-party signed private capabilities**: Delivered outputs use query-free HMAC-signed URLs (`https://opengen.dev/media/v1...`) served with `Cache-Control: private, no-store`, `Content-Security-Policy: default-src 'none'; sandbox`, `Cross-Origin-Resource-Policy: cross-origin`, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and `X-Robots-Tag: noindex, nofollow, noarchive`. - **On-demand output purge**: Call `DELETE /v1/generations/{id}/outputs` (or MCP `purge_job_outputs` / `opengen job purge-outputs `) on any terminal settled job to permanently delete retained output bytes and immediately invalidate all `/media` links (`410 Gone`). See [Generations Lifecycle](/docs/generations), [Private Assets](/docs/assets), and [/privacy](/privacy) for full operational details. --- Source: https://opengen.dev/docs/generations.md (Reviewed 2026-12-02) # 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. ## Agent Prompt ```text 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). ``` ## All 8 generation endpoints Every endpoint under the `generations` OpenAPI tag is strictly workspace-private and served with `Cache-Control: no-store`: | Method & Path | Operation ID | Scope | Purpose | | ------------------------------------- | ------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /v1/generations` | `media.generate` | `generate` | Submit one canonical generation with required `Idempotency-Key` (1–200 chars) and optional `Prefer: wait=N` (`0–25`s). Returns `202 Accepted` (or `200 OK` if ready inside `Prefer: wait`) with `Location: /v1/generations/{id}` | | `GET /v1/generations` | `jobs.list` | `read` | List 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/lookup` | `jobs.lookup` | `read` | Read-only recovery of a job by `?idempotencyKey=` when the original submit response was lost. Never creates a job | | `GET /v1/generations/{id}` | `jobs.get` | `read` | Read full job details, billing state, `structuredError`, and fresh short-lived signed `/media` output URLs while retained | | `GET /v1/generations/{id}/status` | `jobs.status` | `read` | Compact status long-poll (`?afterRevision=<64-hex>&waitMs=<0..25000>`). Returns `{ job, changed, timedOut }` with 64-hex `revision`, `progress`, and `timings` | | `GET /v1/generations/{id}/events` | `jobs.events` | `read` | Bounded 50-second `text/event-stream` SSE stream (`?afterRevision=` or `Last-Event-ID` header) with 10s heartbeats and clean reconnect cursor | | `POST /v1/generations/{id}/cancel` | `jobs.cancel` | `generate` | Immediately cancels a `queued` job (`200 OK`, releases hold) or requests upstream cancellation on a `running` job (`202 Accepted`, `cancellationState: "requested"`) | | `DELETE /v1/generations/{id}/outputs` | `jobs.purgeOutputs` | `generate` | Permanently 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](/docs/regional-routing)). - `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](/docs/webhooks)). ## 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` | Status | Terminal? | Meaning | | -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `queued` | No | Admitted and reserved locally; waiting for worker dispatch | | `submitting` | No | Worker is actively submitting to the upstream provider | | `running` | No | Upstream provider accepted the task and is executing | | `submission-unknown` | Yes (reconciliation) | Upstream acceptance could not be confirmed after timeout or transport failure. Reserved funds stay held pending reconciliation — **never** blind-retry | | `succeeded` | Yes | Upstream provider reported completion; inspect `deliveryStatus` before downloading outputs | | `failed` | Yes | Upstream or admission failure recorded in `structuredError` | | `cancelled` | Yes | Cancellation 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. > [!WARNING] > Cancellation does **not** establish refundability on a running provider task. Only confirmed non-billable cancellation releases reserved managed credit. ## 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–25`s) 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=&waitMs=25000` to receive `{ job, changed, timedOut }` without resending full input payloads or re-signing media links until the job finishes. ```bash tab="cURL" # 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" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; // Follow status via compact long-poll using revision tokens let afterRevision: string | undefined; while (true) { const qs = new URLSearchParams({ waitMs: '25000' }); if (afterRevision) qs.set('afterRevision', afterRevision); const { job } = await fetch(`${baseUrl}/v1/generations/${jobId}/status?${qs}`, { headers, }).then((r) => r.json()); afterRevision = job.revision; if ( ['failed', 'cancelled', 'submission-unknown'].includes(job.status) || (job.status === 'succeeded' && job.deliveryStatus !== 'pending') ) { break; } } // Fetch full job once delivered to obtain fresh signed /media URLs const completed = await fetch(`${baseUrl}/v1/generations/${jobId}`, { headers }).then((r) => r.json(), ); console.log(completed.outputs); ``` ```python tab="Python" import json import os import time import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with httpx.Client(base_url=base_url, headers=headers, timeout=60.0) as client: after_revision = None done = False while not done: params = {"afterRevision": after_revision} if after_revision else None event_name = None retry_ms = 1000 with client.stream("GET", f"/v1/generations/{job_id}/events", params=params) as stream: stream.raise_for_status() for line in stream.iter_lines(): if line.startswith("id: "): after_revision = line[4:].strip() elif line.startswith("event: "): event_name = line[7:].strip() elif line.startswith("retry: "): retry_ms = int(line[7:].strip()) elif line.startswith("data: "): data = line[6:] print(event_name or "message", data) if event_name == "reconnect": payload = json.loads(data) after_revision = payload.get("afterRevision") or after_revision elif event_name == "done": done = True break elif line == "": if event_name == "done": done = True break event_name = None if not done: time.sleep(max(0.0, retry_ms / 1000.0)) completed = client.get(f"/v1/generations/{job_id}").raise_for_status().json() print(completed["outputs"]) ``` ```json tab="MCP" { "tool": "job_get", "arguments": { "id": "00000000-0000-4000-8000-000000000001", "afterRevision": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "waitMs": 25000 } } ``` ```bash tab="CLI" # Wait/resume an existing job (Ctrl+C stops waiting only; never cancels upstream work) opengen job resume "$JOB_ID" # Recover a lost submission response safely by original idempotency key opengen job recover --idempotency-key "$OPENGEN_IDEMPOTENCY_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": "", "outputIndex": 0 }` to feed a generated image or video into a downstream edit or video model. - **Cancelling and purging outputs**: ```bash tab="cURL" # 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" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const purged = await fetch(`${baseUrl}/v1/generations/${jobId}/outputs`, { method: 'DELETE', headers, }).then((r) => r.json()); console.log(purged.deliveryStatus, purged.outputsPurgedAt, purged.deletedCount); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") response = httpx.delete( f"{base_url}/v1/generations/{job_id}/outputs", headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}, timeout=30.0, ) response.raise_for_status() print(response.json()) ``` ```json tab="MCP" { "tool": "purge_job_outputs", "arguments": { "id": "00000000-0000-4000-8000-000000000001" } } ``` ```bash tab="CLI" opengen job cancel "$JOB_ID" opengen job purge-outputs "$JOB_ID" ``` 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. --- Source: https://opengen.dev/docs/assets.md (Reviewed 2026-12-02) # Private Assets > OpenGen manages private workspace input media through four REST endpoints (POST /v1/assets, POST /v1/assets/complete, GET /v1/assets, DELETE /v1/assets) and four MCP tools. Choose direct multipart (<= 4 MiB), JSON base64 (<= 3 MiB), MCP inline base64 (<= 64 KiB), or presigned single-PUT and public HTTPS import (<= 100 MiB) to obtain reusable assetKey handles. ## Agent Prompt ```text Ingest and manage private input media safely using https://opengen.dev/docs/assets: 1. Never pass raw binary files through LLM tokens when a direct or presigned path exists. Over MCP, prefer upload_asset with source="url" (public HTTPS), source="job_output" (prior OpenGen job output), upload_attachment (hosted chat attachment), or source="presign_prepare"+"presign_complete" (local files up to 100 MiB); use source="base64" only as a last resort strictly <= 64 KiB. 2. Over REST, call POST https://opengen.dev/v1/assets using multipart/form-data (<= 4 MiB), JSON base64 (<= 3 MiB), JSON { source: "url", url, type } with Idempotency-Key, JSON { source: "job_output", sourceJobId, outputIndex } with Idempotency-Key, or JSON { mediaType, size } followed by PUT to uploadUrl and POST https://opengen.dev/v1/assets/complete (<= 100 MiB). 3. Reference the returned ready key as { "assetKey": "" } inside canonical generation input roles (firstFrame, references, sourceVideo, mask), then run POST https://opengen.dev/v1/pricing/estimate before confirming spend and submitting with an Idempotency-Key. ``` ## Unified 4-route asset API Every `/v1/assets*` route is workspace-private and served with `Cache-Control: no-store`. Instead of repeating large files across retries or passing external URLs directly to multiple providers, upload or import media once into private workspace storage and reference the returned `assetKey` (`inputs//.`) inside generation requests. | Method & Path | Operation ID | Scope | Purpose | | -------------------------- | ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /v1/assets` | `assets.create` | `generate` | Unified create/upload endpoint supporting `multipart/form-data` direct upload, JSON `base64`, public HTTPS `url` import, owned `job_output` reuse, or presigned single-PUT upload preparation | | `POST /v1/assets/complete` | `assets.complete` | `generate` | Verifies uploaded bytes (magic signature, byte length, SHA-256) after a presigned PUT and transitions the asset to `state: "ready"` | | `GET /v1/assets` | `assets.get` | `read` | Lists workspace assets (`?state=`, `?mediaTypePrefix=`, `?limit=1..100`, `?cursor=`) **or** inspects one asset by `?key=` (cannot combine `?key=` with list filters) | | `DELETE /v1/assets` | `assets.delete` | `generate` | Tombstones and deletes a workspace-owned asset via `?key=` query parameter **or** JSON body `{ "key": "" }` (missing or conflicting keys return `400`) | ## Exact upload modes and byte limits Choose the upload path that matches your file size and runtime environment: | Mode | Transport / Payload | Max Size | Steps | `Idempotency-Key` | | ------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------------- | ----------------- | | REST direct multipart | `POST /v1/assets` (`multipart/form-data`, single `"file"` part) | **4 MiB** (`4,194,304` bytes) | 1 (returns `ready`) | Optional | | REST JSON base64 | `POST /v1/assets` (`{ "source": "base64", "mediaType", "dataBase64" }`) | **3 MiB** (`3,145,728` decoded bytes) | 1 (returns `ready`) | Optional | | REST / MCP presigned PUT | `POST /v1/assets` (`{ "mediaType", "size" }`) → `PUT uploadUrl` → `POST /v1/assets/complete` | **100 MiB** (`104,857,600` bytes) | 3 (direct to storage) | Not required | | Public HTTPS URL import | `POST /v1/assets` (`{ "source": "url", "url", "type" }`) or MCP `upload_asset` / `upload_attachment` | **100 MiB** (`104,857,600` bytes) | 1 (bounded SSRF-safe GET) | **Required** | | Owned output reuse | `POST /v1/assets` (`{ "source": "job_output", "sourceJobId", "outputIndex" }`) or MCP `upload_asset` | Bound by retained output | 1 (server-side copy) | **Required** | | MCP inline base64 (last resort) | MCP `upload_asset` (`source: "base64"`) | **64 KiB** (`65,536` decoded bytes) | 1 (returns `ready`) | **Required** | > [!WARNING] > Exceeding `4 MiB` on multipart or `3 MiB` on REST JSON base64 returns `413 upload_too_large`. Exceeding `64 KiB` on MCP `upload_asset(source="base64")` returns `upload_too_large` — switch to presigned PUT (`source="presign_prepare"` + `source="presign_complete"`), `source="url"`, or `upload_attachment`. ### Supported media types and container validation OpenGen validates actual file magic bytes and container structure (not just file extensions or `Content-Type` headers) across **11** supported MIME types: - **Images**: `image/png`, `image/jpeg`, `image/webp` - **Video**: `video/mp4`, `video/webm` - **Audio**: `audio/mpeg`, `audio/wav`, `audio/ogg`, `audio/flac`, `audio/mp4`, `audio/webm` ### Public HTTPS URL import security (`source: "url"`) URL imports are strictly credential-free, no-redirect HTTPS `GET` fetches on public IP addresses (DNS is resolved and pinned before TLS connection; local, private, link-local, mapped, and reserved addresses are rejected), with `Accept-Encoding: identity`, `30`-second timeout (`408 input_download_timeout`), and strict magic-byte verification. ## Uploading and reusing assets ### Small direct uploads (`<= 4 MiB`) and URL/output imports ```bash tab="cURL" # 1. Single-step multipart upload (<= 4 MiB, exactly one part named "file") curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -F "file=@frame.png;type=image/png" # 2. Bounded public HTTPS import (requires Idempotency-Key) curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: import-frame-001" \ -d '{ "source": "url", "url": "https://cdn.example.com/media/frame.png", "type": "image" }' # 3. Reuse a prior completed job output by its stable outputIndex curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: reuse-job-output-001" \ -d '{ "source": "job_output", "sourceJobId": "00000000-0000-4000-8000-000000000001", "outputIndex": 0 }' ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const bytes = await readFile('frame.png'); const form = new FormData(); form.append('file', new Blob([bytes], { type: 'image/png' }), 'frame.png'); const asset = await fetch(`${baseUrl}/v1/assets`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }, body: form, }).then((r) => r.json()); console.log(asset.assetKey, asset.state); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with open("frame.png", "rb") as handle: response = httpx.post( f"{base_url}/v1/assets", headers=headers, files={"file": ("frame.png", handle, "image/png")}, timeout=30.0, ) response.raise_for_status() asset = response.json() print(asset["assetKey"], asset["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "job_output", "sourceJobId": "00000000-0000-4000-8000-000000000001", "outputIndex": 0, "idempotencyKey": "reuse-job-output-001" } } ``` ```bash tab="CLI" # The CLI automatically prepares a presigned PUT (up to 100 MiB), uploads, and completes opengen upload frame.png --media-type image/png ``` ### Large files up to 100 MiB (presigned single-PUT + complete) For files larger than `4 MiB` (or any file up to `100 MiB`), prepare a presigned single-PUT upload, stream the raw bytes directly to object storage with the exact returned `headers` (do **not** send your OpenGen `Authorization` header to the storage `uploadUrl` and do **not** follow redirects), and finalize with `POST /v1/assets/complete`: ```bash tab="cURL" FILE_SIZE=$(wc -c < clip.mp4 | tr -d ' ') # 1. Prepare presigned PUT plan PLAN=$(curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"mediaType\":\"video/mp4\",\"size\":$FILE_SIZE}") ASSET_KEY=$(printf '%s' "$PLAN" | jq -r '.key') UPLOAD_URL=$(printf '%s' "$PLAN" | jq -r '.uploadUrl') # 2. PUT bytes directly to private storage forwarding every required header in PLAN.headers # (Content-Type plus signed storage preconditions such as If-None-Match or x-goog-if-generation-match) printf '%s' "$PLAN" \ | jq -r '.headers | to_entries[] | "header = " + ("\(.key): \(.value)" | @json)' \ | curl --fail -X PUT "$UPLOAD_URL" -K - --data-binary @clip.mp4 # 3. Verify and finalize the uploaded asset curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/assets/complete" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"key\":\"$ASSET_KEY\"}" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const apiHeaders = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const bytes = await readFile('clip.mp4'); const plan = await fetch(`${baseUrl}/v1/assets`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ mediaType: 'video/mp4', size: bytes.byteLength }), }).then((r) => r.json()); const putRes = await fetch(plan.uploadUrl, { method: 'PUT', headers: plan.headers, body: bytes, redirect: 'error', }); if (!putRes.ok) throw new Error(`Storage PUT failed (${putRes.status})`); const ready = await fetch(`${baseUrl}/v1/assets/complete`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ key: plan.key }), }).then((r) => r.json()); console.log(ready.assetKey, ready.state, ready.sha256); ``` ```python tab="Python" import os from pathlib import Path import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") api_headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} data = Path("clip.mp4").read_bytes() with httpx.Client(timeout=60.0) as client: plan = client.post( f"{base_url}/v1/assets", headers=api_headers, json={"mediaType": "video/mp4", "size": len(data)}, ).raise_for_status().json() client.put( plan["uploadUrl"], headers=plan["headers"], content=data, follow_redirects=False, ).raise_for_status() ready = client.post( f"{base_url}/v1/assets/complete", headers=api_headers, json={"key": plan["key"]}, ).raise_for_status().json() print(ready["assetKey"], ready["state"], ready["sha256"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "presign_prepare", "mediaType": "video/mp4", "size": 12582912 } } ``` ```bash tab="CLI" opengen upload clip.mp4 --media-type video/mp4 ``` ### Hosted chat attachments over MCP (`upload_attachment`) Hosted chat assistants that support file parameter references (`_meta['openai/fileParams']`) call `upload_attachment` with `{ "file": { "download_url", "file_id", "mime_type?", "file_name?" }, "type": "image" | "video" | "audio", "idempotencyKey": "..." }`. OpenGen downloads the attachment directly via its SSRF-safe HTTPS importer into private workspace storage and returns a reusable `assetKey` without passing binary bytes through model context tokens. ## Listing, inspecting, and deleting assets Assets transition through `prepared`, `uploading`, `processing`, `ready`, `failed`, `expired`, and `deleted`. Only `ready` assets can be admitted into new generations. Calling `DELETE /v1/assets` tombstones the key immediately (blocking new admissions while preserving pinned references for already-accepted jobs) and returns `{ "state": "deleted", "inUse": }`. ```bash tab="cURL" # List ready image assets with cursor pagination curl --fail-with-body \ "$OPENGEN_API_URL/v1/assets?state=ready&mediaTypePrefix=image/&limit=25" \ -H "Authorization: Bearer $OPENGEN_API_KEY" # Inspect a single asset by key curl --fail-with-body \ "$OPENGEN_API_URL/v1/assets?key=$(printf '%s' "$ASSET_KEY" | jq -sRr @uri)" \ -H "Authorization: Bearer $OPENGEN_API_KEY" # Delete an owned asset via query parameter (or JSON body {"key": "..."}) curl --fail-with-body -X DELETE \ "$OPENGEN_API_URL/v1/assets?key=$(printf '%s' "$ASSET_KEY" | jq -sRr @uri)" \ -H "Authorization: Bearer $OPENGEN_API_KEY" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const page = await fetch(`${baseUrl}/v1/assets?state=ready&mediaTypePrefix=image/&limit=25`, { headers, }).then((r) => r.json()); const deleted = await fetch( `${baseUrl}/v1/assets?key=${encodeURIComponent(page.items[0].assetKey)}`, { method: 'DELETE', headers }, ).then((r) => r.json()); console.log(deleted); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with httpx.Client(base_url=base_url, headers=headers, timeout=30.0) as client: page = client.get( "/v1/assets", params={"state": "ready", "mediaTypePrefix": "image/", "limit": 25}, ).raise_for_status().json() key = page["items"][0]["assetKey"] deleted = client.delete("/v1/assets", params={"key": key}).raise_for_status().json() print(deleted) ``` ```json tab="MCP" { "tool": "delete_asset", "arguments": { "key": "inputs/workspace_demo/00000000-0000-4000-8000-000000000001.png" } } ``` ```bash tab="CLI" opengen assets list --state ready --media-type-prefix image/ --limit 25 opengen call assets.delete --input - <<< '{"key":"inputs/workspace_demo/00000000-0000-4000-8000-000000000001.png"}' ``` ## Referencing assets in generation payloads Pass `{ "assetKey": "" }` inside any canonical media field (`firstFrame`, `lastFrame`, `keyframes[].image`, `sourceVideo`, `mask`, `references[].asset`, `elements[].images[]`, `elements[].video`, `elements[].voice`, or `targetAudio`). See [Image to Video](/docs/guides/image-to-video), [Image Edit](/docs/guides/image-edit), and [Reference to Video](/docs/guides/reference-to-video) for complete runnable examples. --- Source: https://opengen.dev/docs/webhooks.md (Reviewed 2026-12-02) # Webhooks & Ed25519 Verification > OpenGen sends per-request generation lifecycle webhooks to public HTTPS destinations supplied via webhookUrl and webhookEvents on POST /v1/generations or MCP generate. Every delivery is signed with Ed25519 keys published at GET /.well-known/webhook-jwks.json using five X-OpenGen-Webhook-* headers over the raw UTF-8 body, with replay protection and up to eight retry attempts. ## Agent Prompt ```text Configure and verify OpenGen per-request webhooks using https://opengen.dev/docs/webhooks: 1. Pass webhookUrl (public HTTPS on port 443, no credentials or fragments) and optional webhookEvents (subset of generation.started, generation.completed, generation.failed, generation.cancelled, generation.delivery_ready) on POST https://opengen.dev/v1/generations or MCP generate — remember webhookUrl and webhookEvents are part of the canonical Idempotency-Key request hash. 2. Always verify inbound deliveries using the exact raw UTF-8 body BEFORE JSON parsing: check the 5 X-OpenGen-Webhook-* headers, enforce a replay window (e.g. +/- 300s), fetch/cache public Ed25519 keys from GET https://opengen.dev/.well-known/webhook-jwks.json (refreshing on unknown kid), verify the 128-char lowercase hex signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`, and deduplicate by body.id. 3. Never expect prompts or signed output URLs inside webhook payloads; fetch GET https://opengen.dev/v1/generations/{jobId} separately to retrieve fresh private media links. ``` ## Registering a per-request webhook OpenGen delivers generation lifecycle events strictly via **per-request ad-hoc webhooks** (legacy workspace webhook subscription CRUD is retired). Supply `webhookUrl` and optional `webhookEvents` directly on `POST /v1/generations` or MCP `generate`: ```bash tab="cURL" curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: webhook-demo-001" \ -d '{ "modelId": "bytedance/seedance-2.5", "operation": "text-to-video", "input": { "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise", "resolution": "720p", "duration": 5, "aspectRatio": "16:9" }, "billing": "managed", "maxCostMicros": 1500000, "webhookUrl": "https://hooks.example.com/opengen", "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"] }' ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const job = await fetch(`${baseUrl}/v1/generations`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': 'webhook-demo-001', }, body: JSON.stringify({ modelId: 'bytedance/seedance-2.5', operation: 'text-to-video', input: { prompt: 'Aerial tracking shot along a misty basalt coastline at sunrise', resolution: '720p', duration: 5, aspectRatio: '16:9', }, billing: 'managed', maxCostMicros: 1500000, webhookUrl: 'https://hooks.example.com/opengen', webhookEvents: ['generation.completed', 'generation.failed', 'generation.delivery_ready'], }), }).then((r) => r.json()); console.log(job.id, job.status); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") response = httpx.post( f"{base_url}/v1/generations", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": "webhook-demo-001", }, json={ "modelId": "bytedance/seedance-2.5", "operation": "text-to-video", "input": { "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise", "resolution": "720p", "duration": 5, "aspectRatio": "16:9", }, "billing": "managed", "maxCostMicros": 1500000, "webhookUrl": "https://hooks.example.com/opengen", "webhookEvents": [ "generation.completed", "generation.failed", "generation.delivery_ready", ], }, timeout=30.0, ) response.raise_for_status() print(response.json()["id"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "modelId": "bytedance/seedance-2.5", "operation": "text-to-video", "input": { "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise", "resolution": "720p", "duration": 5, "aspectRatio": "16:9" }, "billing": "managed", "maxCostMicros": 1500000, "webhookUrl": "https://hooks.example.com/opengen", "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"], "idempotencyKey": "webhook-demo-001" } } ``` ### Supported `webhookEvents` (5 events) | Event | Included by Default? | Trigger | | --------------------------- | -------------------- | -------------------------------------------------------------------------- | | `generation.started` | No | Job transitioned into upstream execution | | `generation.completed` | **Yes** | Job reached `status: "succeeded"` (delivery may still be `pending`) | | `generation.failed` | **Yes** | Job reached `status: "failed"` | | `generation.cancelled` | **Yes** | Job reached `status: "cancelled"` | | `generation.delivery_ready` | No | Private output capture completed and `deliveryStatus` became `"available"` | When `webhookEvents` is omitted alongside `webhookUrl`, OpenGen defaults to `["generation.completed", "generation.failed", "generation.cancelled"]`. Supplying `webhookEvents` without `webhookUrl` fails validation with `400 invalid_generation` (`field: "webhookEvents"`). Both `webhookUrl` and `webhookEvents` are hashed into `Idempotency-Key` validation — changing either on a replay returns `409 idempotency_conflict`. ### Destination security rules - Must be a public `https://` URL on port `443` (max 2,048 characters), without embedded credentials (userinfo) or `#fragments`. - DNS is re-resolved on submission and on every delivery attempt; all resolved answers are validated against local, private, link-local, mapped, transition, and reserved IP ranges, and the TLS connection is pinned to a validated public IP. - HTTP redirects are never followed and count as failed delivery attempts. ## Payload envelope OpenGen sends a compact UTF-8 JSON body. Prompts, credentials, signed output URLs, and private supplier cost internals are **never** placed in webhook payloads. Fetch `GET /v1/generations/{jobId}` separately to obtain fresh short-lived signed `/media` links. ```json { "id": "8e31c7f2-6d5c-4c36-9f64-29f2d8d5f210", "jobId": "00000000-0000-4000-8000-000000000001", "workspaceId": "ws_demo", "event": "generation.delivery_ready", "createdAt": "2026-12-02T12:00:00.000Z", "data": { "jobId": "00000000-0000-4000-8000-000000000001", "status": "succeeded", "deliveryStatus": "available" } } ``` ## Public Ed25519 JWKS endpoint & 5 signature headers OpenGen publishes active and rotated Ed25519 verification keys unauthenticated at **`GET /.well-known/webhook-jwks.json`** (`Cache-Control: public, max-age=3600`, `Access-Control-Allow-Origin: *`) as an RFC 7517 JWK Set (`kty: "OKP"`, `crv: "Ed25519"`, `alg: "EdDSA"`, `use: "sig"`, `kid`, `x`). Private key material (`d`) is never exposed. Every outbound webhook `POST` includes exactly five verification headers: | Header | Description | | -------------------------------- | ------------------------------------------------------------------------------ | | `X-OpenGen-Webhook-Request-Id` | Unique delivery UUID (idempotency / deduplication key; matches JSON `body.id`) | | `X-OpenGen-Webhook-Workspace-Id` | Owning workspace ID (matches JSON `body.workspaceId`) | | `X-OpenGen-Webhook-Timestamp` | Unix timestamp in whole seconds (used for replay window checks) | | `X-OpenGen-Webhook-Key-Id` | Active signing key `kid` matching an entry in `/.well-known/webhook-jwks.json` | | `X-OpenGen-Webhook-Signature` | **128-character lowercase hex** Ed25519 signature (64 raw bytes) | ### Canonical signing string Compute the signed UTF-8 message from the **exact raw UTF-8 request body bytes** (before calling `JSON.parse`): ```text ${X-OpenGen-Webhook-Request-Id}\n${X-OpenGen-Webhook-Workspace-Id}\n${X-OpenGen-Webhook-Timestamp}\n${sha256Hex(rawBody)} ``` Where `sha256Hex(rawBody)` is the 64-character lowercase hexadecimal SHA-256 digest of the raw body bytes, and `\n` is a single ASCII line feed (`0x0a`). ## Verifying Ed25519 signatures (Node.js & Python) Follow these five checks on every inbound webhook request: 1. Reject any request missing one of the five headers, with a non-numeric timestamp, or outside your replay tolerance (recommended `±300` seconds). 2. Validate that `X-OpenGen-Webhook-Signature` is 128 hex characters (`64` bytes). 3. Look up the public Ed25519 JWK matching `X-OpenGen-Webhook-Key-Id` from `GET https://opengen.dev/.well-known/webhook-jwks.json` — refresh your cached JWKS once if the `kid` is unknown so key rotations succeed seamlessly. 4. Verify the Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`. 5. Parse JSON only after signature verification succeeds, assert `body.id === requestId` and `body.workspaceId === workspaceId`, **verify that `body.workspaceId` matches your configured trusted workspace (`OPENGEN_WORKSPACE_ID` or an explicit authorized-workspace allowlist — never skip this check, because OpenGen signing keys are gateway-wide and another workspace can point callbacks at your URL)**, and deduplicate by `body.id` transactionally with your business side effect. ```ts tab="TypeScript" import { createHash, createPublicKey, verify, type JsonWebKey } from 'node:crypto'; interface WebhookPublicJwk { kty: 'OKP'; crv: 'Ed25519'; alg: 'EdDSA'; use: 'sig'; kid: string; x: string; } const JWKS_URL = 'https://opengen.dev/.well-known/webhook-jwks.json'; const JWKS_TTL_MS = 5 * 60 * 1000; let cachedJwks: { fetchedAt: number; keys: Map } | null = null; async function loadKey(kid: string): Promise { const now = Date.now(); const isFresh = cachedJwks !== null && now - cachedJwks.fetchedAt < JWKS_TTL_MS; if (isFresh && cachedJwks!.keys.has(kid)) { return cachedJwks!.keys.get(kid); } // Refresh when the TTL has expired (evicting removed/revoked keys) or on an unknown kid during rotation. const res = await fetch(JWKS_URL, { cache: 'no-store' }); if (!res.ok) throw new Error(`Failed to fetch JWKS (${res.status})`); const jwks = (await res.json()) as { keys: WebhookPublicJwk[] }; const nextKeys = new Map(); for (const key of jwks.keys) { if (key.kty === 'OKP' && key.crv === 'Ed25519' && key.kid) { nextKeys.set(key.kid, key); } } cachedJwks = { fetchedAt: now, keys: nextKeys }; return nextKeys.get(kid); } export async function verifyOpenGenWebhook( headers: Record, rawBody: string | Uint8Array, expectedWorkspaceId: string = process.env.OPENGEN_WORKSPACE_ID?.trim() ?? '', maxSkewSeconds = 300, ): Promise<{ id: string; jobId: string; workspaceId: string; event: string; data: unknown }> { const trustedWorkspaceId = expectedWorkspaceId.trim(); if (!trustedWorkspaceId) { throw new Error('OPENGEN_WORKSPACE_ID must be configured before accepting webhooks.'); } const lowered = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])); const get = (name: string) => lowered[name.toLowerCase()]; const requestId = get('X-OpenGen-Webhook-Request-Id'); const workspaceId = get('X-OpenGen-Webhook-Workspace-Id'); const timestamp = get('X-OpenGen-Webhook-Timestamp'); const keyId = get('X-OpenGen-Webhook-Key-Id'); const signatureHex = get('X-OpenGen-Webhook-Signature'); if (!requestId || !workspaceId || !timestamp || !keyId || !signatureHex) { throw new Error('Missing required OpenGen webhook headers.'); } if (!/^\d{1,15}$/.test(timestamp)) { throw new Error('Invalid webhook timestamp.'); } const nowSeconds = Math.floor(Date.now() / 1000); if (Math.abs(nowSeconds - Number(timestamp)) > maxSkewSeconds) { throw new Error('Webhook timestamp outside replay window.'); } if (!/^[0-9a-f]{128}$/.test(signatureHex)) { throw new Error('Invalid Ed25519 signature format.'); } const jwk = await loadKey(keyId); if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') { throw new Error(`Unknown webhook signing key id: ${keyId}`); } const bodyHash = createHash('sha256').update(rawBody).digest('hex'); const message = Buffer.from(`${requestId}\n${workspaceId}\n${timestamp}\n${bodyHash}`, 'utf8'); const publicKey = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x } as JsonWebKey, format: 'jwk', }); const ok = verify(null, message, publicKey, Buffer.from(signatureHex, 'hex')); if (!ok) { throw new Error('Invalid OpenGen webhook signature.'); } const payload = JSON.parse( typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody).toString('utf8'), ); if (payload.id !== requestId || payload.workspaceId !== workspaceId) { throw new Error('Webhook header and payload identity mismatch.'); } if (payload.workspaceId !== trustedWorkspaceId) { throw new Error('Webhook workspaceId does not match the configured trusted workspace.'); } return payload; } ``` ```python tab="Python" import base64 import hashlib import json import os import re import time from typing import Any, Optional import httpx from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey JWKS_URL = "https://opengen.dev/.well-known/webhook-jwks.json" _JWKS_TTL_SECONDS = 300.0 _CACHED_KEYS: dict[str, dict[str, Any]] = {} _CACHED_AT: float = 0.0 def _b64url_decode(value: str) -> bytes: padding = "=" * (-len(value) % 4) return base64.urlsafe_b64decode(value + padding) def _get_jwk(kid: str) -> dict[str, Any]: global _CACHED_AT now = time.monotonic() is_fresh = _CACHED_AT > 0.0 and (now - _CACHED_AT) < _JWKS_TTL_SECONDS if not is_fresh or kid not in _CACHED_KEYS: response = httpx.get(JWKS_URL, timeout=10.0) response.raise_for_status() refreshed: dict[str, dict[str, Any]] = {} for item in response.json().get("keys", []): if item.get("kty") == "OKP" and item.get("crv") == "Ed25519" and item.get("kid"): refreshed[item["kid"]] = item _CACHED_KEYS.clear() _CACHED_KEYS.update(refreshed) _CACHED_AT = now if kid not in _CACHED_KEYS: raise ValueError(f"Unknown webhook signing key id: {kid}") return _CACHED_KEYS[kid] def verify_opengen_webhook( headers: dict[str, str], raw_body: bytes, expected_workspace_id: Optional[str] = None, max_skew_seconds: int = 300, ) -> dict[str, Any]: trusted_workspace_id = ( expected_workspace_id if expected_workspace_id is not None else os.environ.get("OPENGEN_WORKSPACE_ID", "") ).strip() if not trusted_workspace_id: raise ValueError("OPENGEN_WORKSPACE_ID must be configured before accepting webhooks.") lowered = {k.lower(): v for k, v in headers.items()} request_id = lowered.get("x-opengen-webhook-request-id") workspace_id = lowered.get("x-opengen-webhook-workspace-id") timestamp = lowered.get("x-opengen-webhook-timestamp") key_id = lowered.get("x-opengen-webhook-key-id") signature_hex = lowered.get("x-opengen-webhook-signature") if not all([request_id, workspace_id, timestamp, key_id, signature_hex]): raise ValueError("Missing required OpenGen webhook headers.") if not re.fullmatch(r"\d{1,15}", timestamp): raise ValueError("Invalid webhook timestamp.") if abs(int(time.time()) - int(timestamp)) > max_skew_seconds: raise ValueError("Webhook timestamp outside replay window.") if not re.fullmatch(r"[0-9a-f]{128}", signature_hex): raise ValueError("Invalid Ed25519 signature format.") jwk = _get_jwk(key_id) public_key = Ed25519PublicKey.from_public_bytes(_b64url_decode(jwk["x"])) body_hash = hashlib.sha256(raw_body).hexdigest() message = f"{request_id}\n{workspace_id}\n{timestamp}\n{body_hash}".encode("utf-8") try: public_key.verify(bytes.fromhex(signature_hex), message) except InvalidSignature as exc: raise ValueError("Invalid OpenGen webhook signature.") from exc payload = json.loads(raw_body.decode("utf-8")) if payload.get("id") != request_id or payload.get("workspaceId") != workspace_id: raise ValueError("Webhook header and payload identity mismatch.") if payload.get("workspaceId") != trusted_workspace_id: raise ValueError("Webhook workspaceId does not match the configured trusted workspace.") return payload ``` > [!TIP] > Building on Next.js App Router? Grab the complete copy-paste `app/api/webhooks/opengen/route.ts` handler in [Next.js Webhooks Guide](/docs/guides/webhooks-nextjs). ## Delivery semantics, retries, and key rotation - **At-least-once delivery**: Return any `2xx` status within `10` seconds. Receiver response bodies are discarded and bounded to `8 KiB`. - **Retry backoff schedule**: Non-2xx responses, redirects, and network errors retry up to **8 total attempts** with delays of `30 seconds`, `2 minutes`, `10 minutes`, `30 minutes`, `2 hours`, `6 hours`, and `24 hours`. Each retry preserves the exact `id` and JSON body while minting a fresh `X-OpenGen-Webhook-Timestamp` and `X-OpenGen-Webhook-Signature`. - **Self-hosted key rotation**: Self-hosted operators configure `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` as a multi-key JSON array. The first entry with `active: true` signs new deliveries while older verification-only public keys remain published in `/.well-known/webhook-jwks.json` during the 24-hour+ retry grace window. See [Self-Hosting Guide](/docs/guides/self-hosting). --- Source: https://opengen.dev/docs/pricing-and-analytics.md (Reviewed 2026-12-03) # Pricing & Analytics > OpenGen expresses all prices and balances in positive integer micro-USD (1 USD equals 1,000,000 micro-USD) sourced strictly from @media-router/catalog, with unknown prices kept null and never zero. Inspect published rates at GET /v1/pricing, run side-effect-free estimates at POST /v1/pricing/estimate, check credit at GET /v1/balance, and query 31-day spend and latency rollups at GET /v1/analytics. ## Agent Prompt ```text Estimate costs and audit workspace spend cleanly using https://opengen.dev/docs/pricing-and-analytics: 1. Read single-source published rates via GET https://opengen.dev/v1/pricing (or MCP resource opengen://pricing); treat series-page Pricing at a Glance starting rates as catalog list rates only. Remember 1 USD = 1,000,000 micro-USD, and null/Unknown means unknown or unsettled — never treat it as free or $0. 2. Always run stateless POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) with the exact generation payload and check GET https://opengen.dev/v1/balance (or MCP balance) before asking the user to approve a maxCostMicros spend ceiling. 3. Pass maxCostMicros and private metadata ({ project, tags }) on POST https://opengen.dev/v1/generations (with a persisted Idempotency-Key), then monitor settledMicros, heldMicros, byKey, byTag, and p50Ms/p95Ms latency cohorts via GET https://opengen.dev/v1/analytics or MCP analytics. ``` ## Single-source micro-USD pricing OpenGen represents every price, reservation, settlement, and balance as an exact **integer in micro-USD**, where **`1 USD = 1,000,000 micro-USD`** (`$0.01 = 10,000` micro-USD; `$0.00598 = 5,980` micro-USD). - **Single source of truth**: All per-unit `rates`, `publishedPricing`, and dated credential-free HTTPS `pricingSource` links are defined once in `@media-router/catalog` and projected identically across `GET /v1/pricing`, `GET /v1/routes`, `GET /v1/models/{provider}/{model}`, MCP `get_model` / `opengen://pricing`, `@opengen-dev/cli`, [/pricing](/pricing), and every `/[provider]/[series]` page (plus its `.md` twin). - **Modality-matched billing units**: `image`, `output-second`, `character-1k`, and `megapixel`. - **Honest unknowns**: When a provider does not publish a deterministic per-request formula or a route has media-dependent token billing, OpenGen keeps prices `null` or omitted — **never** `$0` or "free". ## Interpreting series-page Pricing at a Glance Every model series page (`/[provider]/[series]`, such as `/bytedance/seedance-2.5` or `/alibaba/wan-3.0`) and its Markdown twin (`/[provider]/[series].md` / `Accept: text/markdown`) includes an above-the-fold **Pricing at a Glance** prose lead and `Provider | Unit Price | Cost per 1,000 ... | Region` summary table derived strictly from `@media-router/catalog`: - **Starting list rate per provider**: Each provider row reports that provider's lowest published starting rate across active (non-retired) routes in the series, labeled with the exact variant and default resolution/quality tier it represents. Rates marked with `≈` are approximate or token-derived estimates; providers with unpriced or mixed-unit routes show `Unknown` (`—` for per-1,000 cost) rather than `$0`. - **Exact-unit per-1,000 column**: The per-1,000 column (`Cost per 1,000 images`, `Cost per 1,000 sec`, `Cost per 1,000 MP`, or `Cost per 1,000 (1M chars)`) is computed only when all priced variants in the series share a common billing unit and the provider row matches that unit; mixed-unit or unpriced rows fall back to `Cost per 1,000` with `—` and are never cross-unit sorted. - **Exact variant boundaries**: `Lowest` badges and cross-provider savings percentages compare only providers serving the **same exact `modelId` and billing unit** when at least two providers quote different positive rates — never across distinct derivatives (such as `Fast` vs `Standard`). - **Regional spread and unified review date**: Region cells show disclosed endpoint regions for the provider's lowest rate and distinguish higher-priced regions (`+SG higher`), regions serving other variants (`+... other variants`), and unpriced regions (`+... unpriced`) without implying data residency. The `Checked YYYY-MM-DD` / `Latest catalog source check` date is unified across the HTML summary, Markdown twin, JSON-LD, and sitemap. - **Not an executable quote or spend cap**: Summary starting rates include `documented` catalog routes and lowest default tiers. Higher resolutions, audio-on tiers, edit operations, or regional pins can cost more, and route executability depends on the target gateway and workspace policy. Always inspect `GET /v1/models/{provider}/{model}?operation=` (or MCP `get_model`) and run stateless `POST /v1/pricing/estimate` (or MCP `estimate_cost`) with the exact canonical request before approving spend or setting `maxCostMicros`. ## Pricing and account endpoints (4 routes) | Endpoint | Operation ID | Auth | Purpose | | --------------------------- | ------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /v1/pricing` | `pricing.list` | Public (`max-age=60, s-maxage=300`) | Lists published per-unit route rates, `publishedPricing`, `pricingSource`, `operationPricing`, and `status` / `liveVerification`. Filters: `modelId`, `routeId`, `providerId`, `endpointRegion`, `modality`, `operation` | | `POST /v1/pricing/estimate` | `pricing.estimate` | Public or `read` (CORS `*`) | Stateless, side-effect-free dry-run estimator. Validates the exact generation request, returns per-route `estimatedCostMicros`, `recommendedMaxCostMicros`, `reservationMicros`, `estimateOnly: true`, and `workspaceEligibility` when authenticated. Never reserves credits or creates a quote ID | | `GET /v1/balance` | `balance.get` | `read` (`no-store`) | Returns `{ availableMicros, reservedMicros, currency: "USD" }`. Supports optional `X-OpenGen-Expected-Workspace` header (`409 workspace_changed` on mismatch). MCP `balance` adds `workspaceId`, plus `billingUrl` and `minTopUpUsd` (`5`) when hosted top-ups are enabled | | `GET /v1/analytics` | `analytics.get` | `read` (`no-store`) | Bounded private workspace spend (`settledMicros`, `heldMicros`, `unknownAccountingCount`, `byKey`, `byTag`) and per-model/route reliability & latency `cohorts` (`p50Ms`, `p95Ms`) over a date window up to **31 days** (default last 7 days) | ### Querying published tariffs and running dry-run estimates ```bash tab="cURL" # Inspect published pricing across all serving providers for one exact variant curl --fail-with-body \ "$OPENGEN_API_URL/v1/pricing?modelId=openai%2Fgpt-image-2&operation=text-to-image" # Stateless dry-run cost and route-eligibility estimate (no credit hold) curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "Technical isometric diagram of a copper espresso boiler", "resolution": "1K", "quality": "low" }, "billing": "managed" }' ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const tariffs = await fetch( `${baseUrl}/v1/pricing?modelId=${encodeURIComponent('openai/gpt-image-2')}`, ).then((r) => r.json()); const estimate = await fetch(`${baseUrl}/v1/pricing/estimate`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ modelId: 'openai/gpt-image-2', operation: 'text-to-image', input: { prompt: 'Technical isometric diagram of a copper espresso boiler', resolution: '1K', quality: 'low', }, billing: 'managed', }), }).then((r) => r.json()); console.log( tariffs.data.length, estimate.lowestEstimatedCostMicros, estimate.recommendedMaxCostMicros, ); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with httpx.Client(base_url=base_url, timeout=30.0) as client: tariffs = client.get( "/v1/pricing", params={"modelId": "openai/gpt-image-2", "operation": "text-to-image"}, ).raise_for_status().json() estimate = client.post( "/v1/pricing/estimate", headers=headers, json={ "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "Technical isometric diagram of a copper espresso boiler", "resolution": "1K", "quality": "low", }, "billing": "managed", }, ).raise_for_status().json() print(len(tariffs["data"]), estimate["recommendedMaxCostMicros"]) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "Technical isometric diagram of a copper espresso boiler", "resolution": "1K", "quality": "low" }, "billing": "managed" } } ``` ```bash tab="CLI" opengen pricing --model openai/gpt-image-2 --operation text-to-image opengen pricing estimate --input request.json ``` ## Managed credit vs BYOK (Bring Your Own Key) | Dimension | Managed Credit (`"billing": "managed"`) | Bring Your Own Key (`"billing": "byok"`) | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | Provider credentials | OpenGen-operated supplier accounts | Your own encrypted provider keys stored per deployment in `/app/providers` | | Funding & billing | Prepaid USD workspace balance via `/billing` (new workspaces start at `$0`; `$5` USD minimum top-up) | Provider bills your supplier account directly; OpenGen reserves `$0` managed credit | | Reservation & ceiling | Reserves a bounded `reservedMicros` ceiling at admission, settles actual `settledMicros`, and releases unused hold back to `availableMicros` | No managed credit reservation; still enforces governance routing policies and workspace isolation | | Spend guards | Request `maxCostMicros`, key `monthlyCapMicros`, and policy `maxCostMicros` | Governance routing policy (`modelIds`, `providerIds`, `endpointRegions`) | > [!IMPORTANT] > **`settledMicros: null` never means free.** On an in-flight, `submission-unknown`, or awaiting-reconciliation managed job, `settledMicros` remains `null` while `reservedMicros` stays held until verified provider cost or confirmed non-billable failure/cancellation is recorded. ## Workspace balance and 31-day analytics (`GET /v1/analytics`) `GET /v1/analytics` (and MCP `analytics`) provides private operational visibility across a bounded window of at most **31 days** (defaulting to the last 7 days when `since`/`until` are omitted). Filter by `since` (inclusive ISO-8601 UTC), `until` (exclusive ISO-8601 UTC), `modelId`, `providerId`, `deploymentId`, `endpointRegion`, `operation`, `keyId`, `status`, or `project`. Each response returns: - **Top-level accounting**: `sampleCount`, `settledMicros`, `heldMicros`, `unknownAccountingCount` (jobs whose accounting is unsettled/unknown rather than silently treated as zero), plus truncation indicators (`truncated`, `attributionTruncated`, `tagsTruncated`). - **Spend attribution**: `byKey[]` (per API key ID) and `byTag[]` (per `metadata.tags` key/value pair). - **Per-route cohorts (`cohorts[]`)**: grouped by `modelId`, `operation`, `routeId`, `deploymentId`, and `configurationFingerprint`, reporting `succeeded`, `failed`, `cancelled`, `unresolved`, `delivered`, `unverifiedDelivery`, and observed `p50Ms` / `p95Ms` across `providerOutcomeLatency`, `queueLatency`, `executionLatency`, `deliveryLatency`, and `endToEndLatency`. ```bash tab="cURL" # Check workspace balance curl --fail-with-body "$OPENGEN_API_URL/v1/balance" \ -H "Authorization: Bearer $OPENGEN_API_KEY" # Query 7-day workspace spend and latency analytics for a project curl --fail-with-body \ "$OPENGEN_API_URL/v1/analytics?project=catalog-hero&since=2026-11-25T00:00:00Z&until=2026-12-02T00:00:00Z" \ -H "Authorization: Bearer $OPENGEN_API_KEY" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const analytics = await fetch( `${baseUrl}/v1/analytics?project=catalog-hero&since=2026-11-25T00:00:00Z&until=2026-12-02T00:00:00Z`, { headers }, ).then((r) => r.json()); console.log({ samples: analytics.sampleCount, settledMicros: analytics.settledMicros, heldMicros: analytics.heldMicros, cohorts: analytics.cohorts.length, }); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} response = httpx.get( f"{base_url}/v1/analytics", headers=headers, params={ "project": "catalog-hero", "since": "2026-11-25T00:00:00Z", "until": "2026-12-02T00:00:00Z", }, timeout=30.0, ) response.raise_for_status() data = response.json() print(data["sampleCount"], data["settledMicros"], data["heldMicros"]) ``` ```json tab="MCP" { "tool": "analytics", "arguments": { "project": "catalog-hero", "since": "2026-11-25T00:00:00Z", "until": "2026-12-02T00:00:00Z" } } ``` ```bash tab="CLI" opengen balance opengen call analytics.get --input - <<< '{"project":"catalog-hero","since":"2026-11-25T00:00:00Z","until":"2026-12-02T00:00:00Z"}' ``` > [!TIP] > Tag every production generation with `metadata: { project, tags }` on `POST /v1/generations` so `byTag` rollups in `GET /v1/analytics` break down spend by tenant, feature, or environment without leaking customer identifiers into public logs. --- Source: https://opengen.dev/docs/guides/text-to-image.md (Reviewed 2026-12-02) # Generate images from text prompts > OpenGen routes text-to-image prompts across 25 exact model variants through one canonical request schema. Discover models with GET /v1/models?operation=text-to-image, inspect exact pricing and resolution tiers via GET /v1/models/{provider}/{model}, verify spend with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key. All generated outputs stay private to your workspace and download through short-lived first-party capability URLs. ## Agent Prompt ```text Walk me through a text-to-image generation on OpenGen (https://opengen.dev): 1. Discover image models with GET https://opengen.dev/v1/models?operation=text-to-image (or MCP find_models with operation="text-to-image"). 2. Inspect the selected exact model's schema, regional routes, privacy disclosures, and published pricing in one call via GET https://opengen.dev/v1/models/{provider}/{model}?operation=text-to-image (or MCP get_model, e.g. id="openai/gpt-image-2", operation="text-to-image"). 3. Run a stateless dry-run estimate with POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) using the exact canonical payload. 4. Show me the selected route, published unit pricing, workspaceEligibility, and recommendedMaxCostMicros, and wait for my confirmation of the route and maxCostMicros cap before spending. 5. After I confirm, persist a unique Idempotency-Key and submit once via POST https://opengen.dev/v1/generations (with Prefer: wait=20) or MCP generate (with waitMs=20000). 6. If still pending, poll GET https://opengen.dev/v1/generations/{id}/status or MCP job_get without ever creating a second Idempotency-Key. When delivered, return clickable private output links alongside the job ID and expiresAt. ``` OpenGen lets you generate private images across official and partner routes using a single canonical payload (`modelId`, `operation: "text-to-image"`, and typed `input`). Rather than rewriting SDK calls for every vendor, you inspect one model schema, verify exact pricing with a stateless dry run, and submit once under a persisted `Idempotency-Key`. ## Prerequisites - An OpenGen workspace API key with `read` and `generate` scopes (`OPENGEN_API_KEY`), an OAuth MCP connection to `https://opengen.dev/mcp`, or a logged-in [`@opengen-dev/cli`](https://www.npmjs.com/package/@opengen-dev/cli) session (see [Authentication](/docs/authentication) and [Client Setup](/docs/clients)). - Prepaid workspace credit for `billing: "managed"` or an encrypted workspace provider connection for `billing: "byok"`. - Zero authentication is needed for Steps 1 and 2 (`GET /v1/models`, `GET /v1/models/{provider}/{model}`, and `https://opengen.dev/mcp/readonly`). ## 1. Choose an exact image model and inspect its schema Start by listing models registered for `text-to-image`, then inspect the exact variant you plan to call. Never merge derivatives by marketing name—each variant exposes its own resolutions, quality tiers, and output formats. For a fast, live-verified baseline, this walkthrough uses [GPT Image 2](/openai/gpt-image-2) (`openai/gpt-image-2`, official route `openai-undisclosed/openai-gpt-image-2`, live-verified for `text-to-image` at `1K`). If you want low flat per-image pricing, compare [FLUX 3 Klein](/bfl/flux-3-image?variant=bfl%2Fflux-3-klein) (`bfl/flux-3-klein`, published `$0.008` at `768sq` and `$0.009` at `1K`; live-verified for `text-to-image` at `768sq`, with `1K` also exercised in hosted comparison smoke) or [Seedream 5.0 Flash](/bytedance/seedream-5.0-flash) (`bytedance/seedream-5.0-flash`, flat `$0.018` across `1K`–`2K` on BytePlus ModelArk Singapore; live-verified for `text-to-image` at `1K`). ```bash tab="cURL" # Compact model list filtered by operation (unauthenticated) curl --fail-with-body \ "https://opengen.dev/v1/models?operation=text-to-image" # Single-call schema, regional routes, privacy disclosures, and published pricing curl --fail-with-body \ "https://opengen.dev/v1/models/openai/gpt-image-2?operation=text-to-image" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const listRes = await fetch(`${origin}/v1/models?operation=text-to-image`); if (!listRes.ok) throw new Error(`Model list failed: ${listRes.status}`); const { data: models } = await listRes.json(); const detailRes = await fetch(`${origin}/v1/models/openai/gpt-image-2?operation=text-to-image`); if (!detailRes.ok) throw new Error(`Model inspect failed: ${detailRes.status}`); const detail = await detailRes.json(); console.log( models.length, detail.routes.map((r: { id: string }) => r.id), ); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: models = client.get(f"{origin}/v1/models", params={"operation": "text-to-image"}).raise_for_status().json() detail = client.get( f"{origin}/v1/models/openai/gpt-image-2", params={"operation": "text-to-image"}, ).raise_for_status().json() print(len(models["data"]), [route["id"] for route in detail["routes"]]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "openai/gpt-image-2", "operation": "text-to-image" } } ``` ```bash tab="CLI" opengen catalog search --operation text-to-image opengen catalog get openai/gpt-image-2 opengen pricing --model openai/gpt-image-2 --operation text-to-image ``` ### Canonical `text-to-image` input fields | Field | Required | Notes | | -------------- | -------- | ------------------------------------------------------------------------------------------------------------- | | `prompt` | Yes | Non-empty description (up to 32,000 chars on `openai/gpt-image-2`). | | `resolution` | Optional | Model-specific tier (`1K`, `2K`, `4K` on `openai/gpt-image-2`; default `1K`). Mutually exclusive with `size`. | | `aspectRatio` | Optional | Common ratios such as `1:1`, `16:9`, `9:16`, `3:2`, `4:5` (default `1:1`). Mutually exclusive with `size`. | | `size` | Optional | Explicit `{ width, height }` object on models that support custom dimensions (multiples of 16 on GPT Image). | | `quality` | Optional | `auto`, `low`, `medium`, or `high` on `openai/gpt-image-2` (default `medium`). | | `outputFormat` | Optional | `png`, `jpeg`, or `webp` (`bfl/flux-3-image` supports `png` and `jpeg` only). | | `background` | Optional | `auto`, `opaque`, or `transparent` (requires `png` or `webp` when `transparent`). | | `count` | Optional | Number of images (`1`–`10` on `openai/gpt-image-2`; varies by variant). | > [!NOTE] > `text-to-image` rejects any source media fields (`references`, `firstFrame`, `lastFrame`, `sourceVideo`, `mask`). To condition on existing images, switch to the [Image Edit guide](/docs/guides/image-edit). ## 2. Estimate cost and verify route eligibility Before reserving credits or invoking an upstream provider, pass your exact payload to `POST /v1/pricing/estimate` (or MCP `estimate_cost`). When authenticated with a `read`-scoped credential, the response includes per-route `estimatedCostMicros`, `recommendedMaxCostMicros`, and `workspaceEligibility`. ```bash tab="cURL" set -eu umask 077 if [ -e t2i-submission.key ]; then echo "Existing t2i-submission.key found; recover read-only via GET /v1/generations/lookup before replacing request.json." >&2 exit 1 fi rm -f request.json cat <<'JSON' > request.json { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brushed brass maritime compass resting on natural oatmeal linen, soft morning window light, shallow depth of field.", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000 } JSON chmod 600 request.json curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @request.json ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const payload = { modelId: 'openai/gpt-image-2', operation: 'text-to-image', input: { prompt: 'A brushed brass maritime compass resting on natural oatmeal linen, soft morning window light, shallow depth of field.', resolution: '1K', aspectRatio: '1:1', quality: 'low', outputFormat: 'png', }, routeId: 'openai-undisclosed/openai-gpt-image-2', billing: 'managed', maxCostMicros: 50000, } as const; const estimateRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); if (!estimateRes.ok) throw new Error(await estimateRes.text()); console.log(await estimateRes.json()); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") payload = { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brushed brass maritime compass resting on natural oatmeal linen, soft morning window light, shallow depth of field.", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", "outputFormat": "png", }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, } with httpx.Client(timeout=30.0) as client: estimate = client.post( f"{origin}/v1/pricing/estimate", headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}, json=payload, ).raise_for_status().json() print(estimate) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brushed brass maritime compass resting on natural oatmeal linen, soft morning window light, shallow depth of field.", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000 } } ``` ```bash tab="CLI" opengen pricing estimate --input request.json ``` `maxCostMicros` is an integer micro-USD spend ceiling (`50000` micro-USD = `$0.05`). For token-billed models such as `openai/gpt-image-2`, OpenGen reserves a conservative upper bound at admission and settles the exact reported upstream usage once the provider finishes, releasing any unused hold back to your workspace balance. ## 3. Submit once with an `Idempotency-Key` Persist the request body and a freshly generated `Idempotency-Key` before submitting. For fast image models, send the standard RFC 7240 `Prefer: wait=20` header (clamped to `0`–`25` seconds) on REST, `waitMs: 20000` on MCP, or `--wait 20` on the CLI so completed renders return `200 OK` with private output URLs in a single round trip. If the render takes longer than the wait window, OpenGen returns `202 Accepted` with the durable job ID and `Location` header. ```bash tab="cURL" set -eu umask 077 if [ -e t2i-submission.key ]; then echo "Existing t2i-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="t2i-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > t2i-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data @request.json > generation-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const idempotencyKey = `t2i-${randomUUID()}`; // flag: 'wx' refuses to overwrite an existing unresolved submission record. await writeFile('t2i-submission.json', JSON.stringify({ idempotencyKey, payload }, null, 2), { mode: 0o600, flag: 'wx', }); const res = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20', }, body: JSON.stringify(payload), }); if (!res.ok) throw new Error(await res.text()); const job = await res.json(); console.log({ id: job.id, status: job.status, deliveryStatus: job.deliveryStatus }); ``` ```python tab="Python" import json import os import uuid idempotency_key = f"t2i-{uuid.uuid4()}" # O_EXCL refuses to overwrite an existing unresolved submission record. fd = os.open("t2i-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": payload}, handle, indent=2) with httpx.Client(timeout=45.0) as client: res = client.post( f"{origin}/v1/generations", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": idempotency_key, "Prefer": "wait=20", }, json=payload, ) res.raise_for_status() job = res.json() print(job["id"], job["status"], job.get("deliveryStatus")) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "t2i-example-001", "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brushed brass maritime compass resting on natural oatmeal linen, soft morning window light, shallow depth of field.", "resolution": "1K", "aspectRatio": "1:1", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e t2i-submission.key ]; then echo "Existing t2i-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat t2i-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="t2i-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > t2i-submission.key) opengen generate --input request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > generation-receipt.json ``` ## 4. Poll, recover, and download private outputs If the submission returned `202 Accepted` (or `deliveryStatus: "pending"`), follow the existing job ID with `GET /v1/generations/{id}/status?waitMs=25000` (passing the returned `revision` as `afterRevision` on subsequent polls), then fetch fresh signed output links with `GET /v1/generations/{id}`. ```bash tab="cURL" # Check status and wait up to 25s for changes curl --fail-with-body \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ "https://opengen.dev/v1/generations/$JOB_ID/status?waitMs=25000" # Fetch fresh first-party /media/... capability URLs and settled cost curl --fail-with-body \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ "https://opengen.dev/v1/generations/$JOB_ID" ``` ```ts tab="TypeScript" let current = job; while ( ['queued', 'submitting', 'running'].includes(current.status) || (current.status === 'succeeded' && current.deliveryStatus === 'pending') ) { const query = new URLSearchParams({ waitMs: '25000' }); if (current.revision) query.set('afterRevision', current.revision); const poll = await fetch(`${origin}/v1/generations/${current.id}/status?${query}`, { headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }, }); if (!poll.ok) throw new Error(await poll.text()); const snapshot = await poll.json(); current = snapshot.job ?? snapshot; } const fullRes = await fetch(`${origin}/v1/generations/${current.id}`, { headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }, }); if (!fullRes.ok) throw new Error(await fullRes.text()); const full = await fullRes.json(); console.log(full.status, full.deliveryStatus, full.outputs); ``` ```python tab="Python" with httpx.Client(timeout=40.0) as client: auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} current = job while current.get("status") in {"queued", "submitting", "running"} or ( current.get("status") == "succeeded" and current.get("deliveryStatus") == "pending" ): params = {"waitMs": 25000} if current.get("revision"): params["afterRevision"] = current["revision"] snap = client.get(f"{origin}/v1/generations/{current['id']}/status", headers=auth, params=params).raise_for_status().json() current = snap.get("job", snap) full = client.get(f"{origin}/v1/generations/{current['id']}", headers=auth).raise_for_status().json() print(full["status"], full.get("deliveryStatus"), full["outputs"]) ``` ```json tab="MCP" { "tool": "job_get", "arguments": { "id": "EXISTING_JOB_ID", "waitMs": 25000 } } ``` ```bash tab="CLI" opengen job wait "$JOB_ID" opengen job get "$JOB_ID" ``` > [!IMPORTANT] > Never create a second `Idempotency-Key` if a `POST /v1/generations` call times out or disconnects. Run read-only recovery with `GET https://opengen.dev/v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY` (MCP `job_get` with `{ "idempotencyKey": "..." }`, CLI `opengen job recover --idempotency-key "$IDEMPOTENCY_KEY"`). Signed first-party `/media/...` URLs expire after roughly 15 minutes; call `GET /v1/generations/{id}` again to refresh them while the object is retained. ## Next steps - Need to edit an existing image or apply an alpha mask? Continue to [Image Editing](/docs/guides/image-edit). - Want to push generation lifecycle events to your app instead of polling? See [Next.js Webhook Verification](/docs/guides/webhooks-nextjs). - Compare regional privacy disclosures and billing settlement in [Regional Routing](/docs/regional-routing) and [Pricing and Analytics](/docs/pricing-and-analytics). ## Supported Models Live catalog variants supporting `text-to-image` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Seedream 5.0 Pro](https://opengen.dev/bytedance/seedream-5.0-pro#variant-bytedance-seedream-5.0-pro) | `bytedance/seedream-5.0-pro` | ByteDance | 5 | $0.03825 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-pro?operation=text-to-image` | | [GPT Image 2](https://opengen.dev/openai/gpt-image-2#variant-openai-gpt-image-2) | `openai/gpt-image-2` | OpenAI | 5 | ≈$0.0044 / image | Closed | `GET /v1/models/openai/gpt-image-2?operation=text-to-image` | | [FLUX 3 Image](https://opengen.dev/bfl/flux-3-image#variant-bfl-flux-3-image) | `bfl/flux-3-image` | Black Forest Labs | 2 | ≈$0.0283 / image | Closed | `GET /v1/models/bfl/flux-3-image?operation=text-to-image` | | [FLUX 3 Klein](https://opengen.dev/bfl/flux-3-image#variant-bfl-flux-3-klein) | `bfl/flux-3-klein` | Black Forest Labs | 2 | $0.008 / image | Open weights | `GET /v1/models/bfl/flux-3-klein?operation=text-to-image` | | [Seedream 5.0 Flash](https://opengen.dev/bytedance/seedream-5.0-flash#variant-bytedance-seedream-5.0-flash) | `bytedance/seedream-5.0-flash` | ByteDance | 2 | $0.018 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-flash?operation=text-to-image` | | [Nano Banana 2 Lite](https://opengen.dev/google/nano-banana-2-lite#variant-google-nano-banana-2-lite) | `google/nano-banana-2-lite` | Google | 2 | ≈$0.0336 / image | Closed | `GET /v1/models/google/nano-banana-2-lite?operation=text-to-image` | | [MiniMax H3 Image Highspeed](https://opengen.dev/minimax/h3-image#variant-minimax-h3-image-highspeed) | `minimax/h3-image-highspeed` | MiniMax | 2 | ≈$0.0156 / image | Closed | `GET /v1/models/minimax/h3-image-highspeed?operation=text-to-image` | | [Qwen Image 3 · fal](https://opengen.dev/qwen/image-3.0-pro#variant-fal-qwen-image-3) | `fal/qwen-image-3` | fal | 1 | $0.04 / image | Closed | `GET /v1/models/fal/qwen-image-3?operation=text-to-image` | | [Qwen Image 3.0 Pro](https://opengen.dev/qwen/image-3.0-pro#variant-alibaba-qwen-image-3.0-pro) | `alibaba/qwen-image-3.0-pro` | Alibaba | 7 | $0.03438 / image | Closed | `GET /v1/models/alibaba/qwen-image-3.0-pro?operation=text-to-image` | | [Qwen Image 2.1 Pro · Hosted](https://opengen.dev/qwen/image-2.1#variant-alibaba-qwen-image-2.1-pro) | `alibaba/qwen-image-2.1-pro` | Alibaba | 6 | $0.035333 / image | Closed | `GET /v1/models/alibaba/qwen-image-2.1-pro?operation=text-to-image` | | [Qwen Image 2.1 Turbo](https://opengen.dev/qwen/image-2.1#variant-qwen-image-2.1-turbo) | `qwen/image-2.1-turbo` | Qwen | 6 | $0.014133 / image | Open weights | `GET /v1/models/qwen/image-2.1-turbo?operation=text-to-image` | | [Nano Banana 2.1](https://opengen.dev/google/nano-banana-2.1#variant-google-nano-banana-2.1) | `google/nano-banana-2.1` | Google | 5 | $0.0336 / image | Closed | `GET /v1/models/google/nano-banana-2.1?operation=text-to-image` | | [GPT Image 2.5 Flare](https://opengen.dev/openai/gpt-image-2.5#variant-openai-gpt-image-2.5-flare) | `openai/gpt-image-2.5-flare` | OpenAI | 5 | ≈$0.0056 / image | Closed | `GET /v1/models/openai/gpt-image-2.5-flare?operation=text-to-image` | | [GPT Image 2.5 Sunburst](https://opengen.dev/openai/gpt-image-2.5#variant-openai-gpt-image-2.5-sunburst) | `openai/gpt-image-2.5-sunburst` | OpenAI | 5 | ≈$0.0056 / image | Closed | `GET /v1/models/openai/gpt-image-2.5-sunburst?operation=text-to-image` | | [Grok Imagine Image 2.0](https://opengen.dev/xai/grok-imagine-image-2.0#variant-xai-grok-imagine-image-2.0) | `xai/grok-imagine-image-2.0` | xAI | 5 | $0.04 / image | Closed | `GET /v1/models/xai/grok-imagine-image-2.0?operation=text-to-image` | | [Seedream 4.0](https://opengen.dev/bytedance/seedream-4.0#variant-bytedance-seedream-4.0) | `bytedance/seedream-4.0` | ByteDance | 2 | $0.03 / image | Closed | `GET /v1/models/bytedance/seedream-4.0?operation=text-to-image` | | [Seedream 4.5](https://opengen.dev/bytedance/seedream-4.5#variant-bytedance-seedream-4.5) | `bytedance/seedream-4.5` | ByteDance | 2 | $0.04 / image | Closed | `GET /v1/models/bytedance/seedream-4.5?operation=text-to-image` | | [Seedream 5.0 Lite](https://opengen.dev/bytedance/seedream-5.0-lite#variant-bytedance-seedream-5.0-lite) | `bytedance/seedream-5.0-lite` | ByteDance | 2 | $0.035 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-lite?operation=text-to-image` | | [Seedream 5.5](https://opengen.dev/bytedance/seedream-5.5#variant-bytedance-seedream-5.5) | `bytedance/seedream-5.5` | ByteDance | 2 | $0.02 / image | Closed | `GET /v1/models/bytedance/seedream-5.5?operation=text-to-image` | | [Nano Banana 2](https://opengen.dev/google/nano-banana-2#variant-google-nano-banana-2) | `google/nano-banana-2` | Google | 2 | ≈$0.0448 / image | Closed | `GET /v1/models/google/nano-banana-2?operation=text-to-image` | | [Nano Banana Pro](https://opengen.dev/google/nano-banana-pro#variant-google-nano-banana-pro) | `google/nano-banana-pro` | Google | 2 | ≈$0.1344 / image | Closed | `GET /v1/models/google/nano-banana-pro?operation=text-to-image` | | [MiniMax H3 Image](https://opengen.dev/minimax/h3-image#variant-minimax-h3-image) | `minimax/h3-image` | MiniMax | 2 | ≈$0.0078 / image | Closed | `GET /v1/models/minimax/h3-image?operation=text-to-image` | | [GPT Image 2.6 Flare](https://opengen.dev/openai/gpt-image-2.6#variant-openai-gpt-image-2.6-flare) | `openai/gpt-image-2.6-flare` | OpenAI | 2 | ≈$0.0247 / image | Closed | `GET /v1/models/openai/gpt-image-2.6-flare?operation=text-to-image` | | [GPT Image 2.6 Sunburst](https://opengen.dev/openai/gpt-image-2.6#variant-openai-gpt-image-2.6-sunburst) | `openai/gpt-image-2.6-sunburst` | OpenAI | 2 | ≈$0.0247 / image | Closed | `GET /v1/models/openai/gpt-image-2.6-sunburst?operation=text-to-image` | --- Source: https://opengen.dev/docs/guides/image-edit.md (Reviewed 2026-12-02) # Edit images with private references and masks > OpenGen image editing pairs workspace-private uploaded assets with one canonical input schema across 25 image models. Upload your source image via POST /v1/assets to receive a ready assetKey, pass it inside input.references (plus optional input.mask on models such as GPT Image 2), check pricing with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key so retries never double-bill. ## Agent Prompt ```text Walk me through an image-edit generation on OpenGen (https://opengen.dev): 1. Discover models supporting image-edit via GET https://opengen.dev/v1/models?operation=image-edit (or MCP find_models with operation="image-edit"; add inputRole="mask" if inpainting is needed). 2. Inspect the exact model via GET https://opengen.dev/v1/models/{provider}/{model}?operation=image-edit (or MCP get_model, e.g. id="openai/gpt-image-2", operation="image-edit") to check maximum reference counts, mask support, and published pricing. 3. Upload each private source image (and optional mask) using POST https://opengen.dev/v1/assets (or MCP upload_asset) and confirm state="ready" before referencing its assetKey. 4. Estimate spend via POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and confirm the route and maxCostMicros cap with me. 5. Submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations (Prefer: wait=20) or MCP generate (waitMs=20000), then follow or refresh private output links via job_get without blind resubmission. ``` OpenGen `image-edit` transforms one or more workspace-private reference images using natural-language instructions and, on mask-capable variants, an explicit alpha mask. Source images always enter through OpenGen's private asset API so files stay scoped to your workspace rather than being published to public URLs. ## Prerequisites - An OpenGen credential with `read` and `generate` scopes (`OPENGEN_API_KEY`, MCP OAuth on `https://opengen.dev/mcp`, or `@opengen-dev/cli` login). - A local PNG, JPEG, or WebP source image you own or have permission to edit (plus an optional PNG mask when using mask inpainting). ## 1. Inspect an image-edit model and its media limits Reference limits, mask support, and transparent-background rules vary by exact variant. Check them before uploading or building a payload: - [GPT Image 2](/openai/gpt-image-2) (`openai/gpt-image-2`, official route `openai-undisclosed/openai-gpt-image-2` is live-verified for `text-to-image` at `1K`, while `image-edit` remains `documented` with an active OpenAI adapter): up to `16` image references, supports optional `mask`, `background: "transparent"` with `png`/`webp`, and `1K`–`4K` output. - [Seedream 5.0 Pro](/bytedance/seedream-5.0-pro) (`bytedance/seedream-5.0-pro`): up to `10` image references, supports constrained transparent PNG editing (`references.length === 1`, `background: "transparent"`, `outputFormat: "png"`). - [Nano Banana 2](/google/nano-banana-2) (`google/nano-banana-2`): `0.5K`–`4K` editing, up to `14` references, with `thinkingLevel: "minimal" | "high"`. ```bash tab="cURL" # Filter models supporting image-edit (add &inputRole=mask for mask inpainting) curl --fail-with-body \ "https://opengen.dev/v1/models?operation=image-edit&inputRole=mask" # Inspect exact schema, routes, and published pricing for GPT Image 2 curl --fail-with-body \ "https://opengen.dev/v1/models/openai/gpt-image-2?operation=image-edit" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch(`${origin}/v1/models/openai/gpt-image-2?operation=image-edit`).then( (r) => r.json(), ); console.log(detail.model.generationProfiles[0].capabilities.references); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/openai/gpt-image-2", params={"operation": "image-edit"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0]["capabilities"]["references"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "openai/gpt-image-2", "operation": "image-edit" } } ``` ```bash tab="CLI" opengen catalog search --operation image-edit --input-role mask opengen catalog get openai/gpt-image-2 ``` ## 2. Upload your private source image (and optional mask) Use `POST /v1/assets` to register your source image privately inside your workspace. Single-step `multipart/form-data` handles files up to **4 MiB** (JSON `base64` handles up to **3 MiB** decoded; files up to **100 MiB** use presigned single-PUT + `POST /v1/assets/complete`—see [Owned Assets](/docs/assets)). Require `state: "ready"` before referencing `assetKey`. ```bash tab="cURL" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: asset-src-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./ceramic-mug.png;type=image/png" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const form = new FormData(); const bytes = await readFile('./ceramic-mug.png'); form.append('file', new Blob([bytes], { type: 'image/png' }), 'ceramic-mug.png'); const uploadRes = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Idempotency-Key': `asset-src-${randomUUID()}`, }, body: form, }); if (!uploadRes.ok) throw new Error(await uploadRes.text()); const asset = await uploadRes.json(); // Verify asset.state === 'ready' and save asset.assetKey console.log(asset.assetKey, asset.state); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with open("ceramic-mug.png", "rb") as fh, httpx.Client(timeout=60.0) as client: asset = client.post( f"{origin}/v1/assets", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": f"asset-src-{uuid.uuid4()}", }, files={"file": ("ceramic-mug.png", fh, "image/png")}, ).raise_for_status().json() print(asset["assetKey"], asset["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "presign_prepare", "mediaType": "image/png", "size": 245760 } } ``` ```bash tab="CLI" opengen upload /absolute/path/ceramic-mug.png --media-type image/png ``` > [!TIP] > To iterate on a previous OpenGen image output without downloading and re-uploading bytes, reuse it directly via `POST https://opengen.dev/v1/assets` with `{ "source": "job_output", "sourceJobId": "", "outputIndex": 0 }` and a stable `Idempotency-Key` (or MCP `upload_asset` with `source: "job_output"`). ## 3. Estimate route eligibility before submitting Pass uploaded images in `input.references` as `{ "type": "image", "asset": { "assetKey": "..." } }`. Image operations never use video-frame fields (`firstFrame` or `lastFrame`). > [!IMPORTANT] > Because image-edit billing varies with input-image tokens and dimensions, managed `image-edit` estimates on `openai-undisclosed/openai-gpt-image-2` are currently comparison-only (`selectedRouteId: null`). To execute live `image-edit` jobs today, connect your own provider credential and submit with `"billing": "byok"` (your connected provider account is billed directly; omit `maxCostMicros`, since OpenGen does not cap direct BYOK charges). ```bash tab="cURL" set -eu umask 077 if [ -e edit-submission.key ]; then echo "Existing edit-submission.key found; recover read-only via GET /v1/generations/lookup before replacing edit-request.json." >&2 exit 1 fi rm -f edit-request.json cat <<'JSON' > edit-request.json { "modelId": "openai/gpt-image-2", "operation": "image-edit", "input": { "prompt": "Replace the tabletop background with warm honed travertine stone while keeping the ceramic mug and shadows identical.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "resolution": "1K", "quality": "medium", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "byok" } JSON chmod 600 edit-request.json # Dry-run estimate only (review selectedRouteId and workspaceEligibility before submitting) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @edit-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "openai/gpt-image-2", "operation": "image-edit", "input": { "prompt": "Replace the tabletop background with warm honed travertine stone while keeping the ceramic mug and shadows identical.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "resolution": "1K", "quality": "medium", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "byok" } } ``` ```bash tab="CLI" opengen pricing estimate --input edit-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming `selectedRouteId`, `workspaceEligibility` (`policyAllowed: true`, `hasActiveBillingHold: false`, `executableCandidateCount > 0`, `blockers: []`), and your BYOK billing payer. ```bash tab="cURL" set -eu umask 077 if [ -e edit-submission.key ]; then echo "Existing edit-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="edit-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > edit-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data @edit-request.json > edit-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const editPayload = { modelId: 'openai/gpt-image-2', operation: 'image-edit', input: { prompt: 'Replace the tabletop background with warm honed travertine stone while keeping the ceramic mug and shadows identical.', references: [ { type: 'image', asset: { assetKey: asset.assetKey }, }, ], resolution: '1K', quality: 'medium', outputFormat: 'png', }, routeId: 'openai-undisclosed/openai-gpt-image-2', billing: 'byok', } as const; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; // 1. Run stateless dry-run estimate and stop if the request is rejected or ineligible. const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers, body: JSON.stringify(editPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); // 2. Only after the estimate is eligible and the user confirms the route and billing payer: const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `edit-${randomUUID()}`; await writeFile( 'edit-submission.json', JSON.stringify({ idempotencyKey, payload: editPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' }, body: JSON.stringify(editPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log({ jobId: job.id, status: job.status }); } ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") edit_payload = { "modelId": "openai/gpt-image-2", "operation": "image-edit", "input": { "prompt": "Replace the tabletop background with warm honed travertine stone while keeping the ceramic mug and shadows identical.", "references": [ {"type": "image", "asset": {"assetKey": asset["assetKey"]}}, ], "resolution": "1K", "quality": "medium", "outputFormat": "png", }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "byok", } with httpx.Client(timeout=45.0) as client: auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=edit_payload).raise_for_status().json() print("Review estimate before submitting:", estimate) # Submit only after confirming route eligibility and billing payer, persisting the key exclusively first. eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"edit-{uuid.uuid4()}" fd = os.open("edit-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": edit_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"}, json=edit_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "edit-example-001", "modelId": "openai/gpt-image-2", "operation": "image-edit", "input": { "prompt": "Replace the tabletop background with warm honed travertine stone while keeping the ceramic mug and shadows identical.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "resolution": "1K", "quality": "medium", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "byok", "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e edit-submission.key ]; then echo "Existing edit-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat edit-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="edit-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > edit-submission.key) opengen generate --input edit-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > edit-receipt.json ``` ### Adding an optional inpainting mask On mask-capable variants (`openai/gpt-image-2`, `openai/gpt-image-2.5-*`, `openai/gpt-image-2.6-*`), upload a second workspace-private PNG mask and attach it under `input.mask` alongside at least one `image` entry in `input.references` (using `"billing": "byok"` since managed `image-edit` quotes are currently comparison-only): ```json { "modelId": "openai/gpt-image-2", "operation": "image-edit", "input": { "prompt": "Replace only the masked mug handle with fluted matte brass.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "mask": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_MASK_UUID.png" }, "resolution": "1K", "quality": "medium", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "byok" } ``` ## 4. Retrieve outputs and clean up unused inputs Poll `GET /v1/generations/{id}/status?waitMs=25000` (or MCP `job_get`) until `deliveryStatus` is `available`, then download from the returned first-party `/media/...` capability URL. If a submission disconnects before returning a job ID, recover with `GET /v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY`. When you no longer need the uploaded source image for future jobs, tombstone it with `DELETE https://opengen.dev/v1/assets?key=` (or MCP `delete_asset`). Accepted jobs keep their private input pins until finished. ## Next steps - Need higher resolution without re-composing the scene? See [Image Upscaling](/docs/guides/image-upscale). - Need a transparent subject cutout? See [Background Removal](/docs/guides/background-remove). - Ready to animate the edited still into video? See [Image to Video](/docs/guides/image-to-video). ## Supported Models Live catalog variants supporting `image-edit` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Seedream 5.0 Pro](https://opengen.dev/bytedance/seedream-5.0-pro#variant-bytedance-seedream-5.0-pro) | `bytedance/seedream-5.0-pro` | ByteDance | 5 | $0.03825 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-pro?operation=image-edit` | | [GPT Image 2](https://opengen.dev/openai/gpt-image-2#variant-openai-gpt-image-2) | `openai/gpt-image-2` | OpenAI | 5 | ≈$0.0059 / image | Closed | `GET /v1/models/openai/gpt-image-2?operation=image-edit` | | [FLUX 3 Image](https://opengen.dev/bfl/flux-3-image#variant-bfl-flux-3-image) | `bfl/flux-3-image` | Black Forest Labs | 2 | ≈$0.0283 / image | Closed | `GET /v1/models/bfl/flux-3-image?operation=image-edit` | | [FLUX 3 Klein](https://opengen.dev/bfl/flux-3-image#variant-bfl-flux-3-klein) | `bfl/flux-3-klein` | Black Forest Labs | 2 | $0.008 / image | Open weights | `GET /v1/models/bfl/flux-3-klein?operation=image-edit` | | [Seedream 5.0 Flash](https://opengen.dev/bytedance/seedream-5.0-flash#variant-bytedance-seedream-5.0-flash) | `bytedance/seedream-5.0-flash` | ByteDance | 2 | $0.018 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-flash?operation=image-edit` | | [MiniMax H3 Image Highspeed](https://opengen.dev/minimax/h3-image#variant-minimax-h3-image-highspeed) | `minimax/h3-image-highspeed` | MiniMax | 2 | ≈$0.0156 / image | Closed | `GET /v1/models/minimax/h3-image-highspeed?operation=image-edit` | | [Qwen Image 3 · fal](https://opengen.dev/qwen/image-3.0-pro#variant-fal-qwen-image-3) | `fal/qwen-image-3` | fal | 1 | $0.04 / image | Closed | `GET /v1/models/fal/qwen-image-3?operation=image-edit` | | [Nano Banana 2 Lite](https://opengen.dev/google/nano-banana-2-lite#variant-google-nano-banana-2-lite) | `google/nano-banana-2-lite` | Google | 1 | ≈$0.0336 / image | Closed | `GET /v1/models/google/nano-banana-2-lite?operation=image-edit` | | [Qwen Image 3.0 Pro](https://opengen.dev/qwen/image-3.0-pro#variant-alibaba-qwen-image-3.0-pro) | `alibaba/qwen-image-3.0-pro` | Alibaba | 7 | $0.03438 / image | Closed | `GET /v1/models/alibaba/qwen-image-3.0-pro?operation=image-edit` | | [Qwen Image 2.1 Pro · Hosted](https://opengen.dev/qwen/image-2.1#variant-alibaba-qwen-image-2.1-pro) | `alibaba/qwen-image-2.1-pro` | Alibaba | 6 | $0.035333 / image | Closed | `GET /v1/models/alibaba/qwen-image-2.1-pro?operation=image-edit` | | [Qwen Image 2.1 Turbo](https://opengen.dev/qwen/image-2.1#variant-qwen-image-2.1-turbo) | `qwen/image-2.1-turbo` | Qwen | 6 | $0.014133 / image | Open weights | `GET /v1/models/qwen/image-2.1-turbo?operation=image-edit` | | [Nano Banana 2.1](https://opengen.dev/google/nano-banana-2.1#variant-google-nano-banana-2.1) | `google/nano-banana-2.1` | Google | 5 | $0.0336 / image | Closed | `GET /v1/models/google/nano-banana-2.1?operation=image-edit` | | [GPT Image 2.5 Flare](https://opengen.dev/openai/gpt-image-2.5#variant-openai-gpt-image-2.5-flare) | `openai/gpt-image-2.5-flare` | OpenAI | 5 | ≈$0.0056 / image | Closed | `GET /v1/models/openai/gpt-image-2.5-flare?operation=image-edit` | | [GPT Image 2.5 Sunburst](https://opengen.dev/openai/gpt-image-2.5#variant-openai-gpt-image-2.5-sunburst) | `openai/gpt-image-2.5-sunburst` | OpenAI | 5 | ≈$0.0056 / image | Closed | `GET /v1/models/openai/gpt-image-2.5-sunburst?operation=image-edit` | | [Grok Imagine Image 2.0](https://opengen.dev/xai/grok-imagine-image-2.0#variant-xai-grok-imagine-image-2.0) | `xai/grok-imagine-image-2.0` | xAI | 5 | $0.04 / image | Closed | `GET /v1/models/xai/grok-imagine-image-2.0?operation=image-edit` | | [Seedream 4.0](https://opengen.dev/bytedance/seedream-4.0#variant-bytedance-seedream-4.0) | `bytedance/seedream-4.0` | ByteDance | 2 | $0.03 / image | Closed | `GET /v1/models/bytedance/seedream-4.0?operation=image-edit` | | [Seedream 4.5](https://opengen.dev/bytedance/seedream-4.5#variant-bytedance-seedream-4.5) | `bytedance/seedream-4.5` | ByteDance | 2 | $0.04 / image | Closed | `GET /v1/models/bytedance/seedream-4.5?operation=image-edit` | | [Seedream 5.0 Lite](https://opengen.dev/bytedance/seedream-5.0-lite#variant-bytedance-seedream-5.0-lite) | `bytedance/seedream-5.0-lite` | ByteDance | 2 | $0.035 / image | Closed | `GET /v1/models/bytedance/seedream-5.0-lite?operation=image-edit` | | [Seedream 5.5](https://opengen.dev/bytedance/seedream-5.5#variant-bytedance-seedream-5.5) | `bytedance/seedream-5.5` | ByteDance | 2 | $0.02 / image | Closed | `GET /v1/models/bytedance/seedream-5.5?operation=image-edit` | | [Nano Banana 2](https://opengen.dev/google/nano-banana-2#variant-google-nano-banana-2) | `google/nano-banana-2` | Google | 2 | ≈$0.0448 / image | Closed | `GET /v1/models/google/nano-banana-2?operation=image-edit` | | [Nano Banana Pro](https://opengen.dev/google/nano-banana-pro#variant-google-nano-banana-pro) | `google/nano-banana-pro` | Google | 2 | ≈$0.1344 / image | Closed | `GET /v1/models/google/nano-banana-pro?operation=image-edit` | | [MiniMax H3 Image](https://opengen.dev/minimax/h3-image#variant-minimax-h3-image) | `minimax/h3-image` | MiniMax | 2 | ≈$0.0078 / image | Closed | `GET /v1/models/minimax/h3-image?operation=image-edit` | | [GPT Image 2.6 Flare](https://opengen.dev/openai/gpt-image-2.6#variant-openai-gpt-image-2.6-flare) | `openai/gpt-image-2.6-flare` | OpenAI | 2 | ≈$0.0247 / image | Closed | `GET /v1/models/openai/gpt-image-2.6-flare?operation=image-edit` | | [GPT Image 2.6 Sunburst](https://opengen.dev/openai/gpt-image-2.6#variant-openai-gpt-image-2.6-sunburst) | `openai/gpt-image-2.6-sunburst` | OpenAI | 2 | ≈$0.0247 / image | Closed | `GET /v1/models/openai/gpt-image-2.6-sunburst?operation=image-edit` | --- Source: https://opengen.dev/docs/guides/image-upscale.md (Reviewed 2026-12-02) # Upscale images with megapixel-aware controls > OpenGen models image upscaling as a dedicated image-upscale operation with scale-factor controls and megapixel-aware pricing inspection. Upload one workspace-private source image through POST /v1/assets, inspect exact schema limits for clarity/clarity-upscaler via GET /v1/models/clarity/clarity-upscaler?operation=image-upscale, check route readiness and pricing with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key when an executable route is configured. ## Agent Prompt ```text Walk me through an image-upscale request on OpenGen (https://opengen.dev): 1. Discover upscaling models with GET https://opengen.dev/v1/models?operation=image-upscale (or MCP find_models with operation="image-upscale"). 2. Inspect exact schema bounds and published megapixel pricing via GET https://opengen.dev/v1/models/clarity/clarity-upscaler?operation=image-upscale (or MCP get_model with id="clarity/clarity-upscaler", operation="image-upscale"). Note that resolution and aspectRatio are unsupported; use scale (1-4) and optional strength (0-1). 3. Upload the single private source image with POST https://opengen.dev/v1/assets (or MCP upload_asset) and verify state="ready". 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) to inspect workspaceEligibility and megapixel pricing disclosures. Stop and report if the route is documented/comparison-only on the current gateway. 5. Only when an executable route is eligible and I confirm the spend cap, submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate. ``` OpenGen separates detail-preserving upscaling into its own `image-upscale` operation so clients can specify numeric `scale` factors and optional creativity `strength` without overloading general image-edit schemas. > [!NOTE] > Verify route executability before promising a live run. In the current catalog snapshot, `fal-undisclosed/clarity-clarity-upscaler` is registered with `status: "documented"` and no active execution adapter (comparison-only until an adapter is enabled on your target gateway). Always inspect `GET /v1/models/clarity/clarity-upscaler?operation=image-upscale` and `workspaceEligibility` from `POST /v1/pricing/estimate`. ## 1. Inspect the upscaler schema and pricing [Clarity Upscaler](/clarity/clarity-upscaler) (`clarity/clarity-upscaler`) is an open-weights upscaler documented on fal (`fal-undisclosed/clarity-clarity-upscaler`) with published megapixel pricing (`$0.03` per output megapixel—for example, a 4 MP output is `$0.12`, scaling proportionally with input dimensions and `scale`). ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=image-upscale" curl --fail-with-body \ "https://opengen.dev/v1/models/clarity/clarity-upscaler?operation=image-upscale" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch( `${origin}/v1/models/clarity/clarity-upscaler?operation=image-upscale`, ).then((r) => r.json()); console.log(detail.model.generationProfiles[0], detail.pricing); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/clarity/clarity-upscaler", params={"operation": "image-upscale"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0], detail["pricing"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "clarity/clarity-upscaler", "operation": "image-upscale" } } ``` ```bash tab="CLI" opengen catalog search --operation image-upscale opengen catalog get clarity/clarity-upscaler opengen pricing --model clarity/clarity-upscaler --operation image-upscale ``` ### Valid `clarity/clarity-upscaler` fields | Field | Required | Allowed values | | ---------------- | -------- | ------------------------------------------------------------------------------------ | | `references` | Yes | Exactly `1` image reference (`{ "type": "image", "asset": { "assetKey": "..." } }`). | | `scale` | Optional | Number from `1` to `4` (default `2`). | | `strength` | Optional | Number from `0` to `1` controlling detail hallucination vs source faithfulness. | | `prompt` | Optional | Guidance prompt (up to 4,000 characters); not required. | | `negativePrompt` | Optional | Artifacts to suppress during upscaling. | | `outputFormat` | Optional | `png`, `jpeg`, or `webp`. | | `seed` | Optional | Integer seed for reproducible enhancement. | Passing `resolution`, `aspectRatio`, `firstFrame`, or `mask` is rejected with `400 invalid_generation` before any credits are reserved because output dimensions derive directly from the source image and `scale`. ## 2. Upload the private source image Upload the source image privately via `POST /v1/assets` (`<= 4 MiB` multipart, `<= 3 MiB` JSON base64, or presigned PUT up to `100 MiB`) or reuse a previous OpenGen image output with `{ "source": "job_output", "sourceJobId": "", "outputIndex": 0 }`. ```bash tab="cURL" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: upscale-src-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./product-shot.png;type=image/png" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const form = new FormData(); form.append( 'file', new Blob([await readFile('./product-shot.png')], { type: 'image/png' }), 'product-shot.png', ); const asset = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Idempotency-Key': `upscale-src-${randomUUID()}`, }, body: form, }).then((r) => r.json()); console.log(asset.assetKey, asset.state); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with open("product-shot.png", "rb") as fh, httpx.Client(timeout=60.0) as client: asset = client.post( f"{origin}/v1/assets", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": f"upscale-src-{uuid.uuid4()}", }, files={"file": ("product-shot.png", fh, "image/png")}, ).raise_for_status().json() print(asset["assetKey"], asset["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, "idempotencyKey": "upscale-reuse-001" } } ``` ```bash tab="CLI" opengen upload /absolute/path/product-shot.png --media-type image/png ``` ## 3. Estimate route eligibility before submitting Run `POST /v1/pricing/estimate` first to validate the canonical request and check `workspaceEligibility`. Because megapixel billing scales with the source image's actual pixel area (`width * height * scale^2`), managed `image-upscale` quotes are currently comparison-only (`selectedRouteId: null`); once an execution adapter is enabled on your gateway, use `"billing": "byok"` with your connected provider credential (omitting `maxCostMicros`, since OpenGen cannot cap direct BYOK provider charges). ```bash tab="cURL" set -eu umask 077 if [ -e upscale-submission.key ]; then echo "Existing upscale-submission.key found; recover read-only via GET /v1/generations/lookup before replacing upscale-request.json." >&2 exit 1 fi rm -f upscale-request.json cat <<'JSON' > upscale-request.json { "modelId": "clarity/clarity-upscaler", "operation": "image-upscale", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "scale": 2, "strength": 0.35, "prompt": "Sharp architectural detail, crisp textures, faithful preservation of original edges", "outputFormat": "png" }, "routeId": "fal-undisclosed/clarity-clarity-upscaler", "billing": "byok" } JSON chmod 600 upscale-request.json # Dry-run estimate only (review selectedRouteId and workspaceEligibility before submitting) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @upscale-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "clarity/clarity-upscaler", "operation": "image-upscale", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "scale": 2, "strength": 0.35, "prompt": "Sharp architectural detail, crisp textures, faithful preservation of original edges", "outputFormat": "png" }, "routeId": "fal-undisclosed/clarity-clarity-upscaler", "billing": "byok" } } ``` ```bash tab="CLI" opengen pricing estimate --input upscale-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming an executable route is eligible (`selectedRouteId != null`, `executableCandidateCount > 0`, `blockers: []`) and confirming your billing payer. ```bash tab="cURL" set -eu umask 077 if [ -e upscale-submission.key ]; then echo "Existing upscale-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="upscale-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > upscale-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data @upscale-request.json > upscale-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const upscalePayload = { modelId: 'clarity/clarity-upscaler', operation: 'image-upscale', input: { references: [{ type: 'image', asset: { assetKey: asset.assetKey } }], scale: 2, strength: 0.35, prompt: 'Sharp architectural detail, crisp textures, faithful preservation of original edges', outputFormat: 'png', }, routeId: 'fal-undisclosed/clarity-clarity-upscaler', billing: 'byok', } as const; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers, body: JSON.stringify(upscalePayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); // Submit only when the selected route is eligible and approved, persisting the key first. const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `upscale-${randomUUID()}`; await writeFile( 'upscale-submission.json', JSON.stringify({ idempotencyKey, payload: upscalePayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' }, body: JSON.stringify(upscalePayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status); } ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") upscale_payload = { "modelId": "clarity/clarity-upscaler", "operation": "image-upscale", "input": { "references": [{"type": "image", "asset": {"assetKey": asset["assetKey"]}}], "scale": 2, "strength": 0.35, "prompt": "Sharp architectural detail, crisp textures, faithful preservation of original edges", "outputFormat": "png", }, "routeId": "fal-undisclosed/clarity-clarity-upscaler", "billing": "byok", } with httpx.Client(timeout=45.0) as client: auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=upscale_payload).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"upscale-{uuid.uuid4()}" fd = os.open("upscale-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": upscale_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"}, json=upscale_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "upscale-example-001", "modelId": "clarity/clarity-upscaler", "operation": "image-upscale", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.png" } } ], "scale": 2, "strength": 0.35, "prompt": "Sharp architectural detail, crisp textures, faithful preservation of original edges", "outputFormat": "png" }, "routeId": "fal-undisclosed/clarity-clarity-upscaler", "billing": "byok", "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e upscale-submission.key ]; then echo "Existing upscale-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat upscale-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="upscale-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > upscale-submission.key) opengen generate --input upscale-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > upscale-receipt.json ``` ## 4. Check job status and download privately If a generation returns `202 Accepted`, poll `GET /v1/generations/{id}/status?waitMs=25000` or call MCP `job_get`. Recover any interrupted submission with `GET /v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY` instead of generating a new key. ## Next steps - Need transparent subject extraction before or after upscaling? See [Background Removal](/docs/guides/background-remove). - Need prompt-driven local edits at `2K` or `4K` on models with active image-edit adapters? See [Image Editing](/docs/guides/image-edit). ## Supported Models Live catalog variants supporting `image-upscale` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Clarity Upscaler](https://opengen.dev/clarity/clarity-upscaler#variant-clarity-clarity-upscaler) | `clarity/clarity-upscaler` | Clarity AI | 1 | $0.03 / MP | Open weights | `GET /v1/models/clarity/clarity-upscaler?operation=image-upscale` | --- Source: https://opengen.dev/docs/guides/background-remove.md (Reviewed 2026-12-02) # Remove image backgrounds into transparent cutouts > OpenGen exposes foreground segmentation and alpha cutout extraction under the dedicated background-remove operation. Upload a private source image via POST /v1/assets, inspect exact constraints for bria/remove-background (alpha-capable PNG or WebP output only, with no prompt field), verify route availability and published per-image rates via POST /v1/pricing/estimate, and submit with a persisted Idempotency-Key once an executable route is configured. ## Agent Prompt ```text Walk me through a background-remove workflow on OpenGen (https://opengen.dev): 1. Discover background removal models with GET https://opengen.dev/v1/models?operation=background-remove (or MCP find_models with operation="background-remove"). 2. Inspect exact schema limits and published pricing via GET https://opengen.dev/v1/models/bria/remove-background?operation=background-remove (or MCP get_model with id="bria/remove-background", operation="background-remove"). Note that prompt is NOT accepted and outputFormat must be "png" or "webp". 3. Upload the single private source image via POST https://opengen.dev/v1/assets (or MCP upload_asset) and confirm state="ready". 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) to inspect workspaceEligibility and published per-image rates. Stop and report if routes are documented/comparison-only on the current gateway. 5. Only when an executable route is eligible and I approve the spend cap, submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate. ``` OpenGen models transparent foreground segmentation under the dedicated `background-remove` operation. Because background removal does not use text prompts or opaque JPEG outputs, the canonical schema enforces those guardrails before any credit reservation or upstream call occurs. > [!NOTE] > Check route executability before promising live dispatch. In the current catalog snapshot, `fal-undisclosed/bria-remove-background` and `replicate-undisclosed/bria-remove-background` carry `status: "documented"` with no active execution adapter (comparison-only until enabled on your gateway). Also note the licensing distinction: BRIA RMBG 2.0 open weights carry a `CC BY-NC 4.0` non-commercial license, while partner API routes include commercial usage under each provider's terms. ## 1. Inspect `bria/remove-background` schema and pricing [BRIA RMBG 2.0](/bria/remove-background) (`bria/remove-background`) is documented across fal (`$0.018` per output image) and Replicate. Inspect its live schema and routes in one call: ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=background-remove" curl --fail-with-body \ "https://opengen.dev/v1/models/bria/remove-background?operation=background-remove" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch( `${origin}/v1/models/bria/remove-background?operation=background-remove`, ).then((r) => r.json()); console.log(detail.model.generationProfiles[0], detail.pricing); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/bria/remove-background", params={"operation": "background-remove"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0], detail["pricing"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "bria/remove-background", "operation": "background-remove" } } ``` ```bash tab="CLI" opengen catalog search --operation background-remove opengen catalog get bria/remove-background opengen pricing --model bria/remove-background --operation background-remove ``` ### Valid `bria/remove-background` fields | Field | Required | Allowed values | | -------------- | -------- | ------------------------------------------------------------------------------------ | | `references` | Yes | Exactly `1` image reference (`{ "type": "image", "asset": { "assetKey": "..." } }`). | | `outputFormat` | Optional | Alpha-capable format only: `png` (default) or `webp`. | `prompt`, `resolution`, `aspectRatio`, `mask`, and `outputFormat: "jpeg"` are rejected with `400 invalid_generation`. ## 2. Upload your private source image Upload a workspace-private image via `POST /v1/assets` or reuse an earlier OpenGen generation output with `{ "source": "job_output", "sourceJobId": "", "outputIndex": 0 }`. ```bash tab="cURL" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: bgrem-src-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./sneaker-photo.jpg;type=image/jpeg" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const form = new FormData(); form.append( 'file', new Blob([await readFile('./sneaker-photo.jpg')], { type: 'image/jpeg' }), 'sneaker-photo.jpg', ); const asset = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Idempotency-Key': `bgrem-src-${randomUUID()}`, }, body: form, }).then((r) => r.json()); console.log(asset.assetKey, asset.state); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with open("sneaker-photo.jpg", "rb") as fh, httpx.Client(timeout=60.0) as client: asset = client.post( f"{origin}/v1/assets", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": f"bgrem-src-{uuid.uuid4()}", }, files={"file": ("sneaker-photo.jpg", fh, "image/jpeg")}, ).raise_for_status().json() print(asset["assetKey"], asset["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "url", "url": "https://assets.example.com/catalog/sneaker-photo.jpg", "type": "image", "idempotencyKey": "bgrem-import-001" } } ``` ```bash tab="CLI" opengen upload /absolute/path/sneaker-photo.jpg --media-type image/jpeg ``` ## 3. Estimate cost and route eligibility before submitting Notice that `input` contains **only** `references` and `outputFormat`—do not include `prompt`. Run `POST /v1/pricing/estimate` first to review published pricing and `workspaceEligibility`. ```bash tab="cURL" set -eu umask 077 if [ -e bg-remove-submission.key ]; then echo "Existing bg-remove-submission.key found; recover read-only via GET /v1/generations/lookup before replacing bg-remove-request.json." >&2 exit 1 fi rm -f bg-remove-request.json cat <<'JSON' > bg-remove-request.json { "modelId": "bria/remove-background", "operation": "background-remove", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg" } } ], "outputFormat": "png" }, "routeId": "fal-undisclosed/bria-remove-background", "billing": "managed", "maxCostMicros": 50000 } JSON chmod 600 bg-remove-request.json # Dry-run estimate only (review selectedRouteId, recommendedMaxCostMicros, and workspaceEligibility) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @bg-remove-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "bria/remove-background", "operation": "background-remove", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg" } } ], "outputFormat": "png" }, "routeId": "fal-undisclosed/bria-remove-background", "billing": "managed", "maxCostMicros": 50000 } } ``` ```bash tab="CLI" opengen pricing estimate --input bg-remove-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming an executable route is eligible (`selectedRouteId != null`, `executableCandidateCount > 0`, `blockers: []`) and confirming `maxCostMicros`. ```bash tab="cURL" set -eu umask 077 if [ -e bg-remove-submission.key ]; then echo "Existing bg-remove-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="bgrem-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > bg-remove-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data @bg-remove-request.json > bg-remove-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const bgPayload = { modelId: 'bria/remove-background', operation: 'background-remove', input: { references: [{ type: 'image', asset: { assetKey: asset.assetKey } }], outputFormat: 'png', }, routeId: 'fal-undisclosed/bria-remove-background', billing: 'managed', maxCostMicros: 50000, } as const; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers, body: JSON.stringify(bgPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `bgrem-${randomUUID()}`; await writeFile( 'bg-remove-submission.json', JSON.stringify({ idempotencyKey, payload: bgPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' }, body: JSON.stringify(bgPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status); } ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") bg_payload = { "modelId": "bria/remove-background", "operation": "background-remove", "input": { "references": [{"type": "image", "asset": {"assetKey": asset["assetKey"]}}], "outputFormat": "png", }, "routeId": "fal-undisclosed/bria-remove-background", "billing": "managed", "maxCostMicros": 50000, } with httpx.Client(timeout=45.0) as client: auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=bg_payload).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"bgrem-{uuid.uuid4()}" fd = os.open("bg-remove-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": bg_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"}, json=bg_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "bgrem-example-001", "modelId": "bria/remove-background", "operation": "background-remove", "input": { "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg" } } ], "outputFormat": "png" }, "routeId": "fal-undisclosed/bria-remove-background", "billing": "managed", "maxCostMicros": 50000, "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e bg-remove-submission.key ]; then echo "Existing bg-remove-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat bg-remove-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="bgrem-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > bg-remove-submission.key) opengen generate --input bg-remove-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > bg-remove-receipt.json ``` > [!TIP] > Need an executable transparent-background image workflow today? [GPT Image 2](/openai/gpt-image-2) (`image-edit`) supports `background: "transparent"` with `outputFormat: "png"` through its active official OpenAI adapter (note that `openai-undisclosed/openai-gpt-image-2` is live-verified for `text-to-image` at `1K`, while `image-edit` and transparent cutouts remain `documented`)—see [Image Editing](/docs/guides/image-edit). ## Next steps - Composite your cutout into a new scene with [Image Editing](/docs/guides/image-edit). - Use the cutout as a character reference in [Reference to Video](/docs/guides/reference-to-video). ## Supported Models Live catalog variants supporting `background-remove` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [BRIA RMBG 2.0](https://opengen.dev/bria/remove-background#variant-bria-remove-background) | `bria/remove-background` | BRIA AI | 2 | $0.018 / image | Open weights | `GET /v1/models/bria/remove-background?operation=background-remove` | --- Source: https://opengen.dev/docs/guides/text-to-video.md (Reviewed 2026-12-02) # Generate video from text prompts > OpenGen routes text-to-video prompts across 25 exact video model variants using one canonical schema for resolution, duration, aspect ratio, and native audio. Inspect regional endpoints and published per-second or token pricing via GET /v1/models/{provider}/{model}, verify spend with POST /v1/pricing/estimate, submit once with a persisted Idempotency-Key, and stream or poll private delivery progress without risking duplicate charges. ## Agent Prompt ```text Walk me through a text-to-video generation on OpenGen (https://opengen.dev): 1. Discover video models via GET https://opengen.dev/v1/models?operation=text-to-video (or MCP find_models with operation="text-to-video"). 2. Inspect the exact model's resolutions, integer duration bounds, native audio policy, regional endpoints, privacy disclosures, and published pricing via GET https://opengen.dev/v1/models/{provider}/{model}?operation=text-to-video (or MCP get_model, e.g. id="alibaba/wan-3.0", operation="text-to-video"). 3. Run a stateless dry-run estimate with POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and present the selected regional route, estimatedCostMicros, recommendedMaxCostMicros, and workspaceEligibility. 4. Wait for my confirmation of the route and maxCostMicros spend ceiling before submitting. 5. Persist a unique Idempotency-Key and submit once via POST https://opengen.dev/v1/generations or MCP generate, then follow progress via GET https://opengen.dev/v1/generations/{id}/status (or /events SSE) or MCP job_get(id, afterRevision, waitMs=25000) without ever creating a second Idempotency-Key. ``` OpenGen `text-to-video` turns a text prompt into a private MP4 clip across 25 exact video variants while keeping regional endpoints, native audio policies, and per-second or token pricing explicit before you spend. ## 1. Compare exact video variants and regional routes Video models differ sharply in resolution tiers, duration ranges, audio support (`switchable`, `always-on`, or `unsupported`), and regional endpoints: - [Wan 3.0](/alibaba/wan-3.0) (`alibaba/wan-3.0`): official Singapore route `alibaba/ap-southeast-1/wan-3.0` is live-verified for `text-to-video` and `image-to-video` at `480p` / `2s` (higher resolutions and longer durations remain documented), supporting `480p`/`720p`/`1080p`, `2`–`30` seconds (or `"auto"`), switchable audio, and published per-second tariffs of `$0.05/s` at `480p`, `$0.10/s` at `720p`, and `$0.20/s` at `1080p`. - [Kling 4.0](/kling/kling-4.0) (`kling/kling-4.0`): live-verified for `text-to-video` at `720p` / `3s` on `kling-ap-southeast-1/kling-kling-4.0` and `runway-undisclosed/kling-kling-4.0` (other resolutions and durations remain documented), supporting `720p`/`1080p`/`4K`, `3`–`30` seconds, always-on native audio, and multi-shot `shots` arrays. - [FLUX 3 Video](/bfl/flux-3-video) (`bfl/flux-3-video`): live-verified for `text-to-video` at `720p` / `5s` on `bfl-undisclosed/bfl-flux-3-video` (higher resolutions and other durations remain documented), supporting `720p`–`2160p`, `5`–`20` seconds (or `"auto"`), and switchable audio. - [Seedance 2.5](/bytedance/seedance-2.5) (`bytedance/seedance-2.5`): `480p`–`1080p`, `4`–`30` seconds, with optional `draft` preview mode (`480p` with `audio: false`) and `codec`/`bitrateMode` controls on compatible routes. ```bash tab="cURL" # List text-to-video models (filter by region or collection if needed) curl --fail-with-body \ "https://opengen.dev/v1/models?operation=text-to-video®ion=ap-southeast-1" # Inspect Wan 3.0 schema, regional deployments, privacy disclosures, and pricing curl --fail-with-body \ "https://opengen.dev/v1/models/alibaba/wan-3.0?operation=text-to-video" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch(`${origin}/v1/models/alibaba/wan-3.0?operation=text-to-video`).then( (r) => r.json(), ); console.log( detail.routes.map((r: { id: string; status: string }) => ({ id: r.id, status: r.status })), ); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/alibaba/wan-3.0", params={"operation": "text-to-video"}, ).raise_for_status().json() print([(r["id"], r["status"]) for r in detail["routes"]]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "alibaba/wan-3.0", "operation": "text-to-video" } } ``` ```bash tab="CLI" opengen catalog search --operation text-to-video --region ap-southeast-1 opengen catalog get alibaba/wan-3.0 opengen pricing --model alibaba/wan-3.0 --operation text-to-video ``` > [!NOTE] > Endpoint location (`ap-southeast-1`, `us-east-1`, `eu-central-1`) is distinct from inference scope and storage residency. Always inspect each route's `privacyDisclosure` object from `GET /v1/models/{provider}/{model}` and see [Regional Routing](/docs/regional-routing). ## 2. Estimate cost and pin your regional route Validate your exact payload with `POST /v1/pricing/estimate` before submitting. Pin a specific `routeId` (or narrow allowed providers and regions via `routing`) so OpenGen never routes outside your residency or cost policy. ```bash tab="cURL" set -eu umask 077 if [ -e t2v-submission.key ]; then echo "Existing t2v-submission.key found; recover read-only via GET /v1/generations/lookup before replacing t2v-request.json." >&2 exit 1 fi rm -f t2v-request.json cat <<'JSON' > t2v-request.json { "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "A wooden ferry crossing a misty fjord at dawn, slow aerial tracking shot, crisp ripples on dark blue water.", "resolution": "720p", "duration": 5, "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba/ap-southeast-1/wan-3.0", "billing": "managed", "maxCostMicros": 600000 } JSON chmod 600 t2v-request.json curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @t2v-request.json ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const t2vPayload = { modelId: 'alibaba/wan-3.0', operation: 'text-to-video', input: { prompt: 'A wooden ferry crossing a misty fjord at dawn, slow aerial tracking shot, crisp ripples on dark blue water.', resolution: '720p', duration: 5, aspectRatio: '16:9', audio: true, }, routeId: 'alibaba/ap-southeast-1/wan-3.0', billing: 'managed', maxCostMicros: 600000, } as const; const estimate = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(t2vPayload), }).then((r) => r.json()); console.log(estimate); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") t2v_payload = { "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "A wooden ferry crossing a misty fjord at dawn, slow aerial tracking shot, crisp ripples on dark blue water.", "resolution": "720p", "duration": 5, "aspectRatio": "16:9", "audio": True, }, "routeId": "alibaba/ap-southeast-1/wan-3.0", "billing": "managed", "maxCostMicros": 600000, } with httpx.Client(timeout=30.0) as client: estimate = client.post( f"{origin}/v1/pricing/estimate", headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}, json=t2v_payload, ).raise_for_status().json() print(estimate) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "A wooden ferry crossing a misty fjord at dawn, slow aerial tracking shot, crisp ripples on dark blue water.", "resolution": "720p", "duration": 5, "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba/ap-southeast-1/wan-3.0", "billing": "managed", "maxCostMicros": 600000 } } ``` ```bash tab="CLI" opengen pricing estimate --input t2v-request.json ``` ## 3. Submit once and follow asynchronous progress Video jobs run asynchronously on OpenGen's durable worker pool. Persist your `Idempotency-Key` and request body before calling `POST /v1/generations`. Save the returned `job.id` immediately, then follow progress via long-polling (`GET /v1/generations/{id}/status?waitMs=25000`), Server-Sent Events (`GET /v1/generations/{id}/events`), or a per-request [Ed25519 webhook](/docs/guides/webhooks-nextjs). ```bash tab="cURL" set -eu umask 077 if [ -e t2v-submission.key ]; then echo "Existing t2v-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="t2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > t2v-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data @t2v-request.json > t2v-receipt.json # Stream real-time job lifecycle updates over SSE JOB_ID="$(jq -r '.id' t2v-receipt.json)" curl -N \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Accept: text/event-stream" \ "https://opengen.dev/v1/generations/$JOB_ID/events" ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const idempotencyKey = `t2v-${randomUUID()}`; // flag: 'wx' refuses to overwrite an existing unresolved submission record. await writeFile( 't2v-submission.json', JSON.stringify({ idempotencyKey, payload: t2vPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const auth = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const acceptRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey }, body: JSON.stringify(t2vPayload), }); if (!acceptRes.ok) throw new Error(`Generation failed (${acceptRes.status}): ${await acceptRes.text()}`); const accepted = await acceptRes.json(); let current = accepted; while ( ['queued', 'submitting', 'running'].includes(current.status) || (current.status === 'succeeded' && current.deliveryStatus === 'pending') ) { const qs = new URLSearchParams({ waitMs: '25000' }); if (current.revision) qs.set('afterRevision', current.revision); const pollRes = await fetch(`${origin}/v1/generations/${accepted.id}/status?${qs}`, { headers: auth, }); if (!pollRes.ok) throw new Error(`Status poll failed (${pollRes.status}): ${await pollRes.text()}`); const poll = await pollRes.json(); current = poll.job ?? poll; } const completedRes = await fetch(`${origin}/v1/generations/${accepted.id}`, { headers: auth, }); if (!completedRes.ok) { throw new Error(`Job detail failed (${completedRes.status}): ${await completedRes.text()}`); } const completed = await completedRes.json(); console.log(completed.status, completed.outputs, completed.settledMicros); ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} idempotency_key = f"t2v-{uuid.uuid4()}" # O_EXCL refuses to overwrite an existing unresolved submission record. fd = os.open("t2v-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": t2v_payload}, handle, indent=2) with httpx.Client(timeout=45.0) as client: job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key}, json=t2v_payload, ).raise_for_status().json() current = job while current.get("status") in {"queued", "submitting", "running"} or ( current.get("status") == "succeeded" and current.get("deliveryStatus") == "pending" ): params = {"waitMs": 25000} if current.get("revision"): params["afterRevision"] = current["revision"] snap = client.get( f"{origin}/v1/generations/{job['id']}/status", headers=auth, params=params, ).raise_for_status().json() current = snap.get("job", snap) completed = client.get(f"{origin}/v1/generations/{job['id']}", headers=auth).raise_for_status().json() print(completed["status"], completed["outputs"], completed.get("settledMicros")) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "t2v-example-001", "modelId": "alibaba/wan-3.0", "operation": "text-to-video", "input": { "prompt": "A wooden ferry crossing a misty fjord at dawn, slow aerial tracking shot, crisp ripples on dark blue water.", "resolution": "720p", "duration": 5, "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba/ap-southeast-1/wan-3.0", "billing": "managed", "maxCostMicros": 600000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e t2v-submission.key ]; then echo "Existing t2v-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat t2v-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="t2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > t2v-submission.key) opengen generate --input t2v-request.json --idempotency-key "$IDEMPOTENCY_KEY" > t2v-receipt.json JOB_ID="$(jq -r '.id' t2v-receipt.json)" opengen job wait "$JOB_ID" --timeout-ms 900000 opengen job get "$JOB_ID" ``` ## 4. Handle timeouts, cancellation, and delivery safely - **Separate observations:** upstream `status: "succeeded"`, private archive `deliveryStatus: "available"`, and billing `settledMicros` are independent states. Wait for `deliveryStatus: "available"` before downloading, and never assume `settledMicros: null` means free. - **No blind retries:** if `POST /v1/generations` times out, look up the original key with `GET /v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY` (CLI `opengen job recover --idempotency-key "$IDEMPOTENCY_KEY"`). If the job enters `submission-unknown`, keep the receipt and reconcile through your installation operator. - **Explicit cancellation:** `POST /v1/generations/{id}/cancel` requests cancellation, but running upstream video tasks may reject cancellation and cancellation does not establish refundability. ## Next steps - Start from an owned still frame instead of text alone in [Image to Video](/docs/guides/image-to-video). - Reuse your generated video clip directly in [Video Editing](/docs/guides/video-edit) or [Video Extension](/docs/guides/video-extend). - Receive completion callbacks without polling in [Next.js Webhook Verification](/docs/guides/webhooks-nextjs). ## Supported Models Live catalog variants supporting `text-to-video` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Wan 3.0](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0) | `alibaba/wan-3.0` | Alibaba | 10 | $0.0325 / sec | Closed | `GET /v1/models/alibaba/wan-3.0?operation=text-to-video` | | [Wan 3.0 Prime](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0-prime) | `alibaba/wan-3.0-prime` | Alibaba | 10 | $0.051 / sec | Closed | `GET /v1/models/alibaba/wan-3.0-prime?operation=text-to-video` | | [HappyHorse 1.1](https://opengen.dev/alibaba/happy-horse-1.1#variant-alibaba-happy-horse-1.1) | `alibaba/happy-horse-1.1` | Alibaba | 6 | $0.061885 / sec | Closed | `GET /v1/models/alibaba/happy-horse-1.1?operation=text-to-video` | | [Kling 4.0](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0) | `kling/kling-4.0` | Kling AI | 5 | $0.157 / sec | Closed | `GET /v1/models/kling/kling-4.0?operation=text-to-video` | | [Kling 4.0 Flash](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0-flash) | `kling/kling-4.0-flash` | Kling AI | 3 | $0.094 / sec | Closed | `GET /v1/models/kling/kling-4.0-flash?operation=text-to-video` | | [FLUX 3 Video](https://opengen.dev/bfl/flux-3-video#variant-bfl-flux-3-video) | `bfl/flux-3-video` | Black Forest Labs | 2 | $0.15 / sec | Closed | `GET /v1/models/bfl/flux-3-video?operation=text-to-video` | | [H3 Flex · Pika](https://opengen.dev/minimax/h3#variant-pika-h3-flex) | `pika/h3-flex` | Pika | 1 | $0.01 / sec | Open weights | `GET /v1/models/pika/h3-flex?operation=text-to-video` | | [Seedance 2.0](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0) | `bytedance/seedance-2.0` | ByteDance | 6 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0?operation=text-to-video` | | [Seedance 2.0 Fast](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-fast) | `bytedance/seedance-2.0-fast` | ByteDance | 5 | ≈$0.0591 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-fast?operation=text-to-video` | | [Seedance 2.0 Mini](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-mini) | `bytedance/seedance-2.0-mini` | ByteDance | 5 | ≈$0.0369 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-mini?operation=text-to-video` | | [Seedance 2.5](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5) | `bytedance/seedance-2.5` | ByteDance | 5 | $0.1028 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5?operation=text-to-video` | | [Gemini Omni 1.1 Flash](https://opengen.dev/google/gemini-omni-1.1-flash#variant-google-gemini-omni-1.1-flash) | `google/gemini-omni-1.1-flash` | Google | 5 | $0.03 / sec | Closed | `GET /v1/models/google/gemini-omni-1.1-flash?operation=text-to-video` | | [MiniMax H3](https://opengen.dev/minimax/h3#variant-minimax-h3) | `minimax/h3` | MiniMax | 5 | $0.05 / sec | Open weights | `GET /v1/models/minimax/h3?operation=text-to-video` | | [Seedance 2.5 Flash](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5-flash) | `bytedance/seedance-2.5-flash` | ByteDance | 4 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5-flash?operation=text-to-video` | | [Gemini Omni 1.2 Flash](https://opengen.dev/google/gemini-omni-1.2-flash#variant-google-gemini-omni-1.2-flash) | `google/gemini-omni-1.2-flash` | Google | 3 | $0.02 / sec | Closed | `GET /v1/models/google/gemini-omni-1.2-flash?operation=text-to-video` | | [MiniMax H3 Max](https://opengen.dev/minimax/h3#variant-minimax-h3-max) | `minimax/h3-max` | MiniMax | 3 | $0.05 / sec | Closed | `GET /v1/models/minimax/h3-max?operation=text-to-video` | | [Grok Imagine Video 1.5](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video-1.5) | `xai/grok-imagine-video-1.5` | xAI | 3 | $0.08 / sec | Closed | `GET /v1/models/xai/grok-imagine-video-1.5?operation=text-to-video` | | [Grok Imagine Video 1.5 Lite](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video-1.5-lite) | `xai/grok-imagine-video-1.5-lite` | xAI | 3 | $0.02 / sec | Closed | `GET /v1/models/xai/grok-imagine-video-1.5-lite?operation=text-to-video` | | [Seedance 1.0 Pro](https://opengen.dev/bytedance/seedance-1.0#variant-bytedance-seedance-1.0-pro) | `bytedance/seedance-1.0-pro` | ByteDance | 2 | ≈$0.0251 / sec | Closed | `GET /v1/models/bytedance/seedance-1.0-pro?operation=text-to-video` | | [Seedance 1.0 Pro Fast](https://opengen.dev/bytedance/seedance-1.0#variant-bytedance-seedance-1.0-pro-fast) | `bytedance/seedance-1.0-pro-fast` | ByteDance | 2 | ≈$0.01 / sec | Closed | `GET /v1/models/bytedance/seedance-1.0-pro-fast?operation=text-to-video` | | [MiniMax H3 Highspeed](https://opengen.dev/minimax/h3#variant-minimax-h3-highspeed) | `minimax/h3-highspeed` | MiniMax | 2 | $0.03 / sec | Closed | `GET /v1/models/minimax/h3-highspeed?operation=text-to-video` | | [MiniMax H3 Lite](https://opengen.dev/minimax/h3#variant-minimax-h3-lite) | `minimax/h3-lite` | MiniMax | 2 | $0.0125 / sec | Closed | `GET /v1/models/minimax/h3-lite?operation=text-to-video` | | [FLUX 3 Max Video · fal](https://opengen.dev/bfl/flux-3-video#variant-fal-flux-3-max-video) | `fal/flux-3-max-video` | fal | 1 | $0.17 / sec | Closed | `GET /v1/models/fal/flux-3-max-video?operation=text-to-video` | | [H3 Max Turbo · fal](https://opengen.dev/minimax/h3#variant-fal-h3-max-turbo) | `fal/h3-max-turbo` | fal | 1 | $0.025 / sec | Closed | `GET /v1/models/fal/h3-max-turbo?operation=text-to-video` | --- Source: https://opengen.dev/docs/guides/image-to-video.md (Reviewed 2026-12-02) # Animate an owned image into video > OpenGen image-to-video animates workspace-private start and optional end frames across 25 video models without publishing your source media. Upload your image through POST /v1/assets until state is ready, place its assetKey in input.firstFrame, run POST /v1/pricing/estimate to verify route capabilities and cost, submit once with a persisted Idempotency-Key, and resume or recover read-only until private video delivery is available. ## Agent Prompt ```text Walk me through an image-to-video generation on OpenGen (https://opengen.dev): 1. Discover image-to-video models with GET https://opengen.dev/v1/models?operation=image-to-video&inputRole=firstFrame (or MCP find_models with operation="image-to-video", inputRole="firstFrame"). 2. Inspect the exact chosen model via GET https://opengen.dev/v1/models/{provider}/{model}?operation=image-to-video (or MCP get_model, e.g. id="bytedance/seedance-2.5", operation="image-to-video") to verify supported resolutions, duration bounds, firstFrame/lastFrame support, regional routes, and published pricing. 3. Upload the user's private image via POST https://opengen.dev/v1/assets (or MCP upload_asset / upload_attachment) and require state="ready" before placing its assetKey in input.firstFrame. 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and wait for my confirmation of the selected route, billing payer, and maxCostMicros spend cap. 5. Persist a unique Idempotency-Key and submit once via POST https://opengen.dev/v1/generations or MCP generate, then follow via job_get(id, afterRevision, waitMs=25000) without ever resubmitting under a new key. ``` OpenGen `image-to-video` animates an owned start frame (and optional end frame or keyframes on supported models) while keeping both input media and generated clips private to your workspace. ## Prerequisites - An OpenGen credential with `read` and `generate` scopes (`OPENGEN_API_KEY`, OAuth MCP at `https://opengen.dev/mcp`, or `@opengen-dev/cli` browser login via `opengen login && opengen doctor`). - A valid PNG, JPEG, or WebP image you own or have permission to animate (up to `4 MiB` for single-step multipart upload or up to `100 MiB` via presigned single-PUT). ## 1. Inspect the exact model, frame roles, and routes Check which frame controls your exact variant supports before uploading: - [Seedance 2.5](/bytedance/seedance-2.5) (`bytedance/seedance-2.5`): `firstFrame` and optional `lastFrame`, `480p`/`720p`/`1080p`, `4`–`30` seconds (or `"auto"`), `aspectRatio: "source"`. Native BytePlus prohibits mixing strict frames with `references`. - [Wan 3.0](/alibaba/wan-3.0) (`alibaba/wan-3.0`): Singapore route `alibaba/ap-southeast-1/wan-3.0` is live-verified for `image-to-video` at `480p` / `2s` (higher resolutions and longer durations remain documented), supporting `480p`/`720p`/`1080p`, `2`–`30` seconds, `firstFrame` + optional `lastFrame`. - [Kling 4.0](/kling/kling-4.0) (`kling/kling-4.0`): active official adapter on `kling-ap-southeast-1/kling-kling-4.0` (live-verified for `text-to-video` at `720p` / `3s`; `image-to-video` remains `documented`), supporting `firstFrame`, `lastFrame`, and up to 10 combined `keyframes` + reference images. ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=image-to-video&inputRole=firstFrame" curl --fail-with-body \ "https://opengen.dev/v1/models/bytedance/seedance-2.5?operation=image-to-video" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch( `${origin}/v1/models/bytedance/seedance-2.5?operation=image-to-video`, ).then((r) => r.json()); console.log(detail.model.generationProfiles[0].capabilities.frames, detail.routes.length); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/bytedance/seedance-2.5", params={"operation": "image-to-video"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0]["capabilities"]["frames"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "bytedance/seedance-2.5", "operation": "image-to-video" } } ``` ```bash tab="CLI" opengen catalog search --operation image-to-video --input-role firstFrame --modality video opengen catalog get bytedance/seedance-2.5 opengen pricing --model bytedance/seedance-2.5 --operation image-to-video ``` ## 2. Upload your private first frame and verify `state: "ready"` Never publish a private reference image to a public host or pass a local file path in `assetKey`. Use single-step `POST /v1/assets` (`multipart/form-data` up to `4 MiB`) or presigned single-PUT (`<= 100 MiB` via `POST /v1/assets` `{ mediaType, size }` -> `PUT` to `uploadUrl` without your OpenGen token -> `POST /v1/assets/complete`). ```bash tab="cURL" # Single-step private upload (<= 4 MiB); for files up to 100 MiB use presigned PUT + /v1/assets/complete curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: frame-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./owned-reference.png;type=image/png" ``` ```ts tab="TypeScript" import { readFile, stat } from 'node:fs/promises'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const auth = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; const filePath = './owned-reference.png'; const { size } = await stat(filePath); // Presigned single-PUT flow (supports up to 100 MiB) const plan = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json' }, body: JSON.stringify({ mediaType: 'image/png', size }), }).then((r) => r.json()); const putRes = await fetch(plan.uploadUrl, { method: 'PUT', headers: plan.headers, // Never send OpenGen Authorization to storage body: await readFile(filePath), }); if (!putRes.ok) throw new Error(`Storage PUT failed: ${putRes.status}`); const completed = await fetch(`${origin}/v1/assets/complete`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json' }, body: JSON.stringify({ key: plan.key }), }).then((r) => r.json()); if (completed.state !== 'ready') throw new Error(`Asset not ready: ${completed.state}`); console.log(completed.assetKey); ``` ```python tab="Python" import os from pathlib import Path import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} data = Path("owned-reference.png").read_bytes() with httpx.Client(timeout=120.0) as client: plan = client.post( f"{origin}/v1/assets", headers=auth, json={"mediaType": "image/png", "size": len(data)}, ).raise_for_status().json() client.put(plan["uploadUrl"], headers=plan["headers"], content=data).raise_for_status() asset = client.post( f"{origin}/v1/assets/complete", headers=auth, json={"key": plan["key"]}, ).raise_for_status().json() assert asset["state"] == "ready" print(asset["assetKey"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "presign_prepare", "mediaType": "image/png", "size": 123456 } } ``` ```bash tab="CLI" opengen upload /absolute/path/owned-reference.png --media-type image/png ``` > [!IMPORTANT] > Over MCP with `presign_prepare`, PUT the exact file bytes directly to the returned `uploadUrl` with its supplied headers, then call `upload_asset` with `{ "source": "presign_complete", "key": "" }`. Preparation plans expire after 10 minutes. For hosted chat attachments, use `upload_attachment`; for reusing an existing OpenGen image output, use `source: "job_output"`. ## 3. Build, estimate, and review the canonical request Place the ready workspace key in `input.firstFrame` (and optionally `input.lastFrame` for start-to-end interpolation on models that support `frames.last`). Using `aspectRatio: "source"` preserves the input image's framing. Run `POST /v1/pricing/estimate` before submitting so you see exact route eligibility, published pricing, and `recommendedMaxCostMicros`. ```bash tab="cURL" set -eu umask 077 if [ -e i2v-submission.key ]; then echo "Existing i2v-submission.key found; recover read-only via GET /v1/generations/lookup before replacing i2v-request.json." >&2 exit 1 fi rm -f i2v-request.json cat <<'JSON' > i2v-request.json { "modelId": "bytedance/seedance-2.5", "operation": "image-to-video", "input": { "prompt": "A slow camera push toward the subject, keeping the original lighting and composition steady.", "firstFrame": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_FRAME_UUID.png" }, "duration": 5, "resolution": "720p", "aspectRatio": "source" }, "routeId": "byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5", "billing": "managed", "maxCostMicros": 1500000 } JSON chmod 600 i2v-request.json curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @i2v-request.json ``` ```ts tab="TypeScript" const i2vPayload = { modelId: 'bytedance/seedance-2.5', operation: 'image-to-video', input: { prompt: 'A slow camera push toward the subject, keeping the original lighting and composition steady.', firstFrame: { assetKey: completed.assetKey }, duration: 5, resolution: '720p', aspectRatio: 'source', }, routeId: 'byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5', billing: 'managed', maxCostMicros: 1500000, } as const; const estimate = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json' }, body: JSON.stringify(i2vPayload), }).then((r) => r.json()); console.log(estimate); ``` ```python tab="Python" i2v_payload = { "modelId": "bytedance/seedance-2.5", "operation": "image-to-video", "input": { "prompt": "A slow camera push toward the subject, keeping the original lighting and composition steady.", "firstFrame": {"assetKey": asset["assetKey"]}, "duration": 5, "resolution": "720p", "aspectRatio": "source", }, "routeId": "byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5", "billing": "managed", "maxCostMicros": 1500000, } with httpx.Client(timeout=30.0) as client: estimate = client.post( f"{origin}/v1/pricing/estimate", headers=auth, json=i2v_payload, ).raise_for_status().json() print(estimate) ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "bytedance/seedance-2.5", "operation": "image-to-video", "input": { "prompt": "A slow camera push toward the subject, keeping the original lighting and composition steady.", "firstFrame": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_FRAME_UUID.png" }, "duration": 5, "resolution": "720p", "aspectRatio": "source" }, "routeId": "byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5", "billing": "managed", "maxCostMicros": 1500000 } } ``` ```bash tab="CLI" opengen pricing estimate --input i2v-request.json ``` `maxCostMicros: 1500000` (`$1.50`) is an illustrative ceiling above the route's published 5-second `720p` reservation (`1,220,656` micro-USD), not a price commitment or permission to spend it. Set `billing: "byok"` only after connecting your own encrypted provider key and confirming that provider account as the payer. ## 4. Submit once and keep the receipt Save the canonical request and one unique `Idempotency-Key` in a private file (`umask 077`, refusing to overwrite an existing unresolved record) before calling `POST /v1/generations`. Save the returned job ID immediately before waiting. ```bash tab="cURL" set -eu umask 077 # Refuse to overwrite an existing unresolved submission record so retries never create a second paid job if [ -e i2v-submission.key ]; then echo "Existing i2v-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="i2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > i2v-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data @i2v-request.json > i2v-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const idempotencyKey = `i2v-${randomUUID()}`; // flag: 'wx' refuses to overwrite an existing unresolved submission record. await writeFile( 'i2v-submission.json', JSON.stringify({ idempotencyKey, payload: i2vPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const res = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify(i2vPayload), }); if (!res.ok) throw new Error(`Generation submission failed (${res.status}): ${await res.text()}`); const job = await res.json(); console.log(job.id, job.status); ``` ```python tab="Python" import json import os import uuid idempotency_key = f"i2v-{uuid.uuid4()}" # O_EXCL refuses to overwrite an existing unresolved submission record. fd = os.open("i2v-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": i2v_payload}, handle, indent=2) with httpx.Client(timeout=45.0) as client: job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key}, json=i2v_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "i2v-example-001", "modelId": "bytedance/seedance-2.5", "operation": "image-to-video", "input": { "prompt": "A slow camera push toward the subject, keeping the original lighting and composition steady.", "firstFrame": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_FRAME_UUID.png" }, "duration": 5, "resolution": "720p", "aspectRatio": "source" }, "routeId": "byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5", "billing": "managed", "maxCostMicros": 1500000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e i2v-submission.key ]; then echo "Existing i2v-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat i2v-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="i2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > i2v-submission.key) opengen generate --input i2v-request.json --idempotency-key "$IDEMPOTENCY_KEY" > i2v-receipt.json ``` ## 5. Wait, recover read-only, and refresh expiring download URLs Follow the existing job ID with `GET /v1/generations/{id}/status?waitMs=25000` (passing `afterRevision` on subsequent polls) or `opengen job wait`. If your client lost the submission response before seeing a job ID, recover read-only with the original `Idempotency-Key` via `GET /v1/generations/lookup` or `opengen job recover --idempotency-key`: ```bash tab="cURL" # Load the saved Idempotency-Key and recover read-only without resubmitting IDEMPOTENCY_KEY="$(cat i2v-submission.key)" curl --fail-with-body \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ "https://opengen.dev/v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY" # Fetch fresh ~15-minute first-party /media/... capability URLs right before downloading curl --fail-with-body \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ "https://opengen.dev/v1/generations/$JOB_ID" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; const saved = JSON.parse(await readFile('i2v-submission.json', 'utf8')) as { idempotencyKey: string; }; const recovered = await fetch( `${origin}/v1/generations/lookup?idempotencyKey=${encodeURIComponent(saved.idempotencyKey)}`, { headers: auth }, ).then((r) => r.json()); const fullJob = await fetch(`${origin}/v1/generations/${recovered.id}`, { headers: auth, }).then((r) => r.json()); console.log(fullJob.deliveryStatus, fullJob.outputs); ``` ```python tab="Python" import json from pathlib import Path saved = json.loads(Path("i2v-submission.json").read_text(encoding="utf-8")) with httpx.Client(timeout=30.0) as client: recovered = client.get( f"{origin}/v1/generations/lookup", headers=auth, params={"idempotencyKey": saved["idempotencyKey"]}, ).raise_for_status().json() full_job = client.get(f"{origin}/v1/generations/{recovered['id']}", headers=auth).raise_for_status().json() print(full_job["deliveryStatus"], full_job["outputs"]) ``` ```json tab="MCP" { "tool": "job_get", "arguments": { "idempotencyKey": "i2v-example-001" } } ``` ```bash tab="CLI" IDEMPOTENCY_KEY="$(cat i2v-submission.key)" opengen job recover --idempotency-key "$IDEMPOTENCY_KEY" opengen job resume "$JOB_ID" --timeout-ms 900000 opengen job get "$JOB_ID" ``` > [!WARNING] > A `404` on recovery does not prove a concurrent submission was rejected, and `submission-unknown` requires operator reconciliation rather than a replacement submission. Signed output URLs expire after roughly 15 minutes; call `GET /v1/generations/{id}` (or MCP `job_get`) again to receive fresh URLs while the file is retained. ## Next steps - Need multiple character, object, or audio references instead of strict start/end frames? See [Reference to Video](/docs/guides/reference-to-video). - Want to continue the finished video clip? See [Video Extension](/docs/guides/video-extend). - Review client verification boundaries in [Client Setup](/docs/clients). ## Supported Models Live catalog variants supporting `image-to-video` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Wan 3.0](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0) | `alibaba/wan-3.0` | Alibaba | 10 | $0.0325 / sec | Closed | `GET /v1/models/alibaba/wan-3.0?operation=image-to-video` | | [Wan 3.0 Prime](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0-prime) | `alibaba/wan-3.0-prime` | Alibaba | 10 | $0.051 / sec | Closed | `GET /v1/models/alibaba/wan-3.0-prime?operation=image-to-video` | | [HappyHorse 1.1](https://opengen.dev/alibaba/happy-horse-1.1#variant-alibaba-happy-horse-1.1) | `alibaba/happy-horse-1.1` | Alibaba | 6 | $0.061885 / sec | Closed | `GET /v1/models/alibaba/happy-horse-1.1?operation=image-to-video` | | [Kling 4.0](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0) | `kling/kling-4.0` | Kling AI | 5 | $0.157 / sec | Closed | `GET /v1/models/kling/kling-4.0?operation=image-to-video` | | [Kling 4.0 Flash](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0-flash) | `kling/kling-4.0-flash` | Kling AI | 3 | $0.094 / sec | Closed | `GET /v1/models/kling/kling-4.0-flash?operation=image-to-video` | | [FLUX 3 Video](https://opengen.dev/bfl/flux-3-video#variant-bfl-flux-3-video) | `bfl/flux-3-video` | Black Forest Labs | 2 | $0.15 / sec | Closed | `GET /v1/models/bfl/flux-3-video?operation=image-to-video` | | [H3 Flex · Pika](https://opengen.dev/minimax/h3#variant-pika-h3-flex) | `pika/h3-flex` | Pika | 1 | $0.01 / sec | Open weights | `GET /v1/models/pika/h3-flex?operation=image-to-video` | | [Seedance 2.0](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0) | `bytedance/seedance-2.0` | ByteDance | 6 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0?operation=image-to-video` | | [Seedance 2.0 Fast](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-fast) | `bytedance/seedance-2.0-fast` | ByteDance | 5 | ≈$0.0591 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-fast?operation=image-to-video` | | [Seedance 2.0 Mini](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-mini) | `bytedance/seedance-2.0-mini` | ByteDance | 5 | ≈$0.0369 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-mini?operation=image-to-video` | | [Seedance 2.5](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5) | `bytedance/seedance-2.5` | ByteDance | 5 | $0.1028 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5?operation=image-to-video` | | [Gemini Omni 1.1 Flash](https://opengen.dev/google/gemini-omni-1.1-flash#variant-google-gemini-omni-1.1-flash) | `google/gemini-omni-1.1-flash` | Google | 5 | $0.03 / sec | Closed | `GET /v1/models/google/gemini-omni-1.1-flash?operation=image-to-video` | | [MiniMax H3](https://opengen.dev/minimax/h3#variant-minimax-h3) | `minimax/h3` | MiniMax | 5 | $0.05 / sec | Open weights | `GET /v1/models/minimax/h3?operation=image-to-video` | | [Grok Imagine Video 1.5](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video-1.5) | `xai/grok-imagine-video-1.5` | xAI | 5 | $0.08 / sec | Closed | `GET /v1/models/xai/grok-imagine-video-1.5?operation=image-to-video` | | [Seedance 2.5 Flash](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5-flash) | `bytedance/seedance-2.5-flash` | ByteDance | 4 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5-flash?operation=image-to-video` | | [Gemini Omni 1.2 Flash](https://opengen.dev/google/gemini-omni-1.2-flash#variant-google-gemini-omni-1.2-flash) | `google/gemini-omni-1.2-flash` | Google | 3 | $0.02 / sec | Closed | `GET /v1/models/google/gemini-omni-1.2-flash?operation=image-to-video` | | [MiniMax H3 Max](https://opengen.dev/minimax/h3#variant-minimax-h3-max) | `minimax/h3-max` | MiniMax | 3 | $0.05 / sec | Closed | `GET /v1/models/minimax/h3-max?operation=image-to-video` | | [Grok Imagine Video 1.5 Lite](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video-1.5-lite) | `xai/grok-imagine-video-1.5-lite` | xAI | 3 | $0.02 / sec | Closed | `GET /v1/models/xai/grok-imagine-video-1.5-lite?operation=image-to-video` | | [Seedance 1.0 Pro](https://opengen.dev/bytedance/seedance-1.0#variant-bytedance-seedance-1.0-pro) | `bytedance/seedance-1.0-pro` | ByteDance | 2 | ≈$0.0251 / sec | Closed | `GET /v1/models/bytedance/seedance-1.0-pro?operation=image-to-video` | | [Seedance 1.0 Pro Fast](https://opengen.dev/bytedance/seedance-1.0#variant-bytedance-seedance-1.0-pro-fast) | `bytedance/seedance-1.0-pro-fast` | ByteDance | 2 | ≈$0.01 / sec | Closed | `GET /v1/models/bytedance/seedance-1.0-pro-fast?operation=image-to-video` | | [MiniMax H3 Highspeed](https://opengen.dev/minimax/h3#variant-minimax-h3-highspeed) | `minimax/h3-highspeed` | MiniMax | 2 | $0.03 / sec | Closed | `GET /v1/models/minimax/h3-highspeed?operation=image-to-video` | | [MiniMax H3 Lite](https://opengen.dev/minimax/h3#variant-minimax-h3-lite) | `minimax/h3-lite` | MiniMax | 2 | $0.0125 / sec | Closed | `GET /v1/models/minimax/h3-lite?operation=image-to-video` | | [FLUX 3 Max Video · fal](https://opengen.dev/bfl/flux-3-video#variant-fal-flux-3-max-video) | `fal/flux-3-max-video` | fal | 1 | $0.17 / sec | Closed | `GET /v1/models/fal/flux-3-max-video?operation=image-to-video` | | [H3 Max Turbo · fal](https://opengen.dev/minimax/h3#variant-fal-h3-max-turbo) | `fal/h3-max-turbo` | fal | 1 | $0.025 / sec | Closed | `GET /v1/models/fal/h3-max-turbo?operation=image-to-video` | --- Source: https://opengen.dev/docs/guides/reference-to-video.md (Reviewed 2026-12-02) # Keep subjects consistent with reference-to-video > OpenGen reference-to-video preserves characters, products, and style across 20 video models using typed input.references entries and structured Kling elements. Upload private reference media via POST /v1/assets, inspect per-type reference limits via GET /v1/models/{provider}/{model}?operation=reference-to-video, confirm pricing with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key without mixing incompatible frame modes. ## Agent Prompt ```text Walk me through a reference-to-video generation on OpenGen (https://opengen.dev): 1. Discover models supporting reference-to-video via GET https://opengen.dev/v1/models?operation=reference-to-video (or MCP find_models with operation="reference-to-video"; filter by inputRole="references.image", "references.video", "references.audio", or "elements" as needed). 2. Inspect the exact chosen model via GET https://opengen.dev/v1/models/{provider}/{model}?operation=reference-to-video (or MCP get_model, e.g. id="alibaba/happy-horse-1.1", operation="reference-to-video") to verify per-type reference caps, resolution limits, and published pricing. 3. Upload each private reference file via POST https://opengen.dev/v1/assets (or MCP upload_asset) and confirm state="ready". 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and obtain my explicit confirmation of the route and maxCostMicros spend cap. 5. Submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate, then follow via job_get(id, afterRevision, waitMs=25000) without blind resubmission. ``` OpenGen `reference-to-video` conditions video generation on one or more workspace-private subject images, reference videos, audio clips, or structured elements so characters and products stay consistent across camera moves. ## 1. Pick a model for your reference types and caps Every model enforces exact reference media types, counts, and resolution limits: - [HappyHorse 1.1](/alibaba/happy-horse-1.1) (`alibaba/happy-horse-1.1`): active official routes across Alibaba Model Studio Singapore (`alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1`), Tokyo (`ap-northeast-1`), and Virginia (`us-east-1`)—each live-verified for `text-to-video` at `480p` / `3s`, while `reference-to-video` remains `documented`. Supports up to `9` image references, `3`–`15` seconds, `480p`/`720p`/`1080p`, and always-on synchronized audio. - [Kling 4.0](/kling/kling-4.0) (`kling/kling-4.0`): active official route on `kling-ap-southeast-1/kling-kling-4.0` (live-verified for `text-to-video` at `720p` / `3s`; `reference-to-video` remains `documented`), supporting up to `10` images, `5` videos, and `3` audio clips (`15` total) plus structured `elements` (`id`, `description`, `images` or `video`, optional `voice`). - [Seedance 2.5](/bytedance/seedance-2.5) (`bytedance/seedance-2.5`): up to `30` images, `10` videos, and `10` audio clips (`50` combined), `4`–`30` seconds, `480p`–`1080p`. - [Wan 3.0](/alibaba/wan-3.0) (`alibaba/wan-3.0`): active Singapore route `alibaba/ap-southeast-1/wan-3.0` (live-verified for `text-to-video` and `image-to-video` at `480p` / `2s`; `reference-to-video` remains `documented`), up to `10` images, `5` videos, `5` audio clips, and `1` document reference. ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=reference-to-video&inputRole=references.image" curl --fail-with-body \ "https://opengen.dev/v1/models/alibaba/happy-horse-1.1?operation=reference-to-video" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch( `${origin}/v1/models/alibaba/happy-horse-1.1?operation=reference-to-video`, ).then((r) => r.json()); console.log(detail.model.generationProfiles[0].capabilities.references); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/alibaba/happy-horse-1.1", params={"operation": "reference-to-video"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0]["capabilities"]["references"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "alibaba/happy-horse-1.1", "operation": "reference-to-video" } } ``` ```bash tab="CLI" opengen catalog search --operation reference-to-video --input-role references.image opengen catalog get alibaba/happy-horse-1.1 opengen pricing --model alibaba/happy-horse-1.1 --operation reference-to-video ``` > [!NOTE] > `reference-to-video` uses typed `input.references` entries (`{ type: "image" | "video" | "audio" | "document", asset: { assetKey } }`) or Kling `input.elements`—never `input.sourceVideo`. Native BytePlus and Alibaba routes prohibit combining `firstFrame`/`lastFrame` with `references`, and `xai/grok-imagine-video-1.5` caps image-reference output at `720p`. ## 2. Upload your private reference assets Upload each reference image, video, or audio clip privately via `POST /v1/assets` and verify every returned asset reports `state: "ready"`. ```bash tab="cURL" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: ref-front-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./character-front.png;type=image/png" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Idempotency-Key: ref-side-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ -F "file=@./character-side.png;type=image/png" ``` ```ts tab="TypeScript" import { readFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; async function uploadImage(path: string, filename: string): Promise { const form = new FormData(); form.append('file', new Blob([await readFile(path)], { type: 'image/png' }), filename); const res = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Idempotency-Key': `ref-${randomUUID()}`, }, body: form, }); if (!res.ok) throw new Error(await res.text()); const asset = await res.json(); if (asset.state !== 'ready') throw new Error(`Asset not ready: ${asset.state}`); return asset.assetKey; } const frontKey = await uploadImage('./character-front.png', 'character-front.png'); const sideKey = await uploadImage('./character-side.png', 'character-side.png'); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} def upload_image(client: httpx.Client, path: str) -> str: with open(path, "rb") as fh: asset = client.post( f"{origin}/v1/assets", headers={**auth, "Idempotency-Key": f"ref-{uuid.uuid4()}"}, files={"file": (path, fh, "image/png")}, ).raise_for_status().json() assert asset["state"] == "ready" return asset["assetKey"] with httpx.Client(timeout=60.0) as client: front_key = upload_image(client, "character-front.png") side_key = upload_image(client, "character-side.png") ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, "idempotencyKey": "ref-reuse-character-front" } } ``` ```bash tab="CLI" opengen upload /absolute/path/character-front.png --media-type image/png opengen upload /absolute/path/character-side.png --media-type image/png ``` ## 3. Estimate route eligibility before submitting Order your uploaded references inside `input.references`, run `POST /v1/pricing/estimate`, and review route eligibility before submitting. > [!IMPORTANT] > On `alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1`, managed `reference-to-video` quotes are currently comparison-only (`selectedRouteId: null`). The executable example below uses `"billing": "byok"` with your connected Alibaba Model Studio credential (omit `maxCostMicros`, since BYOK bills your own provider account directly). For managed credit reservations on `reference-to-video`, inspect qualified routes on [Seedance 2.5](/bytedance/seedance-2.5) (`byteplus-modelark-ap-southeast-1/bytedance-seedance-2.5`). ```bash tab="cURL" set -eu umask 077 if [ -e r2v-submission.key ]; then echo "Existing r2v-submission.key found; recover read-only via GET /v1/generations/lookup before replacing r2v-request.json." >&2 exit 1 fi rm -f r2v-request.json cat <<'JSON' > r2v-request.json { "modelId": "alibaba/happy-horse-1.1", "operation": "reference-to-video", "input": { "prompt": "The ceramic character from the reference images walks across a sunlit studio workbench and picks up a brass wrench, steady medium shot.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_FRONT_UUID.png" } }, { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_SIDE_UUID.png" } } ], "duration": 5, "resolution": "720p", "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1", "billing": "byok" } JSON chmod 600 r2v-request.json # Dry-run estimate only (review selectedRouteId and workspaceEligibility before submitting) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @r2v-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "alibaba/happy-horse-1.1", "operation": "reference-to-video", "input": { "prompt": "The ceramic character from the reference images walks across a sunlit studio workbench and picks up a brass wrench, steady medium shot.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_FRONT_UUID.png" } }, { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_SIDE_UUID.png" } } ], "duration": 5, "resolution": "720p", "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1", "billing": "byok" } } ``` ```bash tab="CLI" opengen pricing estimate --input r2v-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming `selectedRouteId`, `workspaceEligibility`, and your BYOK billing payer. ```bash tab="cURL" set -eu umask 077 if [ -e r2v-submission.key ]; then echo "Existing r2v-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="r2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > r2v-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data @r2v-request.json > r2v-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const r2vPayload = { modelId: 'alibaba/happy-horse-1.1', operation: 'reference-to-video', input: { prompt: 'The ceramic character from the reference images walks across a sunlit studio workbench and picks up a brass wrench, steady medium shot.', references: [ { type: 'image', asset: { assetKey: frontKey } }, { type: 'image', asset: { assetKey: sideKey } }, ], duration: 5, resolution: '720p', aspectRatio: '16:9', audio: true, }, routeId: 'alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1', billing: 'byok', } as const; const auth = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; // 1. Run dry-run estimate and stop if rejected. const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: auth, body: JSON.stringify(r2vPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); // 2. Submit only when the estimate is eligible and confirmed, persisting the key exclusively first. const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `r2v-${randomUUID()}`; await writeFile( 'r2v-submission.json', JSON.stringify({ idempotencyKey, payload: r2vPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': idempotencyKey }, body: JSON.stringify(r2vPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status); } ``` ```python tab="Python" import json import os import uuid r2v_payload = { "modelId": "alibaba/happy-horse-1.1", "operation": "reference-to-video", "input": { "prompt": "The ceramic character from the reference images walks across a sunlit studio workbench and picks up a brass wrench, steady medium shot.", "references": [ {"type": "image", "asset": {"assetKey": front_key}}, {"type": "image", "asset": {"assetKey": side_key}}, ], "duration": 5, "resolution": "720p", "aspectRatio": "16:9", "audio": True, }, "routeId": "alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1", "billing": "byok", } with httpx.Client(timeout=45.0) as client: estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=r2v_payload).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"r2v-{uuid.uuid4()}" fd = os.open("r2v-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": r2v_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key}, json=r2v_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "r2v-example-001", "modelId": "alibaba/happy-horse-1.1", "operation": "reference-to-video", "input": { "prompt": "The ceramic character from the reference images walks across a sunlit studio workbench and picks up a brass wrench, steady medium shot.", "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_FRONT_UUID.png" } }, { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_SIDE_UUID.png" } } ], "duration": 5, "resolution": "720p", "aspectRatio": "16:9", "audio": true }, "routeId": "alibaba-model-studio-ap-southeast-1/alibaba-happy-horse-1.1", "billing": "byok" } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e r2v-submission.key ]; then echo "Existing r2v-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat r2v-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="r2v-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > r2v-submission.key) opengen generate --input r2v-request.json --idempotency-key "$IDEMPOTENCY_KEY" > r2v-receipt.json ``` ### Structured subject `elements` on Kling 4.0 On [Kling 4.0](/kling/kling-4.0) (`kling/kling-4.0`), you can group multi-angle images (or a reference video) under named `input.elements` entries so the prompt can address each subject explicitly (using `"billing": "byok"` while managed `reference-to-video` quotes on `kling-ap-southeast-1/kling-kling-4.0` remain comparison-only): ```json { "modelId": "kling/kling-4.0", "operation": "reference-to-video", "input": { "prompt": "Hero_Robot walks across the greenhouse and adjusts a hanging lantern while rain taps on the glass roof.", "elements": [ { "id": "Hero_Robot", "description": "Small brushed-aluminum workshop robot with amber optics", "images": [ { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_FRONT_UUID.png" }, { "assetKey": "inputs/YOUR_WORKSPACE/CHARACTER_SIDE_UUID.png" } ] } ], "duration": 5, "resolution": "720p", "aspectRatio": "16:9", "audio": true }, "routeId": "kling-ap-southeast-1/kling-kling-4.0", "billing": "byok" } ``` ## 4. Follow progress and retrieve privately Poll `GET /v1/generations/{id}/status?waitMs=25000` (or `GET /v1/generations/{id}/events` SSE / MCP `job_get`) until `deliveryStatus: "available"`, then download your private MP4 from the signed `/media/...` URL returned by `GET /v1/generations/{id}`. ## Next steps - Need to restyle or modify an existing video clip? See [Video Editing](/docs/guides/video-edit). - Need to lengthen an existing shot? See [Video Extension](/docs/guides/video-extend). - Remove backgrounds from subject reference stills first with [Background Removal](/docs/guides/background-remove). ## Supported Models Live catalog variants supporting `reference-to-video` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Wan 3.0](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0) | `alibaba/wan-3.0` | Alibaba | 8 | $0.0325 / sec | Closed | `GET /v1/models/alibaba/wan-3.0?operation=reference-to-video` | | [Wan 3.0 Prime](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0-prime) | `alibaba/wan-3.0-prime` | Alibaba | 8 | $0.051 / sec | Closed | `GET /v1/models/alibaba/wan-3.0-prime?operation=reference-to-video` | | [HappyHorse 1.1](https://opengen.dev/alibaba/happy-horse-1.1#variant-alibaba-happy-horse-1.1) | `alibaba/happy-horse-1.1` | Alibaba | 6 | $0.061885 / sec | Closed | `GET /v1/models/alibaba/happy-horse-1.1?operation=reference-to-video` | | [Kling 4.0](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0) | `kling/kling-4.0` | Kling AI | 4 | $0.157 / sec | Closed | `GET /v1/models/kling/kling-4.0?operation=reference-to-video` | | [Kling 4.0 Flash](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0-flash) | `kling/kling-4.0-flash` | Kling AI | 2 | $0.094 / sec | Closed | `GET /v1/models/kling/kling-4.0-flash?operation=reference-to-video` | | [H3 Flex · Pika](https://opengen.dev/minimax/h3#variant-pika-h3-flex) | `pika/h3-flex` | Pika | 1 | $0.03 / sec | Open weights | `GET /v1/models/pika/h3-flex?operation=reference-to-video` | | [Seedance 2.0](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0) | `bytedance/seedance-2.0` | ByteDance | 6 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0?operation=reference-to-video` | | [Seedance 2.0 Fast](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-fast) | `bytedance/seedance-2.0-fast` | ByteDance | 5 | ≈$0.0591 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-fast?operation=reference-to-video` | | [Seedance 2.0 Mini](https://opengen.dev/bytedance/seedance-2.0#variant-bytedance-seedance-2.0-mini) | `bytedance/seedance-2.0-mini` | ByteDance | 5 | ≈$0.0369 / sec | Closed | `GET /v1/models/bytedance/seedance-2.0-mini?operation=reference-to-video` | | [Seedance 2.5](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5) | `bytedance/seedance-2.5` | ByteDance | 5 | $0.1028 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5?operation=reference-to-video` | | [Gemini Omni 1.1 Flash](https://opengen.dev/google/gemini-omni-1.1-flash#variant-google-gemini-omni-1.1-flash) | `google/gemini-omni-1.1-flash` | Google | 5 | $0.03 / sec | Closed | `GET /v1/models/google/gemini-omni-1.1-flash?operation=reference-to-video` | | [MiniMax H3](https://opengen.dev/minimax/h3#variant-minimax-h3) | `minimax/h3` | MiniMax | 5 | $0.05 / sec | Open weights | `GET /v1/models/minimax/h3?operation=reference-to-video` | | [Seedance 2.5 Flash](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5-flash) | `bytedance/seedance-2.5-flash` | ByteDance | 4 | ≈$0.07 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5-flash?operation=reference-to-video` | | [Gemini Omni 1.2 Flash](https://opengen.dev/google/gemini-omni-1.2-flash#variant-google-gemini-omni-1.2-flash) | `google/gemini-omni-1.2-flash` | Google | 3 | $0.02 / sec | Closed | `GET /v1/models/google/gemini-omni-1.2-flash?operation=reference-to-video` | | [Grok Imagine Video 1.5](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video-1.5) | `xai/grok-imagine-video-1.5` | xAI | 3 | $0.08 / sec | Closed | `GET /v1/models/xai/grok-imagine-video-1.5?operation=reference-to-video` | | [MiniMax H3 Highspeed](https://opengen.dev/minimax/h3#variant-minimax-h3-highspeed) | `minimax/h3-highspeed` | MiniMax | 2 | $0.03 / sec | Closed | `GET /v1/models/minimax/h3-highspeed?operation=reference-to-video` | | [MiniMax H3 Lite](https://opengen.dev/minimax/h3#variant-minimax-h3-lite) | `minimax/h3-lite` | MiniMax | 2 | $0.0125 / sec | Closed | `GET /v1/models/minimax/h3-lite?operation=reference-to-video` | | [MiniMax H3 Max](https://opengen.dev/minimax/h3#variant-minimax-h3-max) | `minimax/h3-max` | MiniMax | 2 | $0.05 / sec | Closed | `GET /v1/models/minimax/h3-max?operation=reference-to-video` | | [H3 Max Turbo · fal](https://opengen.dev/minimax/h3#variant-fal-h3-max-turbo) | `fal/h3-max-turbo` | fal | 1 | $0.05 / sec | Closed | `GET /v1/models/fal/h3-max-turbo?operation=reference-to-video` | --- Source: https://opengen.dev/docs/guides/video-edit.md (Reviewed 2026-12-02) # Edit videos with source clips and references > OpenGen video-edit modifies an existing workspace-private clip via input.sourceVideo (uploaded up to 100 MiB or reused from an owned prior job output) or top-level previousJobId. Inspect each model's exact override restrictions with GET /v1/models/{provider}/{model}?operation=video-edit because models like FLUX 3 Video preserve source duration and dimensions, estimate cost with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key. ## Agent Prompt ```text Walk me through a video-edit generation on OpenGen (https://opengen.dev): 1. Discover models supporting video-edit via GET https://opengen.dev/v1/models?operation=video-edit (or MCP find_models with operation="video-edit"). 2. Inspect the exact model via GET https://opengen.dev/v1/models/{provider}/{model}?operation=video-edit (or MCP get_model, e.g. id="bfl/flux-3-video" or "xai/grok-imagine-video", operation="video-edit") to check which override fields (duration, resolution, aspectRatio, audio) are forbidden vs allowed. 3. Upload the source MP4/WebM via POST https://opengen.dev/v1/assets (presigned PUT up to 100 MiB) or reuse an owned OpenGen video output via POST https://opengen.dev/v1/assets with source="job_output" (or pass top-level previousJobId when supported). 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and wait for my confirmation of the selected route and maxCostMicros spend ceiling. 5. Submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate, and follow read-only via job_get until delivered. ``` OpenGen `video-edit` transforms an existing private video clip (`input.sourceVideo`) or continues a prior owned generation (`previousJobId`) with prompt-guided lighting, weather, object, or style edits. Because providers enforce very different override rules on video editing, OpenGen validates every field before admission instead of silently discarding unsupported parameters. ## 1. Check per-model `video-edit` constraints | Model | Route(s) & verification scope | Required source | Forbidden / restricted fields on `video-edit` | | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [FLUX 3 Video](/bfl/flux-3-video) (`bfl/flux-3-video`) | `bfl-undisclosed/bfl-flux-3-video` (active BFL adapter; live-verified for `text-to-video` `720p`/`5s`, `video-edit` remains `documented`) | `sourceVideo` or `previousJobId` | Preserves source clip length (up to 15s), dimensions (downscales >720p to 720p), and audio; `duration`, `resolution`, `aspectRatio`, and `audio` are rejected. Published tariff: `$0.03/s`. | | [Grok Imagine Video](/xai/grok-imagine-video?variant=xai%2Fgrok-imagine-video) (`xai/grok-imagine-video`) | `xai-undisclosed/xai-grok-imagine-video` (live-verified for `video-edit` at `720p`/`3s`; other durations/resolutions remain `documented`) | `sourceVideo` or `previousJobId` | Preserves source clip duration (`duration` is rejected); accepts `resolution` (`480p`/`720p`), `aspectRatio`, `audio`, and up to `7` image `references`. | | [Kling 4.0](/kling/kling-4.0) (`kling/kling-4.0`) | `kling-ap-southeast-1/kling-kling-4.0`, `runway-undisclosed/kling-kling-4.0` (live-verified for `text-to-video` `720p`/`3s`; `video-edit` is `documented`) | `sourceVideo` or `previousJobId` | Accepts `prompt` (required), `duration`, `resolution`, `references`, and `elements`; `audio` is always on. | | [Gemini Omni 1.2 Flash](/google/gemini-omni-1.2-flash) (`google/gemini-omni-1.2-flash`) | Documented routes | `sourceVideo` or `previousJobId` | Supports stateful `previousJobId` continuation pinned to the originating deployment and model version. | ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=video-edit" curl --fail-with-body \ "https://opengen.dev/v1/models/bfl/flux-3-video?operation=video-edit" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch(`${origin}/v1/models/bfl/flux-3-video?operation=video-edit`).then((r) => r.json(), ); console.log(detail.model.generationProfiles[0].commonArguments); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/bfl/flux-3-video", params={"operation": "video-edit"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0]["commonArguments"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "bfl/flux-3-video", "operation": "video-edit" } } ``` ```bash tab="CLI" opengen catalog search --operation video-edit opengen catalog get bfl/flux-3-video opengen pricing --model bfl/flux-3-video --operation video-edit ``` ## 2. Upload a private MP4/WebM or reuse a prior OpenGen video output For local video clips (up to **100 MiB** MP4 or WebM), use the presigned single-PUT flow (`POST /v1/assets` -> storage `PUT` -> `POST /v1/assets/complete`). If the clip was generated by an earlier OpenGen job in the same workspace, skip re-uploading completely and copy it server-side with `source: "job_output"`: ```bash tab="cURL" # Reuse a completed OpenGen video output as an independent ready input asset curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: reuse-vid-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ --data '{ "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0 }' ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const auth = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const reused = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': `reuse-vid-${randomUUID()}` }, body: JSON.stringify({ source: 'job_output', sourceJobId: '550e8400-e29b-41d4-a716-446655440000', outputIndex: 0, }), }).then((r) => r.json()); console.log(reused.assetKey, reused.state); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with httpx.Client(timeout=60.0) as client: reused = client.post( f"{origin}/v1/assets", headers={**auth, "Idempotency-Key": f"reuse-vid-{uuid.uuid4()}"}, json={ "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, }, ).raise_for_status().json() print(reused["assetKey"], reused["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, "idempotencyKey": "reuse-vid-001" } } ``` ```bash tab="CLI" # For a local clip up to 100 MiB: opengen upload /absolute/path/source-clip.mp4 --media-type video/mp4 ``` ## 3. Estimate route eligibility before submitting Notice that `bfl/flux-3-video` on `video-edit` accepts only `prompt` and `sourceVideo` (plus optional `count`). > [!IMPORTANT] > Because `video-edit` pricing depends on the decoded duration and dimensions of `input.sourceVideo`, managed `video-edit` quotes on `bfl-undisclosed/bfl-flux-3-video` (and other `video-edit` routes in the current catalog) are **comparison-only** (`estimatedCostMicros: null`, `selectedRouteId: null`, reason `"Request price is not qualified; comparison only."`). To execute live `video-edit` jobs today, connect your own provider credential and submit with `"billing": "byok"` (your connected provider account is billed directly; omit `maxCostMicros`, since OpenGen cannot enforce a spend cap on direct BYOK charges). ```bash tab="cURL" set -eu umask 077 if [ -e video-edit-submission.key ]; then echo "Existing video-edit-submission.key found; recover read-only via GET /v1/generations/lookup before replacing video-edit-request.json." >&2 exit 1 fi rm -f video-edit-request.json cat <<'JSON' > video-edit-request.json { "modelId": "bfl/flux-3-video", "operation": "video-edit", "input": { "prompt": "Change the overcast sky to warm golden-hour sunlight and add gentle reflections on the wet pavement.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" } }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } JSON chmod 600 video-edit-request.json # Dry-run estimate only (review selectedRouteId and workspaceEligibility before submitting) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @video-edit-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "bfl/flux-3-video", "operation": "video-edit", "input": { "prompt": "Change the overcast sky to warm golden-hour sunlight and add gentle reflections on the wet pavement.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" } }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } } ``` ```bash tab="CLI" opengen pricing estimate --input video-edit-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming `selectedRouteId`, `workspaceEligibility`, and your BYOK billing payer. ```bash tab="cURL" set -eu umask 077 if [ -e video-edit-submission.key ]; then echo "Existing video-edit-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="vedit-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > video-edit-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data @video-edit-request.json > video-edit-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const editVideoPayload = { modelId: 'bfl/flux-3-video', operation: 'video-edit', input: { prompt: 'Change the overcast sky to warm golden-hour sunlight and add gentle reflections on the wet pavement.', sourceVideo: { assetKey: reused.assetKey }, }, routeId: 'bfl-undisclosed/bfl-flux-3-video', billing: 'byok', } as const; const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: auth, body: JSON.stringify(editVideoPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `vedit-${randomUUID()}`; await writeFile( 'video-edit-submission.json', JSON.stringify({ idempotencyKey, payload: editVideoPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': idempotencyKey }, body: JSON.stringify(editVideoPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status); } ``` ```python tab="Python" import json import os import uuid edit_video_payload = { "modelId": "bfl/flux-3-video", "operation": "video-edit", "input": { "prompt": "Change the overcast sky to warm golden-hour sunlight and add gentle reflections on the wet pavement.", "sourceVideo": {"assetKey": reused["assetKey"]}, }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok", } with httpx.Client(timeout=45.0) as client: estimate = client.post( f"{origin}/v1/pricing/estimate", headers=auth, json=edit_video_payload, ).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"vedit-{uuid.uuid4()}" fd = os.open("video-edit-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": edit_video_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key}, json=edit_video_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "vedit-example-001", "modelId": "bfl/flux-3-video", "operation": "video-edit", "input": { "prompt": "Change the overcast sky to warm golden-hour sunlight and add gentle reflections on the wet pavement.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" } }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e video-edit-submission.key ]; then echo "Existing video-edit-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat video-edit-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="vedit-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > video-edit-submission.key) opengen generate --input video-edit-request.json --idempotency-key "$IDEMPOTENCY_KEY" > video-edit-receipt.json ``` ### Reference-guided editing on Grok Imagine Video If you want to specify target resolution (`480p` or `720p`) or supply reference images alongside `sourceVideo`, use [Grok Imagine Video](/xai/grok-imagine-video?variant=xai%2Fgrok-imagine-video) (`xai/grok-imagine-video`, omitting `duration`, with `"billing": "byok"` since managed `video-edit` quotes are comparison-only): ```json { "modelId": "xai/grok-imagine-video", "operation": "video-edit", "input": { "prompt": "Swap the jacket in the clip to the emerald wool coat shown in the reference image.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" }, "references": [ { "type": "image", "asset": { "assetKey": "inputs/YOUR_WORKSPACE/COAT_REF_UUID.png" } } ], "resolution": "720p", "aspectRatio": "source" }, "routeId": "xai-undisclosed/xai-grok-imagine-video", "billing": "byok" } ``` ## 4. Poll and verify delivered output Poll `GET /v1/generations/{id}/status?waitMs=25000` (or MCP `job_get`) until `deliveryStatus: "available"`, then download privately via `GET /v1/generations/{id}`. Recover any interrupted submission read-only via `GET /v1/generations/lookup?idempotencyKey=$IDEMPOTENCY_KEY`. ## Next steps - Need to add new footage to the end of a clip instead of editing existing frames? See [Video Extension](/docs/guides/video-extend). - Learn how input pins protect tombstoned source videos during active jobs in [Owned Assets](/docs/assets). ## Supported Models Live catalog variants supporting `video-edit` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Wan 3.0](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0) | `alibaba/wan-3.0` | Alibaba | 6 | $0.041256 / sec | Closed | `GET /v1/models/alibaba/wan-3.0?operation=video-edit` | | [Wan 3.0 Prime](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0-prime) | `alibaba/wan-3.0-prime` | Alibaba | 6 | $0.0636 / sec | Closed | `GET /v1/models/alibaba/wan-3.0-prime?operation=video-edit` | | [Grok Imagine Video · Edit / Extend](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video) | `xai/grok-imagine-video` | xAI | 4 | $0.05 / sec | Closed | `GET /v1/models/xai/grok-imagine-video?operation=video-edit` | | [Kling 4.0](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0) | `kling/kling-4.0` | Kling AI | 3 | $0.157 / sec | Closed | `GET /v1/models/kling/kling-4.0?operation=video-edit` | | [Kling 4.0 Flash](https://opengen.dev/kling/kling-4.0#variant-kling-kling-4.0-flash) | `kling/kling-4.0-flash` | Kling AI | 3 | $0.094 / sec | Closed | `GET /v1/models/kling/kling-4.0-flash?operation=video-edit` | | [FLUX 3 Video](https://opengen.dev/bfl/flux-3-video#variant-bfl-flux-3-video) | `bfl/flux-3-video` | Black Forest Labs | 2 | $0.03 / sec | Closed | `GET /v1/models/bfl/flux-3-video?operation=video-edit` | | [Gemini Omni 1.1 Flash](https://opengen.dev/google/gemini-omni-1.1-flash#variant-google-gemini-omni-1.1-flash) | `google/gemini-omni-1.1-flash` | Google | 5 | $0.03 / sec | Closed | `GET /v1/models/google/gemini-omni-1.1-flash?operation=video-edit` | | [Gemini Omni 1.2 Flash](https://opengen.dev/google/gemini-omni-1.2-flash#variant-google-gemini-omni-1.2-flash) | `google/gemini-omni-1.2-flash` | Google | 3 | $0.02 / sec | Closed | `GET /v1/models/google/gemini-omni-1.2-flash?operation=video-edit` | | [Seedance 2.5](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5) | `bytedance/seedance-2.5` | ByteDance | 1 | $0.20 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5?operation=video-edit` | | [Seedance 2.5 Flash](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5-flash) | `bytedance/seedance-2.5-flash` | ByteDance | 1 | $0.13 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5-flash?operation=video-edit` | | [MiniMax H3](https://opengen.dev/minimax/h3#variant-minimax-h3) | `minimax/h3` | MiniMax | 1 | $0.08 / sec | Open weights | `GET /v1/models/minimax/h3?operation=video-edit` | --- Source: https://opengen.dev/docs/guides/video-extend.md (Reviewed 2026-12-02) # Extend video clips and continue owned jobs > OpenGen video-extend continues an existing clip across six video models using either an uploaded or reused input.sourceVideo asset or a stateful top-level previousJobId continuation pinned to the original model and deployment. Inspect route-specific duration caps via GET /v1/models/{provider}/{model}?operation=video-extend, verify spend with POST /v1/pricing/estimate, and submit once with a persisted Idempotency-Key while keeping all outputs workspace-private. ## Agent Prompt ```text Walk me through a video-extend generation on OpenGen (https://opengen.dev): 1. Discover models supporting video-extend via GET https://opengen.dev/v1/models?operation=video-extend (or MCP find_models with operation="video-extend"). 2. Inspect the exact model via GET https://opengen.dev/v1/models/{provider}/{model}?operation=video-extend (or MCP get_model, e.g. id="bfl/flux-3-video" or "google/gemini-omni-1.2-flash", operation="video-extend") to verify route-specific extension duration bounds and field restrictions. 3. Either upload/reuse a private source clip via POST https://opengen.dev/v1/assets (placed in input.sourceVideo) or pass top-level previousJobId for an owned continuation pinned to the original deployment. 4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) and wait for my confirmation of the selected route and maxCostMicros spend cap. 5. Submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate, then follow via job_get until delivered. ``` OpenGen `video-extend` lengthens an existing shot using either a workspace-private source clip (`input.sourceVideo`) or a stateful top-level `previousJobId` continuation. Every model enforces its own extension duration window and parameter rules before billing admission. ## 1. Choose an extension model and inspect route duration caps | Model | Extension duration | Key constraints on `video-extend` | | --------------------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [FLUX 3 Video](/bfl/flux-3-video) (`bfl/flux-3-video`) | `5`–`15`s on official BFL route | Active official route `bfl-undisclosed/bfl-flux-3-video` (live-verified for `text-to-video` at `720p`/`5s`; `video-extend` remains `documented`). Published continuation tariff: `$0.21/s` at `720p`, `$0.27/s` at `1080p`, `$0.31/s` at `1440p`, `$0.45/s` at `2160p`. | | [Grok Imagine Video](/xai/grok-imagine-video?variant=xai%2Fgrok-imagine-video) (`xai/grok-imagine-video`) | `1`–`15`s (`2`–`10`s on fal/Replicate) | Active official route `xai-undisclosed/xai-grok-imagine-video` (live-verified for `video-edit` at `720p`/`3s`; `video-extend` remains `documented`). Preserves source resolution (`input.resolution` is rejected on `video-extend`). | | [Gemini Omni 1.2 Flash](/google/gemini-omni-1.2-flash) (`google/gemini-omni-1.2-flash`) | `3`–`10`s per extension call | Supports stateful `previousJobId` continuation pinned to the originating deployment and model version; `audio` is always on. | | [Seedance 2.5](/bytedance/seedance-2.5) (`bytedance/seedance-2.5`) | `4`–`30`s (or `"auto"`) | Documented on Runway route; supports `480p`/`720p`/`1080p` and `aspectRatio: "source"`. | ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=video-extend" curl --fail-with-body \ "https://opengen.dev/v1/models/bfl/flux-3-video?operation=video-extend" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch(`${origin}/v1/models/bfl/flux-3-video?operation=video-extend`).then( (r) => r.json(), ); console.log(detail.pricing); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/bfl/flux-3-video", params={"operation": "video-extend"}, ).raise_for_status().json() print(detail["pricing"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "bfl/flux-3-video", "operation": "video-extend" } } ``` ```bash tab="CLI" opengen catalog search --operation video-extend opengen catalog get bfl/flux-3-video opengen pricing --model bfl/flux-3-video --operation video-extend ``` ## 2. Provide `input.sourceVideo` (upload or reuse an owned output) Upload a local MP4/WebM clip (up to `100 MiB` via presigned single-PUT + `POST /v1/assets/complete`) or promote an existing OpenGen job output into a ready workspace input with `{ "source": "job_output", "sourceJobId": "", "outputIndex": 0 }`: ```bash tab="cURL" curl --fail-with-body \ -X POST "https://opengen.dev/v1/assets" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: extend-src-$(uuidgen | tr '[:upper:]' '[:lower:]')" \ --data '{ "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0 }' ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const auth = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const sourceAsset = await fetch(`${origin}/v1/assets`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': `extend-src-${randomUUID()}` }, body: JSON.stringify({ source: 'job_output', sourceJobId: '550e8400-e29b-41d4-a716-446655440000', outputIndex: 0, }), }).then((r) => r.json()); console.log(sourceAsset.assetKey, sourceAsset.state); ``` ```python tab="Python" import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} with httpx.Client(timeout=60.0) as client: source_asset = client.post( f"{origin}/v1/assets", headers={**auth, "Idempotency-Key": f"extend-src-{uuid.uuid4()}"}, json={ "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, }, ).raise_for_status().json() print(source_asset["assetKey"], source_asset["state"]) ``` ```json tab="MCP" { "tool": "upload_asset", "arguments": { "source": "job_output", "sourceJobId": "550e8400-e29b-41d4-a716-446655440000", "outputIndex": 0, "idempotencyKey": "extend-src-001" } } ``` ```bash tab="CLI" opengen upload /absolute/path/clip-to-extend.mp4 --media-type video/mp4 ``` ## 3. Estimate route eligibility before submitting Run `POST /v1/pricing/estimate` first to confirm route and duration eligibility before submitting. > [!IMPORTANT] > Because `video-extend` billing depends on source-video duration and extension rules, managed `video-extend` quotes on `bfl-undisclosed/bfl-flux-3-video` are currently **comparison-only** (`selectedRouteId: null`). The executable example below uses `"billing": "byok"` with your connected provider account (omit `maxCostMicros`, since OpenGen cannot cap direct BYOK provider charges). ```bash tab="cURL" set -eu umask 077 if [ -e video-extend-submission.key ]; then echo "Existing video-extend-submission.key found; recover read-only via GET /v1/generations/lookup before replacing video-extend-request.json." >&2 exit 1 fi rm -f video-extend-request.json cat <<'JSON' > video-extend-request.json { "modelId": "bfl/flux-3-video", "operation": "video-extend", "input": { "prompt": "Continue the tracking shot smoothly past the lighthouse as evening clouds drift across the horizon.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" }, "duration": 5, "resolution": "720p", "aspectRatio": "source", "audio": true }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } JSON chmod 600 video-extend-request.json # Dry-run estimate only (review selectedRouteId and workspaceEligibility before submitting) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @video-extend-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "bfl/flux-3-video", "operation": "video-extend", "input": { "prompt": "Continue the tracking shot smoothly past the lighthouse as evening clouds drift across the horizon.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" }, "duration": 5, "resolution": "720p", "aspectRatio": "source", "audio": true }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } } ``` ```bash tab="CLI" opengen pricing estimate --input video-extend-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming `selectedRouteId`, `workspaceEligibility`, and your BYOK billing payer. ```bash tab="cURL" set -eu umask 077 if [ -e video-extend-submission.key ]; then echo "Existing video-extend-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="vext-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > video-extend-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data @video-extend-request.json > video-extend-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const extendPayload = { modelId: 'bfl/flux-3-video', operation: 'video-extend', input: { prompt: 'Continue the tracking shot smoothly past the lighthouse as evening clouds drift across the horizon.', sourceVideo: { assetKey: sourceAsset.assetKey }, duration: 5, resolution: '720p', aspectRatio: 'source', audio: true, }, routeId: 'bfl-undisclosed/bfl-flux-3-video', billing: 'byok', } as const; const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers: auth, body: JSON.stringify(extendPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `vext-${randomUUID()}`; await writeFile( 'video-extend-submission.json', JSON.stringify({ idempotencyKey, payload: extendPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': idempotencyKey }, body: JSON.stringify(extendPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status); } ``` ```python tab="Python" import json import os import uuid extend_payload = { "modelId": "bfl/flux-3-video", "operation": "video-extend", "input": { "prompt": "Continue the tracking shot smoothly past the lighthouse as evening clouds drift across the horizon.", "sourceVideo": {"assetKey": source_asset["assetKey"]}, "duration": 5, "resolution": "720p", "aspectRatio": "source", "audio": True, }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok", } with httpx.Client(timeout=45.0) as client: estimate = client.post( f"{origin}/v1/pricing/estimate", headers=auth, json=extend_payload, ).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"vext-{uuid.uuid4()}" fd = os.open("video-extend-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": extend_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key}, json=extend_payload, ).raise_for_status().json() print(job["id"], job["status"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "vext-example-001", "modelId": "bfl/flux-3-video", "operation": "video-extend", "input": { "prompt": "Continue the tracking shot smoothly past the lighthouse as evening clouds drift across the horizon.", "sourceVideo": { "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_VIDEO_UUID.mp4" }, "duration": 5, "resolution": "720p", "aspectRatio": "source", "audio": true }, "routeId": "bfl-undisclosed/bfl-flux-3-video", "billing": "byok" } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e video-extend-submission.key ]; then echo "Existing video-extend-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat video-extend-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="vext-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > video-extend-submission.key) opengen generate --input video-extend-request.json --idempotency-key "$IDEMPOTENCY_KEY" > video-extend-receipt.json ``` ### Stateful continuation with top-level `previousJobId` On stateful continuation models such as [Gemini Omni 1.2 Flash](/google/gemini-omni-1.2-flash) (`google/gemini-omni-1.2-flash`), you can omit `input.sourceVideo` and pass top-level `previousJobId` instead. OpenGen verifies workspace ownership and pins the continuation to the original model version and deployment (use `"billing": "byok"` while managed `video-extend` quotes remain comparison-only): ```json { "modelId": "google/gemini-omni-1.2-flash", "operation": "video-extend", "previousJobId": "550e8400-e29b-41d4-a716-446655440000", "input": { "prompt": "Keep the camera gliding through the archway as lantern light warms the courtyard.", "duration": 5, "resolution": "720p", "aspectRatio": "source" }, "routeId": "google-undisclosed/google-gemini-omni-1.2-flash", "billing": "byok" } ``` > [!NOTE] > `google/gemini-omni-1.2-flash` caps `video-extend` duration at `3`–`10` seconds per call (even though `text-to-video` allows up to `15` seconds). Submitting `duration > 10` is rejected with `400 invalid_generation`. ## 4. Follow progress and retrieve privately Poll `GET /v1/generations/{id}/status?waitMs=25000` (or `GET /v1/generations/{id}/events` / MCP `job_get`) until `deliveryStatus: "available"`, then fetch fresh signed output links via `GET /v1/generations/{id}`. ## Next steps - Need to restyle an existing clip rather than lengthen it? See [Video Editing](/docs/guides/video-edit). - Deliver video completion events to your Next.js backend via [Next.js Webhook Verification](/docs/guides/webhooks-nextjs). ## Supported Models Live catalog variants supporting `video-extend` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [Wan 3.0](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0) | `alibaba/wan-3.0` | Alibaba | 6 | $0.041256 / sec | Closed | `GET /v1/models/alibaba/wan-3.0?operation=video-extend` | | [Wan 3.0 Prime](https://opengen.dev/alibaba/wan-3.0#variant-alibaba-wan-3.0-prime) | `alibaba/wan-3.0-prime` | Alibaba | 6 | $0.0636 / sec | Closed | `GET /v1/models/alibaba/wan-3.0-prime?operation=video-extend` | | [Grok Imagine Video · Edit / Extend](https://opengen.dev/xai/grok-imagine-video#variant-xai-grok-imagine-video) | `xai/grok-imagine-video` | xAI | 3 | $0.05 / sec | Closed | `GET /v1/models/xai/grok-imagine-video?operation=video-extend` | | [FLUX 3 Video](https://opengen.dev/bfl/flux-3-video#variant-bfl-flux-3-video) | `bfl/flux-3-video` | Black Forest Labs | 2 | $0.17 / sec | Closed | `GET /v1/models/bfl/flux-3-video?operation=video-extend` | | [Gemini Omni 1.2 Flash](https://opengen.dev/google/gemini-omni-1.2-flash#variant-google-gemini-omni-1.2-flash) | `google/gemini-omni-1.2-flash` | Google | 3 | $0.02 / sec | Closed | `GET /v1/models/google/gemini-omni-1.2-flash?operation=video-extend` | | [Gemini Omni 1.1 Flash](https://opengen.dev/google/gemini-omni-1.1-flash#variant-google-gemini-omni-1.1-flash) | `google/gemini-omni-1.1-flash` | Google | 2 | ≈$0.0338 / sec | Closed | `GET /v1/models/google/gemini-omni-1.1-flash?operation=video-extend` | | [Seedance 2.5](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5) | `bytedance/seedance-2.5` | ByteDance | 1 | $0.20 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5?operation=video-extend` | | [Seedance 2.5 Flash](https://opengen.dev/bytedance/seedance-2.5#variant-bytedance-seedance-2.5-flash) | `bytedance/seedance-2.5-flash` | ByteDance | 1 | $0.13 / sec | Closed | `GET /v1/models/bytedance/seedance-2.5-flash?operation=video-extend` | | [MiniMax H3](https://opengen.dev/minimax/h3#variant-minimax-h3) | `minimax/h3` | MiniMax | 1 | $0.08 / sec | Open weights | `GET /v1/models/minimax/h3?operation=video-extend` | --- Source: https://opengen.dev/docs/guides/text-to-speech.md (Reviewed 2026-12-02) # Synthesize speech from text prompts > OpenGen models speech synthesis under the text-to-speech operation with typed voice, speed, audio outputFormat, and optional style systemPrompt controls. Inspect exact character limits and published character or token pricing for minimax/speech-02-hd and openai/gpt-4o-mini-tts via GET /v1/models/{provider}/{model}?operation=text-to-speech, run POST /v1/pricing/estimate to verify route eligibility, and submit once with a persisted Idempotency-Key when an executable route is configured. ## Agent Prompt ```text Walk me through a text-to-speech synthesis request on OpenGen (https://opengen.dev): 1. Discover speech models via GET https://opengen.dev/v1/models?operation=text-to-speech (or MCP find_models with operation="text-to-speech"). 2. Inspect minimax/speech-02-hd or openai/gpt-4o-mini-tts via GET https://opengen.dev/v1/models/{provider}/{model}?operation=text-to-speech (or MCP get_model) to verify prompt length limits, speed range, outputFormat ("mp3" or "wav"), voice, and optional systemPrompt support. 3. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) to inspect workspaceEligibility and character or token pricing disclosures. Stop and report if routes are documented/comparison-only on the current gateway. 4. Only when an executable route is eligible and I confirm the spend cap, submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate, then retrieve the private audio output via job_get. ``` OpenGen `text-to-speech` uses the same canonical generation envelope (`modelId`, `operation: "text-to-speech"`, `input`) and workspace-private delivery pipeline as image and video models, returning short-lived first-party `/media/...` links for MP3 or WAV audio files. > [!NOTE] > Verify route executability before promising live speech synthesis. In the current catalog snapshot, `minimax-undisclosed/minimax-speech-02-hd`, `fal-undisclosed/minimax-speech-02-hd`, and `openai-undisclosed/openai-gpt-4o-mini-tts` carry `status: "documented"` with no active execution adapter (comparison-only until enabled on your target gateway). Always check `workspaceEligibility` in `POST /v1/pricing/estimate`. ## 1. Compare the catalog speech models | Model | Prompt limit | Speed bounds | Extra controls | Published tariff | | ---------------------------------------------------------------------- | -------------- | ------------ | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | [MiniMax Speech-02 HD](/minimax/speech-02-hd) (`minimax/speech-02-hd`) | `10,000` chars | `0.5`–`2` | `voice`, `speed`, `outputFormat` (`mp3`/`wav`) | `$0.10` per `1,000` characters (`$100.00 / 1M` characters) across MiniMax and fal. | | [GPT-4o mini TTS](/openai/gpt-4o-mini-tts) (`openai/gpt-4o-mini-tts`) | `4,096` chars | `0.25`–`4` | `voice`, `speed`, `systemPrompt` (tone/pacing instructions), `outputFormat` (`mp3`/`wav`) | `$0.60 / 1M` text input tokens + `$12.00 / 1M` audio output tokens (estimated `~$0.015 / minute`). | `text-to-speech` rejects image/video fields (`references`, `firstFrame`, `lastFrame`, `sourceVideo`, `mask`, `resolution`, `aspectRatio`) and rejects non-audio `outputFormat` values (`png`, `jpeg`, `webp`, `mp4`) with `400 invalid_generation`. ```bash tab="cURL" curl --fail-with-body \ "https://opengen.dev/v1/models?operation=text-to-speech" curl --fail-with-body \ "https://opengen.dev/v1/models/minimax/speech-02-hd?operation=text-to-speech" curl --fail-with-body \ "https://opengen.dev/v1/models/openai/gpt-4o-mini-tts?operation=text-to-speech" ``` ```ts tab="TypeScript" const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const detail = await fetch( `${origin}/v1/models/minimax/speech-02-hd?operation=text-to-speech`, ).then((r) => r.json()); console.log(detail.model.generationProfiles[0], detail.pricing); ``` ```python tab="Python" import os import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(timeout=30.0) as client: detail = client.get( f"{origin}/v1/models/minimax/speech-02-hd", params={"operation": "text-to-speech"}, ).raise_for_status().json() print(detail["model"]["generationProfiles"][0], detail["pricing"]) ``` ```json tab="MCP" { "tool": "get_model", "arguments": { "id": "minimax/speech-02-hd", "operation": "text-to-speech" } } ``` ```bash tab="CLI" opengen catalog search --operation text-to-speech opengen catalog get minimax/speech-02-hd opengen pricing --model minimax/speech-02-hd --operation text-to-speech ``` ## 2. Estimate cost and route eligibility with MiniMax Speech-02 HD Use `POST /v1/pricing/estimate` first to check route eligibility and character-based pricing (`$0.10 / 1,000` characters). ```bash tab="cURL" set -eu umask 077 if [ -e tts-submission.key ]; then echo "Existing tts-submission.key found; recover read-only via GET /v1/generations/lookup before replacing tts-request.json." >&2 exit 1 fi rm -f tts-request.json cat <<'JSON' > tts-request.json { "modelId": "minimax/speech-02-hd", "operation": "text-to-speech", "input": { "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.", "voice": "English_CalmWoman", "speed": 1, "outputFormat": "mp3" }, "routeId": "minimax-undisclosed/minimax-speech-02-hd", "billing": "managed", "maxCostMicros": 150000 } JSON chmod 600 tts-request.json # Dry-run estimate only (review selectedRouteId, recommendedMaxCostMicros, and workspaceEligibility) curl --fail-with-body \ -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ --data @tts-request.json ``` ```json tab="MCP" { "tool": "estimate_cost", "arguments": { "modelId": "minimax/speech-02-hd", "operation": "text-to-speech", "input": { "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.", "voice": "English_CalmWoman", "speed": 1, "outputFormat": "mp3" }, "routeId": "minimax-undisclosed/minimax-speech-02-hd", "billing": "managed", "maxCostMicros": 150000 } } ``` ```bash tab="CLI" opengen pricing estimate --input tts-request.json ``` ### Submit once after reviewing the estimate Run this step only after reviewing the estimate output above and confirming an executable route is eligible (`selectedRouteId != null`, `executableCandidateCount > 0`, `blockers: []`) and confirming `maxCostMicros`. ```bash tab="cURL" set -eu umask 077 if [ -e tts-submission.key ]; then echo "Existing tts-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="tts-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > tts-submission.key) curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -H "Prefer: wait=20" \ --data @tts-request.json > tts-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', }; const ttsPayload = { modelId: 'minimax/speech-02-hd', operation: 'text-to-speech', input: { prompt: 'Welcome to OpenGen. Your private media generation job has finished and is ready to download.', voice: 'English_CalmWoman', speed: 1, outputFormat: 'mp3', }, routeId: 'minimax-undisclosed/minimax-speech-02-hd', billing: 'managed', maxCostMicros: 150000, } as const; const estRes = await fetch(`${origin}/v1/pricing/estimate`, { method: 'POST', headers, body: JSON.stringify(ttsPayload), }); if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`); const estimate = await estRes.json(); console.log('Review estimate before submitting:', estimate); const eligibility = estimate.workspaceEligibility; const canSubmit = Boolean( estimate.selectedRouteId && eligibility?.policyAllowed === true && eligibility.hasActiveBillingHold === false && eligibility.executableCandidateCount > 0 && (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) && Array.isArray(eligibility.blockers) && eligibility.blockers.length === 0, ); if (canSubmit && process.env.CONFIRM_SUBMIT === '1') { const idempotencyKey = `tts-${randomUUID()}`; await writeFile( 'tts-submission.json', JSON.stringify({ idempotencyKey, payload: ttsPayload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const genRes = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' }, body: JSON.stringify(ttsPayload), }); if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`); const job = await genRes.json(); console.log(job.id, job.status, job.outputs); } ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} tts_payload = { "modelId": "minimax/speech-02-hd", "operation": "text-to-speech", "input": { "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.", "voice": "English_CalmWoman", "speed": 1, "outputFormat": "mp3", }, "routeId": "minimax-undisclosed/minimax-speech-02-hd", "billing": "managed", "maxCostMicros": 150000, } with httpx.Client(timeout=45.0) as client: estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=tts_payload).raise_for_status().json() print("Review estimate before submitting:", estimate) eligibility = estimate.get("workspaceEligibility") or {} can_submit = ( bool(estimate.get("selectedRouteId")) and eligibility.get("policyAllowed") is True and eligibility.get("hasActiveBillingHold") is False and eligibility.get("executableCandidateCount", 0) > 0 and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True) and eligibility.get("blockers") == [] ) if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1": idempotency_key = f"tts-{uuid.uuid4()}" fd = os.open("tts-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": tts_payload}, handle, indent=2) job = client.post( f"{origin}/v1/generations", headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"}, json=tts_payload, ).raise_for_status().json() print(job["id"], job["status"], job.get("outputs")) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "tts-example-001", "modelId": "minimax/speech-02-hd", "operation": "text-to-speech", "input": { "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.", "voice": "English_CalmWoman", "speed": 1, "outputFormat": "mp3" }, "routeId": "minimax-undisclosed/minimax-speech-02-hd", "billing": "managed", "maxCostMicros": 150000, "waitMs": 20000 } } ``` ```bash tab="CLI" set -eu umask 077 if [ -e tts-submission.key ]; then echo "Existing tts-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat tts-submission.key)\"' before creating a new submission." >&2 exit 1 fi RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="tts-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" (set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > tts-submission.key) opengen generate --input tts-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > tts-receipt.json ``` ## 3. Steerable delivery instructions with GPT-4o mini TTS [GPT-4o mini TTS](/openai/gpt-4o-mini-tts) (`openai/gpt-4o-mini-tts`) adds `input.systemPrompt` to steer speaking tone, pacing, and emphasis (up to `4,096` prompt characters and `speed` `0.25`–`4`). Because audio-token output length varies dynamically, managed quotes are currently comparison-only (`selectedRouteId: null`); once an execution adapter is enabled, use `"billing": "byok"` (omitting `maxCostMicros`): ```json { "modelId": "openai/gpt-4o-mini-tts", "operation": "text-to-speech", "input": { "prompt": "Your build pipeline succeeded with zero warnings.", "voice": "coral", "speed": 1, "systemPrompt": "Speak in a calm, clear technical narration style with brief pauses between clauses.", "outputFormat": "mp3" }, "routeId": "openai-undisclosed/openai-gpt-4o-mini-tts", "billing": "byok" } ``` ## 4. Download audio privately or feed it into video Delivered MP3 (`audio/mpeg`) and WAV (`audio/wav`) outputs download over short-lived first-party `/media/...` URLs and can also be promoted into private workspace inputs with `POST /v1/assets` (`{ "source": "job_output", "sourceJobId": "", "outputIndex": 0 }`) for audio-conditioned [Reference to Video](/docs/guides/reference-to-video) workflows. ## Next steps - Pair generated narration with synchronized visual clips in [Reference to Video](/docs/guides/reference-to-video). - Compare per-unit pricing disclosures across all modalities in [Pricing and Analytics](/docs/pricing-and-analytics). ## Supported Models Live catalog variants supporting `text-to-speech` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`). | Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema | | --- | --- | --- | --- | --- | --- | --- | | [MiniMax Speech-02 HD](https://opengen.dev/minimax/speech-02-hd#variant-minimax-speech-02-hd) | `minimax/speech-02-hd` | MiniMax | 2 | $0.10 / 1k chars | Closed | `GET /v1/models/minimax/speech-02-hd?operation=text-to-speech` | | [GPT-4o mini TTS](https://opengen.dev/openai/gpt-4o-mini-tts#variant-openai-gpt-4o-mini-tts) | `openai/gpt-4o-mini-tts` | OpenAI | 1 | ≈$0.00025 / sec | Closed | `GET /v1/models/openai/gpt-4o-mini-tts?operation=text-to-speech` | --- Source: https://opengen.dev/docs/guides/webhooks-nextjs.md (Reviewed 2026-12-02) # Verify OpenGen webhooks in Next.js App Router > OpenGen delivers per-request generation lifecycle webhooks signed with Ed25519 keys published at GET /.well-known/webhook-jwks.json. Read the exact raw UTF-8 request body in a Next.js App Router Route Handler, validate all five X-OpenGen-Webhook headers and a 300-second replay window, verify the 128-character hex Ed25519 signature via node crypto, deduplicate by envelope id, and fetch private outputs separately via GET /v1/generations/{jobId}. ## Agent Prompt ```text Implement a production OpenGen webhook receiver in my Next.js App Router project against https://opengen.dev: 1. Create app/api/webhooks/opengen/route.ts with export const runtime = 'nodejs'. 2. Read the exact raw UTF-8 body via await request.text() BEFORE JSON.parse(). 3. Require all five headers: X-OpenGen-Webhook-Request-Id, X-OpenGen-Webhook-Workspace-Id, X-OpenGen-Webhook-Timestamp, X-OpenGen-Webhook-Key-Id, and X-OpenGen-Webhook-Signature. 4. Enforce a +/-300-second timestamp replay window and a 128-character lowercase hex Ed25519 signature format. 5. Fetch and cache https://opengen.dev/.well-known/webhook-jwks.json (forcing one refresh when an unknown kid appears during key rotation) and verify the Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}` using node:crypto. 6. Require a configured OPENGEN_WORKSPACE_ID (fail closed with 500 if unset), confirm envelope.id === requestId, envelope.workspaceId === workspaceId, and envelope.workspaceId === OPENGEN_WORKSPACE_ID (return 403 on mismatch), deduplicate transactionally by envelope.id, and on generation.delivery_ready fetch fresh private output links from GET https://opengen.dev/v1/generations/{jobId}. ``` OpenGen delivers generation lifecycle events to a **per-request `webhookUrl`** supplied directly on `POST /v1/generations` (or MCP `generate`). Every delivery is signed asymmetrically with **Ed25519** (`OKP` / `EdDSA`) public keys published unauthenticated at `GET https://opengen.dev/.well-known/webhook-jwks.json`, so your Next.js App Router handler needs zero shared HMAC secrets. ## 1. Pass `webhookUrl` and `webhookEvents` when submitting a job Attach `webhookUrl` (must be a public HTTPS URL on port `443` with no embedded credentials or `#fragment`) and an optional `webhookEvents` array on `POST /v1/generations`. Supported `webhookEvents` values: - `generation.started` - `generation.completed` (default) - `generation.failed` (default) - `generation.cancelled` (default) - `generation.delivery_ready` (recommended when downloading private outputs) ```bash tab="cURL" set -eu umask 077 RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="wh-job-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" SUBMISSION_JSON="$(cat <<'JSON' | jq --arg key "$IDEMPOTENCY_KEY" '{ idempotencyKey: $key, payload: . }' { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass on linen, soft studio light", "resolution": "1K", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, "webhookUrl": "https://app.example.com/api/webhooks/opengen", "webhookEvents": [ "generation.completed", "generation.failed", "generation.delivery_ready" ] } JSON )" # Atomically claim the submission record with both key and exact payload (refuses overwrite/races) (set -C; printf '%s\n' "$SUBMISSION_JSON" > webhook-job-submission.json) jq '.payload' webhook-job-submission.json | curl --fail-with-body \ -X POST "https://opengen.dev/v1/generations" \ -H "Authorization: Bearer $OPENGEN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ --data-binary @- > webhook-job-receipt.json ``` ```ts tab="TypeScript" import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const payload = { modelId: 'openai/gpt-image-2', operation: 'text-to-image', input: { prompt: 'A brass compass on linen, soft studio light', resolution: '1K', quality: 'low', outputFormat: 'png', }, routeId: 'openai-undisclosed/openai-gpt-image-2', billing: 'managed', maxCostMicros: 50000, webhookUrl: 'https://app.example.com/api/webhooks/opengen', webhookEvents: ['generation.completed', 'generation.failed', 'generation.delivery_ready'], } as const; // Save idempotencyKey + exact payload exclusively (flag: 'wx' refuses to overwrite an unresolved submission). const idempotencyKey = `wh-job-${randomUUID()}`; await writeFile( 'webhook-job-submission.json', JSON.stringify({ idempotencyKey, payload }, null, 2), { mode: 0o600, flag: 'wx' }, ); const res = await fetch(`${origin}/v1/generations`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify(payload), }); if (!res.ok) throw new Error(`Generation submission failed (${res.status}): ${await res.text()}`); const job = await res.json(); console.log(job.id); ``` ```python tab="Python" import json import os import uuid import httpx origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") payload = { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass on linen, soft studio light", "resolution": "1K", "quality": "low", "outputFormat": "png", }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, "webhookUrl": "https://app.example.com/api/webhooks/opengen", "webhookEvents": [ "generation.completed", "generation.failed", "generation.delivery_ready", ], } # Persist idempotency_key + exact payload exclusively (O_EXCL refuses to overwrite an unresolved submission). idempotency_key = f"wh-job-{uuid.uuid4()}" fd = os.open("webhook-job-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump({"idempotencyKey": idempotency_key, "payload": payload}, handle, indent=2) with httpx.Client(timeout=30.0) as client: job = client.post( f"{origin}/v1/generations", headers={ "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}", "Idempotency-Key": idempotency_key, }, json=payload, ).raise_for_status().json() print(job["id"]) ``` ```json tab="MCP" { "tool": "generate", "arguments": { "idempotencyKey": "wh-job-example-001", "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass on linen, soft studio light", "resolution": "1K", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, "webhookUrl": "https://app.example.com/api/webhooks/opengen", "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"] } } ``` ```bash tab="CLI" set -eu umask 077 RAW_UUID="$(uuidgen)" [ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; } IDEMPOTENCY_KEY="wh-job-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')" SUBMISSION_JSON="$(cat <<'JSON' | jq --arg key "$IDEMPOTENCY_KEY" '{ idempotencyKey: $key, payload: . }' { "modelId": "openai/gpt-image-2", "operation": "text-to-image", "input": { "prompt": "A brass compass on linen, soft studio light", "resolution": "1K", "quality": "low", "outputFormat": "png" }, "routeId": "openai-undisclosed/openai-gpt-image-2", "billing": "managed", "maxCostMicros": 50000, "webhookUrl": "https://app.example.com/api/webhooks/opengen", "webhookEvents": [ "generation.completed", "generation.failed", "generation.delivery_ready" ] } JSON )" # Atomically claim the submission record (key + exact payload) before writing the CLI input file (set -C; printf '%s\n' "$SUBMISSION_JSON" > webhook-job-submission.json) jq '.payload' webhook-job-submission.json > webhook-job.json chmod 600 webhook-job.json opengen generate --input webhook-job.json --idempotency-key "$IDEMPOTENCY_KEY" > webhook-job-receipt.json ``` > [!NOTE] > `webhookUrl` and `webhookEvents` are hashed into the `Idempotency-Key` request digest. Reusing the same key with a different webhook URL or event list returns `409 idempotency_conflict`. ## 2. Understand the five headers and signed message Every webhook `POST` from OpenGen sends these exact five headers: | Header | Format / Purpose | | -------------------------------- | ------------------------------------------------------------------------- | | `X-OpenGen-Webhook-Request-Id` | Unique delivery UUID (deduplication key; matches JSON envelope `id`). | | `X-OpenGen-Webhook-Workspace-Id` | Owning workspace ID (matches JSON envelope `workspaceId`). | | `X-OpenGen-Webhook-Timestamp` | Unix epoch timestamp in whole seconds (refreshed on every retry attempt). | | `X-OpenGen-Webhook-Key-Id` | Signing key `kid` published in `GET /.well-known/webhook-jwks.json`. | | `X-OpenGen-Webhook-Signature` | 128-character lowercase hex Ed25519 signature (64 raw bytes). | The canonical UTF-8 message signed by Ed25519 is: ```text {X-OpenGen-Webhook-Request-Id}\n{X-OpenGen-Webhook-Workspace-Id}\n{X-OpenGen-Webhook-Timestamp}\n{sha256Hex(rawBody)} ``` And the raw JSON envelope has this shape (prompts, credentials, and signed output URLs are intentionally omitted): ```json { "id": "delivery-uuid", "jobId": "job-uuid", "workspaceId": "workspace-id", "event": "generation.delivery_ready", "createdAt": "2026-12-02T12:00:00.000Z", "data": { "jobId": "job-uuid", "status": "succeeded", "deliveryStatus": "available" } } ``` ## 3. Create `app/api/webhooks/opengen/route.ts` Before deploying the handler, configure these required environment variables in your Next.js runtime: - **`OPENGEN_WORKSPACE_ID`** (**required**): Your OpenGen workspace ID (from `GET /v1/balance` or the [Dashboard](/app)). OpenGen signing keys are gateway-wide and any workspace can configure a public `webhookUrl`, so signature verification alone proves the event came from the gateway — not that it belongs to your workspace. The handler below fails closed with `500` when `OPENGEN_WORKSPACE_ID` is unset and rejects foreign workspaces with `403`. (Multi-tenant apps should replace the single env check with a database lookup of authorized workspace IDs.) - **`OPENGEN_API_KEY`** (**required**): A `read`-scoped (or higher) API key for fetching private outputs on `generation.delivery_ready`. - **`OPENGEN_API_URL`** (optional): Defaults to `https://opengen.dev`. Copy this complete Route Handler into your Next.js App Router project. Keep `export const runtime = 'nodejs'` so `node:crypto` Ed25519 verification works cleanly with zero third-party dependencies. ```ts import { createHash, createPublicKey, verify, type KeyObject } from 'node:crypto'; import { NextResponse } from 'next/server'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; function stripTrailingSlash(url: string): string { let end = url.length; while (end > 0 && url.charCodeAt(end - 1) === 47) end -= 1; return url.slice(0, end); } const OPENGEN_ORIGIN = stripTrailingSlash(process.env.OPENGEN_API_URL ?? 'https://opengen.dev'); const JWKS_URL = `${OPENGEN_ORIGIN}/.well-known/webhook-jwks.json`; const MAX_SKEW_SECONDS = 300; const JWKS_CACHE_TTL_MS = 60 * 60 * 1000; // Matches Cache-Control: public, max-age=3600 interface WebhookPublicJwk { kty: 'OKP'; crv: 'Ed25519'; alg?: string; use?: string; kid: string; x: string; } interface WebhookEnvelope { id: string; jobId: string; workspaceId: string; event: | 'generation.started' | 'generation.completed' | 'generation.failed' | 'generation.cancelled' | 'generation.delivery_ready'; createdAt: string; data: Record; } let cachedJwks: { fetchedAt: number; keys: Map } | null = null; async function loadVerificationKey(kid: string): Promise { const now = Date.now(); const isFresh = cachedJwks !== null && now - cachedJwks.fetchedAt < JWKS_CACHE_TTL_MS; if (isFresh && cachedJwks!.keys.has(kid)) { return cachedJwks!.keys.get(kid)!; } // Force a refresh when cache is expired OR an unknown kid arrives during key rotation. const res = await fetch(JWKS_URL, { headers: { Accept: 'application/json' }, cache: 'no-store', }); if (!res.ok) { throw new Error(`Failed to fetch OpenGen webhook JWKS (${res.status})`); } const doc = (await res.json()) as { keys?: WebhookPublicJwk[] }; const keys = new Map(); for (const jwk of doc.keys ?? []) { if ( jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.kid !== 'string' || typeof jwk.x !== 'string' ) { continue; } keys.set( jwk.kid, createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, format: 'jwk', }), ); } cachedJwks = { fetchedAt: now, keys }; return keys.get(kid) ?? null; } // Replace with a durable database table in production (see Step 4 below). const deliveryStates = new Map(); async function claimDeliveryOnce( deliveryId: string, ): Promise<'claimed' | 'completed' | 'in_flight'> { const existing = deliveryStates.get(deliveryId); if (existing === 'completed') return 'completed'; if (existing === 'pending') return 'in_flight'; deliveryStates.set(deliveryId, 'pending'); return 'claimed'; } function completeDelivery(deliveryId: string): void { deliveryStates.set(deliveryId, 'completed'); } function releaseDeliveryClaim(deliveryId: string): void { if (deliveryStates.get(deliveryId) === 'pending') { deliveryStates.delete(deliveryId); } } export async function POST(request: Request): Promise { // 0. Fail closed unless expected workspace binding is configured. const expectedWorkspaceId = process.env.OPENGEN_WORKSPACE_ID?.trim(); if (!expectedWorkspaceId) { return NextResponse.json({ error: 'webhook_workspace_unconfigured' }, { status: 500 }); } // 1. Read exact raw UTF-8 body BEFORE parsing JSON. const rawBody = await request.text(); // 2. Require all 5 OpenGen webhook headers. const requestId = request.headers.get('x-opengen-webhook-request-id')?.trim(); const workspaceId = request.headers.get('x-opengen-webhook-workspace-id')?.trim(); const timestamp = request.headers.get('x-opengen-webhook-timestamp')?.trim(); const keyId = request.headers.get('x-opengen-webhook-key-id')?.trim(); const signature = request.headers.get('x-opengen-webhook-signature')?.trim(); if (!requestId || !workspaceId || !timestamp || !keyId || !signature) { return NextResponse.json({ error: 'missing_webhook_headers' }, { status: 401 }); } // 3. Enforce numeric Unix timestamp within +/-300 seconds. if (!/^\d{1,15}$/.test(timestamp)) { return NextResponse.json({ error: 'invalid_timestamp' }, { status: 401 }); } const nowSeconds = Math.floor(Date.now() / 1000); if (Math.abs(nowSeconds - Number(timestamp)) > MAX_SKEW_SECONDS) { return NextResponse.json({ error: 'timestamp_out_of_window' }, { status: 401 }); } // 4. Require exact 128-character lowercase hex Ed25519 signature. if (!/^[0-9a-f]{128}$/.test(signature)) { return NextResponse.json({ error: 'invalid_signature_format' }, { status: 401 }); } // 5. Look up public Ed25519 key by kid (refreshing JWKS on miss). let publicKey: KeyObject | null; try { publicKey = await loadVerificationKey(keyId); } catch { return NextResponse.json({ error: 'jwks_unavailable' }, { status: 503 }); } if (!publicKey) { return NextResponse.json({ error: 'unknown_key_id' }, { status: 401 }); } // 6. Verify Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`. const bodySha256 = createHash('sha256').update(rawBody, 'utf8').digest('hex'); const signingMessage = Buffer.from( `${requestId}\n${workspaceId}\n${timestamp}\n${bodySha256}`, 'utf8', ); const sigBytes = Buffer.from(signature, 'hex'); if (!verify(null, signingMessage, publicKey, sigBytes)) { return NextResponse.json({ error: 'invalid_signature' }, { status: 401 }); } // 7. Parse JSON and confirm envelope headers match body fields. let envelope: WebhookEnvelope; try { envelope = JSON.parse(rawBody) as WebhookEnvelope; } catch { return NextResponse.json({ error: 'invalid_json' }, { status: 400 }); } if (envelope.id !== requestId || envelope.workspaceId !== workspaceId) { return NextResponse.json({ error: 'envelope_header_mismatch' }, { status: 401 }); } if (envelope.workspaceId !== expectedWorkspaceId) { return NextResponse.json({ error: 'unexpected_workspace' }, { status: 403 }); } // 8. Deduplicate at-least-once deliveries by envelope.id while keeping failed attempts retryable. const claim = await claimDeliveryOnce(envelope.id); if (claim === 'completed') { return NextResponse.json({ ok: true, deduplicated: true }); } if (claim === 'in_flight') { return NextResponse.json({ error: 'delivery_in_progress' }, { status: 409 }); } // 9. Handle the event quickly (or durably enqueue before returning 2xx within 10 seconds). // Roll back the claim and return a retryable 5xx if downstream processing fails. try { if (envelope.event === 'generation.delivery_ready') { const jobRes = await fetch( `${OPENGEN_ORIGIN}/v1/generations/${encodeURIComponent(envelope.jobId)}`, { headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }, cache: 'no-store', }, ); if (!jobRes.ok) { releaseDeliveryClaim(envelope.id); return NextResponse.json( { error: 'job_detail_unavailable', upstreamStatus: jobRes.status }, { status: 503 }, ); } const job = await jobRes.json(); // Persist job.status, job.settledMicros, and copy job.outputs to your app storage if needed. console.log('Ready outputs for job:', job.id, job.outputs?.length ?? 0); } completeDelivery(envelope.id); return NextResponse.json({ ok: true }); } catch { releaseDeliveryClaim(envelope.id); return NextResponse.json({ error: 'webhook_processing_failed' }, { status: 500 }); } } ``` ## 4. Deduplicate durably across serverless instances An in-memory `Set` only works for single-process local testing—on Vercel or multi-replica deployments, retries will hit different instances. Persist `envelope.id` inside the same database transaction as your business side effect: ```sql CREATE TABLE IF NOT EXISTS opengen_webhook_deliveries ( delivery_id UUID PRIMARY KEY, job_id UUID NOT NULL, event TEXT NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- Inside your handler transaction: INSERT INTO opengen_webhook_deliveries (delivery_id, job_id, event) VALUES ($1, $2, $3) ON CONFLICT (delivery_id) DO NOTHING RETURNING delivery_id; ``` If `RETURNING delivery_id` yields zero rows, commit immediately and return `200 OK` without repeating side effects. ## 5. Delivery, retry, and security semantics - **At-least-once retries:** OpenGen keeps the exact same `id` and raw JSON body across retries, mints a fresh `X-OpenGen-Webhook-Timestamp` and `X-OpenGen-Webhook-Signature` on every attempt, and stops after **8 attempts** with delays of `30s`, `2m`, `10m`, `30m`, `2h`, `6h`, and `24h`. - **Strict transport rules:** destinations must resolve exclusively to public IP addresses over HTTPS on port `443`. OpenGen re-validates DNS on every delivery attempt, pins the connection to the validated IP, follows **zero redirects** (`3xx` fails the attempt), times out after 10 seconds, and discards response bodies beyond `8 KiB`. - **Key rotation:** operators rotate signing keys via `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` while keeping retired public keys in `/.well-known/webhook-jwks.json`. Refreshing the JWKS cache on an unknown `kid` handles rotation with zero downtime. ## Next steps - Review full webhook concepts and Python verification examples in [Webhooks](/docs/webhooks). - Running your own OpenGen gateway and configuring `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON`? Continue to [Self-Hosting OpenGen](/docs/guides/self-hosting). --- Source: https://opengen.dev/docs/guides/self-hosting.md (Reviewed 2026-12-02) # Self-host OpenGen on Docker or Cloud Run and Vercel > OpenGen is Apache-2.0 open source and self-hosts with three Node.js 22 processes (web, api, and worker), PostgreSQL 17 with automatic transactional migrations, and private S3 or R2 object storage—with no Redis or Kubernetes required. Configure AES-256-GCM provider vault encryption, OIDC, GitHub OAuth, or Email OTP sign-in, Ed25519 webhook signing keys, and optional Cloud Run plus keyless Vercel Workload Identity Federation deployment. ## Agent Prompt ```text Help me self-host OpenGen using Docker Compose (local/single-host) or Cloud Run + Vercel (production): 1. Walk me through bootstrapping a 0600 .env file via npm run setup:local and launching PostgreSQL 17, api (:4310), worker, and web (:4320) with deploy/compose.yaml. 2. Verify GET /health reports database readiness and public catalog pages render with zero provider credentials. 3. Guide me through configuring private S3/R2 storage (S3_BUCKET, S3_ENDPOINT, S3_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), 32-byte hex MR_VAULT_KEY, OIDC/GitHub/Email OTP auth, and Ed25519 OPENGEN_WEBHOOK_SIGNING_KEYS_JSON. 4. For Cloud Run + Vercel, inspect infra/deploy-gcp.sh --plan and infra/update-gcp-image.sh --plan first with distinct API and worker service accounts and keyless Vercel Workload Identity Federation before applying any billable infrastructure. ``` OpenGen is Apache-2.0 open source and self-hosts cleanly with three Node.js 22 processes (`web`, `api`, and `worker`), PostgreSQL 17, and an S3-compatible private bucket. No Redis, Kafka, Temporal, or Kubernetes cluster is required—PostgreSQL handles durable job queues, transactional reservations, ledger accounting, and webhook outbox retries. ## Architecture and multi-stage `Dockerfile` The root `Dockerfile` builds two production targets from one TypeScript monorepo (`node:22-bookworm-slim`, running as non-root `USER node`): | Target | Port | Command | Responsibilities & secret boundary | | ----------------- | ------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `web` | `4320` | Next.js production server | Public catalog/docs/SEO UI + authenticated Playground/Dashboard BFF proxy. Receives **zero** provider keys, DB credentials, Stripe keys, or storage HMAC keys. | | `server` (API) | `4310` | `npm run dev:api` | Fastify REST + Streamable HTTP `/mcp` & `/mcp/readonly`, OAuth/OIDC/GitHub/OTP auth, `/.well-known/webhook-jwks.json`, `/media/:token` capability serving. | | `server` (Worker) | none | `npm run worker` | Continuous background poll loop executing provider adapters, archiving outputs to private S3, dispatching Ed25519 webhooks, and running bounded asset cleanup. Includes `/usr/bin/ffmpeg` and `/usr/bin/ffprobe`. Isolated from API-only session, IdP, and Stripe secrets. | ## 1. Quick start with Docker Compose and PostgreSQL 17 Generate private local cryptographic material (`POSTGRES_PASSWORD`, `MR_API_TOKEN`, `MR_VAULT_KEY`, and `MR_SESSION_SECRET`) with `0600` file permissions, then launch the full four-service stack (`db`, `api`, `worker`, `web`): ```bash git clone https://github.com/atomstobits/opengen.git cd opengen # Generates private 0600 .env without printing secrets (fails safely if .env already exists) npm run setup:local # Build and start PostgreSQL 17, API (:4310), worker, and web (:4320) docker compose --env-file .env -f deploy/compose.yaml up --build --detach --wait # Verify API health and public catalog availability (zero provider keys needed) curl --fail-with-body http://127.0.0.1:4310/health curl --fail-with-body http://127.0.0.1:4320/v1/models ``` ### Automatic PostgreSQL 17 migrations `deploy/compose.yaml` runs `postgres:17-bookworm`. On startup, `engine.initialize()` acquires a PostgreSQL transaction advisory lock (`pg_advisory_xact_lock(hashtext('media-router-schema'))`), applies contiguous migrations `001.sql` through `044.sql` from `packages/engine/migrations/`, and records each migration's SHA-256 checksum in `mr_migrations`. > [!WARNING] > Historical migrations are immutable. Never edit an already-applied `.sql` file—checksum mismatches fail startup intentionally. Before upgrading a production database with new migrations, take a verified PostgreSQL backup and quiesce admissions and workers first. ## 2. Configure private S3 / Cloudflare R2 / GCS HMAC storage Private uploaded inputs (`inputs//...`) and archived generation outputs (`outputs//...`) require a **private** S3-compatible bucket (AWS S3, Cloudflare R2, or Google Cloud Storage S3-interoperability HMAC). Never expose storage credentials to `web` or `NEXT_PUBLIC_*` variables. ```dotenv # Shared by API and worker only (never Vercel / web) S3_BUCKET=your-private-opengen-bucket S3_ENDPOINT=https://.r2.cloudflarestorage.com S3_REGION=auto AWS_ACCESS_KEY_ID=your-restricted-access-key AWS_SECRET_ACCESS_KEY=your-restricted-secret-key # Ready-input lifetime in milliseconds (604800000 = 7 days; blank disables automatic expiry) MR_INPUT_RETENTION_MS=604800000 ``` Storage requirements: - **Private ACL / block public access:** every customer input and output stays private; `api` serves temporary first-party `/media/v1...` capability links signed with `OPENGEN_MEDIA_SIGNING_SECRET` (or domain-separated `MR_SESSION_SECRET`, >= 32 characters). - **Bucket CORS for presigned browser PUTs:** allow `PUT` from your `OPENGEN_PUBLIC_URL` origin with headers `Content-Type`, `If-None-Match` (S3/R2), and `x-goog-if-generation-match` (GCS). - **No age-only bucket lifecycle deletion on `inputs/`:** OpenGen pins accepted generation inputs in PostgreSQL and performs bounded cleanup in the worker only once pins and active write leases clear. ## 3. Encrypted provider vault and provider credentials Workspace BYOK provider connections are encrypted at rest with **AES-256-GCM** using `MR_VAULT_KEY` (must be a 64-character / 32-byte hex secret; keep an offline backup separate from database backups). For operator-managed routes (`billing: "managed"`), configure only the exact provider keys you intend to serve on **both** `api` and `worker`: ```dotenv MR_VAULT_KEY=<64-hex-char-32-byte-secret> OPENGEN_EXECUTION_SCOPE=unrestricted OPENGEN_PROVIDER_EXECUTION_ENABLED=true METRICS_ORIGIN_REGION=us-central1 # Optional managed provider credentials (add only what you activate) OPENAI_API_KEY= BFL_API_KEY= KLING_API_KEY= BYTEPLUS_API_KEY= FAL_KEY= FAL_BILLING_KEY= GOOGLE_API_KEY= XAI_API_KEY= MINIMAX_API_KEY= REPLICATE_API_TOKEN= RUNWAYML_API_SECRET= PIKA_API_KEY= # Alibaba Model Studio credentials are bound per exact region: # ALIBABA_AP_SOUTHEAST_1_API_KEY / ALIBABA_AP_SOUTHEAST_1_ENDPOINT, etc. ALIBABA_AP_SOUTHEAST_1_API_KEY= ALIBABA_AP_SOUTHEAST_1_ENDPOINT= ``` Self-hosting does **not** require Stripe. Use the operator bootstrap token `MR_API_TOKEN` (`Authorization: Bearer $MR_API_TOKEN`) to create workspaces (`POST /v1/workspaces`) and grant accounting credit (`POST /v1/workspaces/{id}/credits` with `{ "amountMicros": 5000000, "reference": "unique-funding-ref" }`), or let users connect their own encrypted provider keys for `billing: "byok"`. ## 4. Configure authentication (OIDC, GitHub OAuth, and Email OTP) All identity and session secrets belong on the **API process only** (never the worker or `web` frontend). Set `OPENGEN_PUBLIC_URL` to your exact public HTTPS origin (no trailing slash) on both `api` and `web`. ```dotenv OPENGEN_PUBLIC_URL=https://opengen.example.com MR_SESSION_SECRET= # Option A: OpenID Connect (Google, Okta, Auth0, Keycloak, etc.) # Register callback URL: https://opengen.example.com/auth/callback OIDC_ISSUER=https://accounts.google.com OIDC_CLIENT_ID= OIDC_CLIENT_SECRET= OPENGEN_OIDC_DISPLAY_NAME=Google # Option B: GitHub OAuth # Register callback URL: https://opengen.example.com/auth/callback OPENGEN_GITHUB_CLIENT_ID= OPENGEN_GITHUB_CLIENT_SECRET= # Option C: Email OTP (via Resend or an HTTPS relay) OPENGEN_EMAIL_OTP_ENABLED=true RESEND_API_KEY= RESEND_FROM_EMAIL=login@opengen.example.com # Or use OPENGEN_EMAIL_OTP_RELAY_URL + OPENGEN_EMAIL_OTP_RELAY_AUTH_TOKEN + OPENGEN_EMAIL_OTP_FROM # Reverse-proxy client-IP attribution (API + web shared >=32 char HMAC secret) OPENGEN_PROXY_CLIENT_SECRET= # Optional comma-separated ingress IP/CIDR allowlist for Fastify trustProxy (never "true" or /0) OPENGEN_TRUSTED_PROXIES= # Optional single header overwritten by non-Vercel ingress (set on web) OPENGEN_TRUSTED_CLIENT_IP_HEADER= ``` Notice that both OIDC and GitHub OAuth use the exact redirect callback `${OPENGEN_PUBLIC_URL}/auth/callback`. For external OAuth resource tokens on `/mcp`, optionally set `OIDC_JWKS_URI`, `OIDC_API_AUDIENCE=https://opengen.example.com/mcp`, and `OIDC_ALLOWED_SCOPES="read generate"`. ## 5. Configure Ed25519 webhook signing keys (`OPENGEN_WEBHOOK_SIGNING_KEYS_JSON`) Both `api` (serving public JWKs at `GET /.well-known/webhook-jwks.json`) and `worker` (signing outbound webhook deliveries) load Ed25519 keys from `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` (multi-key rotation array) or single-key `OPENGEN_WEBHOOK_SIGNING_PRIVATE_KEY_PEM` / `OPENGEN_WEBHOOK_SIGNING_KEY_JWK`. Generate a fresh Ed25519 key entry locally with Node.js 22: ```bash node -e ' const { generateKeyPairSync } = require("node:crypto"); const { privateKey } = generateKeyPairSync("ed25519"); const jwk = privateKey.export({ format: "jwk" }); console.log(JSON.stringify([{ kid: "og_whk_2026_12", active: true, ...jwk }])); ' ``` To rotate keys with zero downtime, roll out in two phases so recipients never see a signature signed with an unpublished `kid`: 1. **Publish the new public key on `api` first**: add the new key's **public-only** JWK (`kty`, `crv`, `kid`, `x` — without `d` or `"active": true`) alongside the existing active key in `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` on `api`, roll out `api`, and allow recipient JWKS caches to refresh. 2. **Activate the new private key on `worker` (and `api`)**: switch `"active": true` to the new key (with `d`) while keeping the retired key's **public-only** JWK in the array during your grace window, then remove the retired key after the grace window completes: ```json [ { "kid": "og_whk_2027_01", "active": true, "kty": "OKP", "crv": "Ed25519", "x": "", "d": "" }, { "kid": "og_whk_2026_12", "kty": "OKP", "crv": "Ed25519", "x": "" } ] ``` Verify that `GET https://opengen.example.com/.well-known/webhook-jwks.json` returns **only** public keys (`kty: "OKP"`, `crv: "Ed25519"`, `alg: "EdDSA"`, `use: "sig"`, `kid`, `x`) and never exposes `d`. ## 6. Production deployment on Google Cloud Run and Vercel OpenGen's reference production topology runs the `web` frontend on **Vercel**, an IAM-private **Cloud Run service** (`opengen-api`), a continuous **Cloud Run worker pool** (`opengen-worker`), **Cloud SQL PostgreSQL 17**, and **Secret Manager** with pinned secret versions. ### Build and deploy immutable Cloud Run images Copy `infra/opengen.env.example` into git-ignored `infra/.local/opengen.env` (never commit real identifiers or secrets), configure distinct `OPENGEN_API_RUNTIME_SA` and `OPENGEN_WORKER_RUNTIME_SA` service accounts (granting per-secret Secret Manager access rather than project-wide roles), and preview before applying: ```bash # 1. Offline validation and rollout preview (zero GCP mutations) bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --plan # 2. Build Dockerfile --target server in Cloud Build and pin the exact @sha256 digest bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --build # 3. Roll out the pinned digest to both opengen-api and opengen-worker OPENGEN_BILLABLE_RUNTIME_APPROVED=yes \ bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --skip-build --apply ``` ### Connect Vercel to IAM-private Cloud Run via Workload Identity Federation Keep `opengen-api` IAM-private (no `allUsers` invoker binding) and use `deploy/cloud/vercel-project-settings.json` (`rootDirectory: "apps/web"`, Node `22.x`, root `npm ci`). Set only these **server-only** Vercel environment variables—never put provider keys, database URLs, or service-account JSON on Vercel: | Vercel env var | Purpose | | -------------------------------- | ---------------------------------------------------------------------------------------------- | | `OPENGEN_PUBLIC_URL` | Canonical public website origin (for example `https://opengen.example.com`). | | `MEDIA_ROUTER_API_URL` | Canonical HTTPS Cloud Run service origin ending in `.run.app` (no path or query). | | `GCP_WORKLOAD_IDENTITY_PROVIDER` | `projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID` | | `GCP_SERVICE_ACCOUNT_EMAIL` | Dedicated calling service account granted only `roles/run.invoker` on `opengen-api`. | | `OPENGEN_PROXY_CLIENT_SECRET` | Optional >=32-char HMAC secret shared with `opengen-api` for client-IP attribution. | At runtime, the Vercel BFF exchanges its short-lived OIDC token via Google STS and IAM Credentials into an `X-Serverless-Authorization: Bearer ` header while keeping the caller's `Authorization` header intact for workspace authentication. ## Next steps - Wire up inbound webhook verification in your app with [Next.js Webhook Verification](/docs/guides/webhooks-nextjs). - Connect local coding agents or hosted assistants to your self-hosted `/mcp` endpoint in [Client Setup](/docs/clients) and [Authentication](/docs/authentication). --- Source: https://opengen.dev/docs/errors.md (Reviewed 2026-12-02) # Errors & Recovery > OpenGen returns structured JSON error envelopes with Cache-Control no-store on every non-2xx response, exposes RateLimit, RateLimit-Policy, and Retry-After headers for backpressure, and attaches typed structuredError objects to jobs. On network timeouts or submission-unknown states, recover read-only via GET /v1/generations/lookup or MCP job_get without blind paid retries. ## Agent Prompt ```text Handle OpenGen API errors and timeouts safely using https://opengen.dev/docs/errors: 1. Never invent a new Idempotency-Key after a timeout, 5xx, or dropped connection on POST https://opengen.dev/v1/generations — call read-only GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or MCP job_get({ idempotencyKey }) first. 2. Never treat a 404 lookup on an in-flight request as proof of rejection, and NEVER submit a replacement job when status is submission-unknown or structuredError.recovery is "operator". 3. Inspect RateLimit, RateLimit-Policy, and Retry-After headers on 429 responses before backing off; only retry read/status polls automatically, or replay POST with the exact persisted Idempotency-Key and byte-identical payload. 4. On 400 invalid_generation, read error.issues[] and inspect GET https://opengen.dev/v1/models/{provider}/{model} (or get_model) to correct unsupported arguments before asking the user to re-confirm budget. ``` ## Standard error envelopes Every HTTP error response is served with `Cache-Control: no-store` and returns a consistent JSON object. Schema validation failures on canonical generation requests (`400 invalid_generation`) also attach an `issues[]` array pinpointing each offending field: ```json { "error": { "code": "invalid_generation", "message": "input.duration: Duration is outside this model capability.", "issues": [ { "code": "unsupported_duration", "field": "input.duration", "message": "Duration is outside this model capability.", "limit": "4–12", "received": 30 } ] } } ``` Over Streamable HTTP MCP (`/mcp` and `/mcp/readonly`), tool failures set `isError: true` and carry the same `{ "error": { "code", "message" } }` object in `structuredContent` and text content. ## HTTP status codes and API error codes | Status | Verified `error.code` Values | Cause & Recommended Action | | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `invalid_generation`, `invalid_input`, `idempotency_key_required`, `idempotency_required`, `invalid_prefer_header`, `invalid_status_wait`, `invalid_upload`, `invalid_asset_query`, `invalid_activity_query`, `invalid_input_url`, `invalid_input_media`, `invalid_base64` | Request failed schema, header, or container validation. Inspect `error.issues[]` or `GET /v1/models/{provider}/{model}` and fix the request before retrying | | `401` | `unauthorized` | Missing, expired, malformed, or revoked Bearer token, session cookie, or audience-mismatched OAuth token. Refresh OAuth token or rotate API key | | `402` | `insufficient_balance`, `budget_exceeded` | Workspace `availableMicros` is below the required reservation, or the route estimate exceeds `maxCostMicros`. Top up at `/billing` or adjust `maxCostMicros` with explicit user approval | | `403` | `insufficient_scope`, `policy_denied`, `origin_denied` | Token lacks `read`/`generate` scope, request violates a governance routing policy or spend cap, or a cookie-bearing request failed CSRF `Origin` validation | | `404` | `not_found`, `collection_not_found`, `generation_schema_not_found`, `asset_not_found`, `workspace_not_found` | Owned job, asset, model, or collection does not exist in this workspace. Note: `404` on `/v1/generations/lookup` is **not** proof that a still-in-flight submission failed | | `405` | `method_not_allowed` | Unsupported HTTP verb (for example `GET /mcp` returns `405` with `Allow: POST, OPTIONS`) | | `406` | `Not Acceptable` (JSON-RPC `-32000`) | MCP caller sent an `Accept` header explicitly rejecting `application/json` (such as `application/json;q=0, text/event-stream`) | | `408` | `input_download_timeout` | Public HTTPS URL import exceeded the 30-second fetch deadline | | `409` | `idempotency_conflict`, `billing_hold`, `asset_not_ready`, `asset_write_in_progress`, `job_not_terminal`, `output_purge_pending_settlement`, `output_delivery_in_progress`, `workspace_changed` | State conflict: reusing an `Idempotency-Key` with a modified body (including `webhookUrl`/`webhookEvents`), active billing hold, unready asset, or attempting to purge outputs before terminal settlement | | `410` | _(expired `/media` capability)_ | Signed first-party `/media/v1....` output link expired or job outputs were purged. Call `GET /v1/generations/{id}` (or MCP `job_get`) to mint a fresh link while retained | | `413` | `upload_too_large` | Direct upload exceeded `4 MiB` (`multipart/form-data`), `3 MiB` (REST JSON `base64`), or `64 KiB` (MCP `upload_asset` `base64`). Switch to presigned single-PUT (`<= 100 MiB`) | | `415` | `invalid_upload` | Missing `multipart/form-data` boundary or unsupported `Content-Type` | | `422` | `no_executable_route`, `invalid_generation_input`, `unsupported_operation`, `execution_scope_denied` | Valid canonical request, but no candidate route matches your `routing` constraints, BYOK credentials, or server execution scope. Inspect `POST /v1/pricing/estimate` `candidates[].reason` | | `429` | `rate_limited`, `slow_down` | Rate limit or dispatch backpressure exceeded. Honor `Retry-After` and `RateLimit` / `RateLimit-Policy` headers before retrying reads or idempotent lookups | | `503` | `database_not_configured`, `storage_not_configured`, `authentication_not_configured`, `vault_not_configured`, `webhook_signing_not_configured` | Optional installation subsystem is unconfigured on a self-hosted gateway | ## Job `structuredError` taxonomy When an admitted generation encounters an execution, policy, or delivery issue, `GET /v1/generations/{id}` and `GET /v1/generations/{id}/status` populate `structuredError` (`{ code, category, message, retryable, recovery, field?, providerCode? }`). > [!IMPORTANT] > `structuredError.retryable: true` means it is safe to **retry reading or resuming the same existing job** (`recovery: "same_job"`). It is **never** an authorization to submit a second paid generation! | `structuredError.code` | Category | `retryable` | `recovery` | Meaning | | ------------------------------- | --------------- | ----------- | -------------- | ------------------------------------------------------------------------------------ | | `invalid_input` | `invalid_input` | `false` | `edit_request` | Request contained an invalid or unsupported parameter | | `provider_invalid_input` | `invalid_input` | `false` | `edit_request` | Upstream provider rejected an input parameter | | `policy_rejected` | `policy` | `false` | `edit_request` | Rejected by applicable governance or safety policy | | `provider_policy_rejected` | `policy` | `false` | `edit_request` | Upstream provider rejected the request under its content policy | | `submission_rejected` | `unknown` | `false` | `edit_request` | Upstream provider explicitly rejected submission before execution | | `submission_unknown` | `unknown` | `false` | `operator` | Upstream acceptance could not be confirmed; hold stays active pending reconciliation | | `provider_outcome_unknown` | `unknown` | `false` | `operator` | Upstream execution outcome is unresolved; keep job for reconciliation | | `provider_failed` | `technical` | `false` | `operator` | Upstream execution failed; settlement may require reconciliation | | `status_unavailable` | `technical` | `true` | `same_job` | Upstream status check temporarily unavailable; keep polling the same job | | `capacity_full` | `technical` | `true` | `same_job` | Dispatch pool at capacity; existing queued job waits for a slot | | `input_preparation_unavailable` | `technical` | `true` | `same_job` | Accepted input package not yet ready for dispatch; keep existing job | | `delivery_unavailable` | `technical` | `true` | `same_job` | Output capture temporarily unavailable; resume reading the same job | | `delivery_failed` | `technical` | `false` | `operator` | Private output delivery failed; inspect with operator support, do not resubmit | | `delivery_expired` | `technical` | `false` | `operator` | Upstream output expired before capture; inspect with operator support | | `credentials_unavailable` | `technical` | `false` | `operator` | Original provider connection changed or unavailable for this job | | `start_deadline_exceeded` | `technical` | `false` | `none` | Local `queueStartDeadlineAt` passed before upstream submission | ## Rate limiting & backpressure headers REST responses under `/v1/*` emit standard IETF draft **`RateLimit`** and **`RateLimit-Policy`** headers so automated clients and agents can self-throttle before hitting `429`: - `RateLimit-Policy`: declares the active quota policy and window duration in seconds (for example `"public-read";q=300;w=60` on public catalog reads, `"public-estimate";q=120;w=60` on `POST /v1/pricing/estimate`, `"v1-read";q=120;w=60` on authenticated workspace reads, and `"v1-write";q=60;w=60` on authenticated mutations). - `RateLimit`: reports the active policy's remaining quota and reset countdown in seconds (for example `"public-read";r=299;t=60` or `"v1-write";r=59;t=60`). - `Retry-After`: included on `429` responses with an integer delay in seconds (for example `Retry-After: 3600` on OAuth `slow_down`, or bounded seconds on API rate limits). When you receive `429`, wait at least `Retry-After` seconds (adding small jitter) before retrying read/poll calls. Never loop tightly against `GET /v1/generations/{id}` — prefer `GET /v1/generations/{id}/events` (SSE), `GET /v1/generations/{id}/status?waitMs=25000`, or [webhooks](/docs/webhooks). ## Safe recovery playbook (timeouts & `submission-unknown`) Follow these strict rules whenever a network error or timeout interrupts a generation: 1. **Persist before submitting**: Store your generated `Idempotency-Key` and exact canonical JSON body before calling `POST /v1/generations`. 2. **Recover read-only first**: If the client disconnects before receiving the `202`/`200` response, call `GET /v1/generations/lookup?idempotencyKey=` (or MCP `job_get({ idempotencyKey })` / `opengen job recover --idempotency-key `). 3. **Never mint a replacement key blindly**: If `lookup` finds the job, persist its `id` and resume polling. If the job is in `status: "submission-unknown"`, reserved funds remain held until reconciliation confirms whether the provider accepted the task — **do not** submit a second job. 4. **Never mutate a replayed payload**: Re-sending the same `Idempotency-Key` with a different prompt, model, routing, `maxCostMicros`, `webhookUrl`, or `webhookEvents` fails with `409 idempotency_conflict`. ```bash tab="cURL" # Read-only lost-submit recovery using the exact persisted Idempotency-Key curl --fail-with-body \ "$OPENGEN_API_URL/v1/generations/lookup?idempotencyKey=$(printf '%s' "$OPENGEN_IDEMPOTENCY_KEY" | jq -sRr @uri)" \ -H "Authorization: Bearer $OPENGEN_API_KEY" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` }; async function lookupWithBackoff(idempotencyKey: string, attempts = 3) { for (let i = 0; i < attempts; i += 1) { const res = await fetch( `${baseUrl}/v1/generations/lookup?idempotencyKey=${encodeURIComponent(idempotencyKey)}`, { headers }, ); if (res.status === 429) { const retryAfter = Number(res.headers.get('Retry-After') ?? '2'); await new Promise((r) => setTimeout(r, Math.max(1, retryAfter) * 1000)); continue; } if (res.ok) return await res.json(); if (res.status === 404) return null; // Not proof rejection occurred if POST is still in flight throw new Error(`Lookup failed with HTTP ${res.status}`); } throw new Error('Rate limited while recovering job; retry lookup later without resubmitting.'); } ``` ```python tab="Python" import os import time import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"} def lookup_with_backoff(idempotency_key: str, attempts: int = 3): with httpx.Client(base_url=base_url, headers=headers, timeout=20.0) as client: for _ in range(attempts): res = client.get("/v1/generations/lookup", params={"idempotencyKey": idempotency_key}) if res.status_code == 429: delay = max(1, int(res.headers.get("Retry-After", "2"))) time.sleep(delay) continue if res.status_code == 200: return res.json() if res.status_code == 404: return None # Do not assume rejection if the original POST may still be in flight res.raise_for_status() raise RuntimeError("Rate limited during recovery; do not mint a new idempotency key.") ``` ```json tab="MCP" { "tool": "job_get", "arguments": { "idempotencyKey": "quickstart-2026-12-02-compass-01" } } ``` ```bash tab="CLI" opengen job recover --idempotency-key "$OPENGEN_IDEMPOTENCY_KEY" ``` --- Source: https://opengen.dev/docs/versioning.md (Reviewed 2026-12-03) # Versioning & HTTP Contracts > OpenGen versions its public REST API under /v1 with an OpenAPI 3.1.0 schema at GET /openapi.json covering 24 endpoints across 6 tags and gateway liveness at GET /health. Unauthenticated catalog reads carry public CDN caching and wildcard CORS, while all authenticated, private, MCP, and error responses enforce Cache-Control no-store. ## Agent Prompt ```text Verify OpenGen contract compatibility and HTTP behavior using https://opengen.dev/docs/versioning: 1. Inspect gateway liveness at GET https://opengen.dev/health and fetch the authoritative 24-endpoint OpenAPI 3.1.0 contract at GET https://opengen.dev/openapi.json (cached publicly with max-age=60, s-maxage=300 when unauthenticated). 2. Never hardcode unshipped third-party SDK imports — use raw HTTP (curl, fetch, httpx), Streamable HTTP MCP (https://opengen.dev/mcp or https://opengen.dev/mcp/readonly), or @opengen-dev/cli. 3. Always handle additive response fields gracefully, respect RateLimit / RateLimit-Policy / Retry-After headers, confirm budgets via POST https://opengen.dev/v1/pricing/estimate, and persist an Idempotency-Key before calling POST https://opengen.dev/v1/generations. ``` ## API versioning and schema contract OpenGen's Public Developer API is URL-versioned under **`/v1`** and documented by an authoritative OpenAPI **`3.1.0`** specification at **`GET /openapi.json`** (current contract version `0.1.3`, Apache-2.0 license). - **Public surface size**: **24** public endpoints grouped across **6** tags (`models`, `pricing`, `generations`, `assets`, `webhooks`, `account`). Browse them interactively at [API Reference](/docs/api). - **Gateway liveness**: **`GET /health`** is unauthenticated, CORS-enabled, and served with `Cache-Control: no-store`, returning `{ "status": "ok", "database": , "version": "0.1.3" }`. ```bash tab="cURL" # Check liveness and current contract version curl --fail-with-body -i "$OPENGEN_API_URL/health" # Inspect the live OpenAPI 3.1.0 document (CDN-cached when unauthenticated) curl --fail-with-body -I "$OPENGEN_API_URL/openapi.json" ``` ```ts tab="TypeScript" const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev'; const [health, spec] = await Promise.all([ fetch(`${baseUrl}/health`).then((r) => r.json()), fetch(`${baseUrl}/openapi.json`).then((r) => r.json()), ]); console.log(health.version, spec.openapi, Object.keys(spec.paths).length); ``` ```python tab="Python" import os import httpx base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev") with httpx.Client(base_url=base_url, timeout=15.0) as client: health = client.get("/health").raise_for_status().json() spec = client.get("/openapi.json").raise_for_status().json() print(health["version"], spec["openapi"], len(spec["paths"])) ``` ```bash tab="CLI" opengen status ``` ## Backwards compatibility policy ### Additive (non-breaking) changes Clients and AI agents should tolerate the following additive updates within `/v1`: - New exact model variants, new model series, new curated collections, and new regional deployments/routes in `@media-router/catalog`. - Optional response properties, new optional request parameters, new `structuredError.code` values, and new MCP tools or resources. - New dated pricing evidence entries or route status promotions from `documented` to `live-verified`. ### Fixed execution identities and aliases - **Exact variant IDs** (`provider/model`) and **canonical route IDs** (`deployment/model-slug`) are stable execution contracts. Distinct derivatives are never merged under a shared ID. - Where a legacy split or provider-prefixed route ID is unified, OpenGen preserves resolution through the catalog `routeAliases` table (binding operation constraints when needed so an alias cannot silently execute a conflicting operation). ### Deprecation and Sunset headers (RFC 8594) Active `/v1` endpoints omit `Deprecation` and `Sunset` headers. When an endpoint, parameter, or API version is scheduled for retirement, OpenGen follows RFC 8594 / RFC 9745 signaling and preserves these headers through the web edge proxy and CORS `Access-Control-Expose-Headers`: - **`Deprecation`**: RFC 9745 structured date (`@`) or `true` once deprecation begins. - **`Sunset`**: RFC 8594 HTTP-date announcing the scheduled removal date (minimum 30 days advance notice for non-security breaking removals). - **`Link`**: `Link: ; rel="successor-version"` pointing to the replacement endpoint or migration guide. ### Recent `/v1` surface consolidations OpenGen recently consolidated its public surface around clean, minimal primitives: - **Compact `GET /v1/models`**: omits bulky `generationProfiles` by default (~25 KB); pass `?expand=schemas` when needed or call `GET /v1/models/{provider}/{model}` / `GET /v1/models/schema` for single-model schemas. - **Unified 4-route private assets**: `POST /v1/assets` (multipart, base64, URL import, owned output reuse, presigned PUT), `POST /v1/assets/complete`, `GET /v1/assets` (list or `?key=`), and `DELETE /v1/assets` (`?key=` or JSON `{ "key": "..." }`), replacing legacy split asset action paths. - **Per-request Ed25519 webhooks**: ad-hoc `webhookUrl` + `webhookEvents` on `POST /v1/generations` verified via `GET /.well-known/webhook-jwks.json`, replacing legacy workspace webhook subscription tables. - **Stateless cost estimation**: dry-run `POST /v1/pricing/estimate` replacing legacy stateful quote flows. - **Unified documentation URLs**: all guides, client setup pages, and API references live under `/docs/**` (including `/docs/guides/*` and `/docs/clients/*`). ## CDN caching, CORS, and rate-limit contracts OpenGen enforces strict HTTP caching, CORS, and throttling invariants at the API edge: | Surface | `Cache-Control` | `Vary` | CORS (`Access-Control-Allow-Origin`) | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------- | | Unauthenticated `200 OK` `GET`/`HEAD` on `/openapi.json`, `/v1/models*`, `/v1/collections*`, `/v1/routes`, `/v1/pricing` | `public, max-age=60, s-maxage=300` | `Authorization, Cookie` | `*` (never with `Access-Control-Allow-Credentials: true`; `204` `OPTIONS` preflight `max-age=600`) | | `GET /.well-known/webhook-jwks.json` | `public, max-age=3600` | — | `*` (`GET, HEAD, OPTIONS`) | | `GET /health` | `no-store` | — | `*` (`GET, HEAD, OPTIONS`) | | Cookie-free `POST /v1/pricing/estimate` | `public, max-age=0, s-maxage=60` (unauth) / `private, no-store` (auth) | — | `*` (`POST, OPTIONS`) | | `/mcp` and `/mcp/readonly` | `no-store` (JSON) / `private, no-store, no-transform` (SSE) | `Authorization` | `*` (`POST, OPTIONS`, never with credentials) | | Any request with `Authorization` header or `og_session` cookie, all private `/v1/generations*`, `/v1/assets*`, `/v1/balance`, `/v1/analytics`, and **all error responses** | `no-store` (or `private, no-store` on `/media/*` & status streams) | `Authorization, Cookie` where applicable | No wildcard CORS on private `/v1/*` or `/auth/*` routes | - **Rate-limit headers**: `/v1/*` REST responses include standard RFC `RateLimit` and `RateLimit-Policy` headers, plus `Retry-After` on `429` responses (see [Errors & Recovery](/docs/errors)). - **Allowed & exposed CORS headers** on public CORS routes: - `Access-Control-Allow-Headers`: `Authorization, Content-Type, Accept, Idempotency-Key, Prefer, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID` - `Access-Control-Expose-Headers`: `Mcp-Session-Id, Mcp-Protocol-Version, X-Next-Cursor, Preference-Applied, WWW-Authenticate, Retry-After, RateLimit, RateLimit-Policy, Deprecation, Sunset, Link` ## Agentic Markdown discovery & `llms.txt` Every public documentation, guide, client, provider, pricing, and model page on `https://opengen.dev` is natively machine-readable for AI coding agents and crawlers: - **Explicit `.md` twins & `Accept: text/markdown`**: Append `.md` to any `/docs/**`, `/docs/clients/**`, `/docs/guides/**`, `/providers`, `/pricing`, `/[provider]`, `/[provider]/[series]`, `/about`, or `/contact` URL — or send `Accept: text/markdown` (`200 OK`, `Vary: Accept`, `Content-Type: text/markdown; charset=utf-8`). Explicit `.md` twins emit `Link: ; rel="canonical"` and `X-Robots-Tag: noindex, follow` so search engines consolidate ranking signals on canonical HTML pages while AI agents fetch Markdown freely. Unknown paths return `404` Markdown linking key entry points. - **Discovery indices**: - [`/llms.txt`](/llms.txt) — concise gateway summary and top links. - [`/docs/llms.txt`](/docs/llms.txt) — complete index of all `/docs/**.md` URLs. - [`/llms-full.txt`](/llms-full.txt) — concatenated full Markdown documentation corpus. - [`/skill.md`](/skill.md) — installable agent skill instructions. - [`/sitemap.xml`](/sitemap.xml) — unified XML sitemap with `lastmod` review dates. ## SDK & CLI policy Standalone third-party SDK distribution and language-specific framework adapters are intentionally deferred. OpenGen prioritizes: 1. Crisp, self-contained **raw HTTP** examples (`curl`, standard `fetch`, Python `httpx`) backed by OpenAPI `3.1.0`. 2. **Streamable HTTP MCP** (`/mcp` and zero-auth `/mcp/readonly`). 3. The published, zero-dependency portable CLI [**`@opengen-dev/cli`**](https://www.npmjs.com/package/@opengen-dev/cli) on npm (`Node.js 22.12+`). --- Source: https://opengen.dev/docs/faq.md (Reviewed 2026-12-02) # Frequently Asked Questions > Concise technical answers to the most common questions about OpenGen's privacy guarantees, idempotent timeout recovery, micro-USD billing and null settlement states, managed credit versus BYOK, endpoint regions versus data residency, Ed25519 webhook verification, zero-auth read-only MCP discovery, and how OpenGen compares to fal.ai and Replicate. ## Agent Prompt ```text Consult https://opengen.dev/docs/faq to answer operational, billing, privacy, and architecture questions about OpenGen accurately: 1. Never tell users that outputs are public, that null prices or settledMicros: null mean free, that cancelling a running job guarantees a refund, or that endpointRegion guarantees data residency or Zero Data Retention. 2. Always direct lost-submit or timeout recovery to read-only GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or MCP job_get({ idempotencyKey }) rather than minting a new Idempotency-Key. 3. Direct zero-auth model discovery and cost estimation to https://opengen.dev/mcp/readonly or POST https://opengen.dev/v1/pricing/estimate, and require explicit spend confirmation before calling POST https://opengen.dev/v1/generations. ``` ## Are my prompts, inputs, and generated outputs private, or is there a public gallery? Every prompt, uploaded input asset, generation job, output file, receipt, and metadata tag is strictly private to the owning workspace and its authorized credentials. OpenGen has no public generation gallery, no share or publish toggle, and no private-content SEO. Raw provider output URLs remain internal recovery data, customer downloads use short-lived first-party signed `/media/v1....` links with `Cache-Control: private, no-store` and `X-Robots-Tag: noindex, nofollow, noarchive`, and you can permanently purge retained output bytes anytime via `DELETE /v1/generations/{id}/outputs` or MCP `purge_job_outputs`. ## What happens if a generation request times out or enters submission-unknown? Persist your `Idempotency-Key` and exact JSON request payload before calling `POST /v1/generations`, and never automatically generate a new key after a timeout or disconnect. Call read-only `GET /v1/generations/lookup?idempotencyKey=...` (or MCP `job_get({ idempotencyKey })` / `opengen job recover --idempotency-key ...`) to check whether the job was admitted. If a job enters `status: "submission-unknown"`, upstream provider acceptance could not be confirmed, so reserved funds stay held pending reconciliation and you must not submit a duplicate replacement job. ## Why is settledMicros null on a generation, and does null mean free? All OpenGen monetary amounts use positive integer micro-USD (`1 USD = 1,000,000 micro-USD`), and `null` never means `$0` or free. On a generation job, `settledMicros: null` means actual billing settlement has not completed yet — for example while the job is queued, running, awaiting private delivery verification, or held in `submission-unknown` pending reconciliation. Similarly, in the public catalog (`GET /v1/pricing`), an omitted or `null` price means no deterministic per-request formula has been qualified for that route. ## What is the difference between managed credits and BYOK (Bring Your Own Key)? In `"billing": "managed"` mode, you fund a prepaid USD workspace balance in `/billing` (new personal workspaces start at `$0` with a `$5` USD minimum top-up), and OpenGen reserves a bounded `reservedMicros` ceiling at admission, settles actual cost, and releases any unused hold. In `"billing": "byok"` mode, you store your own encrypted supplier API keys per regional deployment in `/app/providers`; the provider bills your supplier account directly and OpenGen reserves `$0` managed credit. Both modes share the same canonical schemas, workspace isolation, private media delivery, and governance routing policies without mixing managed and BYOK funds. ## Does choosing an endpoint region guarantee data residency or Zero Data Retention (ZDR)? No. OpenGen separates `endpointRegion` (where the provider's API HTTP endpoint terminates), `inferenceScope` (`regional`, `mainland-china`, `international`, `global`, or `undisclosed`), `processingRegions`, and `storageRegions`. Every route attaches a `privacyDisclosure` object where unestablished processing residency, storage residency, payload history, deployment logs, retention caps, and Zero Data Retention (`zeroDataRetention`) remain `null` with `evidence: null`. Optional provider headers such as fal's `X-Fal-Store-IO: 0` are documented as opt-out controls and never establish ZDR or regional residency. ## How do I verify OpenGen webhook signatures? Pass a public HTTPS `webhookUrl` (port 443) and optional `webhookEvents` on `POST /v1/generations` or MCP `generate`, then fetch OpenGen's public Ed25519 verification keys from `GET /.well-known/webhook-jwks.json`. On each inbound webhook `POST`, read the exact raw UTF-8 body before JSON parsing, check the five `X-OpenGen-Webhook-*` headers (`Request-Id`, `Workspace-Id`, `Timestamp`, `Key-Id`, `Signature`), enforce a replay window such as `±300` seconds, and verify the 128-character lowercase hex Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`. See [Webhooks & Ed25519 Verification](/docs/webhooks) for copy-paste Node.js and Python verifiers. ## Can AI agents and IDEs inspect OpenGen models over MCP without signing in? Yes. OpenGen serves a read-only Streamable HTTP MCP endpoint at `/mcp/readonly` where `initialize`, `tools/list`, `resources/*`, `prompts/*`, public `opengen://` resources, and four discovery tools (`find_models`, `get_model`, `estimate_cost`, and `search_docs`) work with zero authentication, wildcard CORS (`Access-Control-Allow-Origin: *`), and standard `curl`/`fetch` `Accept` headers without `406` errors. Workspace-private reads (`balance`, `analytics`, `job_get`, `jobs_list`, `assets_list`) require `read` auth on `/mcp/readonly` (with RFC 9728 metadata at `/.well-known/oauth-protected-resource/mcp/readonly`), while write and billable tools require `/mcp` with `generate` scope. ## How does OpenGen differ from fal.ai and Replicate? fal.ai and Replicate are individual model-hosting inference providers, whereas OpenGen is an Apache-2.0 open-source regional multi-provider gateway and canonical schema router spanning 12 serving providers — including fal and Replicate alongside OpenAI, Google, Alibaba Cloud, BytePlus, Kling AI, MiniMax, Black Forest Labs, xAI, Runway, and Pika. OpenGen keeps exact model variant IDs intact without merging derivatives, exposes side-by-side dated pricing and honest privacy disclosures across official and third-party routes, enforces workspace-private signed delivery with no public gallery, and lets you switch between managed credits and BYOK without rewriting your application schema. ## Does cancelling a running generation guarantee a refund? No. Calling `POST /v1/generations/{id}/cancel` (or MCP `job_cancel`) on a locally `queued` job cancels it immediately (`200 OK`, `cancellationState: "confirmed"`) and releases the full reservation. Calling cancel on an already `running` upstream task returns `202 Accepted` (`cancellationState: "requested"`) and forwards a cancellation request when supported by the provider, keeping reserved credits held until terminal billing confirms whether the provider cancelled without charge. ## What are the file size limits for uploading private input assets? Through the unified `POST /v1/assets` endpoint, single-step `multipart/form-data` uploads (`file` part) support up to `4 MiB`, REST JSON `base64` uploads support up to `3 MiB` decoded, and presigned single-PUT uploads (`POST /v1/assets` followed by direct storage `PUT` and `POST /v1/assets/complete`) as well as bounded public HTTPS URL imports (`source: "url"`) support up to `100 MiB`. Over MCP, `upload_asset` caps inline `base64` strictly at `64 KiB` to protect LLM context windows and provides `source: "url"`, `source: "job_output"`, `upload_attachment`, and `presign_prepare` / `presign_complete` for larger files. ## Does OpenGen publish official TypeScript or Python SDKs? Standalone third-party SDK distribution and language-specific framework adapters are deferred. Instead, OpenGen maintains an authoritative OpenAPI `3.1.0` contract (`GET /openapi.json`), raw HTTP examples using standard `curl`, `fetch`, and Python `httpx`, Streamable HTTP MCP servers (`/mcp` and `/mcp/readonly`), and a published zero-dependency portable CLI ([`@opengen-dev/cli`](https://www.npmjs.com/package/@opengen-dev/cli) on npm). ## Are all 184 routes in the catalog live-verified on opengen.dev? No. OpenGen explicitly distinguishes `live-verified` routes (`19` routes across all `12` providers carrying scoped `liveVerification` operation, resolution, duration, and date metadata) from `documented` routes (`165` catalog routes documented from primary provider sources). Always inspect `route.status`, `route.liveVerification`, and `POST /v1/pricing/estimate` (`selectedRouteId`, `candidates[].executable`, and `workspaceEligibility`) before submitting paid traffic on a route. --- # OpenGen Public Developer API Reference > Machine-readable OpenAPI 3.1 reference covering all 24 Public Developer REST API endpoints across 6 tags. Full JSON specification: [https://opengen.dev/openapi.json](https://opengen.dev/openapi.json) · Interactive explorer: [https://opengen.dev/docs/api](https://opengen.dev/docs/api). ## Agent Prompt ```text Fetch the live OpenAPI 3.1 specification at https://opengen.dev/openapi.json (summarized at https://opengen.dev/docs/api.md). Start with unauthenticated read-only discovery (GET https://opengen.dev/v1/models, GET https://opengen.dev/v1/models/{provider}/{model}, GET https://opengen.dev/v1/pricing, POST https://opengen.dev/v1/pricing/estimate). Confirm the exact modelId, routeId, and maxCostMicros budget with the user before sending Authorization: Bearer $OPENGEN_API_KEY and a persisted Idempotency-Key to POST https://opengen.dev/v1/generations. Honor RateLimit, RateLimit-Policy, and Retry-After headers on all /v1/* calls. ``` ## Base URL, Authentication, Caching & Rate Limits - **Base URL:** `https://opengen.dev` (override via `OPENGEN_API_URL` for self-hosted gateways) - **OpenAPI 3.1 JSON:** [https://opengen.dev/openapi.json](https://opengen.dev/openapi.json) - **Authentication:** Send `Authorization: Bearer ` using a scoped workspace API key (`/app/keys`) or OAuth 2.1 DCR + PKCE token. Never send raw upstream provider keys as OpenGen bearer tokens. Public catalog, pricing, schema, JWKS, and health endpoints require no authentication. - **Caching & CORS:** Unauthenticated `200 OK` `GET`/`HEAD` catalog and `/openapi.json` responses return `Cache-Control: public, max-age=60, s-maxage=300` and `Access-Control-Allow-Origin: *`. Authenticated, cookie-bearing, private, and error responses always return `Cache-Control: no-store`. - **Rate Limits:** `/v1/*` responses include standard RFC `RateLimit-Policy` and `RateLimit` headers so agents and clients can self-throttle, plus `Retry-After` on `429 Too Many Requests`. - **Idempotency & Safety:** Persist a unique `Idempotency-Key` (1–200 chars) alongside the exact request before calling `POST /v1/generations`. Never invent a new key after a timeout or uncertain acceptance; recover read-only via `GET /v1/generations/lookup?idempotencyKey=...`. ## Endpoints by Tag (24 endpoints) ### Models & Catalog (`models`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `GET` | `/v1/models` | `models.list` | Public (no auth) | — | List and search exact model variants (compact default; ?expand=schemas) | | `GET` | `/v1/models/{provider}/{model}` | `models.get` | Public (no auth) | — | Inspect one exact model, its schemas, regional routes, and published pricing | | `GET` | `/v1/models/schema` | `models.schema` | Public (no auth) | — | Read canonical JSON input schema and limits for a model and operation | | `GET` | `/v1/collections` | `collections.list` | Public (no auth) | — | List curated capability collections across image, video, and audio | | `GET` | `/v1/collections/{slug}` | `collections.get` | Public (no auth) | — | Inspect one capability collection and its member variants | | `GET` | `/v1/routes` | `routes.list` | Public (no auth) | — | List regional serving routes with privacy and residency disclosures | ### Pricing & Cost Estimation (`pricing`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `GET` | `/v1/pricing` | `pricing.list` | Public (no auth) | — | List source-linked published micro-USD tariffs per route | | `POST` | `/v1/pricing/estimate` | `pricing.estimate` | Public (no auth) | — | Estimate generation cost and route eligibility without reserving credit | ### Generations & Jobs (`generations`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `POST` | `/v1/generations` | `media.generate` | Bearer token / session | Required | Submit a billable generation once with an Idempotency-Key | | `GET` | `/v1/generations` | `jobs.list` | Bearer token / session | — | List recent private generation jobs in the authenticated workspace | | `GET` | `/v1/generations/lookup` | `jobs.lookup` | Bearer token / session | — | Recover an admitted job by its original Idempotency-Key | | `GET` | `/v1/generations/{id}` | `jobs.get` | Bearer token / session | — | Read full job details and refresh temporary private output download links | | `GET` | `/v1/generations/{id}/status` | `jobs.status` | Bearer token / session | — | Poll or long-poll compact job status (?afterRevision, ?waitMs) | | `POST` | `/v1/generations/{id}/cancel` | `jobs.cancel` | Bearer token / session | — | Request cancellation of an in-flight generation job | | `DELETE` | `/v1/generations/{id}/outputs` | `jobs.purgeOutputs` | Bearer token / session | — | Permanently purge archived output media bytes for a terminal job | | `GET` | `/v1/generations/{id}/events` | `jobs.events` | Bearer token / session | — | Stream private job status updates via Server-Sent Events | ### Private Workspace Assets (`assets`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `POST` | `/v1/assets` | `assets.create` | Bearer token / session | Optional (required for url/job_output) | Upload, import by HTTPS URL, reuse a job output, or prepare a presigned PUT | | `POST` | `/v1/assets/complete` | `assets.complete` | Bearer token / session | — | Finalize a presigned single-PUT input asset upload | | `GET` | `/v1/assets` | `assets.get` | Bearer token / session | — | List workspace-owned input assets or inspect one asset by key | | `DELETE` | `/v1/assets` | `assets.delete` | Bearer token / session | — | Tombstone a workspace-owned input asset (?key= or JSON { key }) | ### Per-Request Ed25519 Webhooks (`webhooks`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `GET` | `/.well-known/webhook-jwks.json` | `webhooks.jwks` | Public (no auth) | — | Read public Ed25519 verification keys for per-request ad-hoc webhooks | ### Account, Analytics & Health (`account`) | Method | Path | Operation ID | Auth | Idempotency-Key | Summary | | --- | --- | --- | --- | --- | --- | | `GET` | `/v1/balance` | `balance.get` | Bearer token / session | — | Inspect available and reserved workspace credit in micro-USD | | `GET` | `/v1/analytics` | `analytics.get` | Bearer token / session | — | Read bounded workspace spend, usage, and latency/reliability cohorts | | `GET` | `/health` | `health` | Public (no auth) | — | Check gateway liveness | ## Quick Raw-HTTP Example ```bash # 1. Inspect one exact model (schema, regional routes, privacy disclosures, pricing) curl -fsS "https://opengen.dev/v1/models/openai/gpt-image-2" # 2. Stateless dry-run cost estimate (no auth required for public catalog estimation) curl -fsS -X POST "https://opengen.dev/v1/pricing/estimate" \ -H "Content-Type: application/json" \ -d '{"modelId":"openai/gpt-image-2","operation":"text-to-image","input":{"prompt":"A matte ceramic teapot on dark slate","resolution":"1K","quality":"low"},"billing":"managed"}' ``` ## Related Documentation - [Quickstart](https://opengen.dev/docs/quickstart.md) - [Authentication & Scopes](https://opengen.dev/docs/authentication.md) - [Generations & Safe Resume](https://opengen.dev/docs/generations.md) - [Private Workspace Assets](https://opengen.dev/docs/assets.md) - [Ed25519 Webhooks](https://opengen.dev/docs/webhooks.md) - [Errors & Recovery](https://opengen.dev/docs/errors.md) --- # Agent Clients & Setup Evidence > Connect hosted assistants, local coding agents, and shell runtimes to OpenGen via remote HTTP MCP (OAuth 2.1 DCR + PKCE), zero-auth read-only MCP (`/mcp/readonly`), or `@opengen-dev/cli`. Latest live verification evidence recorded 2026-11-30; primary client documentation reviewed 2026-11-03. Documentation is not a live interoperability guarantee. ## Agent Prompt ```text Help the user connect their current AI assistant or coding agent to OpenGen at https://opengen.dev. Inspect the client-specific guide at https://opengen.dev/docs/clients/.md (or https://opengen.dev/docs/clients.md), verify whether the client supports remote HTTP MCP with OAuth 2.1 DCR + PKCE (https://opengen.dev/mcp), zero-auth read-only discovery (https://opengen.dev/mcp/readonly), or the portable npm CLI (@opengen-dev/cli). Never paste API keys into chat or checked-in files, and run a read-only balance / doctor check before proposing any paid generation. ``` ## Support & Verification Matrix | Client | Kind | Integration Approach | Verification Status | Dated Evidence | | --- | --- | --- | --- | --- | | [ChatGPT](https://opengen.dev/docs/clients/chatgpt.md) | Hosted assistant | Hosted MCP with OAuth | LIVE GENERATION VERIFIED | ChatGPT web (2026-11-30): live OAuth DCR + PKCE consent, refresh-token rotation, 6/6 tools discovered, bounded openai/gpt-image-2 1K low-quality generation ($0.00606 settled), first-party /media PNG delivery (?utm_source=chatgpt.com), and MCP App preview card verified | | [Claude](https://opengen.dev/docs/clients/claude.md) | Hosted assistant | Remote connector with OAuth | LIVE GENERATION VERIFIED | Claude web (2026-11-30): live OAuth DCR + PKCE consent, refresh-token rotation (on 484d99f), 6/6 tools discovered, bounded openai/gpt-image-2 1K low-quality generation ($0.0061 settled), first-party /media PNG delivery, and MCP App preview card verified | | [Claude Code](https://opengen.dev/docs/clients/claude-code.md) | Local agent | Remote HTTP MCP or OpenGen CLI | LIVE OAUTH CONNECTED | Claude Code 2.1.301 (2026-11-30, 484d99f; logout 2026-11-28): live OAuth DCR + PKCE login and Connected MCP check (clean POST /mcp handshake) verified; LLM tool turn and generation pending | | [Cursor](https://opengen.dev/docs/clients/cursor.md) | Local agent | Streamable HTTP MCP or OpenGen CLI | Documented only | Documentation reviewed 2026-11-03; live connection not yet verified | | [Codex](https://opengen.dev/docs/clients/codex.md) | Local agent | Native MCP OAuth or OpenGen CLI | LIVE GENERATION VERIFIED | codex-cli 0.155.1 (2026-11-30, 484d99f): live OAuth refresh-token rotation, fresh DCR + PKCE login, 6/6 tools discovered, balance/catalog_get/pricing.list, bounded openai/gpt-image-2 1K low-quality generation ($0.00598 settled), and first-party /media PNG delivery (?utm_source=test) verified | | [Muse](https://opengen.dev/docs/clients/muse.md) | Local agent | Streamable HTTP MCP (OAuth DCR) | LIVE OAUTH LOGIN VERIFIED | Muse Code 1.4.25 (2026-11-30, 484d99f; local logout and muse.ai inspection 2026-11-29): live OAuth DCR + RFC 8252 ephemeral-port browser login, consent, and token exchange (auth=logged-in) verified; hosted muse.ai has no custom MCP UI | | [OpenClaw](https://opengen.dev/docs/clients/openclaw.md) | Local agent | Streamable HTTP MCP or OpenGen CLI | Documented only | Documentation reviewed 2026-11-03; live connection not yet verified | | [Hermes Agent](https://opengen.dev/docs/clients/hermes.md) | Local agent | HTTP MCP with OAuth or OpenGen CLI | LIVE OAUTH + TOOLS VERIFIED | Hermes Agent v0.16.0 (2026-11-30, 484d99f): live OAuth 2.1 PKCE login, hermes mcp test opengen (Connected, 6/6 tools discovered), and hermes chat tool registration verified; LLM tool invocation and generation pending | | [OpenCode](https://opengen.dev/docs/clients/opencode.md) | Local agent | Remote MCP OAuth or OpenGen CLI | Documented only | Documentation reviewed 2026-11-03; live connection not yet verified | | [pi](https://opengen.dev/docs/clients/pi.md) | Local agent | CLI through the agent’s shell | Documented only | Documentation reviewed 2026-11-03; live connection not yet verified | | [Grok Bot](https://opengen.dev/docs/clients/grok-bot.md) | Hosted assistant | Custom Remote HTTPS MCP (OAuth DCR) | LIVE GENERATION VERIFIED | Grok Bot web (2026-11-30): live OAuth DCR + MCP connection, refresh-token rotation (on 484d99f), 6/6 tools discovered, balance/catalog_get, bounded openai/gpt-image-2 1K low-quality generation ($0.006 settled), and clickable first-party /media PNG delivery verified | | [CLI & API](https://opengen.dev/docs/clients/cli.md) | CLI / API | OpenGen browser PKCE login / scoped API key | LIVE GENERATION VERIFIED | Source apps/cli 0.1.2 at 484d99f (2026-11-30): unauthenticated pricing (178 routes)/catalog, live browser login, bounded openai/gpt-image-2 1K low-quality generate/wait/get/recover ($0.005985 settled), and first-party /media PNG delivery (?utm_source=test) verified; published @opengen-dev/cli 0.1.2 (2026-11-28) clean npm install, login, read-only doctor/balance/catalog search, and logout revocation verified | ## Individual Client Setup Guides - [ChatGPT](https://opengen.dev/docs/clients/chatgpt.md) ([HTML](https://opengen.dev/docs/clients/chatgpt)) — Add a custom MCP plugin and authorize a paying workspace in your browser. - [Claude](https://opengen.dev/docs/clients/claude.md) ([HTML](https://opengen.dev/docs/clients/claude)) — Use a remote connector, with no local installer or provider credentials. - [Claude Code](https://opengen.dev/docs/clients/claude-code.md) ([HTML](https://opengen.dev/docs/clients/claude-code)) — Register an HTTP MCP server, then use the client’s browser authorization. - [Cursor](https://opengen.dev/docs/clients/cursor.md) ([HTML](https://opengen.dev/docs/clients/cursor)) — Preview a URL-only MCP configuration and authorize through Cursor. - [Codex](https://opengen.dev/docs/clients/codex.md) ([HTML](https://opengen.dev/docs/clients/codex)) — Add a Streamable HTTP server and use OAuth login with read/generate scopes. - [Muse](https://opengen.dev/docs/clients/muse.md) ([HTML](https://opengen.dev/docs/clients/muse)) — Add a Streamable HTTP MCP server in Muse Code with native OAuth. - [OpenClaw](https://opengen.dev/docs/clients/openclaw.md) ([HTML](https://opengen.dev/docs/clients/openclaw)) — Use the client’s MCP settings and browser authorization; verify the connection separately. - [Hermes Agent](https://opengen.dev/docs/clients/hermes.md) ([HTML](https://opengen.dev/docs/clients/hermes)) — Register the remote OAuth MCP server with the Hermes CLI or config.yaml. - [OpenCode](https://opengen.dev/docs/clients/opencode.md) ([HTML](https://opengen.dev/docs/clients/opencode)) — Configure a remote MCP server and complete the client’s OAuth flow. - [pi](https://opengen.dev/docs/clients/pi.md) ([HTML](https://opengen.dev/docs/clients/pi)) — Use the portable OpenGen CLI; native MCP is not assumed. - [Grok Bot](https://opengen.dev/docs/clients/grok-bot.md) ([HTML](https://opengen.dev/docs/clients/grok-bot)) — Add OpenGen as a custom Remote HTTPS MCP connector in Grok Bot or Grok CLI. - [CLI & API](https://opengen.dev/docs/clients/cli.md) ([HTML](https://opengen.dev/docs/clients/cli)) — Use the portable CLI with browser login, or create one scoped workspace API key. ## Related Links - [MCP Integration Guide](https://opengen.dev/docs/mcp.md) - [Quickstart Guide](https://opengen.dev/docs/quickstart.md) - [Installable Skill (skill.md)](https://opengen.dev/skill.md) - [OpenGen CLI on npm](https://www.npmjs.com/package/@opengen-dev/cli)