Grok Imagine API: Aspect Ratio & Response Format Guide

Written by

in

Building visual pipelines with xAI’s image generation API centers on three core controls: the grok-imagine-image-2.0 model (and its predecessor grok-imagine-image), aspect_ratio, and response_format. Exposed via the REST endpoint POST [https://api.x.ai/v1/images/generations](https://api.x.ai/v1/images/generations) and mirrored across the xAI Python SDK, OpenAI-compatible SDKs, and the Vercel AI SDK, these parameters let developers dictate framing, delivery payload, and storage workflows without extra post-processing.


Core Architecture & Request Anatomy

Every image generation call routes to /v1/images/generations. While grok-imagine-image established xAI’s baseline text-to-image endpoint, the current flagship grok-imagine-image-2.0 introduces expanded quality controls, 1K and 2K resolutions, and multi-image editing capabilities alongside flat per-image pricing ($0.04 per image).

A standard REST request combines prompt instructions with structural flags:

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": "Minimalist architectural concrete pavilion in a misty pine forest at dawn",
    "aspect_ratio": "16:9",
    "resolution": "2k",
    "quality": "medium",
    "response_format": "url",
    "n": 1
  }'

Framing with aspect_ratio

Unlike older image APIs that require rigid pixel dimensions (such as 1024x1024 or 1792x1024), xAI abstracts canvas geometry into semantic ratios. When aspect_ratio is omitted, the API defaults to auto, allowing the model to infer the most natural framing from the prompt’s subject matter.

For deterministic layouts, the API supports standard, ultrawide, and device-specific mobile ratios:

Aspect Ratio Orientation Primary Use Case
auto (Default) Dynamic Model-selected framing tailored to prompt intent
1:1 Square Social media feeds, avatars, thumbnails
16:9 / 9:16 Widescreen / Vertical Desktop hero banners, YouTube videos, mobile stories
4:3 / 3:4 Standard / Vertical Presentations, editorial portraits, classic displays
3:2 / 2:3 Photographic DSLR-style photography, print layouts
2:1 / 1:2 Panoramic / Tall Web headers, split-screen UI cards
19.5:9 / 9:19.5 Mobile Full-Screen Modern iPhone viewports
20:9 / 9:20 Mobile Full-Screen Modern Android viewports
21:9 Ultrawide Cinematic widescreen headers

Pairing aspect_ratio with the resolution parameter (1k by default, or 2k for high-detail assets) scales the pixel density proportionally while preserving the exact framing.


Controlling Delivery with response_format

Once an image is rendered, response_format determines how the payload travels back to your application. Selecting the right format directly impacts latency, bandwidth, and data persistence.

1. Hosted URLs ("url")

  • Behavior: This is the default setting when response_format is omitted. The API returns a JSON object containing a temporary, signed URL pointing to the hosted asset.
  • Trade-offs: Keeps JSON payloads lightweight and fast to parse, making it ideal for frontends that immediately render <img> tags or pass URLs to downstream video generation endpoints (such as grok-imagine-video-1.5). However, because hosted URLs expire, production apps must download and re-host the file to permanent object storage (like S3 or R2) if persistence is required.

2. Base64 Payloads ("b64_json" / "base64")

  • Behavior: Instructs the server to encode the raw binary image directly into the JSON response. On the REST API and OpenAI-compatible SDKs, pass response_format: "b64_json"; in the native xAI Python SDK, pass image_format="base64".
  • Trade-offs: Eliminates the extra HTTP round-trip needed to fetch a temporary URL and guarantees immediate local access to the bytes before any link expiration occurs. The downside is larger response sizes and higher memory overhead, especially when generating batches (n up to 10) at 2k resolution.

SDK Implementations & Async Constraints

Because xAI maintains wire-compatibility with the OpenAI API schema alongside its own native SDKs, developers can integrate these parameters across multiple ecosystems:

OpenAI-Compatible Python SDK

import os
import base64
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="Isometric cutaway of a cozy timber-framed library",
    aspect_ratio="4:3",
    response_format="b64_json",
)

with open("library.jpg", "wb") as f:
    f.write(base64.b64decode(response.data[0].b64_json))

Native xAI Python SDK

import xai_sdk

client = xai_sdk.Client()
response = client.image.sample(
    prompt="Isometric cutaway of a cozy timber-framed library",
    model="grok-imagine-image-2.0",
    aspect_ratio="4:3",
    image_format="base64",
)

if response.respect_moderation:
    with open("library.jpg", "wb") as f:
        f.write(response.image)

Deferred Generation Caveat

For heavy workloads or batch jobs where holding an HTTP connection open risks timeouts, /v1/images/generations accepts "deferred": true. This returns a request_id immediately so your worker can poll GET /v1/images/{request_id}. Notably, deferred requests only support response_format: "url"—base64 payloads cannot be requested asynchronously, and completed deferred URLs are retained for 24 hours.

Comments

Leave a Reply

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