xAI API Image Generation: Aspect Ratio & Grok Imagine Guide

Written by

in

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.0 supports text-to-image generation, image editing with up to 5 reference images, quality controls (low, medium, auto), and extended aspect ratios (21:9 and 5:2). Meanwhile, grok-imagine-image remains available alongside grok-imagine-image-2.0, while grok-imagine-image-quality was retired on November 2, 2026 in favor of grok-imagine-image-2.0 (with automatic routing to low quality).
  • Batch generation (n): Request between 1 and 10 images per call on REST and OpenAI-compatible clients (defaulting to 1), or use sample() for a single image and sample_batch(n=...) in the xAI Python SDK.
  • Output formats (response_format): Defaults to url (returning temporary hosted URLs) or can be set to b64_json / base64 when you want to embed or save bytes directly without an extra download step.
  • Resolution & quality controls: Choose 1k (default) or 2k resolution via resolution, and on grok-imagine-image-2.0 set quality to low, medium, or auto.

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 AsyncClient with asyncio.gather in 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: true on /v1/images/generations to receive a request_id and poll GET /v1/images/{request_id} (results use url format and are retained for 24 hours), or configure webhooks for image.generation.completed and image.generation.failed events.
  • 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.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *