Vercel AI SDK UI

Vercel AI SDK UI provides useChat, a React hook for chat UIs. AI Transport provides a transport for useChat that streams each response over an Ably channel, so a tab that reloads or opens during a response can resume it.

Vercel AI SDK UI is Vercel's toolkit for chat UIs. Its useChat hook sends messages and receives responses through a transport that implements the AI SDK's ChatTransport interface. AI Transport's chat transport implements that interface with an Ably channel.

What Vercel AI SDK UI brings

FeatureDescription
useChat hookHolds the conversation's messages and status, and provides sendMessage, regenerate, stop, and resumeStream.
UIMessage modelMessages with parts: text, reasoning, tool calls, tool results, files and sources.
ChatTransport interfacesendMessages sends the conversation and returns the response as chunks, and reconnectToStream resumes a response that is still streaming.
Tool calls and approvalsaddToolOutput and addToolApprovalResponse record a tool's result or the user's approval on the message.
Stream resumptionWith resume: true, useChat asks its transport for a response that is still streaming when the component mounts.

What AI Transport adds

Everything below comes from AI Transport rather than the framework.

FeatureDescription
Responses that survive a reloadA tab that reloads during a response replays the response from its first chunk, then follows it live.
Streams that outlive a connectionThe response streams over the channel, so if a client's connection drops for up to about two minutes, Ably attempts to resume it and deliver the chunks the client missed.
Stop that reaches the agentYour Stop button can publish a cancel message on the channel, and the agent can subscribe to cancel messages wherever it runs.
Multi-device deliveryEvery client subscribed to the conversation's channel receives the response as it streams. useChat receives a turn that another device starts only if your component adds a channel subscription.
Token compactionA client that joins during a response receives the response's text so far in one delivery.

Where they connect

On the client, pass the chat transport to useChat:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

// Client code, in a React component.
import { useEffect, useMemo } from 'react';
import { useChat } from '@ai-sdk/react';
import { createChatTransport } from '@ably/ai-transport/vercel';

// Before, with the default HTTP transport:
// const { messages, sendMessage } = useChat();

// After, with the chat transport:
const channel = ably.channels.get(chatId);
const transport = useMemo(() => createChatTransport({ channel }), [channel]);
const { messages, sendMessage, status, stop } = useChat({ id: chatId, transport, resume: true });
useEffect(() => () => transport.close(), [transport]);

useChat's id is the channel name, so your backend knows which channel to publish the response to. useChat does not close its transport, so the effect closes it when the conversation goes away.

On the server, the agent still calls streamText, and pipes the response to the conversation's channel with vercelAdaptor:

JavaScript

1

2

3

4

5

6

// Agent code. The chat transport POSTs useChat's id as chatId. The default transport POSTs it as id.
const { chatId, messages } = await req.json();
const agent = vercelAdaptor(ably.channels.get(chatId));
await agent.pipe(
  toUIMessageStream({ stream: result.stream, originalMessages: messages, generateMessageId: () => crypto.randomUUID() }),
);

The integration has three parts:

  1. The chat transport, from createChatTransport, implements ChatTransport. It POSTs the conversation to the endpoint in its api option, /api/chat by default, and passes the response's chunks to useChat as they arrive on the channel.
  2. Your agent should publish the response on the same channel with vercelAdaptor. The agent should also publish each new prompt, so other clients receive it.
  3. toUIMessageStream writes a start chunk at the beginning of each response, and a finish, abort, or error chunk at the end, which tells the chat transport that the response has ended.

Choose where the agent runs

useChat passes an abort signal with each message, and the chat transport attaches the signal to the request. What the signal does depends on where the agent runs:

Where the agent runsIf the user presses stopIf the tab reloads or closes
Inside the request, passing the request's abort signal to streamTextThe tab that sent the message aborts the request, so the agent stops.The browser aborts the request, so the agent stops.
In a workflow your backend can reach, such as Temporal or Vercel WDKYour Stop button can call your endpoint, and the endpoint can cancel the workflow.The agent keeps running, and a tab that reloads resumes the response.
Outside the request, where your backend cannot reach it, such as with Next.js after()Your Stop button can publish a cancel message, which the agent can receive on the channel.The agent keeps running, and a tab that reloads resumes the response.

To keep a response running across a reload, run the agent outside the request, and stop it from your Stop button, as the quickstart does. With a workflow engine, keep in mind that a retry after a step has started streaming ends the response in the tab, and the tab receives the retried response only after a reload.

Plan when turns start and end

Each prompt and the response to it make up a turn. Keep in mind that the chat transport cannot differentiate two responses on one channel, so your backend should start a turn only once the previous turn has ended with finish, abort, or error, and the previous turn's agent has stopped publishing. If a turn arrives sooner, such as just after the user stops a response, your backend should reject it, as the quickstart does with a 409. Your backend should not queue the turn, because the tab that sent it follows the next response that starts on the channel, which can be the previous turn's response.

