Serve the AI SDK useChat hook from TanStack AI chat(). Read the request with chatParamsFromAISDKRequest, and serve the reply with toUIMessageStreamResponse. Your AI SDK client code, AI Elements included, does not change.
Use this page to move the server first. To keep a plain TanStack route and convert in the browser, see Bridge in the browser. To move the client first, see TanStack useChat with an AI SDK server.
Warning
This bridge is a stop gap while you port. Some features change shape or are dropped on the way (see AI SDK bridge compatibility). When the server works, port the client to TanStack useChat with the migration guide, then remove the bridge.
npm i @tanstack/ai @tanstack/ai-client @tanstack/ai-vercel-compat @tanstack/ai-openaipnpm add @tanstack/ai @tanstack/ai-client @tanstack/ai-vercel-compat @tanstack/ai-openaiyarn add @tanstack/ai @tanstack/ai-client @tanstack/ai-vercel-compat @tanstack/ai-openaibun add @tanstack/ai @tanstack/ai-client @tanstack/ai-vercel-compat @tanstack/ai-openaiKeep the ai package. @tanstack/ai-vercel-compat needs it, and your client still uses useChat.
import { chat } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import {
chatParamsFromAISDKRequest,
toUIMessageStreamResponse,
} from '@tanstack/ai-vercel-compat'
export async function POST(request: Request) {
const params = await chatParamsFromAISDKRequest(request)
const abortController = new AbortController()
const stream = chat({
adapter: openaiText('gpt-6.1-sol'),
...params,
abortController,
})
return toUIMessageStreamResponse(stream, { abortController })
}What each call does:
The client from your AI SDK app works as it is:
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
export function Chat() {
const { messages, sendMessage } = useChat({
transport: new DefaultChatTransport({ api: '/api/chat' }),
})
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.parts.map((p, i) => (p.type === 'text' ? <span key={i}>{p.text}</span> : null))}
</div>
))}
<button onClick={() => sendMessage({ text: 'Hello' })}>Send</button>
</div>
)
}Server tools run in chat(). The client shows each call as a tool-<name> part with its input and output.
import { chat, toolDefinition } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import {
chatParamsFromAISDKRequest,
toUIMessageStreamResponse,
} from '@tanstack/ai-vercel-compat'
import { z } from 'zod'
const getWeather = toolDefinition({
name: 'getWeather',
description: 'Get the weather for a city',
inputSchema: z.object({ city: z.string() }),
}).server(({ city }) => ({ city, temperature: 72 }))
const bookFlight = toolDefinition({
name: 'bookFlight',
description: 'Book a flight',
inputSchema: z.object({ to: z.string() }),
needsApproval: true,
}).server(({ to }) => ({ booked: to }))
export async function POST(request: Request) {
const params = await chatParamsFromAISDKRequest(request)
const stream = chat({
adapter: openaiText('gpt-6.1-sol'),
tools: [getWeather, bookFlight],
...params,
})
return toUIMessageStreamResponse(stream)
}On the client, answer the approval with addToolApprovalResponse. Then sendAutomaticallyWhen sends the answer to the server, and chat() runs or skips the tool.
The server keeps the id of the paused run in the message metadata, under tanstack.runId. If you validate metadata with messageMetadataSchema, allow that key.
import { useChat } from '@ai-sdk/react'
import {
DefaultChatTransport,
lastAssistantMessageIsCompleteWithApprovalResponses,
} from 'ai'
export function Chat() {
const { messages, addToolApprovalResponse } = useChat({
transport: new DefaultChatTransport({ api: '/api/chat' }),
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
})
return messages.map((m) =>
m.parts.map((part) =>
part.type === 'tool-bookFlight' && part.state === 'approval-requested' ? (
<button
key={part.toolCallId}
onClick={() =>
addToolApprovalResponse({ id: part.approval.id, approved: true })
}
>
Book the flight
</button>
) : null,
),
)
}toUIMessageStreamResponse sends each of these as a data part. The client replaces a data part in place when it gets a new value for the same id.
Type the data parts on useChat to read them:
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
import type { SubagentData } from '@tanstack/ai-vercel-compat'
import type { UIMessage } from 'ai'
type ChatMessage = UIMessage<unknown, { subagent: SubagentData }>
export function Subagents() {
const { messages } = useChat<ChatMessage>({
transport: new DefaultChatTransport({ api: '/api/chat' }),
})
return messages.flatMap((m) =>
m.parts.map((part) =>
part.type === 'data-subagent' ? (
<p key={part.id}>
{part.data.name}: {part.data.status}
</p>
) : null,
),
)
}The AI SDK client does not send state back. A change to the state on the client does not reach chat().
AI SDK useChat({ resume: true }) asks GET /api/chat/<id>/stream for the active run when the page loads. To answer it, record each run in a durability log, and keep a record of the active run of each chat. This example uses the runs store of @tanstack/ai-persistence:
import { chat, memoryStream } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import { withPersistence } from '@tanstack/ai-persistence'
import {
chatParamsFromAISDKRequest,
resumeUIMessageStreamResponse,
toResumableUIMessageStreamResponse,
} from '@tanstack/ai-vercel-compat'
import { persistence } from './persistence'
// POST /api/chat
export async function POST(request: Request) {
const params = await chatParamsFromAISDKRequest(request)
const runId = crypto.randomUUID()
const stream = chat({
adapter: openaiText('gpt-6.1-sol'),
runId,
middleware: [withPersistence(persistence)],
...params,
})
return toResumableUIMessageStreamResponse(stream, memoryStream({ runId }))
}
// GET /api/chat/:id/stream
export async function GET(request: Request) {
const chatId = new URL(request.url).pathname.split('/').at(-2) ?? ''
const run = await persistence.stores.runs.findActiveRun(chatId)
return resumeUIMessageStreamResponse(run && memoryStream({ runId: run.runId }))
}Pass toChatTransport(fetchServerSentEvents('/api/chat')) as the transport of AI SDK useChat. The route is a plain TanStack route, with no AI SDK code. The conversion runs in the browser.
Serve chat() as for TanStack useChat:
import {
chat,
chatParamsFromRequest,
toServerSentEventsResponse,
} from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
export async function POST(request: Request) {
const params = await chatParamsFromRequest(request)
return toServerSentEventsResponse(
chat({ ...params, adapter: openaiText('gpt-6.1-sol') }),
)
}Give useChat the transport:
import { useChat } from '@ai-sdk/react'
import { fetchServerSentEvents } from '@tanstack/ai-client'
import { toChatTransport } from '@tanstack/ai-vercel-compat'
const transport = toChatTransport(fetchServerSentEvents('/api/chat'))
export function Chat() {
const { messages, sendMessage } = useChat({ transport })
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.parts.map((p, i) =>
p.type === 'text' ? <span key={i}>{p.text}</span> : null,
)}
</div>
))}
<button onClick={() => sendMessage({ text: 'Hello' })}>Send</button>
</div>
)
}Tools, approvals and client tools work as in Add tools. An approval answer resumes the paused run. If the answer has no paused run id in the message metadata, sendMessages throws. resumeStream() rejoins the last run of the chat in the same page, when the connection has joinRun and the route keeps a durability log.
For every event and message part, see AI SDK bridge compatibility.
Your AI SDK useChat UI streams replies, tools, approvals, activity and subagents from chat(), and it continues a reply after a reload.