Grok Imagine
Call xAI's Grok Imagine image models in the OpenAI Images format to generate and edit images, and submit video tasks to /v1/videos, check their progress and download the result.
xAI's Grok Imagine has image models and video models. Images use the OpenAI Images format's generation and edit endpoints and come back synchronously; video uses /v1/videos, where you submit a task, then check its progress and download the result. Which models you can use depends on your key's group (see Groups), and each model's price is in Model Square.
POST https://codaapi.com/v1/images/generations
POST https://codaapi.com/v1/images/edits
POST https://codaapi.com/v1/videos
GET https://codaapi.com/v1/videos/{task id}
Image requests are synchronous and usually take 10 to 25 seconds, or over a minute with quality set to medium, so set your client's read timeout to at least 120 seconds. Video is an asynchronous task, see Video.
Models
These are the Grok Imagine models on the live site when this page was written. Models come and go, and Model Square is authoritative:
| Model | Type | Billing | Group |
|---|---|---|---|
grok-imagine-image, grok-imagine-image-2.0 |
Image | Per Request | Grok-官转 |
grok-imagine-video-1.5-480p, grok-imagine-video-1.5-720p, grok-imagine-video-1.5-1080p, grok-imagine-video-1.5-preview-480p, grok-imagine-video-1.5-preview-720p, grok-imagine-video-1.5-preview-1080p |
Video | Per Request | Grok-官转 |
To use these models, create your key in the Grok-官转 group. The image parameters below are written for grok-imagine-image-2.0. The last part of a video model's name is its output resolution: each resolution is a separate model with its own price.
Model Square doesn't mark the image generation endpoint for the image models; that marking is generated from the channel type. Call them as this page describes.
Request headers
| Name | Required | Description |
|---|---|---|
Authorization |
Yes | Bearer sk-…, your API key |
Content-Type |
Yes | application/json. The image edit endpoint also takes a JSON body, not multipart/form-data |
Request body
Both image endpoints take a JSON body, and the size is set by aspect_ratio (the ratio) plus resolution (the resolution level).
Generate an image
POST /v1/images/generations:
| Parameter | Type | Required | Description |
|---|---|---|---|
model |
string | Yes | Model name, see Models |
prompt |
string | Yes | A text description of the image, in English or Chinese; text in the picture renders clearly in both |
n |
integer | No | How many images to generate, 1 to 10, 1 by default. For several images, use n |
aspect_ratio |
string | No | Aspect ratio, auto by default (the model decides from the prompt, not necessarily square). One of 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, 21:9 or 5:2 |
resolution |
string | No | Resolution level: 1k (default), 1.5k or 2k. Only these levels work; pixel values such as 1024x1024 return an error. 2k returns PNG (about 7 MB an image), 1k and 1.5k return JPEG |
quality |
string | No | auto (default, the same as low when generating), low or medium. medium gives more detail but is much slower; high returns an error |
response_format |
string | No | url (default, returns an image URL) or b64_json (returns the base64-encoded image) |
size |
string | No | The OpenAI form, such as 1024x1024, converted into a level and a ratio. Using aspect_ratio and resolution directly is recommended |
user |
string | No | An identifier for your end user, which the upstream uses to detect abuse |
Output sizes for some combinations of resolution and aspect_ratio: at 1k, 1:1 is 1024×1024, 16:9 is 1280×720 and 9:16 is 720×1280; at 1.5k, 1:1 is 1408×1408; at 2k, 1:1 is 2048×2048 and 16:9 is 2816×1584.
Edit an image
POST /v1/images/edits, also with a JSON body. Send 1 to 5 reference images and a description of the change; it suits changing the background or the style, changing part of an image, and combining several images:
| Parameter | Type | Required | Description |
|---|---|---|---|
model |
string | Yes | Model name |
prompt |
string | Yes | What to change. To change part of the image, just say which part, for example "make the hat red"; no mask is needed. With several reference images, refer to them as <IMAGE_0>, <IMAGE_1> and so on, in the order of images |
image |
object | One of the two | A single reference image, as an object {"url": "…"}, not a plain string |
images |
object[] | One of the two | Several reference images, each {"url": "…"}, up to 5. Use either image or images, not both |
n |
integer | No | How many images to generate, 1 to 10, 1 by default, each a different result |
aspect_ratio |
string | No | The same values as for generation. When omitted, a single reference image keeps its ratio, and with several the model decides; with a ratio set, the model recomposes the picture at the new ratio rather than stretching it |
resolution |
string | No | The same as for generation |
quality |
string | No | auto (default, the same as medium for edits), low or medium. low is faster and makes little difference for changes such as a new background, so set low for edits in bulk |
response_format |
string | No | The same as for generation |
user |
string | No | The same as for generation |
A reference image's url can be an image URL that can be downloaded directly from the internet, or a base64 data URL (data:image/png;base64,…), and one images array can mix both. JPEG, PNG and WebP are supported; GIF returns an error. The OpenAI SDK's images.edit() sends multipart/form-data, which doesn't fit this model, so the examples below send plain HTTP requests.
Request examples
Generation examples
curl
curl https://codaapi.com/v1/images/generations \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "A lighthouse by the sea at dawn with sailboats in the distance, flat illustration style",
"n": 1,
"aspect_ratio": "16:9",
"resolution": "1k"
}'
Python (pip install openai)
from openai import OpenAI
client = OpenAI(base_url="https://codaapi.com/v1", timeout=120) # the key is read from the OPENAI_API_KEY environment variable
result = client.images.generate(
model="grok-imagine-image-2.0",
prompt="A lighthouse by the sea at dawn with sailboats in the distance, flat illustration style",
extra_body={"aspect_ratio": "16:9", "resolution": "1k"},
)
print(result.data[0].url)
Node.js (npm install openai)
import OpenAI from 'openai';
const client = new OpenAI({ baseURL: 'https://codaapi.com/v1', timeout: 120_000 }); // the key is read from the OPENAI_API_KEY environment variable
const result = await client.images.generate({
model: 'grok-imagine-image-2.0',
prompt: 'A lighthouse by the sea at dawn with sailboats in the distance, flat illustration style',
aspect_ratio: '16:9',
resolution: '1k',
});
console.log(result.data[0].url);
Several images at once, returned as base64 (for example a poster with text):
curl https://codaapi.com/v1/images/generations \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "A minimalist bakery poster, the big title \"FRESH BAKE\" at the top, the subtitle \"Baked every day\" below, a croissant in the middle",
"n": 2,
"aspect_ratio": "3:4",
"quality": "medium",
"response_format": "b64_json"
}'
Edit examples
curl (one reference image)
curl https://codaapi.com/v1/images/edits \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "Change the background to a forest after snow",
"image": {"url": "https://example.com/portrait.jpg"},
"quality": "low"
}'
A local image, sent as a base64 data URL:
IMG_B64=$(base64 < jacket.jpg | tr -d '\n')
curl https://codaapi.com/v1/images/edits \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-image-2.0",
"prompt": "Make the jacket dark blue",
"image": {"url": "data:image/jpeg;base64,'"$IMG_B64"'"},
"quality": "low"
}'
Python (pip install requests, combining several reference images)
import os
import requests
resp = requests.post(
"https://codaapi.com/v1/images/edits",
headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
json={
"model": "grok-imagine-image-2.0",
"prompt": "Put the straw hat from <IMAGE_1> on the kitten in <IMAGE_0>",
"images": [
{"url": "https://example.com/kitten.jpg"},
{"url": "https://example.com/straw-hat.jpg"},
],
"aspect_ratio": "1:1",
},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["data"][0]["url"])
Node.js
const resp = await fetch('https://codaapi.com/v1/images/edits', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'grok-imagine-image-2.0',
prompt: 'Put the straw hat from <IMAGE_1> on the kitten in <IMAGE_0>',
images: [{ url: 'https://example.com/kitten.jpg' }, { url: 'https://example.com/straw-hat.jpg' }],
aspect_ratio: '1:1',
}),
});
if (!resp.ok) throw new Error(await resp.text());
console.log((await resp.json()).data[0].url);
Response
Both image endpoints return the same format; the gateway returns xAI's response as it is:
{
"data": [
{ "url": "https://…/xai-tmp-imgen-….jpeg", "mime_type": "image/jpeg" }
],
"usage": { "cost_in_usd_ticks": 400000000 }
}
| Field | Description |
|---|---|
data[].url |
The image URL (when response_format is url or omitted). It's temporary, so download and save the image soon |
data[].b64_json |
The base64-encoded image, without a data: prefix (when response_format is b64_json) |
data[].mime_type |
The image format: image/jpeg at 1k and 1.5k, image/png at 2k |
usage.cost_in_usd_ticks |
The cost of the request as xAI reports it, for reference only; CodaAPI charges by the prices in Model Square, as shown in the usage logs |
Video
Video generation is asynchronous and takes three steps:
- Submit a task with
POST /v1/videosand get itsid. - Check it with
GET /v1/videos/{task id}every 5 to 10 seconds untilstatusbecomescompleted(orfailed). - Download the MP4 from the
video_urlin the completed response.
Submit a task
POST /v1/videos, with a JSON body:
| Parameter | Type | Required | Description |
|---|---|---|---|
model |
string | Yes | Video model name, see Models |
prompt |
string | Yes | A text description of what happens on screen and how the camera moves |
seconds |
string | No | Length in seconds, written as a string such as "6"; setting it is recommended. Text-to-video and first-frame image-to-video go up to 15 seconds, reference images up to 10 |
aspect_ratio |
string | No | Aspect ratio, for example 16:9, 9:16, 1:1, 4:3, 3:4, 3:2 or 2:3 |
size |
string | No | The frame as width and height: 1280x720, 720x1280, 1792x1024 or 1024x1792. 1792x1024 and 1024x1792 are the same level as 720p, not sharper; for a square video set aspect_ratio to 1:1 rather than writing 960x960. Set either size or aspect_ratio |
resolution |
string | No | Output resolution: 480p, 720p or 1080p. If you set it, keep it the same as the resolution in the model name |
input_reference |
string | No | A first-frame reference image: an image URL or a base64 data URL (data:image/png;base64,…). Turn a local image into a data URL first, or upload it somewhere public |
reference_images |
string[] | No | URLs or data URLs of several reference images, up to 7; it can't be combined with input_reference, and reference images don't support 1080p |
Three ways to generate:
| Mode | Required parameters | Notes |
|---|---|---|
| Text-to-video | model, prompt |
Up to 15 seconds |
| First-frame image-to-video | model, prompt, input_reference |
The image becomes the first frame; up to 15 seconds |
| Reference images | model, prompt, reference_images |
The images guide the picture; up to 7 images and 10 seconds |
A successful submission returns the task; note its id:
{
"id": "task_6cY1mJ0bQeT3vX9…",
"object": "video",
"model": "grok-imagine-video-1.5-720p",
"status": "queued",
"progress": 0,
"created_at": 1764547200
}
Check a task
GET /v1/videos/{task id}, with {task id} replaced by the id returned when you submitted; checking every 5 to 10 seconds is recommended. The response once complete:
{
"id": "task_6cY1mJ0bQeT3vX9…",
"object": "video",
"model": "grok-imagine-video-1.5-720p",
"status": "completed",
"progress": 100,
"created_at": 1764547200,
"completed_at": 1764547296,
"seconds": "6",
"video_url": "https://…/video.mp4"
}
| Field | Description |
|---|---|
status |
queued, in_progress, completed or failed |
progress |
Progress, 0 to 100 |
video_url |
Present once complete: the address of the MP4 file |
seconds |
The length of the video in seconds |
error |
Present on failure; error.message gives the reason |
Download the video
Once the task is complete, download the MP4 from video_url (replace VIDEO_URL below with the address in the response), and save it soon:
curl -L "$VIDEO_URL" -o video.mp4
You can also request GET /v1/videos/{task id}/content (with the same Authorization), and the gateway passes the video file on to you.
Video examples
curl (text-to-video)
curl https://codaapi.com/v1/videos \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-video-1.5-720p",
"prompt": "A paper crane slowly circling above a desk in soft morning light, the camera slowly pushing in",
"seconds": "6",
"aspect_ratio": "16:9",
"resolution": "720p"
}'
First-frame image-to-video, with the image as a URL:
curl https://codaapi.com/v1/videos \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-video-1.5-720p",
"prompt": "Make the leaves in the picture sway gently in the wind",
"seconds": "6",
"input_reference": "https://example.com/first-frame.jpg",
"resolution": "720p"
}'
When the image is a local file, turn it into a data URL first:
IMAGE_DATA_URL="data:image/png;base64,$(base64 < first-frame.png | tr -d '\n')"
curl https://codaapi.com/v1/videos \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-video-1.5-720p",
"prompt": "Make the leaves in the picture sway gently in the wind",
"seconds": "6",
"input_reference": "'"$IMAGE_DATA_URL"'",
"resolution": "720p"
}'
Several reference images:
curl https://codaapi.com/v1/videos \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-video-1.5-480p",
"prompt": "Using the character and scene in these images, shoot a slow cinematic orbiting shot",
"seconds": "6",
"aspect_ratio": "9:16",
"resolution": "480p",
"reference_images": [
"https://example.com/character.jpg",
"https://example.com/street.jpg"
]
}'
Check a task, where TASK_ID is the id returned when you submitted:
curl https://codaapi.com/v1/videos/$TASK_ID \
-H "Authorization: Bearer $OPENAI_API_KEY"
Python (pip install requests; submit, wait, download)
import os
import time
import requests
BASE = "https://codaapi.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}
resp = requests.post(f"{BASE}/videos", headers=HEADERS, timeout=60, json={
"model": "grok-imagine-video-1.5-720p",
"prompt": "A paper crane slowly circling above a desk in soft morning light, the camera slowly pushing in",
"seconds": "6",
"aspect_ratio": "16:9",
"resolution": "720p",
})
resp.raise_for_status()
task_id = resp.json()["id"]
while True:
time.sleep(8)
video = requests.get(f"{BASE}/videos/{task_id}", headers=HEADERS, timeout=30).json()
print(video["status"], video.get("progress"))
if video["status"] == "completed":
break
if video["status"] == "failed":
raise RuntimeError(video.get("error"))
with requests.get(video["video_url"], stream=True, timeout=300) as file:
file.raise_for_status()
with open("crane.mp4", "wb") as f:
for chunk in file.iter_content(1 << 20):
f.write(chunk)
Node.js (Node 18 and later have fetch built in)
import fs from 'node:fs';
const BASE = 'https://codaapi.com/v1';
const headers = { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json' };
const submit = await fetch(`${BASE}/videos`, {
method: 'POST',
headers,
body: JSON.stringify({
model: 'grok-imagine-video-1.5-720p',
prompt: 'A paper crane slowly circling above a desk in soft morning light, the camera slowly pushing in',
seconds: '6',
aspect_ratio: '16:9',
resolution: '720p',
}),
});
if (!submit.ok) throw new Error(await submit.text());
const { id } = await submit.json();
let video;
do {
await new Promise((resolve) => setTimeout(resolve, 8000));
video = await (await fetch(`${BASE}/videos/${id}`, { headers })).json();
console.log(video.status, video.progress);
} while (video.status === 'queued' || video.status === 'in_progress');
if (video.status !== 'completed') throw new Error(JSON.stringify(video.error));
const file = await fetch(video.video_url);
fs.writeFileSync('crane.mp4', Buffer.from(await file.arrayBuffer()));
Errors
Errors come back as an OpenAI-style body, {"error": {"message": …, "type": …, "code": …}}, where error.message holds the reason and the ID of the request. Common errors from the image endpoints:
qualityset tohigh,noutside 1 to 10, bothimageandimagessent, or more than 5images: 400.resolutionwritten as pixels (for example1024x1024): 422.- A GIF reference image:
invalid_image. A reference image URL that can't be downloaded:Failed to download the provided image; use an address that can be downloaded directly from the internet, or a data URL. - Blocked by content moderation:
imagine:content-moderated; change the prompt before trying again.
Image requests are expensive, so retry only network errors. When a video task fails, its status is failed and the reason is in error.message. For what each status code means and what to do, see Error codes.
Billing
Image models are billed per request, charged the per-request price times the number of images returned: the charge is reserved by n when the request starts and settled by the number actually returned. The charge for each request is in the console under General → Usage Logs (open it directly).
Video models are priced per request, and some are also multiplied by a factor for parameters in the request such as the length. The charge is reserved when you submit the task and refunded if the task fails. The status, result and charge of video tasks are in the console under Task Logs (open it directly). Asynchronous tasks such as video store the submitted content and the task result so you can check their progress (see Data and privacy).
For the rules, see Pricing and multipliers; for prices, see Model Square and the price list.