Skip to content

feat(ai-grok): use xAI Responses API#812

Merged
AlemTuzlak merged 2 commits into
TanStack:mainfrom
Jaaneek:feat/grok-responses-api
Jun 23, 2026
Merged

feat(ai-grok): use xAI Responses API#812
AlemTuzlak merged 2 commits into
TanStack:mainfrom
Jaaneek:feat/grok-responses-api

Conversation

@Jaaneek

@Jaaneek Jaaneek commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

🎯 Changes

  • Move Grok text and summarization adapters to xAI's Responses API for grok-build-0.1 and grok-4.3.
  • Add xAI Responses server-side tools for web search, X search, file search, and MCP, while keeping local function tools working.
  • Update docs, examples, test harness defaults, and model metadata so Grok chat support is limited to grok-build-0.1 and grok-4.3.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Test plan

  • pnpm --filter @tanstack/ai-grok test:types
  • pnpm --filter @tanstack/ai-grok test:lib
  • pnpm --filter @tanstack/ai-grok test:eslint
  • pnpm --filter @tanstack/ai-grok build
  • pnpm test:pr

Summary by CodeRabbit

  • New Features

    • Updated Grok model support to grok-4.3 and grok-build-0.1
    • Added reasoning capabilities with configurable effort levels
    • Enabled structured output using JSON Schema
    • Added function tool calling support
    • Integrated xAI server-side tools (web search, file search, MCP)
  • Documentation

    • Updated Grok adapter documentation with new supported models and features

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6bf7fb6d-e9ab-492b-a137-dd6b9de42d7a

📥 Commits

Reviewing files that changed from the base of the PR and between 97e7190 and 216e280.

📒 Files selected for processing (1)
  • .changeset/grok-responses-api.md
✅ Files skipped from review due to trivial changes (1)
  • .changeset/grok-responses-api.md

📝 Walkthrough

Walkthrough

Migrates the @tanstack/ai-grok adapter from xAI's Chat Completions API to the Responses API, narrowing supported models to grok-build-0.1 and grok-4.3. Introduces Grok server-side tool types and factory functions, updates provider option types to Responses-aligned fields, and propagates the new defaults across examples, evaluation configs, e2e/panel testing, and documentation.

Changes

Grok Responses API Migration

