npm / @ai-sdk/xai
@ai-sdk/xai
What changed in @ai-sdk/xai 2 to 7, from its official release notes, upgrade guides and advisories. Sources checked 2026-11-30.
107 breaking3 security11 deprecations61 new APIs and options2 performance15 behavior and defaults1 tooling24 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli init@ai-sdk/xai 71 changes
Breaking changes 1
The codemod updates named imports and direct re-exports while preserving local binding names and application export names as aliases; namespace member access remains unchanged.
@ai-sdk/xai 5111 changes
Breaking changes 70
Typed output.uploadUrl delivery is supported for video generation, editing, and extension; the option rejects null and requires an HTTPS URL.
The experimental OpenAI Live method can now resolve asynchronously; await its result before using the connection settings.
Together AI Gemini image inputs are marked unsupported by the current single-image request mapping.
This replaces addToolResult; its result parameter is named output, and a tool name is used for type safety.
LangChainAdapter moved to this package, and the adapter now uses UI message streams.
LlamaIndexAdapter was extracted to this package and follows the UI message stream pattern.
The Svelte integration uses updated constructor patterns and readonly properties.
The package has been removed and its exports moved to the main ai package.
The Vue integration replaces the useChat composable with a Chat class.
The useChat configuration body is captured at first render and stays static; pass dynamic values at request time or configure a function.
The Chat Completions API was removed.
The allowEmptySubmit option has been removed from ChatRequestOptions.
The data option has been removed; move its values into body.
RequestOptions has been renamed to CompletionRequestOptions.
Replaces convertToCoreMessages for converting messages passed to streamText.
The generator now requires size in its creation options and returns IDs using that fixed size.
Replaces the CreateMessage type.
The data stream protocol is replaced by Server-Sent Events and UI message streams, with writers emitting typed message objects.
UI messages no longer support the data role; custom data can be written as data parts in UI message streams.
This property has been replaced with the message parts array, including file parts for attachments.
File stream parts are flattened; read mediaType and data directly from the chunk instead of from chunk.file.
The step-finish stream event is renamed finish-step, and finish events expose totalUsage instead of usage.
The reasoning chunk type is renamed from reasoning to reasoning-delta for consistency with UI streams and language model streams.
Message ID generation moves from streamText's experimental_generateMessageId option to toUIMessageStreamResponse's generateMessageId option.
The type is renamed from IDGenerator to IdGenerator.
Managed input has been removed from the Svelte integration; manage input state manually.
Tool definitions use inputSchema instead of parameters.
The deprecated helper has been removed in favor of status.
The stream transform is renamed from DataStreamToSSETransformStream to JsonToSseTransformStream.
The option has been removed because it is no longer needed.
Import LanguageModelV3 from @ai-sdk/provider instead of ai.
LanguageModelV1Middleware is renamed and moved to LanguageModelV3Middleware from @ai-sdk/provider.
The stream part union adds IDs and lifecycle events for text, reasoning, and tool input, plus stream-start and finish events.
Usage fields change from promptTokens and completionTokens to inputTokens and outputTokens, and totalTokens is now required.
Replaces the maxTokens parameter in generateText and streamText with maxOutputTokens for clarity.
The parameter has been removed from Chat and useChat; use server-side stopWhen conditions for multi-step tool execution.
File parts use mediaType and url instead of mimeType and data.
Replaces the CoreMessage type.
The callback receives the new streaming chunk types and IDs, and text-delta content is now exposed as text.
toUIMessageStreamResponse replaces getErrorMessage with onError; error messages are not sent to clients by default to help prevent sensitive information leaks.
The callback has been removed from useChat and useCompletion.
Returning values no longer automatically submits tool results; explicitly call addToolOutput instead.
Messages use a parts array instead of a content string.
Use the UI message stream response helpers in place of the data stream response helpers.
This transport configuration option replaces experimental_prepareRequestBody for preparing request bodies.
The API was removed entirely; use readUIMessageStream or Chat/useChat APIs to process UI message streams.
Replaces providerMetadata as the input parameter for provider-specific options; returned metadata remains named providerMetadata.
Embedding model settings now use provider options instead of model parameters.
Reasoning streams now use start/delta/end events with IDs instead of a single reasoning chunk; consume reasoning text from reasoning-delta.delta.
UI message reasoning is represented as a reasoning part in parts rather than as a top-level property.
The rawResponse property has been renamed to response.
Resume functionality has moved from experimental_resume to resumeStream.
The option has been removed because sending extra message fields is now the default behavior.
Use setter methods such as setMessages to update properties that are now readonly.
Source stream parts are flattened; read sourceType, id, title, and url directly from the part instead of from part.source.
The class is removed; use UI message streams to write custom data and merge model streams.
Temperature is no longer implicitly set to 0; specify temperature: 0 explicitly when desired.
Text delta chunks now include an ID and use the delta property instead of textDelta.
Streaming now uses a three-phase start/delta/end pattern with unique IDs for each content block.
Reasoning UI parts expose their content through text instead of reasoning.
Replaces experimental_toToolResultContent and is no longer experimental.
UI tool parts use typed names such as tool-${toolName} instead of the generic tool-invocation type.
The option is removed because tool call streaming is always enabled by default.
The error class is removed; tool execution failures appear as tool-error content parts in result steps and streams.
Message persistence moves to UIMessage-formatted streams; provide originalMessages and generateMessageId to prevent duplicate or repeated assistant messages.
Replaces the Message type; UI messages now use a parts array instead of a content property.
File parts expose their file URL through url rather than data and mimeType.
The hook has been removed; use useChat configured for the route instead.
The data property has been removed from the hook.
The DataStreamWriter method is removed; write custom data parts with the UI message stream architecture instead.
Security 2
Polling returns an explicit uploaded outcome without downloading or exposing the signed destination, including in request errors.
@ai-sdk/provider-utils has an Uncontrolled Resource Consumption issue
Deprecations 1
The old method remains available but is deprecated and scheduled for removal in version 6.
New APIs and options 17
XaiRealtimeModel implements getServerWebSocketConfig(), providing the upstream voice realtime WebSocket URL with model query parameter and header authentication from configured credentials; unsupported endpoint intents are rejected.
Adds opus as a supported audio format.
Adds grok-imagine-image-2.0 as an image model ID for use with the xAI provider.
Adds auto as an image quality option for the xAI provider.
Adds 1.5k as an image resolution provider option.
Adds support for transcription model IDs.
Adds vadThreshold support for transcription.
Adds missing Responses API provider options.
Adds missing video provider options.
Adds the grok 4.7 model ID for use with @ai-sdk/xai.
Dynamic tools expose a flag for type narrowing when handling mixed static and dynamic tools.
Defines tools whose input and output types are not known at compile time, supporting runtime-defined tools.
embedMany now makes parallel requests, with concurrency configurable using maxParallelCalls.
Usage data can be attached as metadata to individual messages through this function in toUIMessageStreamResponse.
Use this option with lastAssistantMessageIsCompleteWithToolCalls for automatic tool result submission.
This new stream event finalizes a text block.
Tool inputs can be streamed as they are generated through start, delta, and end chunks before the final tool-call chunk.
Performance 1
Construction is deferred until first use to reduce package import time.
Behavior and default changes 9
Known model ID suggestions are derived from each provider’s model catalog declarations, so catalog updates automatically update autocomplete while preserving existing suggestions, endpoint-specific lists, and custom model IDs.
These settings now support promises and synchronous or asynchronous callbacks, resolving credentials per authenticated request while preserving existing authentication behavior and synchronous credential serialization.
The xSearch tool now allows up to 20 allowedXHandles.
The xSearch tool now allows up to 20 excludedXHandles.
Asynchronous capability lookups can resolve to unknown.
Middleware overrides can resolve capability lookups to unknown.
The activeTools option is no longer experimental; use it instead of experimental_activeTools.
The prepareStep option is promoted from experimental_prepareStep and can configure the model, active tools, tool choice, and system message for a step.
wrapLanguageModel is stable and replaces experimental_wrapLanguageModel.
Fixes and other changes 11
The event mapper populates normalized usage for response-done and input-transcription-completed events using xAI's OpenAI-compatible realtime wire shape.
Responses generateText maps incomplete_details.reason to the finish reason, so max_output_tokens reports length instead of other.
Stops emitting each citation twice when streaming responses with web or X search.
xAI Responses now report interrupted when a stream ends cleanly without its provider completion signal; handle this finish reason as incomplete output, not an error.
Provider-returned identifiers are encoded in credentialed follow-up request paths.
Speaker diarization is preserved when available or reported as unavailable, avoiding silent loss of diarization information.
The User-Agent header is now standards-compliant.
QuiverAI Arrow 2 and Arrow 2 Telos are advertised as supporting file input.
Capability declarations use confirmed model IDs, leaving unrecognized model names unknown.
Together AI FLUX.2 Pro and Flex are advertised as supporting single-image editing.
Update other @ai-sdk packages, including this package, to the 2.0.0 release line when upgrading to AI SDK 5.
@ai-sdk/xai 487 changes
Breaking changes 34
Unsupported batch request types are now rejected.
OpenTelemetry span collection is no longer built into the ai package. Install this package and register an OpenTelemetry instance globally to continue receiving traces.
The package is ESM-only; consumers using require() must switch to ESM import syntax.
The baseUrl option has been removed from all providers; use baseURL instead.
Top-level content, tool calls and results, files, sources, and warnings on generateText and streamText results now accumulate across every step; use finalStep for final-step-only values.
Renames the tool callback option experimental_context to context and stabilizes it. Tool context is now scoped and typed using contextSchema, with per-tool values supplied through toolsContext.
Declares each tool's contextual fields so tool context is inferred and limited to the fields declared for that tool.
The deprecated option has been removed. Replace remaining usages in generateText and streamText with activeTools.
Removes the tracer property from experimental_telemetry. Pass a custom tracer to the OpenTelemetry constructor instead.
Use finalStep to access final-step result properties, including reasoning, request, response, providerMetadata, and values previously available only on top-level result properties.
Obsolete Grok 2 models were removed from the provider after shutdown in the xAI API.
Moves the deprecated top-level streamText option includeRawChunks into the include options object as rawChunks.
Request bodies are no longer included in generateText and streamText step results by default. Set include.requestBody to true when application code needs them.
generateText no longer includes response bodies by default. Set include.responseBody to true when application code needs them.
The deprecated function has been removed. Replace imports and calls with isToolUIPart.
Removes the deprecated top-level cachedInputTokens field. Read inputTokenDetails.cacheReadTokens instead.
Removes the deprecated top-level reasoningTokens field. Read outputTokenDetails.reasoningTokens instead.
The deprecated tool-result content part type has been removed. Use the file content part with mediaType and tagged data instead.
The minimum supported Node.js version is 22; supported versions are 22, 24, and 26.
streamText now calls onChunk for every TextStreamPart, including lifecycle, boundary, and terminal parts. Handlers should guard the chunk types they process.
Renames the telemetry integration callback and tracing-channel event type from onEmbedFinish to onEmbedEnd.
Renames the per-call completion callback for embed and embedMany from experimental_onFinish to onEnd.
Renames the per-call completion callback for rerank from experimental_onFinish to onEnd.
The callback follows the result-shape changes: usage and listed content properties include all steps, while final-step-only values are available on finalStep.
Renames the telemetry integration callback and tracing-channel event type from onRerankFinish to onRerankEnd.
Models can return files in reasoning as a distinct content-part type. Update exhaustive unions, switches, validators, renderers, and serializers to handle it.
Shared generation or agent state now flows through runtimeContext instead of the former shared context. Tool-specific values are supplied separately through toolsContext.
Each step's response.messages now contains only messages produced by that step, rather than messages accumulated from earlier steps. Use result.responseMessages for the full history.
Telemetry is opt-out once an integration is registered: calls emit events by default, and isEnabled: false opts out for a specific call.
Configure tool approval on the generation call or agent instead of on tool definitions; approval can vary by request.
The deprecated type has been removed. Replace imports and type references with ToolExecutionOptions.
Supplies tool-specific context values keyed by tool name. Values are scoped to tools that declare contextual data through contextSchema.
generateText and streamText results now report token usage across all steps. Read finalStep.usage for the previous final-step-only behavior.
The Responses API is now the default for the xAI provider.
Security 1
Blank and dot-segment file IDs are rejected or encoded so they cannot retarget request paths.
Deprecations 10
Tool-result file content uses one canonical file variant with mediaType and tagged data; legacy image-* and file-* variants are runtime auto-migrated, but updating output shapes is recommended.
The user-message image content part is deprecated. Use a file part with image mediaType instead.
The tool() and dynamicTool() property is deprecated. Move approval logic to the per-call or agent toolApproval setting so approval policy can vary by request.
Renames the final lifecycle callback from onFinish to onEnd for text generation, streaming, agents, and ToolLoopAgent settings. onFinish remains a deprecated alias; onEnd takes precedence when both are provided.
Renames the per-step lifecycle callback from onStepFinish to onStepEnd across generation, streaming, agents, workflow agents, and UI message stream helpers. The old name remains a deprecated alias for user-facing callbacks.
The top-level reasoning, reasoningText, request, response, and providerMetadata result properties are deprecated; use finalStep for final-step values.
searchParameters for xAI live search is deprecated in favor of the web_search and x_search agent tools.
Renames the full event stream property to stream. fullStream remains available as a deprecated alias.
The result property is deprecated; use usage, which now contains usage across all steps.
The streamText result helper and its related response and pipe helpers are deprecated. Use stateless helpers exported from ai to transform streams.
New APIs and options 33
Image generation requests are now supported in batches.
Adds batch cancellation and listing capabilities.
Batch requests can now use per-request models.
The xAI batch input file upload accepts an inputFileExpiresAfter provider option.
Batch start results now expose the uploaded input file's expiration time in provider metadata.
Batch start results now expose the ID of the uploaded input file in provider metadata.
File operations now accept abortSignal.
Adds deleteFile to the xAI files interface.
Adds streaming downloadFile to the xAI files interface.
Adds getFileMetadata to the xAI files interface.
File operations now accept headers.
Upload results now expose byteSize.
Upload results now expose createdAt.
Supports streaming uploads using data with type set to stream.
Supports upload TTLs through expiresAfter, an integer from 3600 to 2592000 seconds, emitted before the file part as xAI requires.
Upload results now expose expiresAt.
Batch now supports tool calling.
Responses provider metadata now exposes costInUsdTicks.
A new custom content type is supported.
xai.tools.webSearch() accepts enableImageSearch and forwards it to the API as enable_image_search.
Realtime providers expose a static method for creating ephemeral tokens server-side.
Provider references and file uploads are supported according to provider capabilities.
Providers support a new top-level reasoning parameter.
File parts can now use the reasoning-file type for files that are part of reasoning.
Use the top-level reasoning option for provider-agnostic reasoning effort and remove overlapping providerOptions settings; provider-specific settings take precedence when both are present.
For grok-4.3, reasoningEffort accepts none and medium; top-level reasoning: 'medium' maps to reasoning_effort: 'medium' for chat.
The Responses API provider options now include reasoningSummary.
Adds video extension and reference-to-video (R2V) support.
Image editing now supports multiple input images.
Image models add b64_json response format, usage cost tracking, and quality and user parameters.
Adds speech-to-text transcription support.
Adds text-to-speech support.
Adds xAI realtime speech-to-speech support for server and browser use.
Behavior and default changes 5
Renames experimental_include to include for generateText, streamText, and ToolLoopAgent. The old name remains a deprecated alias; include takes precedence if both are provided.
The Responses API accepts non-image file parts supplied as URLs, including PDF and text files; inline-byte inputs for non-image media types still throw.
Renames experimental_onToolCallFinish to onToolExecutionEnd for generateText and streamText. The old name remains a deprecated fallback.
Renames experimental_onToolCallStart to onToolExecutionStart for generateText and streamText. The old name remains a deprecated fallback.
Renames experimental_telemetry to telemetry across functions and agents. The old name remains a deprecated alias, and mixed use is supported during the deprecation window.
Tooling 1
The autocomplete union is curated to the current xAI model lineup; removed IDs remain usable at runtime because the type is open.
Fixes and other changes 3
Tool schemas now preserve additionalProperties: false.
Preserves the web_search action fields query, sources, and open_page in responses tool results.
Image moderation blocks are reported as content policy errors.
@ai-sdk/xai 316 changes
Breaking changes 2
Provider method textEmbedding has been renamed to embedding; update provider calls to use the new name.
Provider method textEmbeddingModel has been renamed to embeddingModel; update provider calls to use the new name.
New APIs and options 6
The echoed safety identifier is exposed in providerMetadata.xai.safetyIdentifier.
The Responses provider accepts safetyIdentifier and sends it as safety_identifier so xAI can attribute a policy violation to an end user.
Grok 4.1 model IDs are available for use with the provider.
Grok 4 Fast model IDs are available for use with the provider.
The XAI provider supports the parallel_function_calling provider option.
The xAI provider supports server-side tool calling.
Performance 1
Validation schema construction is deferred until first use, reducing provider import time.
Fixes and other changes 7
Provider-returned identifiers are encoded in follow-up request paths.
Generated and streamed results now preserve complete xAI Chat Completions usage objects.
Raw usage metadata now preserves complete xAI Responses usage objects.
Cache input tokens are now included.
The provider no longer emits the JSON schema unsupported warning.
The provider now uses the correct parameter names for maxOutputTokens.
The sources format in searchParameters was corrected.
@ai-sdk/xai 29 changes
New APIs and options 5
Adds the Responses provider option that sends safety_identifier with requests and exposes the echoed value on providerMetadata.xai.safetyIdentifier, allowing xAI to attribute a policy violation to one end user.
Adds Grok-3 models.
Adds a Grok-4 model ID.
Adds live search support.
Adds a native XAI chat language model implementation.
Behavior and default changes 1
Updates Grok-3 model aliases.
Fixes and other changes 3
Filters duplicated reasoning chunks.
Streaming returns actual usage instead of NaN.
Edits the models supported for structured output.