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

grok.md

548 lines19.2 KB

1---
2title: Grok (xAI)
3id: grok-adapter
4order: 5
5description: "Use xAI Grok models in TanStack AI with @tanstack/ai-grok: Grok chat on the Responses API, Grok Imagine images and video, speech, transcription, and realtime voice."
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 adapter calls xAI chat models on the Responses API. It also calls Grok Imagine for images and video, plus speech, transcription, and realtime voice.
19​
20## 1. Install
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## 2. Set the API key
36​
37Put the key in the environment of your server:
38​
39```bash
40XAI_API_KEY=xai-...
41```
42​
43`grokText` and the other short factories read `XAI_API_KEY`. To pass the key in code, use the `create*` factory of the same adapter:
44​
45```typescript
46import { createGrokText } from "@tanstack/ai-grok";
47​
48const adapter = createGrokText("grok-4.7", process.env.XAI_API_KEY!);
49```
50​
51## 3. Stream a chat from the server
52​
53```typescript
54import {
55 chat,
56 chatParamsFromRequest,
57 toServerSentEventsResponse,
58} from "@tanstack/ai";
59import { grokText } from "@tanstack/ai-grok";
60​
61export async function POST(request: Request) {
62 const { messages, threadId, runId } = await chatParamsFromRequest(request);
63​
64 const stream = chat({
65 adapter: grokText("grok-4.7"),
66 messages,
67 threadId,
68 runId,
69 });
70​
71 return toServerSentEventsResponse(stream);
73```
74​
75## 4. Render the chat
76​
77The client is the same for every provider. Point `useChat` at your route:
78​
79```tsx
80import { useState } from "react";
81import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
82​
83export function Chat() {
84 const [input, setInput] = useState("");
85 const { messages, sendMessage } = useChat({
86 connection: fetchServerSentEvents("/api/chat"),
87 threadId: "support-chat",
88 });
89​
90 return (
91 <form
92 onSubmit={(event) => {
93 event.preventDefault();
94 sendMessage(input);
95 setInput("");
96 }}
97 >
98 {messages.map((message) => (
99 <p key={message.id}>
100 {message.parts
101 .map((part) => (part.type === "text" ? part.content : ""))
102 .join("")}
103 </p>
104 ))}
105 <input value={input} onChange={(event) => setInput(event.target.value)} />
106 </form>
107 );
109```
110​
111For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
112​
113You now have a streaming Grok chat. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter.
114​
115## Images
116​
117```typescript
118import { generateImage } from "@tanstack/ai";
119import { grokImage } from "@tanstack/ai-grok";
120​
121const result = await generateImage({
122 adapter: grokImage("grok-imagine-image-2.0"),
123 prompt: "A futuristic cityscape at sunset",
124 threadId: "thread-1",
125 size: "16:9_2k",
126 modelOptions: { quality: "medium" },
127});
128```
129​
130- The image models (`grok-imagine-image`, `grok-imagine-image-2.0`, `grok-imagine-image-quality`) take an aspect ratio as the size. `size` takes an `aspectRatio_resolution` template like `"16:9_2k"`. The `_2k` part is optional.
131- `grok-imagine-image-2.0` is the model that xAI recommends. It adds a `quality` option (`'low'` or `'medium'`, default `'medium'`).
132- To change an existing image, see [Image editing](#image-editing).
133​
134## Video
135​
136Grok Imagine makes short clips (1 to 15 seconds, with audio). Video generation is experimental. You start a job, then poll it:
137​
138```typescript
139import { generateVideo, getVideoJobStatus } from "@tanstack/ai";
140import { grokVideo } from "@tanstack/ai-grok";
141​
142const adapter = grokVideo("grok-imagine-video-1.5");
143​
144// 1. Create the job
145const { jobId } = await generateVideo({
146 adapter,
147 prompt: "A red panda balancing on a bamboo stalk in the rain",
148 threadId: "thread-1",
149 size: "16:9_720p", // "aspectRatio" or "aspectRatio_resolution"
150 duration: 5, // integer seconds, 1 to 15
151});
152​
153// 2. Poll until complete, then read the video URL
154let status = await getVideoJobStatus({ adapter, jobId });
155while (status.status !== "completed" && status.status !== "failed") {
156 await new Promise((r) => setTimeout(r, 5000));
157 status = await getVideoJobStatus({ adapter, jobId });
159​
160console.log(status.url); // hosted .mp4 URL
161```
162​
163- `grok-imagine-video-1.5` is the default that xAI recommends. It does text-to-video (with native 1080p), image-to-video, and reference-to-video.
164- `grok-imagine-video` (v1.0) also edits and extends a source video.
165​
166Image-to-video, references, edits, and sizes are in [Video options](#video-options). For the full flow and the `useGenerateVideo` hook, see [Video Generation](../media/video-generation).
167​
168## Speech
169​
170```typescript
171import { generateSpeech } from "@tanstack/ai";
172import { grokSpeech } from "@tanstack/ai-grok";
173​
174const result = await generateSpeech({
175 adapter: grokSpeech("grok-tts"),
176 text: "Hello from Grok!",
177 threadId: "thread-1",
178 voice: "default",
179 format: "mp3",
180});
181​
182console.log(result.audio); // Base64-encoded audio
183```
184​
185## Transcription
186​
187```typescript
188import { generateTranscription } from "@tanstack/ai";
189import { grokTranscription } from "@tanstack/ai-grok";
190import { audioFile } from "./audio";
191​
192const result = await generateTranscription({
193 adapter: grokTranscription("grok-stt"),
194 audio: audioFile,
195 threadId: "thread-1",
196});
197​
198console.log(result.text);
199```
200​
201## Summarization
202​
203<!-- ignored: grokSummarize()'s resolved provider-options type sits in a
204 contravariant position in SummarizeAdapter, so it isn't assignable to
205 summarize()'s adapter param for any current Grok model. Tracked in #821;
206 un-ignore once the adapter type is corrected. -->
207​
208```typescript ignore
209import { summarize } from "@tanstack/ai";
210import { grokSummarize } from "@tanstack/ai-grok";
211​
212const result = await summarize({
213 adapter: grokSummarize("grok-4.3"),
214 text: "Your long text to summarize...",
215 threadId: "thread-1",
216 maxLength: 100,
217 style: "concise", // "concise" | "bullet-points" | "paragraph"
218});
219​
220console.log(result.summary);
221```
222​
223## Realtime voice and files
224​
225- **Realtime voice**: `grokRealtime` and the token issuer `grokRealtimeToken` run a live voice chat. The default model is `grok-voice-think-fast-2.0`. `grok-voice-latest` always points to the newest model. See [Realtime Voice Chat](../media/realtime-chat).
226- **Files**: `grokFiles` uploads media to the xAI Files API. See [Files API](../advanced/files-api).
227​
228## Provider tools
229​
230xAI runs some tools itself. Import them from `@tanstack/ai-grok/tools` and add them to `tools`:
231​
232```typescript
233import { chat } from "@tanstack/ai";
234import { grokText } from "@tanstack/ai-grok";
235import { grokWebSearchTool } from "@tanstack/ai-grok/tools";
236​
237const stream = chat({
238 adapter: grokText("grok-4.3"),
239 messages: [{ role: "user", content: "What's new in AI this week?" }],
240 threadId: "thread-1",
241 tools: [grokWebSearchTool()],
242});
243```
244​
245- `grokWebSearchTool`: search the web. `filters` takes up to 5 `allowed_domains` or up to 5 `excluded_domains`, not both.
246- `grokXSearchTool`: search posts on X. Takes up to 20 `allowed_x_handles` or up to 20 `excluded_x_handles`, not both.
247- `grokFileSearchTool`: search your xAI file collections with `vector_store_ids`. `max_num_results` is 1 to 50.
248- `grokMCPTool`: connect a remote MCP server with `server_url` and `server_label`.
249​
250**Supported models:** `grok-4.3` and `grok-build-0.1`. For your own tools, use `toolDefinition()`. See [Tools](../tools/tools.md).
251​
252## Models and options
253​
254### Model options
255​
256Provider options go in `modelOptions`, with the names of the xAI Responses API. This includes the sampling options `temperature`, `top_p`, and `max_output_tokens`:
257​
258```typescript
259import { chat } from "@tanstack/ai";
260import { grokText } from "@tanstack/ai-grok";
261​
262const stream = chat({
263 adapter: grokText("grok-4.7"),
264 messages: [{ role: "user", content: "Hello!" }],
265 threadId: "thread-1",
266 modelOptions: {
267 temperature: 0.7,
268 top_p: 0.9,
269 max_output_tokens: 1024,
270 store: false,
271 include: ["reasoning.encrypted_content"],
272 },
273});
274```
275​
276- Requests use `store: false` by default, and include the encrypted reasoning with `include: ["reasoning.encrypted_content"]`. You can change both in `modelOptions`.
277- Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
278​
279### Reasoning
280​
281Want Grok to think harder? Set `reasoning` on `chat()`. It goes out as `reasoning.effort`, with a summary so that the thinking text streams:
282​
283```typescript
284import { chat } from "@tanstack/ai";
285import { grokText } from "@tanstack/ai-grok";
286​
287const stream = chat({
288 adapter: grokText("grok-4.7"),
289 messages: [{ role: "user", content: "Plan a database migration." }],
290 threadId: "thread-1",
291 reasoning: "xhigh",
292});
293```
294​
295| Model | Levels |
296| --- | --- |
297| `grok-4.7`, `grok-4.6` | `low` to `xhigh` |
298| `grok-4.5` | `low`, `medium`, `high` |
299| `grok-4.3` | `off`, `low`, `medium`, `high` |
300​
301- `grok-build-0.1` and the `non-reasoning` models take no `reasoning`.
302- `grok-4.20-reasoning` and `grok-4.1-fast-reasoning` take no `reasoning` either. They always think, and have no levels.
303​
304### Models
305​
306| Activity | Factory | Models |
307| --- | --- | --- |
308| Chat | `grokText` | `grok-4.7`, `grok-4.6`, `grok-4.5`, `grok-4.3`, `grok-build-0.1` |
309| Chat on Vertex | `grokVertexText` | `grok-4.3`, `grok-4.20-reasoning`, `grok-4.20-non-reasoning`, `grok-4.1-fast-reasoning`, `grok-4.1-fast-non-reasoning` |
310| Images | `grokImage` | `grok-imagine-image-2.0`, `grok-imagine-image`, `grok-imagine-image-quality` |
311| Video | `grokVideo` | `grok-imagine-video-1.5`, `grok-imagine-video` |
312| Speech | `grokSpeech` | `grok-tts` |
313| Transcription | `grokTranscription` | `grok-stt` |
314| Realtime voice | `grokRealtime` | `grok-voice-think-fast-2.0`, `grok-voice-latest`, `grok-voice-fast-1.0` |
315​
316`adapter.inputModalities` lists the input kinds of the selected model. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
317​
318## Advanced
319​
320### Configuration
321​
322```typescript
323import { createGrokText, type GrokTextConfig } from "@tanstack/ai-grok";
324​
325const config: Omit<GrokTextConfig, "apiKey"> = {
326 baseURL: "https://api.x.ai/v1", // Optional, this is the default
327};
328​
329const adapter = createGrokText("grok-4.7", process.env.XAI_API_KEY!, config);
330```
331​
332- Need a header on each request, or a log of each model call? The chat adapters of this package support [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call).
333- The text and summarize adapters use the xAI **Responses API** (`/v1/responses`). They support streaming text, reasoning events, structured output through `text.format`, and function tools.
334​
335### Grok on Vertex
336​
337Use `@tanstack/ai-grok/vertex` when Grok must run on Vertex AI. That path uses Google Cloud credentials and the regional or global endpoints of Vertex.
338​
339<!-- ::start:tabs variant="package-manager" mode="install" -->
340​
341react: @tanstack/ai-grok google-auth-library
342vue: @tanstack/ai-grok google-auth-library
343solid: @tanstack/ai-grok google-auth-library
344svelte: @tanstack/ai-grok google-auth-library
345preact: @tanstack/ai-grok google-auth-library
346angular: @tanstack/ai-grok google-auth-library
347vanilla: @tanstack/ai-grok google-auth-library
348octane: @tanstack/ai-grok google-auth-library
349​
350<!-- ::end:tabs -->
351​
352```typescript
353import { chat } from "@tanstack/ai";
354import { grokVertexText } from "@tanstack/ai-grok/vertex";
355​
356const stream = chat({
357 adapter: grokVertexText("grok-4.3", {
358 project: "my-project",
359 location: "global",
360 }),
361 messages: [{ role: "user", content: "Hello!" }],
362 threadId: "thread-1",
363});
364```
365​
366- `project` and `location` use the same names as `@tanstack/ai-vertex`. If you omit `location`, the factory uses `global`.
367- `grokVertexText` accepts only the Grok chat models that Vertex lists. See the [model table](#models). xAI API models such as `grok-4.6` and `grok-build-0.1` are not on Vertex.
368- The adapter sends the Vertex model id `xai/grok-4.3`.
369- Install `google-auth-library` for Application Default Credentials, or pass `authClient` or `getAccessToken`.
370- For summarize on Vertex, use `grokVertexSummarize` from the same entry.
371​
372Gemini on Vertex is in [`@tanstack/ai-vertex`](./vertex).
373​
374### Image editing
375​
376The grok-imagine models take image prompt parts. The adapter then calls the `/v1/images/edits` endpoint of xAI.
377​
378- You can send up to 3 source images. xAI reads them in the order of the prompt.
379- xAI has no syntax to point to an image in the prompt. Write the prompt in plain words. Your text goes out without changes.
380​
381```typescript
382import { generateImage } from "@tanstack/ai";
383import { grokImage } from "@tanstack/ai-grok";
384​
385const result = await generateImage({
386 adapter: grokImage("grok-imagine-image"),
387 prompt: [
388 {
389 type: "text",
390 content: "Render the product in the style of the second image",
391 },
392 {
393 type: "image",
394 source: { type: "url", value: "https://example.com/product.png" },
395 },
396 {
397 type: "image",
398 source: { type: "url", value: "https://example.com/style.png" },
399 },
400 ],
401 threadId: "thread-1",
402});
403```
404​
405The servers of xAI fetch URL sources, so the URLs must be public. For a private image, use a `data` source.
406​
407### Video options
408​
409#### Sizes
410​
411The video `size` takes an `aspectRatio_resolution` template. The resolution part is optional.
412​
413- Aspect ratios: `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, and `2:3`.
414- Resolutions: `480p` and `720p`. `1080p` (for example `"9:16_1080p"`) works only on `grok-imagine-video-1.5` for text-to-video and image-to-video.
415- Price: `grok-imagine-video` costs $0.05 per second of video. `grok-imagine-video-1.5` costs $0.08 per second.
416​
417#### Image-to-video
418​
419Add an `image` prompt part as the first frame. Describe the motion in the text part. The servers of xAI fetch URL sources, so they must be public. For a base64 first frame, use a `data` source.
420​
421```typescript
422import { generateVideo } from "@tanstack/ai";
423import { grokVideo } from "@tanstack/ai-grok";
424​
425const { jobId } = await generateVideo({
426 adapter: grokVideo("grok-imagine-video-1.5"),
427 prompt: [
428 {
429 type: "text",
430 content: "Make the waterfall crash down and slowly pan out the camera",
431 },
432 {
433 type: "image",
434 source: { type: "url", value: "https://example.com/waterfall-still.png" },
435 },
436 ],
437 threadId: "thread-1",
438 size: "16:9_720p",
439 duration: 10,
440});
441```
442​
443#### Reference-to-video
444​
445On `grok-imagine-video-1.5`, image parts with `metadata.role: 'reference'` (or `'character'`) become `reference_images`. They guide subjects and style, but do not lock the first frame. The prompt text names them `<IMAGE_0>`, `<IMAGE_1>`, and so on, in request order.
446​
447- `modelOptions.reference_audios` takes up to 3 preset TTS voices for generated speech. The prompt names them `<AUDIO_0>`, `<AUDIO_1>`, `<AUDIO_2>`.
448- You can add a first-frame image to the references. The first frame fixes the opening frame, and the references guide subjects, style, and voices.
449- The output of reference-to-video is at most 720p.
450- References work only on 1.5. The adapter rejects them on `grok-imagine-video`.
451​
452```typescript
453import { generateVideo } from "@tanstack/ai";
454import { grokVideo } from "@tanstack/ai-grok";
455​
456const { jobId } = await generateVideo({
457 adapter: grokVideo("grok-imagine-video-1.5"),
458 prompt: [
459 {
460 type: "text",
461 content: "<IMAGE_0> walks through a neon-lit alley while <AUDIO_0> narrates",
462 },
463 {
464 type: "image",
465 source: { type: "url", value: "https://example.com/opening-frame.png" },
466 metadata: { role: "start_frame" },
467 },
468 {
469 type: "image",
470 source: { type: "url", value: "https://example.com/character.png" },
471 metadata: { role: "reference" },
472 },
473 ],
474 threadId: "thread-1",
475 size: "16:9_720p",
476 modelOptions: {
477 reference_audios: [{ voice_id: "eve" }],
478 },
479});
480```
481​
482#### Edit and extend a video
483​
484`grok-imagine-video` (v1.0) can change or continue a clip. `grok-imagine-video-1.5` takes no video input, so 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`:
485​
486- `mode: 'edit'` posts to `/v1/videos/edits`. It changes only what the prompt asks for. The clip keeps the duration, aspect ratio, and resolution of the source (at most 720p). So the adapter rejects `size`, `aspect_ratio`, `resolution`, and `duration` in this mode.
487- `mode: 'extend'` posts to `/v1/videos/extensions`. It continues the clip. `duration` is the length of the **added part**, not the total: extending a 10-second clip with `duration: 5` gives 15 seconds. The size still comes from the source, so the adapter rejects `size`, `aspect_ratio`, and `resolution`.
488​
489```typescript
490import { generateVideo } from "@tanstack/ai";
491import { grokVideo } from "@tanstack/ai-grok";
492​
493const adapter = grokVideo("grok-imagine-video");
494​
495// Edit: change the clip in place
496const edit = await generateVideo({
497 adapter,
498 prompt: [
499 { type: "text", content: "Make the sky stormy with distant lightning" },
500 {
501 type: "video",
502 source: { type: "url", value: "https://example.com/clip.mp4" },
503 },
504 ],
505 threadId: "thread-1",
506 modelOptions: { mode: "edit" },
507});
508​
509// Extend: append 5 more seconds
510const extension = await generateVideo({
511 adapter,
512 prompt: [
513 { type: "text", content: "The camera keeps panning right across the bay" },
514 {
515 type: "video",
516 source: { type: "url", value: "https://example.com/clip.mp4" },
517 },
518 ],
519 threadId: "thread-1",
520 duration: 5, // added seconds, not the total
521 modelOptions: { mode: "extend" },
522});
523```
524​
525Both return the usual `{ jobId }`. Poll them like any other Grok video job.
526​
527When the job is complete, the result has the usage from the xAI API:
528​
529- `usage.billed`: the billed seconds of video (`{ quantity, unit: 'seconds' }`).
530- `usage.cost`: the exact cost in USD.
531​
532### API reference
533​
534Each factory pair has the same shape. The short factory reads `XAI_API_KEY` from the environment. The `create*` factory takes an explicit API key. Both take `model` as the first argument.
535​
536| Factories | Creates |
537| --- | --- |
538| `grokText(model, config?)` / `createGrokText(model, apiKey, config?)` | Text adapter |
539| `grokSummarize(model, config?)` / `createGrokSummarize(model, apiKey, config?)` | Summarization adapter |
540| `grokImage(model, config?)` / `createGrokImage(model, apiKey, config?)` | Image adapter |
541| `grokVideo(model, config?)` / `createGrokVideo(model, apiKey, config?)` | Video adapter for the Grok Imagine video models. Experimental |
542| `grokSpeech(model, config?)` / `createGrokSpeech(model, apiKey, config?)` | Text-to-speech adapter |
543| `grokTranscription(model, config?)` / `createGrokTranscription(model, apiKey, config?)` | Speech-to-text adapter |
544| `grokFiles` / `createGrokFiles` | Files API adapter. See [Files API](../advanced/files-api) |
545| `grokRealtime(...)` / `grokRealtimeToken(...)` | Realtime voice adapter and token issuer. See [Realtime Voice Chat](../media/realtime-chat) |
546| `grokVertexText` / `grokVertexSummarize` | Text and summarize adapters on Vertex. Import from `@tanstack/ai-grok/vertex` |
547​
548`config.baseURL` sets a custom base URL. `adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know.