xAI
Access 20 xAI models through Mastra's model router. Authentication is handled automatically using the XAI_API_KEY environment variable.
Learn more in the xAI documentation.
XAI_API_KEY=your-api-key
import { Agent } from "@mastra/core";
const agent = new Agent({
name: "my-agent",
instructions: "You are a helpful assistant",
model: "xai/grok-2",
});
// Generate a response
const response = await agent.generate("Hello!");
// Stream a response
const stream = await agent.stream("Tell me a story");
for await (const chunk of stream) {
console.log(chunk);
}
Models
| Model | Image | Audio | Video | Tools | Streaming | Context Window |
|---|---|---|---|---|---|---|
xai/grok-4-fast-non-reasoning | ✓ | ✗ | ✗ | ✓ | ✗ | 2,000,000 |
xai/grok-3-fast | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-4 | ✗ | ✗ | ✗ | ✓ | ✗ | 256,000 |
xai/grok-2-vision | ✓ | ✗ | ✗ | ✓ | ✗ | 8,192 |
xai/grok-code-fast-1 | ✗ | ✗ | ✗ | ✓ | ✗ | 256,000 |
xai/grok-2 | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-3-mini-fast-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-2-vision-1212 | ✓ | ✗ | ✗ | ✓ | ✗ | 8,192 |
xai/grok-3 | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-4-fast | ✓ | ✗ | ✗ | ✓ | ✗ | 2,000,000 |
xai/grok-2-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-2-1212 | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-3-fast-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-3-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-2-vision-latest | ✓ | ✗ | ✗ | ✓ | ✗ | 8,192 |
xai/grok-vision-beta | ✓ | ✗ | ✗ | ✓ | ✗ | 8,192 |
xai/grok-3-mini | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-beta | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-3-mini-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
xai/grok-3-mini-fast | ✗ | ✗ | ✗ | ✓ | ✗ | 131,072 |
Advanced Configuration
Custom Headers
const agent = new Agent({
name: "custom-agent",
model: {
modelId: "grok-2",
apiKey: process.env.XAI_API_KEY,
headers: {
"X-Custom-Header": "value",
},
},
});
Dynamic Model Selection
const agent = new Agent({
name: "dynamic-agent",
model: ({ runtimeContext }) => {
const useAdvanced = runtimeContext.task === "complex";
return useAdvanced ? "xai/grok-vision-beta" : "xai/grok-2";
},
});
Direct Provider Installation
This provider can also be installed directly as a standalone package, which can be used instead of the Mastra model router string. View the package documentation for more details.
- npm
- yarn
- pnpm
- bun
npm install @ai-sdk/xai
yarn add @ai-sdk/xai
pnpm add @ai-sdk/xai
bun add @ai-sdk/xai