Skip to main content

xAI logoxAI

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

ModelImageAudioVideoToolsStreamingContext Window
xai/grok-2131,072
xai/grok-2-1212131,072
xai/grok-2-latest131,072
xai/grok-2-vision8,192
xai/grok-2-vision-12128,192
xai/grok-2-vision-latest8,192
xai/grok-3131,072
xai/grok-3-fast131,072
xai/grok-3-fast-latest131,072
xai/grok-3-latest131,072
xai/grok-3-mini131,072
xai/grok-3-mini-fast131,072
xai/grok-3-mini-fast-latest131,072
xai/grok-3-mini-latest131,072
xai/grok-4256,000
xai/grok-4-fast2,000,000
xai/grok-4-fast-non-reasoning2,000,000
xai/grok-beta131,072
xai/grok-code-fast-1256,000
xai/grok-vision-beta8,192

Advanced Configuration

Custom Headers

const agent = new Agent({
name: "custom-agent",
model: {
id: "xai/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";
}
});

Provider Options

xAI supports the following provider-specific options via the providerOptions parameter:

const response = await agent.generate("Hello!", {
providerOptions: {
xai: {
// See available options in the table below
}
}
});

Available Options

reasoningEffort?:

"low" | "high" | undefined

searchParameters?:

{ mode: "off" | "auto" | "on"; returnCitations?: boolean | undefined; fromDate?: string | undefined; toDate?: string | undefined; maxSearchResults?: number | undefined; sources?: ({ ...; } | ... 2 more ... | { ...; })[] | undefined; } | undefined

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 install @ai-sdk/xai

For detailed provider-specific documentation, see the AI SDK xAI provider docs.