Repository Public
1<!-- source: https://docs.x.ai/developers/model-capabilities/images/generation (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Model Capabilities34# Image Generation56Generate images from text prompts with Grok Imagine models. The API supports batch generation of multiple images, and control over aspect ratio, resolution, and quality.78## Quick Start910Generate an image with a single API call:1112```python customLanguage="pythonXAI"13import xai_sdk1415client = xai_sdk.Client()1617response = client.image.sample(18 prompt="A collage of London landmarks in a stenciled street‑art style",19 model="grok-imagine-image-2.0",20)2122print(response.url)23```2425```bash26curl -X POST https://api.x.ai/v1/images/generations \27 -H "Content-Type: application/json" \28 -H "Authorization: Bearer $XAI_API_KEY" \29 -d '{30 "model": "grok-imagine-image-2.0",31 "prompt": "A collage of London landmarks in a stenciled street‑art style"32 }'33```3435```python customLanguage="pythonOpenAISDK"36from openai import OpenAI3738client = OpenAI(39 base_url="https://api.x.ai/v1",40 api_key="YOUR_API_KEY",41)4243response = client.images.generate(44 model="grok-imagine-image-2.0",45 prompt="A collage of London landmarks in a stenciled street‑art style",46)4748print(response.data[0].url)49```5051```javascript customLanguage="javascriptOpenAISDK"52import OpenAI from "openai";5354const client = new OpenAI({55 apiKey: process.env.XAI_API_KEY,56 baseURL: 'https://api.x.ai/v1',57});5859const response = await client.images.generate({60 model: "grok-imagine-image-2.0",61 prompt: "A collage of London landmarks in a stenciled street‑art style",62});6364console.log(response.data[0].url);65```6667```javascript customLanguage="javascriptAISDK"68import { xai } from "@ai-sdk/xai";69import { generateImage } from "ai";7071const { image } = await generateImage({72 model: xai.image("grok-imagine-image-2.0"),73 prompt: "A collage of London landmarks in a stenciled street‑art style",74});7576console.log(image.base64);77```7879Images are returned as URLs by default. URLs are temporary, so download or process promptly. You can also request [base64 output](#base64-output) for embedding images directly.8081## Configuration8283### Multiple Images8485Generate multiple images in a single request with the `n` parameter (`1`–`10`). On the REST API and OpenAI-compatible SDKs, `n` is optional and defaults to `1`. The xAI Python SDK uses `sample()` for a single image and `sample_batch(n=...)` for more than one — `n` is required on `sample_batch()`.8687```python customLanguage="pythonXAI"88import xai_sdk8990client = xai_sdk.Client()9192responses = client.image.sample_batch(93 prompt="A futuristic city skyline at night",94 model="grok-imagine-image-2.0",95 n=4,96)9798for i, image in enumerate(responses):99 print(f"Variation {i + 1}: {image.url}")100```101102```python customLanguage="pythonOpenAISDK"103from openai import OpenAI104105client = OpenAI(106 base_url="https://api.x.ai/v1",107 api_key="YOUR_API_KEY",108)109110response = client.images.generate(111 model="grok-imagine-image-2.0",112 prompt="A futuristic city skyline at night",113 n=4,114)115116for i, image in enumerate(response.data):117 print(f"Variation {i + 1}: {image.url}")118```119120```javascript customLanguage="javascriptOpenAISDK"121import OpenAI from "openai";122123const client = new OpenAI({124 apiKey: process.env.XAI_API_KEY,125 baseURL: "https://api.x.ai/v1",126});127128const response = await client.images.generate({129 model: "grok-imagine-image-2.0",130 prompt: "A futuristic city skyline at night",131 n: 4,132});133134response.data.forEach((image, i) => {135 console.log(`Variation ${i + 1}: ${image.url}`);136});137138```139140```javascript customLanguage="javascriptAISDK"141import { xai } from "@ai-sdk/xai";142import { generateImage } from "ai";143144const { images } = await generateImage({145 model: xai.image("grok-imagine-image-2.0"),146 prompt: "A futuristic city skyline at night",147 n: 4,148});149150images.forEach((image, i) => {151 console.log(`Variation ${i + 1}: ${image.base64.slice(0, 50)}...`);152});153154```155156```bash157curl -X POST https://api.x.ai/v1/images/generations \158 -H "Content-Type: application/json" \159 -H "Authorization: Bearer $XAI_API_KEY" \160 -d '{161 "model": "grok-imagine-image-2.0",162 "prompt": "A futuristic city skyline at night",163 "n": 4164 }'165```166167### Aspect Ratio168169Control image dimensions with the `aspect_ratio` parameter. When omitted, the default is `auto`, which lets the model pick the best ratio for the prompt.170171| Ratio | Use case |172|-------|----------|173| `1:1` | Social media, thumbnails |174| `16:9` / `9:16` | Widescreen, mobile, stories |175| `4:3` / `3:4` | Presentations, portraits |176| `3:2` / `2:3` | Photography |177| `2:1` / `1:2` | Banners, headers |178| `19.5:9` / `9:19.5` | Modern smartphone displays (iPhone) |179| `20:9` / `9:20` | Modern smartphone displays (Android) |180| `21:9` | Cinematic widescreen |181| `5:2` | Wide banners |182| `auto` | Model auto-selects the best ratio for the prompt |183184```python customLanguage="pythonXAI"185import xai_sdk186187client = xai_sdk.Client()188189response = client.image.sample(190 prompt="Mountain landscape at sunrise",191 model="grok-imagine-image-2.0",192 aspect_ratio="16:9",193)194195print(response.url)196```197198```python customLanguage="pythonOpenAISDK"199from openai import OpenAI200201client = OpenAI(202 base_url="https://api.x.ai/v1",203 api_key="YOUR_API_KEY",204)205206response = client.images.generate(207 model="grok-imagine-image-2.0",208 prompt="Mountain landscape at sunrise",209 extra_body={"aspect_ratio": "16:9"},210)211212print(response.data[0].url)213```214215```javascript customLanguage="javascriptOpenAISDK"216import OpenAI from "openai";217218const client = new OpenAI({219 apiKey: process.env.XAI_API_KEY,220 baseURL: "https://api.x.ai/v1",221});222223const response = await client.images.generate({224 model: "grok-imagine-image-2.0",225 prompt: "Mountain landscape at sunrise",226227 aspect_ratio: "16:9",228});229230console.log(response.data[0].url);231```232233```javascript customLanguage="javascriptAISDK"234import { xai } from "@ai-sdk/xai";235import { generateImage } from "ai";236237const { image } = await generateImage({238 model: xai.image("grok-imagine-image-2.0"),239 prompt: "Mountain landscape at sunrise",240 aspectRatio: "16:9",241});242243console.log(image.base64);244```245246```bash247curl -X POST https://api.x.ai/v1/images/generations \248 -H "Content-Type: application/json" \249 -H "Authorization: Bearer $XAI_API_KEY" \250 -d '{251 "model": "grok-imagine-image-2.0",252 "prompt": "Mountain landscape at sunrise",253 "aspect_ratio": "16:9"254 }'255```256257### Resolution258259You can specify different resolutions of the output image with the `resolution` parameter. Currently supported image resolutions are:260261* `1k` (default when omitted)262* `2k`263264```python customLanguage="pythonXAI"265import xai_sdk266267client = xai_sdk.Client()268269response = client.image.sample(270 prompt="An astronaut performing EVA in LEO.",271 model="grok-imagine-image-2.0",272 resolution="2k"273)274275print(response.url)276```277278```python customLanguage="pythonOpenAISDK"279from openai import OpenAI280281client = OpenAI(282 base_url="https://api.x.ai/v1",283 api_key="YOUR_API_KEY",284)285286response = client.images.generate(287 model="grok-imagine-image-2.0",288 prompt="An astronaut performing EVA in LEO.",289 extra_body={"resolution": "2k"},290)291292print(response.data[0].url)293```294295```javascript customLanguage="javascriptOpenAISDK"296import OpenAI from "openai";297298const client = new OpenAI({299 apiKey: process.env.XAI_API_KEY,300 baseURL: "https://api.x.ai/v1",301});302303const response = await client.images.generate({304 model: "grok-imagine-image-2.0",305 prompt: "An astronaut performing EVA in LEO.",306307 resolution: "2k",308});309310console.log(response.data[0].url);311```312313```javascript customLanguage="javascriptAISDK"314import { xai } from "@ai-sdk/xai";315import { generateImage } from "ai";316317const { image } = await generateImage({318 model: xai.image("grok-imagine-image-2.0"),319 prompt: "An astronaut performing EVA in LEO.",320 providerOptions: {321 xai: { resolution: "2k" },322 },323});324325console.log(image.base64);326```327328```bash329curl -X POST https://api.x.ai/v1/images/generations \330-H "Content-Type: application/json" \331-H "Authorization: Bearer $XAI_API_KEY" \332-d '{333 "model": "grok-imagine-image-2.0",334 "prompt": "An astronaut performing EVA in LEO.",335 "resolution": "2k"336}'337```338339### Quality340341Control generation quality with the optional `quality` parameter. Allowed values are `low`, `medium`, and `auto`. When omitted, the default is `auto`, which lets the service choose the quality for each request. Auto currently uses `low` for image generation and `medium` for [image editing](/developers/model-capabilities/images/editing). Images are billed at the quality they are served at (see [Pricing](/developers/pricing)). Pass `low` or `medium` to pin a specific quality. The parameter is only supported for `grok-imagine-image-2.0`.342343```python customLanguage="pythonXAI"344import xai_sdk345346client = xai_sdk.Client()347348response = client.image.sample(349 prompt="A watercolor painting of a lighthouse at dawn",350 model="grok-imagine-image-2.0",351 quality="low",352)353354print(response.url)355```356357```bash358curl -X POST https://api.x.ai/v1/images/generations \359 -H "Content-Type: application/json" \360 -H "Authorization: Bearer $XAI_API_KEY" \361 -d '{362 "model": "grok-imagine-image-2.0",363 "prompt": "A watercolor painting of a lighthouse at dawn",364 "quality": "low"365 }'366```367368### Base64 Output369370Control the output format with the `response_format` parameter. When omitted, the default is `url`, which returns temporary hosted URLs. For embedding images directly without downloading, request base64:371372```python customLanguage="pythonXAI"373import xai_sdk374375client = xai_sdk.Client()376377response = client.image.sample(378 prompt="A serene Japanese garden",379 model="grok-imagine-image-2.0",380 image_format="base64",381)382383# Save to file384with open("garden.jpg", "wb") as f:385 f.write(response.image)386```387388```python customLanguage="pythonOpenAISDK"389import base64390from openai import OpenAI391392client = OpenAI(393 base_url="https://api.x.ai/v1",394 api_key="YOUR_API_KEY",395)396397response = client.images.generate(398 model="grok-imagine-image-2.0",399 prompt="A serene Japanese garden",400 response_format="b64_json",401)402403# Save to file404image_bytes = base64.b64decode(response.data[0].b64_json)405with open("garden.jpg", "wb") as f:406 f.write(image_bytes)407```408409```javascript customLanguage="javascriptOpenAISDK"410import OpenAI from "openai";411import fs from "fs";412413const client = new OpenAI({414 apiKey: process.env.XAI_API_KEY,415 baseURL: "https://api.x.ai/v1",416});417418const response = await client.images.generate({419 model: "grok-imagine-image-2.0",420 prompt: "A serene Japanese garden",421 response_format: "b64_json",422});423424// Save to file425const imageBuffer = Buffer.from(response.data[0].b64_json, "base64");426fs.writeFileSync("garden.jpg", imageBuffer);427```428429```javascript customLanguage="javascriptAISDK"430import { xai } from "@ai-sdk/xai";431import { generateImage } from "ai";432import fs from "fs";433434const { image } = await generateImage({435 model: xai.image("grok-imagine-image-2.0"),436 prompt: "A serene Japanese garden",437});438439// Save to file (AI SDK returns base64 by default)440const imageBuffer = Buffer.from(image.base64, "base64");441fs.writeFileSync("garden.jpg", imageBuffer);442```443444```bash445curl -X POST https://api.x.ai/v1/images/generations \446 -H "Content-Type: application/json" \447 -H "Authorization: Bearer $XAI_API_KEY" \448 -d '{449 "model": "grok-imagine-image-2.0",450 "prompt": "A serene Japanese garden",451 "response_format": "b64_json"452 }'453```454455### Response Details456457The xAI SDK exposes additional metadata on the response object beyond the image URL or base64 data.458459**Moderation** — Check whether the generated image passed content moderation:460461```python customLanguage="pythonXAI"462if response.respect_moderation:463 print(response.url)464else:465 print("Image filtered by moderation")466```467468**Model** — Get the actual model used (resolving any aliases):469470```python customLanguage="pythonXAI"471print(f"Model: {response.model}")472```473474## Concurrent Requests475476When you need to generate multiple images with **different prompts**, such as generating unrelated images in parallel, use `AsyncClient` with `asyncio.gather` to fire requests concurrently. This is significantly faster than issuing them one at a time.477478> [!TIP]479>480> If you want multiple variations from the **same prompt**, use [`sample_batch()` with the `n` parameter\`](#multiple-images) instead. That generates all images in a single request and is the most efficient approach for same-prompt generation.481482```python customLanguage="pythonXAI"483import asyncio484import xai_sdk485486async def generate_concurrently():487 client = xai_sdk.AsyncClient()488489 # Each request uses a different prompt490 prompts = [491 "A futuristic city skyline at sunset",492 "A serene Japanese garden in winter",493 "An astronaut floating above Earth",494 "A medieval castle on a misty mountain",495 ]496497 # Fire all requests concurrently498 tasks = [499 client.image.sample(500 prompt=prompt,501 model="grok-imagine-image-2.0",502 )503 for prompt in prompts504 ]505506 results = await asyncio.gather(*tasks)507508 for prompt, result in zip(prompts, results):509 print(f"{prompt}: {result.url}")510511asyncio.run(generate_concurrently())512```513514## Related515516* [Models](/developers/models) — Available image models517* [Image Editing](/developers/model-capabilities/images/editing) — Edit images with natural language518* [Image Generation Tool](/developers/tools/image-generation) — Let Grok generate and edit images inside a conversation519* [Video Generation](/developers/model-capabilities/video/generation) — Generate videos from text prompts520* [API Reference](/developers/rest-api-reference) — Full endpoint documentation521* [Imagine API Landing Page](https://x.ai/api/imagine) — Showcase of the Imagine API in action522