Layer / File(s) Summary
Provider options and model metadata
packages/ai-grok/src/text/text-provider-options.ts, packages/ai-grok/src/model-meta.ts
Introduces GrokReasoningEffort, GrokReasoning, and updates GrokTextProviderOptions with Responses-aligned fields (max_output_tokens, store, include, reasoning). Defines GrokBuildProviderOptions that disallows reasoning. Introduces GrokProviderToolKind union and GROK_RESPONSES_TOOLS, narrows GROK_CHAT_MODELS to two entries, removes GROK_COMBINED_TOOLS_AND_SCHEMA_MODELS, and updates GrokChatModelProviderOptionsByName.
Grok server-side tool types, factories, and conversion
packages/ai-grok/src/tools/index.ts
Rewrites the tools module: defines GrokProviderTool branding, tool config interfaces (web_search, x_search, file_search, mcp), factory functions with runtime validation (mutual exclusivity, list size, required fields), and convertToolsToProviderFormat dispatching between Grok-branded and function tools.
GrokTextAdapter switch to Responses API
packages/ai-grok/src/adapters/text.ts
Changes GrokTextAdapter to extend OpenAIBaseResponsesTextAdapter. Replaces Chat Completions overrides with mapOptionsToRequest that validates grok-build-0.1 reasoning constraint, re-maps tools via convertToolsToProviderFormat, and enforces encrypted-reasoning include and store: false defaults.
Adapter and usage-extraction tests
packages/ai-grok/tests/grok-adapter.test.ts, packages/ai-grok/tests/usage-extraction.test.ts
Rewrites test harness to mock responses.create instead of chat.completions.create. Adds injectMockResponsesClient, consume, and Responses event fixtures. Tests cover model list assertion, store/include defaults, grok-build-0.1 reasoning rejection, tool conversion (function and server-side), tool factory validation, and usage extraction with cached/reasoning token details.
Model defaults propagated across consumers
examples/ts-react-chat/src/..., packages/ai-code-mode/models-eval/..., testing/e2e/src/..., testing/panel/src/...
Updates default model strings to grok-build-0.1 and removes legacy Grok model entries across all example routes, model-selection lists, eval config, e2e providers/features, and panel routes and vendor-config. Also splits Grok's max_output_tokens into its own case in maxTokensModelOptions.
Docs, README, JSDoc, and changeset
docs/adapters/grok.md, packages/ai-grok/README.md, packages/ai-grok/src/adapters/summarize.ts, .changeset/grok-responses-api.md
Updates all documentation to reference grok-build-0.1/grok-4.3, rewrites Model Options examples to Responses-aligned fields, replaces the "Why Chat Completions" Implementation Notes with a Responses API description, removes the Limitations section, and adds the minor-bump changeset.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(173, 216, 230, 0.5)
    Note over Caller,xAI: Responses API path (new)
  end
  participant Caller
  participant GrokTextAdapter
  participant convertToolsToProviderFormat
  participant OpenAIBaseResponsesTextAdapter
  participant xAI as xAI Responses API

  Caller->>GrokTextAdapter: generate(messages, options)
  GrokTextAdapter->>GrokTextAdapter: validate grok-build-0.1 rejects reasoning option
  GrokTextAdapter->>convertToolsToProviderFormat: options.tools
  convertToolsToProviderFormat-->>GrokTextAdapter: GrokResponsesTool[]
  GrokTextAdapter->>OpenAIBaseResponsesTextAdapter: super.mapOptionsToRequest(stripped options)
  OpenAIBaseResponsesTextAdapter-->>GrokTextAdapter: base ResponseCreateParams
  GrokTextAdapter->>GrokTextAdapter: set include=[reasoning.encrypted_content], store=false
  GrokTextAdapter->>xAI: responses.create(params, stream=true)
  xAI-->>GrokTextAdapter: response.created / response.output_text.delta / response.completed
  GrokTextAdapter-->>Caller: AG-UI events (text, reasoning, usage)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • TanStack/ai#609: The main PR updates Grok's supportsCombinedToolsAndSchema() capability gating; this PR removes that mechanism (GROK_COMBINED_TOOLS_AND_SCHEMA_MODELS) entirely as part of the Responses API migration.
  • TanStack/ai#660: Both PRs touch the Grok token-limit mapping in packages/ai-code-mode/models-eval/run-eval.ts; this PR splits Grok's max_output_tokens into its own switch case from the combined Anthropic+Grok branch introduced there.

Suggested reviewers

  • tombeckenham

