Generating images programmatically with the xAI API centers on the /v1/images/generations endpoint and the Grok Imagine family of models—including grok-imagine-image and the newer grok-imagine-image-2.0. Whether you are building creative tools, dynamic marketing assets, or visual pipelines, controlling framing via aspect_ratio, tuning output resolution and quality, and handling batches cleanly makes the difference between rough prototypes and production-ready visuals.
How Image Generation Works in the xAI API
At its core, image generation in docs.x.ai takes a natural-language prompt and a target model (such as grok-imagine-image-2.0 or grok-imagine-image) and returns one or more rendered images. You can call the REST endpoint directly, use the OpenAI-compatible SDK pointed at [https://api.x.ai/v1](https://api.x.ai/v1), or use xAI’s native SDK (xai_sdk) and JavaScript AI SDK (@ai-sdk/xai).
Key capabilities documented across docs.x.ai include:
- Model lineup & migration context:
grok-imagine-image-2.0supports text-to-image generation, image editing with up to 5 reference images,qualitycontrols (low,medium,auto), and extended aspect ratios (21:9and5:2). Meanwhile,grok-imagine-imageremains available alongsidegrok-imagine-image-2.0, whilegrok-imagine-image-qualitywas retired on November 2, 2026 in favor ofgrok-imagine-image-2.0(with automatic routing tolowquality). - Batch generation (
n): Request between1and10images per call on REST and OpenAI-compatible clients (defaulting to1), or usesample()for a single image andsample_batch(n=...)in the xAI Python SDK. - Output formats (
response_format): Defaults tourl(returning temporary hosted URLs) or can be set tob64_json/ base64 when you want to embed or save bytes directly without an extra download step. - Resolution & quality controls: Choose
1k(default) or2kresolution viaresolution, and ongrok-imagine-image-2.0setqualitytolow,medium, orauto.
Mastering aspect_ratio for Framing and Layout
The aspect_ratio parameter controls the proportions of the generated canvas. When omitted, it defaults to auto, allowing the model to pick a ratio that fits the prompt’s composition. Explicitly passing aspect_ratio is essential when your UI slot, video frame, or social card has strict layout constraints.
| Aspect Ratio | Typical Use Case in docs.x.ai |
|---|---|
1:1 |
Social media feeds and thumbnails |
16:9 / 9:16 |
Widescreen displays, mobile screens, and stories |
4:3 / 3:4 |
Presentations and portraits |
3:2 / 2:3 |
Classic photography proportions |
2:1 / 1:2 |
Banners and headers |
19.5:9 / 9:19.5 |
Modern smartphone displays (such as iPhone) |
20:9 / 9:20 |
Modern smartphone displays (such as Android) |
21:9 |
Cinematic widescreen |
5:2 |
Wide banners |
auto |
Lets the model select the best ratio for the prompt |
A practical rule of thumb: match the aspect ratio to the subject’s natural geometry as well as the container. Wide landscapes, architectural panoramas, and hero banners breathe better in 16:9, 21:9, or 5:2, whereas vertical character portraits, posters, and mobile stories work naturally in 3:4, 9:16, or tall phone ratios.
Code Examples Across Environments
Python (xai_sdk)
import xai_sdk
client = xai_sdk.Client()
response = client.image.sample(
prompt="Golden hour mist rolling across terraced rice fields, crisp documentary photography",
model="grok-imagine-image-2.0",
aspect_ratio="16:9",
)
if response.respect_moderation:
print("Image URL:", response.url)
else:
print("Image filtered by moderation")
OpenAI-Compatible SDK (Node / TypeScript)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.XAI_API_KEY,
baseURL: "https://api.x.ai/v1",
});
const response = await client.images.generate({
model: "grok-imagine-image-2.0",
prompt: "Minimalist editorial poster for an astronomy talk, bold geometric typography",
aspect_ratio: "3:4",
n: 2,
});
for (const img of response.data) {
console.log(img.url);
}
Direct REST (cURL)
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": "Architectural cutaway of a sunlit greenhouse with timber beams",
"aspect_ratio": "3:2",
"resolution": "2k",
"quality": "medium",
"response_format": "b64_json",
"n": 1
}'
Production Practices: Batches, Async Jobs, and Prompting
Moving from a single test image to reliable production traffic involves a few operational details highlighted in the xAI documentation:
- Parallelize distinct prompts: If you are generating many unrelated images with different prompts, use concurrent async requests (such as
AsyncClientwithasyncio.gatherin Python) rather than waiting on sequential calls. - Use deferred mode or webhooks for heavy workloads: For long-running batches or avoiding open connections, set
deferred: trueon/v1/images/generationsto receive arequest_idand pollGET /v1/images/{request_id}(results useurlformat and are retained for 24 hours), or configure webhooks forimage.generation.completedandimage.generation.failedevents. - Structure prompts around subject first: Per xAI’s prompting guidance, nail the exact subject, count, materials, and spatial arrangement first before layering lighting, color fields, camera framing, and artistic style.
- Check moderation and billing behavior: Per-image billing depends on model, resolution, and (for
grok-imagine-image-2.0) served quality, and outputs remain subject to moderation checks.
Leave a Reply