Mastering Image Generations with xAI’s Grok Imagine API
Generating images programmatically is rarely just about typing a vivid prompt and hoping for the best. In production workflows—whether you are assembling storyboards, generating social assets, or embedding visuals inside an interactive app—framing, payload delivery, batching, and execution mode determine whether an integration feels effortless or brittle.
With xAI’s Grok image models (such as grok-imagine-image-2.0 on /v1/images/generations), developers get explicit controls over image framing (aspect_ratio), output encoding (response_format), batch counts (n), resolution (1k or 2k), quality (low, medium, or auto), and asynchronous execution.
Framing Your Output with aspect_ratio
A composition that works on a wide desktop banner often crops awkwardly on a vertical mobile screen. Rather than forcing post-generation cropping, aspect_ratio lets you set the target proportions directly in the generation request. When omitted, it defaults to auto, letting the model pick a ratio suited to the prompt.
| Aspect Ratio | Common Use Cases |
|---|---|
1:1 |
Square social feeds, avatars, thumbnails |
16:9 / 9:16 |
Widescreen layouts, mobile screens, vertical stories |
4:3 / 3:4 |
Presentation slides, portraits |
3:2 / 2:3 |
Classic editorial photography |
2:1 / 1:2 |
Wide banners, tall headers |
19.5:9 / 9:19.5 |
Modern smartphone screens (iPhone) |
20:9 / 9:20 |
Modern smartphone screens (Android) |
21:9 / 5:2 |
Ultrawide cinema, panoramic headers |
auto |
Model-selected aspect ratio based on prompt |
Matching aspect_ratio to the container upfront keeps focal subjects centered and avoids wasted pixels or awkward trims.
Choosing response_format: URL vs. Base64
How you receive generated bytes affects network round-trips, memory usage, and downstream storage. The response_format parameter controls how the API delivers each image:
url(Default): Returns temporary hosted URLs for generated images. This keeps JSON responses lightweight and works well when you plan to fetch, inspect, or upload assets to your own object storage—provided you download them before the temporary links expire. Note that deferred requests supportresponse_format: "url"only.base64: Embeds base64-encoded image data directly in the response payload. This is handy when you want to decode bytes in memory or pass data straight into downstream pipelines without a separate download step, at the cost of larger response payloads.
Batches, Quality, Resolution, and Deferred Execution
Beyond framing and encoding, a few operational knobs shape speed, cost, and reliability during image generations:
- Batch size (
n): Request between1and10images from a single prompt on/v1/images/generations(defaulting to1on REST and OpenAI-compatible clients). In the xAI Python SDK,sample()handles a single image whilesample_batch(n=...)requiresnfor multiple variations. When generating different prompts rather than variations of one prompt, firing concurrent requests (such asAsyncClientwithasyncio.gather) is much faster than sequential calls. - Resolution & quality: Supported resolutions are
1k(default) and2k. Ongrok-imagine-image-2.0,qualityacceptslow,medium, orauto(defaulting tolowfor generation andmediumfor edits underauto), with billing tied to the served quality. - Deferred mode & webhooks: For large batches or connections you do not want to hold open, passing
deferred: truereturns arequest_idimmediately so you can pollGET /v1/images/{request_id}(results are retained for 24 hours) or listen forimage.generation.completed/image.generation.failedwebhook events.
Putting It Together in Code
You can call /v1/images/generations directly over HTTP or through official and compatible SDKs:
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": "A terraced tea garden at sunrise with soft mist over rolling hills",
"aspect_ratio": "16:9",
"resolution": "1k",
"quality": "medium",
"response_format": "url",
"n": 1
}'
import xai_sdk
client = xai_sdk.Client()
response = client.image.sample(
prompt="A terraced tea garden at sunrise with soft mist over rolling hills",
model="grok-imagine-image-2.0",
aspect_ratio="16:9",
)
if response.respect_moderation:
print(response.url)
Whether you are prototyping a visual concept at 1k with auto framing or shipping a multi-variant batch with explicit aspect_ratio and response_format choices, treating those parameters as first-class design decisions makes image generations predictable from the very first request.
Leave a Reply