SPB Git

Repository Public

outputs.md 18.6 KB 432 lines markdown

1<!-- source: https://docs.x.ai/developers/model-capabilities/imagine/files/outputs (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Model Capabilities34# Persisting Generated Output56Use `storage_options` on any Imagine request to **persist the generated asset** to your [Files API](/developers/files) storage, where you can retrieve it later through the authenticated Files API. On top of that, set `storage_options.public_url` to additionally generate a **permanent, shareable public URL** for the asset — an unauthenticated link that anyone can open and that stays alive until you revoke it.78Storage and public URL creation are independent: you can store privately without a public URL, or store with a public URL. Either way, the response also includes the ephemeral generation URL that's always returned by default.910## Quick Start1112Generate an image, persist it to Files, and get a shareable public URL — all in one call:1314```python customLanguage="pythonXAI"15import os16import xai_sdk1718client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))1920response = client.image.sample(21    prompt="A serene Japanese garden in winter",22    model="grok-imagine-image-quality",23    storage_options={"filename": "garden.jpg", "public_url": True},24)2526# Ephemeral, short-lived URL.27print(f"Ephemeral:  {response.url}")2829# Persistent file in your Files API storage.30print(f"File ID:    {response.file_output.file_id}")3132# Permanent, shareable public URL.33print(f"Public URL: {response.public_url}")34```3536```bash37curl -s -X POST https://api.x.ai/v1/images/generations \38  -H "Authorization: Bearer $XAI_API_KEY" \39  -H "Content-Type: application/json" \40  -d '{41    "model": "grok-imagine-image-quality",42    "prompt": "A serene Japanese garden in winter",43    "response_format": "url",44    "storage_options": {45      "filename": "garden.jpg",46      "public_url": true47    }48  }'49```5051The response body looks like this:5253```json54{55  "data": [56    {57      "url": "https://imgen.x.ai/xai-imgen/xai-tmp-imgen-abc123.jpg",58      "file_output": {59        "file_id": "file_7de029f4-eb66-42ee-87f8-b2a9d9e7466a",60        "filename": "garden.jpg",61        "public_url": "https://files-cdn.x.ai/ZsqeMtdcSYWPPHTQdxXDKQ/file_7de029f4-eb66-42ee-87f8-b2a9d9e7466a.jpg"62      }63    }64  ]65}66```6768Key things to note:6970* `data[i].url` is the **ephemeral** Imagine URL — short-lived, fine for immediate use. It's always returned, regardless of whether `storage_options` is specified.71* `data[i].file_output.file_id` is the stable Files API identifier for the generated asset.72* `data[i].file_output.public_url` is the **permanent** public URL. Use this for sharing, embedding, and long-term storage in your app.7374## `storage_options` Reference7576| Field                      | Type                        | Description                                                                                                                                |77| -------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |78| `filename`                 | string (**required**)       | Filename for the stored file. The extension on the public URL path is derived from this filename.                                         |79| `expires_after`            | integer (optional)          | Seconds from now until the stored file expires. Must be between `3600` (1 hour) and `2592000` (30 days). Omit for permanent storage.       |80| `public_url`               | boolean or object (optional) | Set to `true` to create a public URL with default settings, or pass an object to configure it. Omit (or `false`) to store privately.      |81| `public_url.expires_after` | integer (optional)          | Seconds from now until the public URL expires. Must be between `3600` (1h) and `2592000` (30d). See [Expiry Behaviour](#expiry-behaviour). |8283`filename` is required. Passing `storage_options={"filename": "..."}` with no other fields persists the asset privately: no expiry on the stored file and no public URL. You can always call [`create_public_url`](/developers/files/public-urls) on the stored `file_id` later if you change your mind.8485```python customLanguage="pythonXAI"86response = client.image.sample(87    prompt="A red circle on a white background",88    model="grok-imagine-image-quality",89    storage_options={"filename": "circle.jpg"},  # store privately, no public URL90)9192print(response.file_output.file_id)    # file_...93print(response.file_output.filename)   # circle.jpg94print(response.public_url)             # None — public URL was not requested95```9697```bash98curl -s -X POST https://api.x.ai/v1/images/generations \99  -H "Authorization: Bearer $XAI_API_KEY" \100  -H "Content-Type: application/json" \101  -d '{102    "model": "grok-imagine-image-quality",103    "prompt": "A red circle on a white background",104    "response_format": "url",105    "storage_options": {"filename": "circle.jpg"}106  }'107```108109## Expiry Behaviour110111`storage_options` exposes two independent expiry knobs: `storage_options.expires_after` controls when the **stored file** auto-deletes, and `storage_options.public_url.expires_after` controls when the **public URL** auto-revokes. Omit `public_url.expires_after` and the URL inherits the file's expiry (or never expires if the file has none).112113A public URL can never outlive its file, and both values must be between **1 hour and 30 days**. See [Public URLs → Expiry Behaviour](/developers/files/public-urls#expiry-behaviour) for the full rules; the examples below show how the two knobs combine on an Imagine request.114115```python customLanguage="pythonXAI"116import os117import xai_sdk118119client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))120121# Permanent file, public URL expires in 24h.122response = client.image.sample(123    prompt="A futuristic city skyline at night",124    model="grok-imagine-image-quality",125    storage_options={"filename": "skyline.jpg", "public_url": {"expires_after": 86400}},  # 24h126)127print(response.file_output.file_id)                # file_...128print(response.public_url)                         # https://files-cdn.x.ai/<token>/file_....jpg129print(response.file_output.public_url_expires_at)  # protobuf Timestamp, ~24h from now130131# File and public URL both expire in 2h (URL inherits the file's expiry).132response = client.image.sample(133    prompt="A futuristic city skyline at night",134    model="grok-imagine-image-quality",135    storage_options={"filename": "skyline.jpg", "expires_after": 7200, "public_url": True},136)137print(response.file_output.file_id)                # file_...138print(response.public_url)139print(response.file_output.expires_at)             # ~2h from now140print(response.file_output.public_url_expires_at)  # matches file's expires_at141142# File expires in 24h, public URL expires in 1h (independent, shorter).143response = client.image.sample(144    prompt="A futuristic city skyline at night",145    model="grok-imagine-image-quality",146    storage_options={147        "filename": "skyline.jpg",148        "expires_after": 86400,149        "public_url": {"expires_after": 3600},150    },151)152print(response.file_output.file_id)                # file_...153print(response.public_url)154print(response.file_output.expires_at)             # ~24h from now155print(response.file_output.public_url_expires_at)  # ~1h from now (URL dies before file)156```157158```bash159# Permanent file, 24h public URL160curl -s -X POST https://api.x.ai/v1/images/generations \161  -H "Authorization: Bearer $XAI_API_KEY" \162  -H "Content-Type: application/json" \163  -d '{164    "model": "grok-imagine-image-quality",165    "prompt": "A futuristic city skyline at night",166    "response_format": "url",167    "storage_options": {168      "filename": "skyline.jpg",169      "public_url": {"expires_after": 86400}170    }171  }'172173# 2h file, public URL inherits the same expiry174curl -s -X POST https://api.x.ai/v1/images/generations \175  -H "Authorization: Bearer $XAI_API_KEY" \176  -H "Content-Type: application/json" \177  -d '{178    "model": "grok-imagine-image-quality",179    "prompt": "A futuristic city skyline at night",180    "response_format": "url",181    "storage_options": {182      "filename": "skyline.jpg",183      "expires_after": 7200,184      "public_url": true185    }186  }'187```188189## The `file_output` Response190191Every Imagine response with `storage_options` set includes a `file_output` block on each generated asset:192193| Field                   | Always present                                                        | Meaning                                                                                                                     |194| ----------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |195| `file_id`               | yes                                                                   | Stable Files API identifier. Use this for `client.files.*` operations.                                                      |196| `filename`              | yes                                                                   | The filename you provided in `storage_options`.                                                                            |197| `expires_at`            | only when the file has an expiration set                              | Unix timestamp when the file expires.                                                                                       |198| `public_url`            | only when `storage_options.public_url` was set and creation succeeded | The permanent shareable URL.                                                                                                |199| `public_url_expires_at` | only when the public URL has an expiry                                | Unix timestamp when the public URL dies. Absent for permanent URLs.                                                         |200| `public_url_error`      | only on partial failure                                               | Human-readable error when the asset was stored but public URL creation failed. See [Public URL Errors](#public-url-errors). |201202The Python SDK also surfaces `response.public_url` and `response.public_url_error` as top-level shortcuts on `ImageResponse` and `VideoResponse`.203204## Multiple Outputs (`n > 1`)205206When you request multiple images in a single call, each image gets its own `file_id` and its own `public_url` with a unique token. The files are completely independent — revoking or deleting one does not affect the others.207208```python customLanguage="pythonXAI"209import os210import xai_sdk211212client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))213214responses = client.image.sample_batch(215    prompt="A cat wearing a hat, four different art styles",216    model="grok-imagine-image-quality",217    n=4,218    storage_options={"filename": "cat-styles.jpg", "public_url": True},219)220221for r in responses:222    print(r.file_output.file_id, r.public_url)223```224225```bash226curl -s -X POST https://api.x.ai/v1/images/generations \227  -H "Authorization: Bearer $XAI_API_KEY" \228  -H "Content-Type: application/json" \229  -d '{230    "model": "grok-imagine-image-quality",231    "prompt": "A cat wearing a hat, four different art styles",232    "n": 4,233    "response_format": "url",234    "storage_options": {"filename": "cat-styles.jpg", "public_url": true}235  }'236```237238## Storing Image Edit Outputs239240`storage_options` works on `/v1/images/edits` the same way as `/v1/images/generations`. The edited result is stored as a new file.241242```python customLanguage="pythonXAI"243import os244import xai_sdk245246client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))247248response = client.image.sample(249    prompt="Add a party hat to the dog",250    model="grok-imagine-image-quality",251    image_url="https://docs.x.ai/assets/api-examples/images/style-realistic.png",252    storage_options={"filename": "party-dog.png", "public_url": True},253)254255print(response.file_output.file_id)  # new file, not the input256print(response.public_url)257```258259```bash260curl -s -X POST https://api.x.ai/v1/images/edits \261  -H "Authorization: Bearer $XAI_API_KEY" \262  -H "Content-Type: application/json" \263  -d '{264    "model": "grok-imagine-image-quality",265    "prompt": "Add a party hat to the dog",266    "image": {267      "url": "https://docs.x.ai/assets/api-examples/images/style-realistic.png"268    },269    "response_format": "url",270    "storage_options": {"filename": "party-dog.png", "public_url": true}271  }'272```273274## Storing Video Outputs275276The video endpoints (`/v1/videos/generations`, `/v1/videos/edits`, `/v1/videos/extensions`) use the same `storage_options` shape. Since video generation is asynchronous, `file_output.public_url` is populated on the **completed** response after the video finishes generating.277278```python customLanguage="pythonXAI"279import os280import xai_sdk281282client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))283284# SDK handles polling automatically and returns the completed video.285response = client.video.generate(286    prompt="A ball bouncing slowly on a flat surface",287    model="grok-imagine-video-1.5",288    duration=5,289    storage_options={"filename": "bouncing-ball.mp4", "public_url": True},290)291292print(response.url)                   # ephemeral vidgen URL293print(response.file_output.file_id)   # file_...294print(response.public_url)            # https://files-cdn.x.ai/<token>/file_....mp4295```296297```bash298# Start the generation299REQUEST_ID=$(curl -s -X POST https://api.x.ai/v1/videos/generations \300  -H "Authorization: Bearer $XAI_API_KEY" \301  -H "Content-Type: application/json" \302  -d '{303    "model": "grok-imagine-video-1.5",304    "prompt": "A ball bouncing slowly on a flat surface",305    "duration": 5,306    "storage_options": {"filename": "bouncing-ball.mp4", "public_url": true}307  }' | jq -r '.request_id')308309# Poll until done310while true; do311  RESULT=$(curl -s "https://api.x.ai/v1/videos/$REQUEST_ID" \312    -H "Authorization: Bearer $XAI_API_KEY")313  STATUS=$(echo "$RESULT" | jq -r '.status')314  if [ "$STATUS" = "done" ]; then315    echo "$RESULT" | jq '.video.file_output'316    break317  fi318  sleep 5319done320```321322Image-to-video, video editing, and video extension all accept `storage_options` the same way.323324## Public URL Errors325326In rare cases, public URL creation can fail even when asset generation and storage succeed — for example, on a transient infrastructure issue or when the team has hit its [active-URL quota](/developers/files/public-urls#limitations). Rather than tearing down the whole request, the response still includes a valid `file_output.file_id` and the original asset URL, and only `public_url` is replaced by `public_url_error`:327328```json329{330  "data": [331    {332      "url": "https://imgen.x.ai/.../xai-tmp-imgen-abc123.jpg",333      "file_output": {334        "file_id": "file_abc123",335        "filename": "poster.jpg",336        "public_url_error": "Public URL creation timed out. The file was stored successfully."337      }338    }339  ]340}341```342343If you see `public_url_error`, the file is still in your storage — you can retry public URL creation directly via the [Files API](/developers/files/public-urls) without regenerating the asset:344345```python customLanguage="pythonXAI"346import os347import xai_sdk348349client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))350351response = client.image.sample(352    prompt="A vintage poster",353    model="grok-imagine-image-quality",354    storage_options={"filename": "poster.jpg", "public_url": True},355)356357if response.public_url_error:358    # The image is stored — just retry the public URL on the file directly.359    resp = client.files.create_public_url(response.file_output.file_id)360    public_url = resp.public_url361else:362    public_url = response.public_url363364print(public_url)365```366367## Managing Files Created via Imagine368369Files created through `storage_options` are full first-class Files API files. Use the [Files API](/developers/files/managing-files) to list, retrieve, update, and delete them, and use the public URL endpoints to revoke or re-create the URL after the fact:370371```python customLanguage="pythonXAI"372import os373import xai_sdk374375client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))376377response = client.image.sample(378    prompt="A futuristic city",379    model="grok-imagine-image-quality",380    storage_options={"filename": "city.jpg", "public_url": True},381)382file_id = response.file_output.file_id383384# Inspect file metadata385file = client.files.get(file_id)386387# Stop sharing publicly (keeps the file in your storage)388client.files.revoke_public_url(file_id)389390# Generate a new public URL later with a different expiry391client.files.create_public_url(file_id, expires_after=604800)  # 7 days392393# Delete the file entirely (also tears down any active public URL)394client.files.delete(file_id)395```396397```bash398FILE_ID="<file_output.file_id from the generation response>"399400# Stop sharing publicly (file stays in your storage)401curl -s -X POST "https://api.x.ai/v1/files/$FILE_ID/public-url/revoke" \402  -H "Authorization: Bearer $XAI_API_KEY"403404# Re-create with a 7-day expiry405curl -s -X POST "https://api.x.ai/v1/files/$FILE_ID/public-url" \406  -H "Authorization: Bearer $XAI_API_KEY" \407  -H "Content-Type: application/json" \408  -d '{"expires_after": 604800}'409410# Delete the file (also revokes the public URL)411curl -s -X DELETE "https://api.x.ai/v1/files/$FILE_ID" \412  -H "Authorization: Bearer $XAI_API_KEY"413```414415## Limitations416417* **Up to 1,000 active public URLs per team.** Hitting the cap sets `public_url_error` on the response; revoke unused URLs to free up slots.418* **Expiry constraints** (see [Expiry Behaviour](#expiry-behaviour)):419  * Both `expires_after` values must be between **1 hour and 30 days**.420  * `public_url.expires_after` must be ≤ the file's `expires_after`.421* **Custom filenames affect the public URL path.** Passing `storage_options.filename = "my-cover.png"` makes the public URL end in `.png`. The stored content type is still determined by the generated asset, not the filename.422* **`response_format` does not affect storage.** `storage_options` runs whether you request `url` or `b64_json`.423* **Public URLs are independent of the ephemeral URL.** Both are returned in the same response but have separate lifecycles. Revoking the public URL does not affect the ephemeral URL.424* **All validation is synchronous.** Invalid storage configs are rejected before generation starts, so you never waste compute on a malformed request.425426## Related427428* [Files API Integration](/developers/model-capabilities/imagine/files) — Overview + capstone example showing inputs and outputs together.429* [Referencing Files as Input](/developers/model-capabilities/imagine/files/inputs) — The input side: pass stored `file_id`s in place of URLs.430* [Files → Public URLs](/developers/files/public-urls) — Public URL lifecycle for any file, regardless of how it was created.431* [Managing Files](/developers/files/managing-files) — Upload, list, retrieve, update, and delete files.432
Files main
Menu

Theme