🐇 Hopping onto Responses with glee,
No more Chat Completions for me!
grok-build-0.1 leads the way,
Encrypted reasoning here to stay,
Server-side tools all validated right,
This little rabbit ships tonight! 🚀

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: migrating Grok adapters to use xAI's Responses API.
Description check ✅ Passed The description follows the template structure with completed 🎯 Changes section detailing key updates, a fully checked ✅ Checklist, completed 🚀 Release Impact with changeset generation, and comprehensive test plan.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/ai-grok/src/tools/index.ts`:
- Around line 18-67: The GrokMCPToolConfig interface is included in the
GrokServerTool union type, but xAI's Responses API documentation only supports
web_search, x_search, code_interpreter, and file_search as native tools, not
MCP. Since GrokServerTool is cast and sent directly to the xAI API, including an
unsupported tool type will cause runtime errors rather than compile-time errors.
Remove GrokMCPToolConfig from the GrokServerTool union type definition to ensure
only documented xAI-supported tool types are sent to the API.

In `@testing/panel/src/routes/api.chat.ts`:
- Line 185: The global default assignment of `model` to 'gpt-4o' at line 168
occurs before the provider-specific fallback at line 185 in the grokText
function call, making the Grok-specific default unreachable. Remove the global
default initialization of `model` at line 168 so that when data.model is not
provided, the provider-specific fallback (grok-build-0.1 for Grok, gpt-4o for
OpenAI, etc.) can be applied correctly based on which adapter is being used.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d35ccf62-5504-431e-b235-bf52a2a0ac42

📥 Commits

Reviewing files that changed from the base of the PR and between 16cb212 and 97e7190.

📒 Files selected for processing (24)
  • .changeset/grok-responses-api.md
  • docs/adapters/grok.md
  • examples/ts-react-chat/src/lib/model-selection.ts
  • examples/ts-react-chat/src/routes/api.structured-output.ts
  • examples/ts-react-chat/src/routes/api.tanchat.ts
  • examples/ts-react-chat/src/routes/generations.structured-output.tsx
  • packages/ai-code-mode/models-eval/eval-config.ts
  • packages/ai-code-mode/models-eval/run-eval.ts
  • packages/ai-grok/README.md
  • packages/ai-grok/src/adapters/summarize.ts
  • packages/ai-grok/src/adapters/text.ts
  • packages/ai-grok/src/model-meta.ts
  • packages/ai-grok/src/text/text-provider-options.ts
  • packages/ai-grok/src/tools/index.ts
  • packages/ai-grok/tests/grok-adapter.test.ts
  • packages/ai-grok/tests/usage-extraction.test.ts
  • testing/e2e/src/lib/features.ts
  • testing/e2e/src/lib/providers.ts
  • testing/e2e/src/routes/api.summarize.ts
  • testing/panel/src/lib/model-selection.ts
  • testing/panel/src/routes/api.chat.ts
  • testing/panel/src/routes/api.structured.ts
  • testing/panel/src/routes/api.summarize.ts
  • testing/panel/tests/vendor-config.ts

Comment on lines +18 to +67
export interface GrokWebSearchToolConfig {
type: 'web_search'
filters?: {
allowed_domains?: Array<string>
excluded_domains?: Array<string>
}
enable_image_understanding?: boolean
enable_image_search?: boolean
}

export interface GrokXSearchToolConfig {
type: 'x_search'
allowed_x_handles?: Array<string>
excluded_x_handles?: Array<string>
from_date?: string
to_date?: string
enable_image_understanding?: boolean
enable_video_understanding?: boolean
}

export interface GrokFileSearchToolConfig {
type: 'file_search'
vector_store_ids: Array<string>
max_num_results?: number
}

export interface GrokMCPToolConfig {
type: 'mcp'
server_label: string
server_url: string
allowed_tools?: Array<string>
server_description?: string
authorization?: string
headers?: Record<string, string>
}

export type GrokServerTool =
| GrokWebSearchToolConfig
| GrokXSearchToolConfig
| GrokFileSearchToolConfig
| GrokMCPToolConfig

type GrokProviderToolMetadata<TKind extends GrokProviderToolKind> = Extract<
GrokServerTool,
{ type: TKind }
> & {
__kind: GrokToolKindMarker<TKind>
}

export type GrokResponsesTool = GrokServerTool | ResponsesFunctionTool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

xAI Grok Responses API server-side tools web_search x_search file_search mcp request format

💡 Result:

The xAI API provides server-side tools—built-in capabilities managed by xAI—that the model executes automatically, alongside user-defined function calling [1][2]. These server-side tools include web_search, x_search, code_interpreter (or code_execution), and file_search (for collections search) [1][3][4][5][6]. API Request Format When using the Responses API (which is compatible with the OpenAI API format), you define these tools within the tools array in your request [1][7][8]. Example Request: curl https://api.x.ai/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $XAI_API_KEY" \ -d '{ "model": "grok-4.3", "tools": [ { "type": "web_search" }, { "type": "x_search" }, { "type": "code_interpreter" }, { "type": "file_search" } ], "input": [ { "role": "user", "content": "Analyze the latest tech trends and perform a calculation." } ] }' Key Tool Details: - Web Search (web_search): Searches the web in real-time [5]. Supports parameters like allowed_domains and enable_image_search [5]. - X Search (x_search): Searches X posts, users, and threads [6]. Supports parameters like from_date, to_date, and enable_video_understanding [6]. - Code Interpreter (code_interpreter/code_execution): Executes Python code in a sandbox [3]. - File Search (file_search/collections_search): Queries your uploaded documents [4]. Requires specifying vector_store_ids or collection_ids [4]. Server-side tools are handled entirely by xAI's infrastructure; the API processes the request, determines which tool to use, executes it, and returns the result to the model [1][2]. This differs from client-side function calling, where the model returns a tool call for your application to execute, requiring you to append the result back to the conversation [2][9]. You can combine both server-side and client-side tools in a single request [2]. Note: The term "MCP" (Model Context Protocol) is not referenced in official xAI documentation as a specific native tool type; xAI documentation distinguishes between built-in server-side tools and custom function calling [1].

Citations:


🏁 Script executed:

# Check the adapters/text.ts file to understand how GrokServerTool is processed
cat -n packages/ai-grok/src/adapters/text.ts | sed -n '80,105p'

Repository: TanStack/ai

Length of output: 1165


🏁 Script executed:

# Also check the full context of the index.ts file to understand the tool structure better
ast-grep outline packages/ai-grok/src/tools/index.ts

Repository: TanStack/ai

Length of output: 1562


🏁 Script executed:

# Search for how GrokMCPToolConfig and MCP tools are used throughout the codebase
rg "GrokMCPToolConfig|mcp" packages/ai-grok/src --type ts -A 3 -B 1

Repository: TanStack/ai

Length of output: 2392


🏁 Script executed:

# Check the ResponsesFunctionTool type and how it differs from GrokServerTool
rg "ResponsesFunctionTool" packages/ai-grok/src/tools/index.ts -A 5 -B 2

Repository: TanStack/ai

Length of output: 864


🏁 Script executed:

# Check if there's any documentation or comments about MCP usage
rg -i "mcp" packages/ai-grok/src --type ts -B 3 -A 3 | head -80

Repository: TanStack/ai

Length of output: 3008


🏁 Script executed:

# Look at how convertToolsToProviderFormat handles these different tool types
ast-grep outline packages/ai-grok/src/tools/index.ts | grep -A 20 "convertToolsToProviderFormat"

Repository: TanStack/ai

Length of output: 200


🏁 Script executed:

# Get more context on convertGrokProviderToolToAdapterFormat to see how tools are actually processed
cat -n packages/ai-grok/src/tools/index.ts | sed -n '187,210p'

Repository: TanStack/ai

Length of output: 1123


Remove GrokMCPToolConfig from GrokServerTool union or verify xAI Responses API support for MCP tool type.

xAI's Responses API documentation lists native server-side tools as web_search, x_search, code_interpreter, and file_search. The MCP tool type is not referenced in xAI's API documentation as a supported native tool. Since GrokMCPToolConfig (type: 'mcp') is included in the GrokServerTool union and sent verbatim to xAI's API via the cast in adapters/text.ts (Line 92), an unsupported tool type will cause a runtime API error rather than a compile-time type error. Either remove MCP from this union or confirm that xAI Responses API supports custom MCP tools. The other tool configs—field names for web_search (filters.allowed_domains, enable_image_search), x_search (from_date, to_date, enable_video_understanding), and file_search (vector_store_ids)—align with xAI's documentation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-grok/src/tools/index.ts` around lines 18 - 67, The
GrokMCPToolConfig interface is included in the GrokServerTool union type, but
xAI's Responses API documentation only supports web_search, x_search,
code_interpreter, and file_search as native tools, not MCP. Since GrokServerTool
is cast and sent directly to the xAI API, including an unsupported tool type
will cause runtime errors rather than compile-time errors. Remove
GrokMCPToolConfig from the GrokServerTool union type definition to ensure only
documented xAI-supported tool types are sent to the API.

