# 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": "<job-uuid>", "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` |
