# 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": "<key>" } 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/<workspaceId>/<uuid>.<ext>`) 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=<assetKey>` (cannot combine `?key=` with list filters)                |
| `DELETE /v1/assets`        | `assets.delete`   | `generate` | Tombstones and deletes a workspace-owned asset via `?key=<assetKey>` query parameter **or** JSON body `{ "key": "<assetKey>" }` (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": <boolean> }`.

```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": "<returned key>" }` 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.
