Mastering the xAI Grok Image Generation API: Aspect Ratios, Response Formats, and Production Workflows
Integrating text-to-image generation into production applications often breaks down in two places: images arrive in the wrong dimensions for the UI, or temporary asset links expire before your backend saves them. In xAI’s image generation documentation (docs.x.ai), solving both problems comes down to how you configure /v1/images/generations with models like grok-imagine-image-2.0—specifically through aspect_ratio, response_format, and asynchronous execution patterns.
Architecture of /v1/images/generations
xAI exposes image generation through an OpenAI-compatible REST endpoint ([https://api.x.ai/v1/images/generations](https://api.x.ai/v1/images/generations)), alongside native support in the official xAI Python SDK (xai_sdk) and the Vercel AI SDK (@ai-sdk/xai).
When targeting grok-imagine-image-2.0, a single request gives you direct control over framing, fidelity, batch size, and payload delivery:
model: Set togrok-imagine-image-2.0for current-generation text-to-image synthesis (and multi-reference editing via/v1/images/edits).n: Generates between1and10image variations in a single call. On REST and OpenAI-compatible clients,ndefaults to1. Inxai_sdk, single generations useclient.image.sample(), while multi-image batches requireclient.image.sample_batch(n=...).resolution: Supports1k(default) and2koutput tiers.quality: Acceptslow,medium, orautoongrok-imagine-image-2.0. When set toauto, the API currently defaults tolowfor text-to-image generation andmediumfor image editing.
Controlling Canvas Geometry with aspect_ratio
Rather than forcing developers to calculate pixel dimensions manually, xAI separates resolution tier (1k or 2k) from framing geometry via aspect_ratio. If omitted, aspect_ratio defaults to auto, allowing the model to infer the most natural proportions from your prompt.
For deterministic layouts—such as hero banners, mobile stories, or product thumbnails—pinning an explicit ratio prevents awkward cropping downstream:
aspect_ratio Value |
Primary Use Case |
|---|---|
auto |
Default; model selects the optimal framing for the prompt |
1:1 |
Social media feeds, avatars, and square thumbnails |
16:9 / 9:16 |
Widescreen video frames, desktop headers, and vertical mobile stories |
4:3 / 3:4 |
Slide presentations, editorial cards, and upright portraits |
3:2 / 2:3 |
Classic DSLR photography proportions |
2:1 / 1:2 & 5:2 |
Website banners, blog headers, and panoramic strips |
19.5:9 / 9:19.5 |
Full-bleed modern iPhone displays |
20:9 / 9:20 |
Full-bleed modern Android smartphone displays |
21:9 |
Ultra-wide cinematic frames |
Pair explicit ratios with spatial prompting: define the subject, camera angle, lighting direction, and what stays inside the frame edges so the composition fills the chosen geometry intentionally.
Managing Payloads with response_format
How your application ingests the generated image depends on response_format, which supports two modes on the REST API:
url(Default): Returns temporary hosted URLs pointing to the generated images. This keeps JSON response payloads lightweight and works well for immediate client previews. However, because these URLs are temporary, you must download and persist the assets to your own object storage (or xAI’s Files API) if you plan to keep them.b64_json: Embeds the raw base64-encoded image string directly inside the JSON response. Requesting base64 eliminates a secondary HTTP fetch, avoids expired-link bugs, and lets your server stream the bytes straight to disk or cloud storage. (Note: In the nativexai_sdk, base64 output is requested viaimage_format="base64", which exposes decoded bytes directly onresponse.image.)
Implementation Examples
REST / cURL (Explicit Framing + Base64 Output):
curl -X POST https://api.x.ai/v1/images/generations
-H "Authorization: Bearer $XAI_API_KEY"
-H "Content-Type: application/json"
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "Overhead view of two ceramic espresso cups on a pale oak table in crisp morning sunlight",
"aspect_ratio": "3:2",
"resolution": "2k",
"quality": "medium",
"response_format": "b64_json",
"n": 1
}'
Python (OpenAI-Compatible SDK):
import base64
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["XAI_API_KEY"],
base_url="https://api.x.ai/v1",
)
response = client.images.generate(
model="grok-imagine-image-2.0",
prompt="Minimalist architectural pavilion in misty mountains at sunrise",
aspect_ratio="16:9",
resolution="2k",
response_format="b64_json",
)
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("pavilion.jpg", "wb") as f:
f.write(image_bytes)
Python (Native xai_sdk):
import xai_sdk
client = xai_sdk.Client()
response = client.image.sample(
prompt="A serene Japanese garden with stone lanterns and raked gravel",
model="grok-imagine-image-2.0",
aspect_ratio="3:4",
image_format="base64",
)
if response.respect_moderation:
with open("garden.jpg", "wb") as f:
f.write(response.image)
Scaling Beyond Single Synchronous Calls
When moving from prototypes to production pipelines, three architectural patterns from the xAI docs prevent bottlenecks:
- Use
deferred: truefor non-blocking jobs: Standard requests hold the HTTP connection open until rendering finishes. For high-resolution batches or serverless environments with strict timeout limits, pass"deferred": true. The endpoint immediately returns arequest_idthat you can poll viaGET /v1/images/{request_id}. Keep in mind that deferred requests only supportresponse_format: "url"and retain results for 24 hours. - Parallelize distinct prompts asynchronously: The
nparameter generates variations of a single prompt. When generating assets for different prompts simultaneously (such as illustrating every section of an article), useAsyncClientwithasyncio.gather()to dispatch requests concurrently rather than blocking sequentially. - Check moderation flags gracefully: In
xai_sdk, inspectresponse.respect_moderationbefore reading image bytes or URLs so your application can handle filtered prompts cleanly without throwing unhandled exceptions.
Leave a Reply