Be mindful of agents that die mid-turn. If the hosting platform stops an agent at its time limit, or the agent process exits, your backend should publish error for the turn as soon as it notices, because until then the response looks like it is still running in every tab. Your backend should keep rejecting new turns until it publishes that error, which also ends the response of any turn posted before it. With durable execution, the workflow's error handling can publish the error: the Temporal workflow from its catch block, and the Vercel WDK workflow from its abortResponse step.

Resume a response after a reload

With resume: true, a tab that loads during a response replays the response from its first chunk, and then follows it live, because the chat transport reads the response from the channel. Your client should pass the stored conversation to useChat as messages, and your backend should save the conversation, including the new prompt, when it accepts the turn, so useChat in a tab that reloads holds the prompt before the resumed response. The agent should give each response an id with the generateMessageId option of toUIMessageStream, so useChat holds the response once, even if a tab resumes it twice. The agent should also pass the posted messages as originalMessages, so a response that continues an assistant message after a tool result keeps that message's id.

Stop a response

stop() ends the response in this tab, and aborts the request that the tab posted. If the agent runs inside the request and passes the request's abort signal to streamText, aborting the request stops the agent. To stop an agent that runs anywhere else, your Stop button should also tell the agent to stop, with a request to your backend or a cancel message on the channel:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// Client code, in the component that calls useChat.
// Each way of cancelling identifies only the conversation, which is enough with one turn at a time.

// An agent your backend can reach: call an endpoint of yours.
const stopViaBackend = () => {
  void fetch(`/api/chat/cancel?chat=${encodeURIComponent(chatId)}`, { method: 'POST', keepalive: true });
  void stop();
};

// An agent subscribed to the channel: publish a cancel message. The token needs the publish capability.
const stopViaChannel = () => {
  void channel.publish('cancel', {});
  void stop();
};

Tell the agent to stop only from the Stop button's handler, so an unmount or a reload leaves an agent outside the request running, and the next load resumes the response. On the agent, abort the model call when your cancel request or message arrives, and pass that abort signal to streamText only, so toUIMessageStream writes the abort chunk that ends the response in every tab.

Show a turn started on another device

useChat receives a response only when its tab sends a message or resumes a response, so useChat in one tab does not receive a turn that another device starts. To show that turn, the component that calls useChat can subscribe to the channel, add each new prompt to useChat's messages and call resumeStream() when the response starts:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

// Client code, in the component that calls useChat. Merge this useChat call into yours.
// channel is the conversation's channel, the one you pass to createChatTransport.
import { useEffect, useRef } from 'react';
import { useChat } from '@ai-sdk/react';
import { vercelDecoder } from '@ably/ai-transport/vercel';

const { messages, setMessages, resumeStream, status } = useChat({ id: chatId, transport, resume: true });
const busyRef = useRef(false);
useEffect(() => {
  busyRef.current = status === 'submitted' || status === 'streaming';
}, [status]);

// Subscribing attaches the channel as the component mounts. The chat transport subscribes before the
// channel finishes attaching, so the transport receives every message, and its close() leaves the channel attached.
useEffect(() => {
  // The agent publishes every message with the name 'ai', so use the decoder to differentiate a prompt
  // from a chunk. A message from another publisher has no event.
  const decoder = vercelDecoder();
  const onMessage = (message) => {
    for (const { event } of decoder.decode(message)) {
      if (event?.type === 'user-message') {
        // Prompts match by id: the agent publishes the prompt with the id that the client sent.
        const prompt = event.message;
        setMessages((previous) => (previous.some((m) => m.id === prompt.id) ? previous : [...previous, prompt]));
      } else if (event?.type === 'start' && !busyRef.current) {
        // The response has started, so the turn is on the channel. Skip a turn that this tab sent.
        void resumeStream();
      }
    }
  };
  channel.subscribe(onMessage);
  return () => {
    channel.unsubscribe(onMessage);
    // The conversation is going away, so detach the channel that this subscription attached.
    void channel.detach();
  };
}, [channel, setMessages, resumeStream]);

This code misses a turn that another device starts while this tab's useChat status is submitted or streaming. It also misses each turn that starts during a disconnection longer than about two minutes, and the first turn that starts after one. Until a tab reloads, useChat in that tab adds a response that another device regenerates as a new message. After another device edits a message, the tab keeps the old message and its old response, followed by the new response.

Scope and trade-offs

Vercel AI SDK UI focuses on one chat in one component, and AI Transport keeps that model. Messages, status, regenerate, tool calls and approvals work as they do with the default transport. stop() ends the response in the tab, and an agent that runs outside the request stops only when your Stop button also tells it to. The stream that went to an HTTP response now goes over an Ably channel, so a tab that reloads or opens during the response receives it.

For what useChat does not cover, your application can use the channel or your database directly:

What you needHow
A turn another device startedA channel subscription that resumes when the response starts.
Older historyLoad it from your database, and add it with setMessages.
Agent status and who is in the conversationPresence on the conversation's channel.
Live artifact stateLiveObjects on a separate channel.
Several responses at the same timeYour code in place of useChat, reading the channel with vercelDecoder.