### createXai constructor options example Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/configuration.md Configuration example for the createXai provider, showing how to set baseURL, apiKey, custom headers, and a custom fetch implementation. The fetch option can intercept requests. The default singleton is equivalent to createXai({}) at module load. ```ts import { createXai } from '@ai-sdk/xai'; const provider = createXai({ baseURL: 'https://api.x.ai/v1', apiKey: 'xai-...', headers: { 'X-Project-ID': 'acme' }, fetch: (input, init) => { console.log('intercepting', input); return fetch(input, init); }, }); // The default singleton is equivalent to createXai({}) at module load: // import { xai } from '@ai-sdk/xai'; ``` -------------------------------- ### Install @ai-sdk/xai with npm Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/README.md Install the xAI Grok provider module using npm. ```bash npm i @ai-sdk/xai ``` -------------------------------- ### Basic doGenerate example Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Basic example of calling doGenerate with a simple user prompt. It creates a model using createXai with an API key from the environment, sends a text prompt with maxOutputTokens and temperature, then iterates over the content blocks to print text blocks and logs usage and finishReason. ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai({ apiKey: process.env.XAI_API_KEY }).chat('grok-3'); const result = await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }], maxOutputTokens: 256, temperature: 0.7, }); for (const block of result.content) { if (block.type === 'text') console.log(block.text); } console.log(result.usage, result.finishReason); ``` -------------------------------- ### Generate text with xai('grok-3-beta') Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/README.md Example of using the xai provider with the 'grok-3-beta' model to generate text. ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const { text } = await generateText({ model: xai('grok-3-beta'), prompt: 'Write a vegetarian lasagna recipe for 4 people.', }); ``` -------------------------------- ### Import VERSION from @ai-sdk/xai Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/internal-modules.md Shows how to import and log the VERSION constant from the package. The comment indicates an example output value. ```ts import { VERSION } from '@ai-sdk/xai'; console.log(VERSION); // e.g. '2.1.0-beta.7' ``` -------------------------------- ### Example — all factory methods Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md Demonstrates using all factory methods of the XaiProvider: chat, languageModel, call signature, image, and imageModel. Comments indicate the returned model types. ```ts import { createXai } from '@ai-sdk/xai'; import { generateImage } from 'ai'; const provider = createXai(); const chatModel = provider.chat('grok-2-1212'); // XaiChatLanguageModel const sameModel = provider.languageModel('grok-2-1212'); const alsoSame = provider('grok-2-1212'); // call signature const imageModel = provider.image('grok-2-image'); // OpenAICompatibleImageModel const img2 = provider.imageModel('grok-2-image'); ``` -------------------------------- ### Basic usage: createXai with generateText Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md Creates a provider with an API key or environment variable, gets a Grok model, and generates text. ```ts import { createXai, xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const provider = createXai({ apiKey: 'xai-...', // or set process.env.XAI_API_KEY }); // or simply use the pre-built singleton: const model = provider('grok-4-fast-reasoning'); const { text } = await generateText({ model, prompt: 'Explain quaternions in one paragraph.', }); ``` -------------------------------- ### doGenerate with provider options and error handling Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Shows how to call doGenerate with provider options for reasoning and search, including error handling. The example sets reasoningEffort to 'high', enables search with citations and date range, and uses a 30-second timeout. The catch block handles xAI API errors (auth, rate limit) or zod validation errors. ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai({ apiKey: process.env.XAI_API_KEY }).chat('grok-3'); try { const result = await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Top AI stories today?' }] }], providerOptions: { xai: { reasoningEffort: 'high', searchParameters: { mode: 'on', returnCitations: true, fromDate: '2025-01-01', toDate: '2025-12-31', maxSearchResults: 10, sources: [{ type: 'web', country: 'US', safeSearch: true }], }, }, }, abortSignal: AbortSignal.timeout(30_000), }); const sources = result.content.filter(b => b.type === 'source'); console.log(result.content, sources); } catch (error) { // xAI API error (auth, rate limit, ...) or zod validation error console.error(error); } ``` -------------------------------- ### XaiProviderOptions Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-options.md Documentation for the XaiProviderOptions type, including its fields, wire mapping, and usage examples with generateText. ```APIDOC ## Type `XaiProviderOptions` ### Description Defines the provider-specific options for the xAI chat model, including reasoning effort and search parameters. ### Type Definition ```ts type XaiProviderOptions = { reasoningEffort?: 'low' | 'high'; searchParameters?: { mode: 'off' | 'auto' | 'on'; returnCitations?: boolean; fromDate?: string; toDate?: string; maxSearchResults?: number; // 1..50 sources?: ( | { type: 'web'; country?: string; excludedWebsites?: string[]; allowedWebsites?: string[]; safeSearch?: boolean } | { type: 'x'; excludedXHandles?: string[]; includedXHandles?: string[]; postFavoriteCount?: number; postViewCount?: number; xHandles?: string[] } | { type: 'news'; country?: string; excludedWebsites?: string[]; safeSearch?: boolean } | { type: 'rss'; links: string[] } )[]; }; }; ``` ### Fields | Field | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | `reasoningEffort` | `'low' \| 'high'` | no | — | Reasoning effort for reasoning models; sent as `reasoning_effort` in the request | | `searchParameters` | object | no | — | Search-mode block; sent as `search_parameters` | | `searchParameters.mode` | `'off' \| 'auto' \| 'on'` | yes (inside block) | `'auto'` per API docs comment | `off` disables search, `auto` lets the model decide, `on` always searches | | `searchParameters.returnCitations` | `boolean` | no | `true` per API docs comment | Whether citations are returned in the response; mapped to `return_citations` | | `searchParameters.fromDate` | `string` | no | — | Search start date, ISO-8601 `YYYY-MM-DD`; mapped to `from_date` | | `searchParameters.toDate` | `string` | no | — | Search end date, ISO-8601 `YYYY-MM-DD`; mapped to `to_date` | | `searchParameters.maxSearchResults` | `number` | no | `20` per API docs comment | Max search results to consider (1–50); mapped to `max_search_results` | | `searchParameters.sources` | array of source unions | no | `["web", "x"]` per API docs comment | Data sources; each carries type-specific filters as in the table above | ### Wire Mapping - `returnCitations` → `return_citations` - `fromDate` → `from_date` - `toDate` → `to_date` - `maxSearchResults` → `max_search_results` - `excludedWebsites` → `excluded_websites` - `allowedWebsites` → `allowed_websites` - `safeSearch` → `safe_search` - `excludedXHandles` → `excluded_x_handles` - `includedXHandles` → `included_x_handles` (falling back to deprecated `xHandles`) - `postFavoriteCount` → `post_favorite_count` - `postViewCount` → `post_view_count` - `links` maps unchanged ### Example — usage with `generateText` ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const { text, sources } = await generateText({ model: xai('grok-3'), prompt: 'What happened in space exploration this week?', providerOptions: { xai: { reasoningEffort: 'high', searchParameters: { mode: 'on', returnCitations: true, fromDate: '2025-11-01', toDate: '2025-11-30', maxSearchResults: 5, sources: [ { type: 'web', country: 'US', safeSearch: true }, { type: 'x', includedXHandles: ['NASA'], postFavoriteCount: 100 }, ], }, }, }, }); ``` ### Example — invalid value rejection ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; try { await generateText({ model: xai('grok-3'), prompt: 'Hello', providerOptions: { xai: { searchParameters: { mode: 'on', maxSearchResults: 500, // violates min(1).max(50) }, }, }, }); } catch (error) { // zod validation error raised by parseProviderOptions console.error(error); } ``` ``` -------------------------------- ### XAI_API_KEY environment variable setup Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/configuration.md Sets the xAI API key in a .env file. Used by the xai singleton when no apiKey option is supplied; required for the default xai singleton. ```typescript // .env XAI_API_KEY=xai-... ``` ```typescript import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; // works without constructor options — key comes from XAI_API_KEY const { text } = await generateText({ model: xai('grok-3'), prompt: 'hi' }); ``` -------------------------------- ### Streaming with streamText Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Demonstrates streaming with streamText from the AI SDK. It creates a model with createXai().chat('grok-3-fast') and passes providerOptions for reasoning. The example iterates over result.textStream and writes each text part to stdout. ```ts import { createXai } from '@ai-sdk/xai'; import { streamText } from 'ai'; const model = createXai().chat('grok-3-fast'); const result = streamText({ model, prompt: 'Explain the difference between Grok 3 and Grok 4.', providerOptions: { xai: { reasoningEffort: 'high' } }, }); for await (const textPart of result.textStream) { process.stdout.write(textPart); } ``` -------------------------------- ### POST {baseURL}/chat/completions Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/endpoints.md Streaming chat completions endpoint with SSE response, including chunk schema details and an example using the XAI SDK. ```APIDOC ## POST {baseURL}/chat/completions ### Description This endpoint is used for streaming chat completions (SSE). It is called by `XaiChatLanguageModel.doStream`. The request body is the non-stream body plus `stream: true` and `stream_options: { include_usage: true }`. The success response is parsed as an event source. ### Method POST ### Endpoint `{baseURL}/chat/completions` ### Parameters #### Request Body - `stream` (boolean) - Required - Set to `true` to enable streaming. - `stream_options` (object) - Required - Contains `include_usage` (boolean) set to `true`. - Other fields from the non-stream request body. ### Response #### Success Response (200) The response is an SSE stream of chunks. Each chunk is validated by `xaiChatChunkSchema` and contains the following fields: - `id` (string | null) - Used in text/reasoning block ids. - `created` (number | null) - First chunk emits `response-metadata`. - `model` (string | null) - Mapped into `response-metadata`. - `choices[]` (array) - Array of choice objects. - `usage` (usage schema | null) - Accumulated; includes `completion_tokens_details.reasoning_tokens`. - `citations` (string[] (url) | null) - Emitted as `source` stream parts (per docs they arrive in the last chunk). Each `choices[]` element contains: - `index` (number) - Index of the choice. - `finish_reason` (string | null) - Drives the final `finish` part via `mapXaiFinishReason`. - `delta.role` ('assistant', optional) - Role of the delta. - `delta.content` (string | null) - Emits `text-start`/`text-delta`; suppressed if identical to the last request assistant message. - `delta.reasoning_content` (string | null) - Emits `reasoning-start`/`reasoning-delta`; consecutive identical deltas deduplicated. - `delta.tool_calls[]` ({ id, type: 'function', function: { name, arguments } } | null) - Emitted atomically: `tool-input-start` → `tool-input-delta` (full arguments) → `tool-input-end` → `tool-call`. ### Example ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai().chat('grok-3-fast'); const { stream } = await model.doStream({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hi' }] }], includeRawChunks: true, }); // stream: ReadableStream ``` ``` -------------------------------- ### XaiChatPrompt messages array and tool_choice example Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-prompt.md Shows the shape of the messages array sent to POST {baseURL}/chat/completions, including system, user, image, assistant with tool_calls, and tool messages. Also shows the corresponding tool_choice value produced by prepareTools, forcing the 'weather' tool. ```ts // The messages array sent to POST {baseURL}/chat/completions const messages: XaiChatPrompt = [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'What is in this image?' }, { role: 'user', content: [ { type: 'image_url', image_url: { url: 'data:image/png;base64,AAAA' } }, ], }, { role: 'assistant', content: '', tool_calls: [ { id: 'call_1', type: 'function', function: { name: 'weather', arguments: '{"location":"Paris"}' }, }, ], }, { role: 'tool', tool_call_id: 'call_1', content: '{"temperature":20}' }, ]; // Corresponding tool_choice values produced by prepareTools: const toolChoice: XaiToolChoice = { type: 'function', function: { name: 'weather' }, }; ``` -------------------------------- ### Raw chunks and reasoning stream consumption Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Shows how to consume the raw stream from doStream with includeRawChunks enabled. It reads the stream and logs raw chunks, reasoning deltas, and finish information. The example uses reasoningEffort 'low' and a simple prompt. ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai().chat('grok-3-mini'); const { stream } = await model.doStream({ prompt: [{ role: 'user', content: [{ type: 'text', text: '2+2?' }] }], includeRawChunks: true, providerOptions: { xai: { reasoningEffort: 'low' } }, }); const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; if (value.type === 'raw') { // raw SSE JSON chunk as parsed by zod (xaiChatChunkSchema) console.log('raw chunk:', value.rawValue); } else if (value.type === 'reasoning-delta') { console.log('reasoning:', value.delta); } else if (value.type === 'finish') { console.log('done', value.finishReason, value.usage); } } ``` -------------------------------- ### Example xAI error envelope JSON Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-error.md Example JSON payload that matches `xaiErrorDataSchema`. Shows the structure of an error response from the xAI API. ```json { "error": { "message": "Incorrect API key provided", "type": "invalid_request_error", "code": 401 } } ``` -------------------------------- ### createXai(options?: XaiProviderSettings) Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/configuration.md Documentation for the createXai constructor options (XaiProviderSettings) and defaults. ```APIDOC ## createXai(options?: XaiProviderSettings) ### Description Creates an xAI provider instance with configurable settings for base URL, API key, custom headers, and fetch implementation. The provider is used to make chat and image model calls. ### Method Constructor function ### Endpoint N/A (SDK constructor) ### Parameters #### Constructor Options (XaiProviderSettings) - **baseURL** (string) - Optional - Base URL for xAI API calls. Default: `'https://api.x.ai/v1'`. Trailing slash is removed. Used as prefix for `POST {baseURL}/chat/completions` and image model paths. - **apiKey** (string) - Optional - API key for authentication. Sent as `Authorization: Bearer `. Default: read from `XAI_API_KEY` environment variable. If both are set, `apiKey` wins. - **headers** (Record) - Optional - Custom headers included in every request. Merged after the `Authorization` header, so they can override it. Default: `{}`. - **fetch** (FetchFunction) - Optional - Custom fetch implementation. Can be used as middleware to intercept requests or for testing. Default: global `fetch`. ### Request Example ```ts import { createXai } from '@ai-sdk/xai'; const provider = createXai({ baseURL: 'https://api.x.ai/v1', apiKey: 'xai-...', headers: { 'X-Project-ID': 'acme' }, fetch: (input, init) => { console.log('intercepting', input); return fetch(input, init); }, }); ``` ### Response Returns a provider instance. The default singleton `xai` is equivalent to `createXai({})` at module load. ### Notes - API key resolution is lazy; missing key surfaces as an error on the first model call. - User agent is suffixed with `ai-sdk/xai/${VERSION}`. - Chat model provider string: `'xai.chat'`; image model provider string: `'xai.image'`. ``` -------------------------------- ### Import xai provider instance Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/README.md Import the default provider instance 'xai' from '@ai-sdk/xai'. ```ts import { xai } from '@ai-sdk/xai'; ``` -------------------------------- ### Example — embedding model throws Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md Shows how to catch the NoSuchModelError thrown by textEmbeddingModel. The error message includes the model ID, e.g., "No such textEmbeddingModel: grok-3". ```ts import { createXai } from '@ai-sdk/xai'; import { NoSuchModelError } from '@ai-sdk/provider'; const provider = createXai(); try { provider.textEmbeddingModel('grok-3'); } catch (error) { if (error instanceof NoSuchModelError) { console.log(error.message); // e.g. "No such textEmbeddingModel: grok-3" } } ``` -------------------------------- ### Example of relying on error mapping in user code Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-error.md Shows how the error mapping works in user code: `generateText` rejections carry the API's error message from `error.message`. ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; try { await generateText({ model: xai('grok-3'), prompt: 'Hello' }); } catch (error) { console.error(error); // message from xAI's error.message, e.g. auth/rate-limit errors } ``` -------------------------------- ### Create X AI client and call chat model with doGenerate Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/endpoints.md Shows a minimal non-streaming invocation using createXai with an API key from XAI_API_KEY, selecting the 'grok-3' model, and passing prompt, maxOutputTokens, temperature, and providerOptions for reasoning effort. The result is a doGenerate response object; the call triggers the POST /chat/completions endpoint. ```typescript import { createXai } from '@ai-sdk/xai'; const model = createXai({ apiKey: process.env.XAI_API_KEY }).chat('grok-3'); const result = await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }], maxOutputTokens: 128, temperature: 0.5, providerOptions: { xai: { reasoningEffort: 'high' } }, }); ``` -------------------------------- ### Import from @ai-sdk/xai Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/index.md Shows how to import the public exports from the package. Use this to import the provider factory, default provider instance, types, and version constant. ```ts import { createXai, xai } from '@ai-sdk/xai'; import type { XaiProvider, XaiProviderSettings, XaiProviderOptions, XaiErrorData, } from '@ai-sdk/xai'; import { VERSION } from '@ai-sdk/xai'; ``` -------------------------------- ### xai — default provider singleton Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md A pre-configured provider instance with default base URL and API key resolution from environment variable. ```APIDOC ## xai — default provider singleton ### Description A pre-configured provider with the default base URL `https://api.x.ai/v1` and no custom headers. The API key is resolved from the `XAI_API_KEY` environment variable when the first request headers are built. ### Usage Example ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const { text } = await generateText({ model: xai('grok-3-mini'), prompt: 'Hi' }); ``` ``` -------------------------------- ### Importing XaiProvider and XaiChatModelId Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-options.md Shows how to import XaiProvider and XaiChatModelId from '@ai-sdk/xai'. Note that XaiChatModelId is not exported from the entry point, so this import may not work for consumers. ```TypeScript import type { XaiProvider } from '@ai-sdk/xai'; import type { XaiChatModelId } from '@ai-sdk/xai'; // NOT exported from entry point ``` -------------------------------- ### Usage with generateText Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-options.md Example of using XaiProviderOptions with generateText. It sets reasoningEffort to 'high' and configures searchParameters with mode 'on', citations, date range, max results, and sources including web and x types. ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const { text, sources } = await generateText({ model: xai('grok-3'), prompt: 'What happened in space exploration this week?', providerOptions: { xai: { reasoningEffort: 'high', searchParameters: { mode: 'on', returnCitations: true, fromDate: '2025-11-01', toDate: '2025-11-30', maxSearchResults: 5, sources: [ { type: 'web', country: 'US', safeSearch: true }, { type: 'x', includedXHandles: ['NASA'], postFavoriteCount: 100 }, ], }, }, }, }); ``` -------------------------------- ### createXai(options?: XaiProviderSettings): XaiProvider Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md Factory function to create an xAI provider instance with configurable settings. ```APIDOC ## createXai(options?: XaiProviderSettings): XaiProvider ### Description Creates a new xAI provider instance with the given settings. The returned provider is a callable function that can be used to create chat models, and also exposes named factory methods for chat and image models. ### Method Function call ### Endpoint `createXai(options?: XaiProviderSettings): XaiProvider` ### Parameters #### Parameters - **options** (`XaiProviderSettings`) - Optional - Provider settings; every field is optional. See configuration.md for details. ### Return `XaiProvider` - A callable provider instance. Because it is a function object, it is both invoked directly as a model factory and carries named factory methods. ### Behavior - Resolves `baseURL` to `options.baseURL ?? 'https://api.x.ai/v1'` with trailing slash removed. - Builds a header factory that lazily calls `loadApiKey({ apiKey: options.apiKey, environmentVariableName: 'XAI_API_KEY', description: 'xAI API key' })` to obtain the bearer token. If no API key is available an error is thrown at header-build time (i.e. when a model request is made). - The `Authorization: Bearer ` header is merged with `options.headers` and suffixed with the user agent `ai-sdk/xai/${VERSION}`. - Chat models are created as `new XaiChatLanguageModel(modelId, { provider: 'xai.chat', baseURL, headers: getHeaders, generateId, fetch: options.fetch })`. - Image models are created as `new OpenAICompatibleImageModel(modelId, { provider: 'xai.image', url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch, errorStructure: xaiErrorStructure })` where `xaiErrorStructure` uses `xaiErrorDataSchema`. ### Request Example ```ts import { createXai, xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const provider = createXai({ apiKey: 'xai-...', // or set process.env.XAI_API_KEY }); // or simply use the pre-built singleton: const model = provider('grok-4-fast-reasoning'); const { text } = await generateText({ model, prompt: 'Explain quaternions in one paragraph.', }); ``` ### Response #### Success Response Returns a `XaiProvider` instance that can be used to create models. #### Response Example ```ts const provider = createXai({ baseURL: 'https://api.x.ai/v1', headers: { 'X-Custom-Header': 'value' }, fetch: (input, init) => fetch(input, init), // custom transport / interception }); const result = streamText({ model: provider.chat('grok-3'), prompt: 'Latest AI news?', providerOptions: { xai: { reasoningEffort: 'high', searchParameters: { mode: 'auto', returnCitations: true }, }, }, }); ``` ``` -------------------------------- ### XaiProviderSettings Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/types.md Settings for configuring the xAI provider. ```APIDOC ## XaiProviderSettings ### Description Settings for configuring the xAI provider. ### Type `interface` ### Fields | Field | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | `baseURL` | `string` | no | `'https://api.x.ai/v1'` | Base URL; trailing slash stripped | | `apiKey` | `string` | no | from `XAI_API_KEY` env var | Bearer-token API key | | `headers` | `Record` | no | — | Extra headers merged into every request | | `fetch` | `FetchFunction` | no | global fetch | Custom fetch / middleware | ### Usage ```ts const provider = createXai({ apiKey: 'your-api-key', baseURL: 'https://api.x.ai/v1' }); ``` ``` -------------------------------- ### Stream chat completion with createXai from @ai-sdk/xai Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/endpoints.md Shows how to instantiate a streaming chat model using `createXai().chat('grok-3-fast')` and call `model.doStream` with a user prompt, enabling raw chunk inclusion. The resulting `stream` is a `ReadableStream`. ```typescript import { createXai } from '@ai-sdk/xai'; const model = createXai().chat('grok-3-fast'); const { stream } = await model.doStream({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hi' }] }], includeRawChunks: true, }); // stream: ReadableStream ``` -------------------------------- ### XaiChatLanguageModel Constructor Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Documentation for the constructor of the XaiChatLanguageModel class, including its parameters and the XaiChatConfig type. ```APIDOC ## Constructor ### Description Creates a new instance of the `XaiChatLanguageModel` class. This class implements the `LanguageModelV3` interface from `@ai-sdk/provider` and is the object returned by `xai(modelId)`, `xai.chat(modelId)`, and `xai.languageModel(modelId)`. In normal usage, instances are obtained through the provider factory rather than constructed directly. ### Signature ```ts constructor(modelId: XaiChatModelId, config: XaiChatConfig) ``` ### Parameters - **modelId** (`XaiChatModelId`) - Required - xAI model identifier (expanded in xai-chat-options.md). - **config.provider** (`string`) - Required - Provider string, set to `'xai.chat'` by `createXai`. - **config.baseURL** (`string | undefined`) - Required (may be `undefined`) - Base URL; requests target `${baseURL}/chat/completions`; falls back to `https://api.x.ai/v1` if `undefined`. - **config.headers** (`() => Record`) - Required - Lazily evaluated request header factory (includes `Authorization`). - **config.generateId** (`() => string`) - Required - ID generator used for synthesized source/citation IDs. - **config.fetch** (`FetchFunction`) - Optional - Optional custom fetch implementation. ### Config Type ```ts type XaiChatConfig = { provider: string; baseURL: string | undefined; headers: () => Record; generateId: () => string; fetch?: FetchFunction; }; ``` ``` -------------------------------- ### doGenerate(options): Promise Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Generates a chat completion using the xAI API. It sends a POST request to the /chat/completions endpoint with the provided options, handles provider-specific options, and returns a structured result containing content blocks, finish reason, usage, and response metadata. ```APIDOC ## doGenerate(options): Promise ### Description Generates a chat completion using the xAI API. It sends a POST request to the /chat/completions endpoint with the provided options, handles provider-specific options, and returns a structured result containing content blocks, finish reason, usage, and response metadata. ### Method POST ### Endpoint ${baseURL}/chat/completions ### Parameters #### Request Body - **prompt** (array) - Required - The prompt messages. Each message has a role (system, user, assistant, tool) and content (text, image, etc.). - **maxOutputTokens** (number) - Optional - Maximum number of tokens to generate. - **temperature** (number) - Optional - Sampling temperature. - **topP** (number) - Optional - Nucleus sampling parameter. - **topK** (number) - Optional - Top-k sampling parameter. Not supported, emits warning. - **frequencyPenalty** (number) - Optional - Frequency penalty. Not supported, emits warning. - **presencePenalty** (number) - Optional - Presence penalty. Not supported, emits warning. - **stopSequences** (string[]) - Optional - Stop sequences. Not supported, emits warning. - **seed** (number) - Optional - Random seed. - **responseFormat** (object) - Optional - Response format. JSON schema not supported, emits warning. - **providerOptions** (object) - Optional - Provider-specific options. `providerOptions.xai` is validated against `xaiProviderOptions` schema. - **tools** (array) - Optional - Tool definitions. - **toolChoice** (string|object) - Optional - Tool choice configuration. - **headers** (object) - Optional - Additional HTTP headers. - **abortSignal** (AbortSignal) - Optional - Abort signal for cancellation. ### Request Example ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai({ apiKey: process.env.XAI_API_KEY }).chat('grok-3'); const result = await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }], maxOutputTokens: 256, temperature: 0.7, }); ``` ### Response #### Success Response (200) - **content** (array) - Array of content blocks. Each block can be: - `{ type: 'text', text }` - Text content. - `{ type: 'reasoning', text }` - Reasoning content. - `{ type: 'tool-call', toolCallId, toolName, input }` - Tool call. - `{ type: 'source', sourceType: 'url', id, url }` - Source citation. - **finishReason** (string) - Reason for finishing generation (mapped from `finish_reason`). - **usage** (object) - Token usage: `inputTokens`, `outputTokens`, `totalTokens`, `reasoningTokens`. - **request** (object) - Request body sent. - **response** (object) - Response metadata: `headers`, `body`, `id`, `modelId`, `timestamp`. - **warnings** (array) - List of warnings emitted during generation. #### Response Example ```json { "content": [ { "type": "text", "text": "Hello!" } ], "finishReason": "stop", "usage": { "inputTokens": 10, "outputTokens": 20, "totalTokens": 30, "reasoningTokens": 5 }, "request": { "body": {} }, "response": { "headers": {}, "body": {}, "id": "chatcmpl-123", "modelId": "grok-3", "timestamp": "2024-01-01T00:00:00Z" }, "warnings": [] } ``` ### Error Handling - **zod validation error** - If `providerOptions.xai` fails validation. - **API error** - If the HTTP response is non-OK. Error message taken from `error.message`. - **UnsupportedFunctionalityError** - If prompt contains a file part with a non-image media type. - **Error** - If prompt contains a role other than `system`/`user`/`assistant`/`tool`. ``` -------------------------------- ### Use xai provider with generateText Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-provider.md Imports the xai provider and uses it with generateText to create a chat model for text generation. The model ID 'grok-3-mini' is used. ```ts import { xai } from '@ai-sdk/xai'; import { generateText } from 'ai'; const { text } = await generateText({ model: xai('grok-3-mini'), prompt: 'Hi' }); ``` -------------------------------- ### doGenerate(options): Promise Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Generates a chat completion using the xAI model. Supports provider options for reasoning effort and search parameters, and returns a result with content and sources. ```APIDOC ## doGenerate(options): Promise ### Description Generates a chat completion using the xAI model. Supports provider options for reasoning effort and search parameters, and returns a result with content and sources. ### Method POST ### Endpoint `${baseURL}/chat/completions` ### Parameters #### Request Body - **prompt** (array) - Required - The prompt messages, each with role and content. - **providerOptions** (object) - Optional - Provider-specific options. - **xai.reasoningEffort** (string) - Optional - Reasoning effort level (e.g., 'high', 'low'). - **xai.searchParameters** (object) - Optional - Search parameters. - **mode** (string) - Optional - Search mode ('on' or 'off'). - **returnCitations** (boolean) - Optional - Whether to return citations. - **fromDate** (string) - Optional - Start date for search. - **toDate** (string) - Optional - End date for search. - **maxSearchResults** (number) - Optional - Maximum number of search results. - **sources** (array) - Optional - List of sources, each with type, country, and safeSearch. - **abortSignal** (AbortSignal) - Optional - Signal to abort the request. ### Request Example ```ts import { createXai } from '@ai-sdk/xai'; const model = createXai({ apiKey: process.env.XAI_API_KEY }).chat('grok-3'); try { const result = await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Top AI stories today?' }] }], providerOptions: { xai: { reasoningEffort: 'high', searchParameters: { mode: 'on', returnCitations: true, fromDate: '2025-01-01', toDate: '2025-12-31', maxSearchResults: 10, sources: [{ type: 'web', country: 'US', safeSearch: true }], }, }, }, abortSignal: AbortSignal.timeout(30_000), }); const sources = result.content.filter(b => b.type === 'source'); console.log(result.content, sources); } catch (error) { // xAI API error (auth, rate limit, ...) or zod validation error console.error(error); } ``` ### Response #### Success Response - **content** (array) - The generated content, including text and source blocks. - **sources** (array) - Extracted source blocks from content. #### Response Example ```json { "content": [ { "type": "text", "text": "..." }, { "type": "source", "sourceType": "url", "id": "...", "url": "..." } ] } ``` ### Error Handling - xAI API errors (auth, rate limit, etc.) or zod validation errors are thrown and can be caught. ``` -------------------------------- ### doGenerate method signature Source: https://github.com/eldon31/xai_ai_sdk_docs/blob/main/_autodocs/api-reference/xai-chat-language-model.md Method signature for doGenerate in the XaiChatLanguageModel class. The options parameter type is the first argument of LanguageModelV3['doGenerate'] from @ai-sdk/provider, which includes call options such as prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, seed, responseFormat, providerOptions (with providerOptions.xai typed by the XaiProviderOptions schema), tools, toolChoice, headers, and abortSignal. ```ts async doGenerate( options: Parameters[0], ): Promise>> ```