
Grok Imagine 1.5: Animate a Photo via the xAI API
Summary
Turn a still image into a 720p video with native audio using xAI's Grok Imagine 1.5 in Python.
xAI quietly flipped a switch this week: image-to-video is now generally available in the Grok Imagine API, running the new grok-imagine-video-1.5 model. You hand the API a still photo and a sentence of direction, and a few seconds later you get back a 720p clip with motion, camera moves, and native audio baked in.
Why it is blowing up right now: on Artificial Analysis' text-to-video leaderboard Grok Imagine landed at rank 1, ahead of Veo 3.1 Fast, Veo 3, and Sora 2 Pro, and xAI is pitching it on the axis everyone actually feels day to day, latency and price, not just quality. For anyone shipping marketing clips, product loops, or social shorts, "animate this photo" went from a research demo to a single HTTP call.
This guide walks the whole loop end to end in Python: get a key, fire an image-to-video job, poll it to completion, feed it your own local image, and save the finished MP4. Every snippet is built against the official xAI docs and the real endpoints, so you can paste and run. By the end you will have a reusable function that turns any photo into a short video.
Prerequisites
- An xAI account with API access and an API key from console.x.ai (the Imagine endpoints bill per second of generated video, so add a payment method).
- Python 3.10 or newer.
pip install requestsfor the raw-HTTP path, and optionallypip install xai-sdkfor the official client.- A still image to animate. A public image URL is easiest to start; a local JPEG/PNG works too via a base64 data URI.
- Basic comfort with environment variables and JSON.
Set your key once in the shell so none of the snippets hardcode a secret:
export XAI_API_KEY="xai-...your-key..."Step 1 - How the image-to-video endpoint actually works
Video generation is asynchronous. You do not get the clip back in the first response, because rendering takes seconds, not milliseconds. The flow is three calls:
- POST
https://api.x.ai/v1/videos/generationswith your model, prompt, source image, and duration. This returns arequest_idimmediately. - GET
https://api.x.ai/v1/videos/{request_id}on a loop. The JSON carries astatusfield that moves from pending todone(orfailed/expired). - When
statusisdone, readvideo.urland download the MP4.
The source image can be supplied three ways: a public URL, a base64 data URI like data:image/jpeg;base64,..., or a file_id from the xAI Files API. We will use a URL first, then a local file.
Step 2 - Your first animation with plain requests
This is the most transparent version. It posts a job, then polls every five seconds until the video is ready. Note the request body shape: the image goes under an image object with a url key.
import os, time, requests
API = "https://api.x.ai/v1"
HEADERS = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ['XAI_API_KEY']}",
}
def animate(image_url: str, prompt: str, duration: int = 6) -> str:
"""Start an image-to-video job and block until the MP4 URL is ready."""
start = requests.post(
f"{API}/videos/generations",
headers=HEADERS,
json={
"model": "grok-imagine-video-1.5",
"prompt": prompt,
"image": {"url": image_url},
"duration": duration,
},
)
start.raise_for_status()
request_id = start.json()["request_id"]
print("job:", request_id)
while True:
r = requests.get(f"{API}/videos/{request_id}",
headers={"Authorization": HEADERS["Authorization"]})
data = r.json()
status = data["status"]
if status == "done":
return data["video"]["url"]
if status in ("failed", "expired"):
raise RuntimeError(f"generation {status}: {data}")
print(" ...", status)
time.sleep(5)
if __name__ == "__main__":
url = animate(
image_url="https://docs.x.ai/assets/api-examples/video/milkyway-still.png",
prompt="Generate a slow, serene time-lapse with drifting stars",
duration=6,
)
print("video:", url)
Example run. The job id and intermediate statuses print as it works, then the final URL:
job: vid_7f3c2a9e10b84d51
... queued
... processing
... processing
video: https://data.x.ai/videos/vid_7f3c2a9e10b84d51/output.mp4
That URL points to an MP4 with the camera move and audio already rendered. It is time-limited, so download it rather than hotlinking it in production.
Step 3 - The shorter path with the official SDK
If you would rather not hand-roll the polling loop, the xai-sdk client wraps it for you. The video.generate call blocks and hands back an object with a url.
import os
import xai_sdk
client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))
response = client.video.generate(
prompt="Generate a slow, serene time-lapse with drifting stars",
model="grok-imagine-video-1.5",
image_url="https://docs.x.ai/assets/api-examples/video/milkyway-still.png",
duration=6,
)
print(response.url)
Use the SDK when you want fewer moving parts; use the raw requests version when you need to log every status transition, run many jobs concurrently, or fire-and-poll from a worker queue.
Step 4 - Animate your own local photo
Most real work starts from a file on disk, not a public URL. Encode the image as a base64 data URI and drop it into the same image.url field. The data URI must include the correct MIME type prefix.
import base64, mimetypes
def to_data_uri(path: str) -> str:
mime = mimetypes.guess_type(path)[0] or "image/jpeg"
with open(path, "rb") as f:
b64 = base64.b64encode(f.read()).decode()
return f"data:{mime};base64,{b64}"
# reuse animate() from Step 2
data_uri = to_data_uri("product_shot.jpg")
url = animate(
image_url=data_uri,
prompt="Slow dolly-in on the product, soft studio light, subtle steam rising",
duration=6,
)
print("video:", url)
Keep source images reasonably sized. A 1024x1024 to 1280x720 JPEG is plenty; multi-megabyte PNGs bloat the request body and slow the upload for no quality gain since output is 720p.
Step 5 - Download and save the MP4
The returned URL is temporary. Stream it to disk as soon as the job finishes so you own the asset:
import requests
def download(url: str, path: str) -> str:
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(path, "wb") as f:
for chunk in r.iter_content(chunk_size=1 << 16):
f.write(chunk)
return path
mp4 = download(url, "animation.mp4")
print("saved:", mp4)
Worked example: a product photo into a 6-second social loop
Here is the full pipeline a small team would actually run: take one product photo, animate it with a marketing-flavored prompt, and save a ready-to-post clip. It stitches Steps 2, 4, and 5 into one script with a timeout guard.
import os, time, base64, mimetypes, requests
API = "https://api.x.ai/v1"
AUTH = {"Authorization": f"Bearer {os.environ['XAI_API_KEY']}"}
def to_data_uri(path):
mime = mimetypes.guess_type(path)[0] or "image/jpeg"
with open(path, "rb") as f:
return f"data:{mime};base64," + base64.b64encode(f.read()).decode()
def animate_file(path, prompt, duration=6, timeout=300):
body = {
"model": "grok-imagine-video-1.5",
"prompt": prompt,
"image": {"url": to_data_uri(path)},
"duration": duration,
}
start = requests.post(f"{API}/videos/generations",
headers={**AUTH, "Content-Type": "application/json"},
json=body)
start.raise_for_status()
rid = start.json()["request_id"]
deadline = time.time() + timeout
while time.time() < deadline:
data = requests.get(f"{API}/videos/{rid}", headers=AUTH).json()
if data["status"] == "done":
return data["video"]["url"]
if data["status"] in ("failed", "expired"):
raise RuntimeError(f"{data['status']}: {data}")
time.sleep(5)
raise TimeoutError(f"job {rid} did not finish in {timeout}s")
def download(url, out):
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(out, "wb") as f:
for c in r.iter_content(1 << 16):
f.write(c)
return out
if __name__ == "__main__":
url = animate_file(
"sneaker.jpg",
"Slow 180-degree orbit around the sneaker on a matte pedestal, "
"soft rim light, faint bass hum, premium ad feel",
duration=6,
)
print(download(url, "sneaker_ad.mp4"))
Run it and you get sneaker_ad.mp4, a vertical-friendly 720p clip with a camera orbit and ambient audio, generated from a single still. Swap the prompt to change the motion: "handheld push-in," "gentle parallax," or "timelapse of clouds behind the product" all produce distinct camera behavior.
Prompt patterns that actually steer the camera
With image-to-video, the model already knows what is in the frame, it reads that from your photo. Your prompt's real job is to direct motion, camera, and mood. Front-load the camera move, then add subject motion, then atmosphere and audio cues. These patterns map reliably to distinct results:
| You want | Prompt phrasing that works |
|---|---|
| Reveal the whole scene | "Slow zoom out, smooth, steady" |
| Draw the eye to the subject | "Gentle dolly-in, shallow depth of field" |
| Product turntable feel | "180-degree orbit around the object, matte pedestal" |
| Lifelike portrait | "Subtle head turn and blink, soft breeze in hair" |
| Landscape energy | "Time-lapse of clouds, sun moving across the sky" |
| Add sound character | "...with faint ambient hum" or "...soft wind audio" |
A few rules of thumb: keep it to one or two camera instructions per clip, because stacking "zoom in and pan and tilt" muddies the result. Describe what should change, not what is static. And remember the model generates native audio, so an audio cue in the prompt nudges the soundtrack it produces.
Common pitfalls and gotchas
- Wrong image field shape. The body expects
"image": {"url": ...}, not a top-levelimage_urlstring. The SDK usesimage_url=as a kwarg, but the raw REST body nests it underimage. Mixing the two is the most common 400. - Treating it as synchronous. The first POST only returns a
request_id. If you look for a video URL in that response you will get a KeyError. You must poll the GET endpoint. - No timeout on the poll loop. A naive
while Truecan hang forever if a job stalls. Always bound it with a deadline and handlefailedandexpiredexplicitly. - Letting the output URL expire. The returned
video.urlis short-lived. Download immediately; do not store the URL and fetch it hours later. - Oversized source images. Output is 720p, so a 12 MP source just inflates your base64 payload. Resize to roughly 720p-ish before encoding.
- Polling too aggressively. Hammering the GET endpoint every 200 ms wastes rate limit and money. Five seconds is a sane interval for clips of a few seconds.
- Forgetting native audio. Grok Imagine generates sound. If your platform expects silent video, you may need to strip the audio track afterward (for example with ffmpeg).
- Prompting like a chatbot. Describe motion and camera, not a static scene. "Dolly in, leaves rustling" beats "a tree in a field," which the model already has from the image.
Quick reference
| Item | Value |
|---|---|
| Start endpoint | POST https://api.x.ai/v1/videos/generations |
| Poll endpoint | GET https://api.x.ai/v1/videos/{request_id} |
| Model | grok-imagine-video-1.5 |
| Auth header | Authorization: Bearer $XAI_API_KEY |
| Body keys | model, prompt, image.{url}, duration |
| Image input | public URL, base64 data URI, or Files API file_id |
| Status values | pending/processing, done, failed, expired |
| Result field | video.url (temporary MP4 link) |
| Output | 720p MP4 with native audio |
| Python SDK | xai_sdk.Client().video.generate(...) |
Next steps
- Chain text-to-image then image-to-video: generate a still with
grok-2-imageat/v1/images/generations, then feed that image straight into the animate loop. - Explore the sibling endpoints: reference-to-video, video editing (add/remove/swap objects), and video extension for longer sequences.
- Move long jobs onto a worker queue. Store the
request_id, poll from a background task, and notify whendoneinstead of blocking a web request. - Batch-generate variants by looping over several prompts for the same image, then pick the best camera move.
- Read the official docs at docs.x.ai under Imagine for the full parameter list and the latest model variants.
That is the whole loop. One photo, one prompt, three HTTP calls, and a finished clip with sound, using the model currently sitting at the top of the text-to-video charts.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,604 newsletter subscribers.