grok: () =>
createChatOptions({
adapter: grokText((model || 'grok-3') as any),
adapter: grokText((model || 'grok-build-0.1') as any),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Provider-specific model fallback is unreachable due earlier global default.

At Line 168, model is always initialized to 'gpt-4o', so Line 185 never falls back to 'grok-build-0.1'. This can send an OpenAI model to Grok when the request omits data.model.

Suggested fix
-        const model: string = data.model || 'gpt-4o'
+        const model: string | undefined = data.model
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@testing/panel/src/routes/api.chat.ts` at line 185, The global default
assignment of `model` to 'gpt-4o' at line 168 occurs before the
provider-specific fallback at line 185 in the grokText function call, making the
Grok-specific default unreachable. Remove the global default initialization of
`model` at line 168 so that when data.model is not provided, the
provider-specific fallback (grok-build-0.1 for Grok, gpt-4o for OpenAI, etc.)
can be applied correctly based on which adapter is being used.

@nx-cloud

nx-cloud Bot commented Jun 23, 2026

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit 97e7190

Command Status Duration Result
nx run-many --targets=build --exclude=examples/... ✅ Succeeded 4s View ↗

☁️ Nx Cloud last updated this comment at 2026-06-23 18:39:40 UTC

@nx-cloud

nx-cloud Bot commented Jun 23, 2026

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit 97e7190

Command Status Duration Result
nx run-many --targets=build --exclude=examples/... ✅ Succeeded 5s View ↗

☁️ Nx Cloud last updated this comment at 2026-06-23 18:41:43 UTC

@pkg-pr-new

pkg-pr-new Bot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@tanstack/ai

npm i https://pkg.pr.new/@tanstack/ai@812

@tanstack/ai-angular

npm i https://pkg.pr.new/@tanstack/ai-angular@812

@tanstack/ai-anthropic

npm i https://pkg.pr.new/@tanstack/ai-anthropic@812

@tanstack/ai-client

npm i https://pkg.pr.new/@tanstack/ai-client@812

@tanstack/ai-code-mode

npm i https://pkg.pr.new/@tanstack/ai-code-mode@812

@tanstack/ai-code-mode-skills

npm i https://pkg.pr.new/@tanstack/ai-code-mode-skills@812

@tanstack/ai-devtools-core

npm i https://pkg.pr.new/@tanstack/ai-devtools-core@812

@tanstack/ai-elevenlabs

npm i https://pkg.pr.new/@tanstack/ai-elevenlabs@812

@tanstack/ai-event-client

npm i https://pkg.pr.new/@tanstack/ai-event-client@812

@tanstack/ai-fal

npm i https://pkg.pr.new/@tanstack/ai-fal@812

@tanstack/ai-gemini

npm i https://pkg.pr.new/@tanstack/ai-gemini@812

@tanstack/ai-grok

npm i https://pkg.pr.new/@tanstack/ai-grok@812

@tanstack/ai-groq

npm i https://pkg.pr.new/@tanstack/ai-groq@812

@tanstack/ai-isolate-cloudflare

npm i https://pkg.pr.new/@tanstack/ai-isolate-cloudflare@812

@tanstack/ai-isolate-node

npm i https://pkg.pr.new/@tanstack/ai-isolate-node@812

@tanstack/ai-isolate-quickjs

npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs@812

@tanstack/ai-mcp

npm i https://pkg.pr.new/@tanstack/ai-mcp@812

@tanstack/ai-ollama

npm i https://pkg.pr.new/@tanstack/ai-ollama@812

@tanstack/ai-openai

npm i https://pkg.pr.new/@tanstack/ai-openai@812

@tanstack/ai-openrouter

npm i https://pkg.pr.new/@tanstack/ai-openrouter@812

@tanstack/ai-preact

npm i https://pkg.pr.new/@tanstack/ai-preact@812

@tanstack/ai-react

npm i https://pkg.pr.new/@tanstack/ai-react@812

@tanstack/ai-react-ui

npm i https://pkg.pr.new/@tanstack/ai-react-ui@812

@tanstack/ai-solid

npm i https://pkg.pr.new/@tanstack/ai-solid@812

@tanstack/ai-solid-ui

npm i https://pkg.pr.new/@tanstack/ai-solid-ui@812

@tanstack/ai-svelte

npm i https://pkg.pr.new/@tanstack/ai-svelte@812

@tanstack/ai-utils

npm i https://pkg.pr.new/@tanstack/ai-utils@812

@tanstack/ai-vue

npm i https://pkg.pr.new/@tanstack/ai-vue@812

@tanstack/ai-vue-ui

npm i https://pkg.pr.new/@tanstack/ai-vue-ui@812

@tanstack/openai-base

npm i https://pkg.pr.new/@tanstack/openai-base@812

@tanstack/preact-ai-devtools

npm i https://pkg.pr.new/@tanstack/preact-ai-devtools@812

@tanstack/react-ai-devtools

npm i https://pkg.pr.new/@tanstack/react-ai-devtools@812

@tanstack/solid-ai-devtools

npm i https://pkg.pr.new/@tanstack/solid-ai-devtools@812

commit: 216e280

@AlemTuzlak AlemTuzlak merged commit 19fc1c7 into TanStack:main Jun 23, 2026
10 checks passed
@github-actions github-actions Bot mentioned this pull request Jun 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants