# 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.<payload>.<hmac>.<ext>`) 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).
