Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

grok.md

550 lines17.4 KB

1---
2title: Grok (xAI)
3id: grok-adapter
4order: 5
5description: "Use xAI Grok models with TanStack AI — Grok 4.3, Grok Build 0.1, Grok Imagine image generation, and Grok Imagine video generation via @tanstack/ai-grok."
6keywords:
7 - tanstack ai
8 - grok
9 - xai
10 - grok 4.3
11 - grok build
12 - image generation
13 - video generation
14 - grok imagine
15 - adapter
16---
17​
18The Grok text and summarization adapters provide access to xAI's Responses API for `grok-4.3` and `grok-build-0.1`, plus Grok Imagine image generation and Grok Imagine video generation.
19​
20## Installation
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24react: @tanstack/ai-grok
25vue: @tanstack/ai-grok
26solid: @tanstack/ai-grok
27svelte: @tanstack/ai-grok
28preact: @tanstack/ai-grok
29angular: @tanstack/ai-grok
30vanilla: @tanstack/ai-grok
31octane: @tanstack/ai-grok
32​
33<!-- ::end:tabs -->
34​
35## Basic Usage
36​
37```typescript
38import { chat } from "@tanstack/ai";
39import { grokText } from "@tanstack/ai-grok";
40​
41const stream = chat({
42 adapter: grokText("grok-build-0.1"),
43 messages: [{ role: "user", content: "Hello!" }],
44});
45```
46​
47## Basic Usage - Custom API Key
48​
49```typescript
50import { chat } from "@tanstack/ai";
51import { createGrokText } from "@tanstack/ai-grok";
52​
53const adapter = createGrokText("grok-build-0.1", process.env.XAI_API_KEY!);
54​
55const stream = chat({
56 adapter,
57 messages: [{ role: "user", content: "Hello!" }],
58});
59```
60​
61## Configuration
62​
63```typescript
64import { createGrokText, type GrokTextConfig } from "@tanstack/ai-grok";
65​
66const config: Omit<GrokTextConfig, "apiKey"> = {
67 baseURL: "https://api.x.ai/v1", // Optional, this is the default
68};
69​
70const adapter = createGrokText("grok-build-0.1", process.env.XAI_API_KEY!, config);
71```
72​
73## Grok on Vertex
74​
75Use `@tanstack/ai-grok/vertex` when Grok must run on Vertex AI. That path
76uses Google Cloud credentials and Vertex regional or global endpoints.
77​
78<!-- ::start:tabs variant="package-manager" mode="install" -->
79​
80react: @tanstack/ai-grok google-auth-library
81vue: @tanstack/ai-grok google-auth-library
82solid: @tanstack/ai-grok google-auth-library
83svelte: @tanstack/ai-grok google-auth-library
84preact: @tanstack/ai-grok google-auth-library
85angular: @tanstack/ai-grok google-auth-library
86vanilla: @tanstack/ai-grok google-auth-library
87octane: @tanstack/ai-grok google-auth-library
88​
89<!-- ::end:tabs -->
90​
91```typescript
92import { chat } from "@tanstack/ai";
93import { grokVertexText } from "@tanstack/ai-grok/vertex";
94​
95const stream = chat({
96 adapter: grokVertexText("grok-4.3", {
97 project: "my-project",
98 location: "global",
99 }),
100 messages: [{ role: "user", content: "Hello!" }],
101});
102```
103​
104`project` and `location` use the same names as `@tanstack/ai-vertex`. If you
105omit `location`, the factory uses `global`.
106​
107`grokVertexText` accepts only the Grok chat models that Vertex lists:
108​
109- `grok-4.3`
110- `grok-4.20-reasoning`
111- `grok-4.20-non-reasoning`
112- `grok-4.1-fast-reasoning`
113- `grok-4.1-fast-non-reasoning`
114​
115xAI API models such as `grok-4.6` and `grok-build-0.1` are not on Vertex.
116​
117The adapter sends the Vertex model id `xai/grok-4.3`. Install
118`google-auth-library` for Application Default Credentials, or pass
119`authClient` or `getAccessToken`.
120​
121Use `grokVertexSummarize` from the same entry when you need summarize on
122Vertex.
123​
124Gemini on Vertex lives in [`@tanstack/ai-vertex`](./vertex).
125​
126## Example: Chat Completion
127​
128```typescript
129import { chat, toServerSentEventsResponse } from "@tanstack/ai";
130import { grokText } from "@tanstack/ai-grok";
131​
132export async function POST(request: Request) {
133 const { messages } = await request.json();
134​
135 const stream = chat({
136 adapter: grokText("grok-build-0.1"),
137 messages,
138 });
139​
140 return toServerSentEventsResponse(stream);
142```
143​
144## Example: With Tools
145​
146```typescript
147import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
148import { grokText } from "@tanstack/ai-grok";
149import { z } from "zod";
150​
151const getWeatherDef = toolDefinition({
152 name: "get_weather",
153 description: "Get the current weather",
154 inputSchema: z.object({
155 location: z.string(),
156 }),
157});
158​
159const getWeather = getWeatherDef.server(async ({ location }) => {
160 // Fetch weather data
161 return { temperature: 72, conditions: "sunny" };
162});
163​
164export async function POST(request: Request) {
165 const { messages } = await request.json();
166​
167 const stream = chat({
168 adapter: grokText("grok-build-0.1"),
169 messages,
170 tools: [getWeather],
171 });
172​
173 return toServerSentEventsResponse(stream);
175```
176​
177## Model Options
178​
179Grok supports xAI Responses API options. Sampling parameters live here too — `temperature`, `top_p`, and `max_output_tokens` — rather than as root-level props on `chat()`:
180​
181```typescript
182import { chat, toServerSentEventsResponse } from "@tanstack/ai";
183import { grokText } from "@tanstack/ai-grok";
184​
185export async function POST(request: Request) {
186 const { messages } = await request.json();
187​
188 const stream = chat({
189 adapter: grokText("grok-build-0.1"),
190 messages,
191 modelOptions: {
192 temperature: 0.7,
193 top_p: 0.9,
194 max_output_tokens: 1024,
195 store: false,
196 include: ["reasoning.encrypted_content"],
197 },
198 });
199​
200 return toServerSentEventsResponse(stream);
202```
203​
204> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
205​
206## Summarization
207​
208Summarize long text content:
209​
210<!-- ignored: grokSummarize()'s resolved provider-options type sits in a
211 contravariant position in SummarizeAdapter, so it isn't assignable to
212 summarize()'s adapter param for any current Grok model. Tracked in #821;
213 un-ignore once the adapter type is corrected. -->
214​
215```typescript ignore
216import { summarize } from "@tanstack/ai";
217import { grokSummarize } from "@tanstack/ai-grok";
218​
219const result = await summarize({
220 adapter: grokSummarize("grok-4.3"),
221 text: "Your long text to summarize...",
222 maxLength: 100,
223 style: "concise", // "concise" | "bullet-points" | "paragraph"
224});
225​
226console.log(result.summary);
227```
228​
229## Image Generation
230​
231Generate images with a Grok Imagine model.
232​
233The image models (`grok-imagine-image`, `grok-imagine-image-2.0`,
234`grok-imagine-image-quality`) are aspect-ratio sized — `size` takes an
235`aspectRatio_resolution` template like `"16:9_2k"` (the `_2k` suffix is
236optional). `grok-imagine-image-2.0` is xAI's recommended model and adds a
2372.0-only `quality` provider option (`'low' | 'medium'`, default `'medium'`):
238​
239```typescript
240import { generateImage } from "@tanstack/ai";
241import { grokImage } from "@tanstack/ai-grok";
242​
243const result = await generateImage({
244 adapter: grokImage("grok-imagine-image-2.0"),
245 prompt: "A futuristic cityscape at sunset",
246 size: "16:9_2k",
247 modelOptions: { quality: "medium" },
248});
249```
250​
251### Image Editing (image-to-image)
252​
253The grok-imagine models accept image prompt parts for image-conditioned
254generation via xAI's `/v1/images/edits` endpoint — up to 3 source images,
255addressed by xAI in the order they appear in the prompt. Per xAI's docs
256there is no in-prompt referencing syntax; write the prompt naturally and
257your text is sent verbatim:
258​
259```typescript
260import { generateImage } from "@tanstack/ai";
261import { grokImage } from "@tanstack/ai-grok";
262​
263const result = await generateImage({
264 adapter: grokImage("grok-imagine-image"),
265 prompt: [
266 {
267 type: "text",
268 content: "Render the product in the style of the second image",
269 },
270 {
271 type: "image",
272 source: { type: "url", value: "https://example.com/product.png" },
273 },
274 {
275 type: "image",
276 source: { type: "url", value: "https://example.com/style.png" },
277 },
278 ],
279});
280```
281​
282URL sources are fetched by xAI's servers, so they must be publicly
283reachable; use a `data` source for private images.
284​
285## Video Generation (Experimental)
286​
287Generate short video clips (1–15 seconds, with audio) with the Grok Imagine video models via xAI's asynchronous jobs/polling API.
288​
289Available models:
290​
291- `grok-imagine-video` (v1.0) — text-to-video, image-to-video, and source-video edit / extend, $0.05 per second of video.
292- `grok-imagine-video-1.5` — xAI's recommended default, $0.08 per second of video. Supports text-to-video (with native 1080p), image-to-video, and reference-to-video. It does not accept a source video.
293​
294Text-to-video:
295​
296```typescript
297import { generateVideo, getVideoJobStatus } from "@tanstack/ai";
298import { grokVideo } from "@tanstack/ai-grok";
299​
300const adapter = grokVideo("grok-imagine-video-1.5");
301​
302// 1. Create the job
303const { jobId } = await generateVideo({
304 adapter,
305 prompt: "A red panda balancing on a bamboo stalk in the rain",
306 size: "16:9_720p", // "aspectRatio" or "aspectRatio_resolution"
307 duration: 5, // integer seconds, 1–15
308});
309​
310// 2. Poll until complete, then read the video URL
311let status = await getVideoJobStatus({ adapter, jobId });
312while (status.status !== "completed" && status.status !== "failed") {
313 await new Promise((r) => setTimeout(r, 5000));
314 status = await getVideoJobStatus({ adapter, jobId });
316​
317console.log(status.url); // hosted .mp4 URL
318```
319​
320For image-to-video, include an `image` prompt part as the starting frame and describe the desired motion in the text part. URL sources are fetched by xAI's servers (so they must be publicly reachable); use a `data` source for a base64 starting frame:
321​
322```typescript
323import { generateVideo } from "@tanstack/ai";
324import { grokVideo } from "@tanstack/ai-grok";
325​
326const { jobId } = await generateVideo({
327 adapter: grokVideo("grok-imagine-video-1.5"),
328 prompt: [
329 {
330 type: "text",
331 content: "Make the waterfall crash down and slowly pan out the camera",
332 },
333 {
334 type: "image",
335 source: { type: "url", value: "https://example.com/waterfall-still.png" },
336 },
337 ],
338 size: "16:9_720p",
339 duration: 10,
340});
341```
342​
343Like the Grok Imagine image models, sizing is aspect-ratio based: the `size` option takes an `aspectRatio_resolution` template. Supported aspect ratios are `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, and `2:3`; supported resolutions are `480p`, `720p`, and (on `grok-imagine-video-1.5` text-to-video / image-to-video only) `1080p` (e.g. `"9:16_1080p"`). The resolution suffix is optional.
344​
345### Reference-to-Video
346​
347On `grok-imagine-video-1.5`, image prompt parts with `metadata.role: 'reference'` (or `'character'`) become `reference_images` — they guide subjects and style without locking the first frame, and are addressed from the prompt text as `<IMAGE_0>`, `<IMAGE_1>`, … in request order. Preset TTS voices (up to 3) can be referenced for generated speech via `modelOptions.reference_audios`, addressed as `<AUDIO_0>`, `<AUDIO_1>`, `<AUDIO_2>`. Reference-to-video output is capped at 720p. A starting-frame image can be combined with reference inputs on 1.5: the start frame pins the opening frame while the references steer subjects, style, and voices. Reference inputs are a 1.5-only feature, so the adapter rejects them on `grok-imagine-video`:
348​
349```typescript
350import { generateVideo } from "@tanstack/ai";
351import { grokVideo } from "@tanstack/ai-grok";
352​
353const { jobId } = await generateVideo({
354 adapter: grokVideo("grok-imagine-video-1.5"),
355 prompt: [
356 {
357 type: "text",
358 content: "<IMAGE_0> walks through a neon-lit alley while <AUDIO_0> narrates",
359 },
360 {
361 type: "image",
362 source: { type: "url", value: "https://example.com/opening-frame.png" },
363 metadata: { role: "start_frame" },
364 },
365 {
366 type: "image",
367 source: { type: "url", value: "https://example.com/character.png" },
368 metadata: { role: "reference" },
369 },
370 ],
371 size: "16:9_720p",
372 modelOptions: {
373 reference_audios: [{ voice_id: "eve" }],
374 },
375});
376```
377​
378### Video Editing and Extension
379​
380`grok-imagine-video` (v1.0) can rewrite or continue an existing clip. `grok-imagine-video-1.5` has no video input — the adapter rejects a source-video part or `mode` on that model. Pass the source clip as a `video` prompt part and pick the mode with `modelOptions.mode`:
381​
382- `mode: 'edit'` posts to `/v1/videos/edits` — modifies only what the prompt asks for, keeping the rest of the clip intact. Duration, aspect ratio, and resolution are inherited from the source (capped at 720p), so the adapter rejects `size`, `aspect_ratio`, `resolution`, and `duration` in this mode rather than sending fields the API ignores.
383- `mode: 'extend'` posts to `/v1/videos/extensions` — continues the clip. `duration` is the length of the **added tail**, not the total: extending a 10-second clip with `duration: 5` yields 15 seconds. Output geometry is still inherited from the source, so `size` / `aspect_ratio` / `resolution` are rejected here too.
384​
385```typescript
386import { generateVideo } from "@tanstack/ai";
387import { grokVideo } from "@tanstack/ai-grok";
388​
389const adapter = grokVideo("grok-imagine-video");
390​
391// Edit: change the clip in place
392const edit = await generateVideo({
393 adapter,
394 prompt: [
395 { type: "text", content: "Make the sky stormy with distant lightning" },
396 {
397 type: "video",
398 source: { type: "url", value: "https://example.com/clip.mp4" },
399 },
400 ],
401 modelOptions: { mode: "edit" },
402});
403​
404// Extend: append 5 more seconds
405const extension = await generateVideo({
406 adapter,
407 prompt: [
408 { type: "text", content: "The camera keeps panning right across the bay" },
409 {
410 type: "video",
411 source: { type: "url", value: "https://example.com/clip.mp4" },
412 },
413 ],
414 duration: 5, // added seconds, not the total
415 modelOptions: { mode: "extend" },
416});
417```
418​
419Both return the usual `{ jobId }` and are polled like any other Grok video job.
420​
421When the job completes, the adapter reports usage on the result: `usage.billed` carries the billed seconds of video (`{ quantity, unit: 'seconds' }`) and `usage.cost` the exact cost in USD, both as returned by the xAI API.
422​
423See [Video Generation](../media/video-generation) for the full jobs/polling flow, streaming mode, and the `useGenerateVideo` hook.
424​
425## Text-to-Speech
426​
427Generate speech with Grok TTS:
428​
429```typescript
430import { generateSpeech } from "@tanstack/ai";
431import { grokSpeech } from "@tanstack/ai-grok";
432​
433const result = await generateSpeech({
434 adapter: grokSpeech("grok-tts"),
435 text: "Hello from Grok!",
436 voice: "default",
437 format: "mp3",
438});
439​
440console.log(result.audio); // Base64-encoded audio
441```
442​
443## Transcription
444​
445Transcribe audio with Grok STT:
446​
447```typescript
448import { generateTranscription } from "@tanstack/ai";
449import { grokTranscription } from "@tanstack/ai-grok";
450import { audioFile } from "./audio";
451​
452const result = await generateTranscription({
453 adapter: grokTranscription("grok-stt"),
454 audio: audioFile,
455});
456​
457console.log(result.text);
458```
459​
460## Realtime Voice
461​
462Grok also exposes a Realtime voice adapter (`grokRealtime`) and a token issuer (`grokRealtimeToken`) for low-latency voice conversations. The default model is `grok-voice-think-fast-2.0` (xAI's current recommended speech-to-speech model); `grok-voice-latest` always points at the newest model. The 1.0 ids remain accepted for compatibility, but xAI has deprecated `grok-voice-think-fast-1.0`. See [Realtime Voice Chat](../media/realtime-chat) for the end-to-end flow.
463​
464## Environment Variables
465​
466Set your API key in environment variables:
467​
468```bash
469XAI_API_KEY=xai-...
470```
471​
472## Implementation Notes
473​
474### Responses API
475​
476The Grok text and summarize adapters use xAI's **Responses API** (`/v1/responses`). Requests default to `store: false` and include encrypted reasoning content with `include: ["reasoning.encrypted_content"]`; both can be overridden through `modelOptions`.
477​
478The shared Responses implementation supports streaming text, reasoning events, structured output via `text.format`, and user-defined function tools.
479​
480## API Reference
481​
482### `grokText(model, config?)`
483​
484Creates a Grok text adapter using environment variables.
485​
486**Parameters:**
487​
488- `model` - The model name (`'grok-4.3'` or `'grok-build-0.1'`)
489- `config.baseURL?` - Custom base URL (optional)
490​
491**Returns:** A Grok text adapter instance.
492​
493### `createGrokText(model, apiKey, config?)`
494​
495Creates a Grok text adapter with an explicit API key.
496​
497**Parameters:**
498​
499- `model` - The model name
500- `apiKey` - Your xAI API key
501- `config.baseURL?` - Custom base URL (optional)
502​
503**Returns:** A Grok text adapter instance.
504​
505### `grokSummarize(model, config?)`
506​
507Creates a Grok summarization adapter using environment variables.
508​
509**Returns:** A Grok summarize adapter instance.
510​
511### `createGrokSummarize(model, apiKey, config?)`
512​
513Creates a Grok summarization adapter with an explicit API key.
514​
515**Returns:** A Grok summarize adapter instance.
516​
517### `grokImage(model, config?)` / `createGrokImage(model, apiKey, config?)`
518​
519Creates a Grok image generation adapter.
520​
521### `grokVideo(model, config?)` / `createGrokVideo(model, apiKey, config?)`
522​
523Creates a Grok video generation adapter (experimental) for the Grok Imagine video models (`'grok-imagine-video'`, `'grok-imagine-video-1.5'`).
524​
525### `grokSpeech(model, config?)` / `createGrokSpeech(model, apiKey, config?)`
526​
527Creates a Grok text-to-speech adapter.
528​
529### `grokTranscription(model, config?)` / `createGrokTranscription(model, apiKey, config?)`
530​
531Creates a Grok speech-to-text adapter.
532​
533### `grokRealtime(...)` / `grokRealtimeToken(...)`
534​
535Realtime voice adapter and token issuer. See [Realtime Voice Chat](../media/realtime-chat) for usage.
536​
537## Next Steps
538​
539- [Getting Started](../getting-started/quick-start) - Learn the basics
540- [Tools Guide](../tools/tools) - Learn about tools
541- [Other Adapters](./openai) - Explore other providers
542​
543## Provider Tools
544​
545Grok does not currently expose provider-specific tool factories.
546Define your own tools with `toolDefinition()` from `@tanstack/ai`.
547​
548See [Tools](../tools/tools.md) for the general tool-definition flow, or
549[Provider Tools](../tools/provider-tools.md) for other providers'
550native-tool offerings.