TypeScript SDK
Images and video
Examples use the client created in the quickstart.
Image generation
Generate images from text prompts with client.images.generate(). Images are returned as temporary URLs by default, so download or persist them promptly. See the Image Generation guide for model capabilities and parameters.
TypeScript
const result = await client.images.generate({
model: 'grok-imagine-image-2.0',
prompt: 'A collage of London landmarks in a stenciled street-art style',
});
console.log(result.data[0]?.url);
console.log(result.usage?.cost_usd);
Request up to 10 images with n, and control output with aspect_ratio, resolution, and quality (supported on grok-imagine-image-2.0). Set response_format: 'b64_json' to receive base64 data instead of URLs:
TypeScript
import { writeFile } from 'node:fs/promises';
const result = await client.images.generate({
model: 'grok-imagine-image-2.0',
prompt: 'A futuristic city skyline at night',
n: 4,
aspect_ratio: '16:9',
resolution: '2k',
response_format: 'b64_json',
});
for (const [index, image] of result.data.entries()) {
if (image.b64_json) {
await writeFile(`skyline-${index}.jpg`, Buffer.from(image.b64_json, 'base64'));
}
}
Base64 encoding increases payload size by roughly a third, so large batches of high-resolution images can exceed the default 32 MiB response limit. Raise maxResponseBodyBytes on those calls:
TypeScript
const result = await client.images.generate(
{
model: 'grok-imagine-image-2.0',
prompt: 'A futuristic city skyline at night',
n: 10,
resolution: '2k',
response_format: 'b64_json',
},
{ maxResponseBodyBytes: 128 * 1024 * 1024 },
);
Each result provides data, usage, and http. usage.cost_usd converts cost_in_usd_ticks to US dollars, and usage is null when omitted by the API.
To upload generated images directly to your own object storage instead of hosting them with SpaceXSI, pass signed HTTP PUT URLs in output.upload_urls (one per image, using the default response_format: 'url'):
TypeScript
const result = await client.images.generate({
model: 'grok-imagine-image-2.0',
prompt: 'A lighthouse at dawn',
n: 2,
output: {
upload_urls: [
'https://storage.example.com/lighthouse-1.jpg?signature=...',
'https://storage.example.com/lighthouse-2.jpg?signature=...',
],
},
});
console.log(result.data.map(image => image.url));
Each upload sets Content-Type to the image's mime_type (image/jpeg unless the requested quality produces PNG), so sign upload URLs for that type or omit a Content-Type constraint. Uploads to Azure Blob SAS URLs also send x-ms-blob-type: BlockBlob.
Image editing
Pass a source image with your prompt to client.images.edit(). The image field accepts a public URL, a base64 data URL, a Files API file_id, or a Blob or File (which the SDK converts to a data URL automatically). See the Image Editing guide for prompting patterns.
TypeScript
import { openAsBlob } from 'node:fs';
const photo = await openAsBlob('./photo.png');
const result = await client.images.edit({
model: 'grok-imagine-image-2.0',
prompt: 'Render this as a pencil sketch with detailed shading',
image: photo,
});
console.log(result.data[0]?.url);
When a Blob or File has no MIME type, such as one returned by openAsBlob(), the SDK detects JPEG, PNG, or WebP from its leading bytes. The API rejects image data URLs that are not typed as one of those formats.
To combine up to five source images, pass images instead of image and reference them in the prompt as <IMAGE_0>, <IMAGE_1>, and so on. The output inherits the first image's aspect ratio unless aspect_ratio is set:
TypeScript
const result = await client.images.edit({
model: 'grok-imagine-image-2.0',
prompt: 'Place the cat from <IMAGE_0> on the sofa from <IMAGE_1>',
images: [
{ url: 'https://example.com/cat.png' },
{ file_id: 'file_abc123' },
],
aspect_ratio: '16:9',
});
Image edits also accept output.upload_urls, as shown in Image generation.
Video generation
Video generation runs asynchronously. client.videos.generate() starts the job and returns a request_id, and client.videos.wait() polls until completion. See the Video Generation guide for all supported modes.
TypeScript
const { request_id } = await client.videos.generate({
model: 'grok-imagine-video-1.5',
prompt: 'A paper boat drifting down a rain-soaked street',
duration: 8,
aspect_ratio: '16:9',
resolution: '720p',
});
const result = await client.videos.wait(request_id);
if (result.status === 'done') {
console.log(result.video?.url);
console.log(result.usage?.cost_usd);
} else {
console.error(result.status, result.error?.code, result.error?.message);
}
wait() resolves once the status leaves 'pending' ('done', 'failed', or 'expired'). Failed jobs include result.error with a code and message. If video.respect_moderation is false, the video did not pass moderation and no URL is returned. Video URLs are temporary, so download outputs promptly.
By default, wait() polls every 5 seconds for up to 10 minutes. Pass interval and timeout in milliseconds to customize polling, or an AbortSignal in signal to stop waiting. Both durations are capped at 24 hours. A timeout rejects with TimeoutError and lets you call wait() again. Timing out or aborting stops local polling only — it does not cancel the remote generation job. Call client.videos.get(request_id) to check status once without polling.
To animate a still frame, pass image (and optionally last_frame for the ending frame). image, last_frame, reference_images, and keyframe images accept a public URL, data URL, file_id, Blob, or File:
TypeScript
import { openAsBlob } from 'node:fs';
const { request_id } = await client.videos.generate({
model: 'grok-imagine-video-1.5',
prompt: 'Make the water crash down and slowly pan out the camera',
image: await openAsBlob('./waterfall.png'),
});
Models that support reference-to-video generation also accept up to three reference_audios. Each entry is a preset voice such as { voice_id: 'ara' } or an audio clip up to 15 seconds as { url }, Blob, or File. The SDK detects WAV or MP3 from leading bytes when a Blob or File has no MIME type.
Edit an existing video with client.videos.edit(), or extend it from its last frame with client.videos.extend(). Both return a request_id for wait(). The source video must be an MP4 provided as a URL, data URL, file_id, Blob, or File. For extensions, duration sets the length of the new segment only:
TypeScript
import { openAsBlob } from 'node:fs';
const edit = await client.videos.edit({
model: 'grok-imagine-video',
prompt: 'Give the woman a silver necklace',
video: await openAsBlob('portrait.mp4'),
});
const extension = await client.videos.extend({
model: 'grok-imagine-video',
prompt: 'The camera slowly zooms out to reveal the city skyline',
video: { file_id: 'file_abc123' },
duration: 6,
});
A Blob or File without a MIME type is sent as video/mp4. Because inline videos are base64-encoded inside the request body, upload large videos (up to 50 MB) with client.files.upload() and pass { file_id } instead.
List available video models with client.models.video.list(), or inspect one with client.models.video.get().
Last updated: December 1, 2026