Chat transport

The chat transport implements the Vercel AI SDK's ChatTransport for useChat. When the user submits a prompt using useChat, the conversation so far is POSTed to your backend. The agent should stream its response over the Ably channel, which will be received by the subscribed chat transport.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

// Client code.
import { createClient } from '@ably/pubsub-device';
import { useChat } from '@ai-sdk/react';
import { createChatTransport } from '@ably/ai-transport/vercel';

const ably = createClient({ authUrl: '/auth' });
const channel = ably.channels.get('conversations:42');
const transport = createChatTransport({ channel });

// In your component.
const { messages, sendMessage, status, stop } = useChat({ id: 'conversations:42', transport, resume: true });

Once you have created the transport and passed it to useChat, you can interact directly with useChat and the responses streamed to your clients over the Ably channel.

Properties

resumeStreamIsReplaytrue
Always true. A resumed stream replays the response from its start chunk, so useChat resets the response it already holds and rebuilds it from the replay. useChat reads this property in @ai-sdk/react 4.0.141 and later releases.

Create a chat transport

createChatTransport(options: ChatTransportOptions): AblyChatTransport

Create a transport on the conversation's channel, and pass it to useChat. Pass the channel name as useChat's id, so your backend receives it as chatId and knows which channel to publish the response to. With resume: true, useChat resumes a response that is still streaming when the component mounts:

JavaScript

1

2

3

4

5

// Client code, in a React component.
const channel = ably.channels.get(channelName);
const transport = useMemo(() => createChatTransport({ channel }), [channel]);
const { messages, sendMessage, status, stop } = useChat({ id: channelName, transport, resume: true });
useEffect(() => () => transport.close(), [transport]);

Parameters

createChatTransport() takes an options object with the following properties:

channelrequiredRealtimeChannel
The conversation's channel, such as ably.channels.get(channelName) on your Ably Pub/Sub client. Use one channel for each conversation, because the transport reads every response on the channel as part of that conversation.
apioptionalString
The endpoint that the transport will POST the conversation to on each new user prompt. Defaults to '/api/chat'.
loggeroptionalLogger
The logger for the transport's diagnostics, such as a request that failed. Create one with makeLogger. The transport does not log when you leave it out.

Returns

AblyChatTransport. Pass it to useChat as transport.

Send a turn

sendMessages(options): Promise<ReadableStream<UIMessageChunk>>

A turn is a prompt and the response to it. sendMessages() POSTs the conversation to your backend, and returns the response as your agent streams it on the channel. useChat calls it when the user sends a message, when you call regenerate() and when useChat sends a tool's result.

The transport POSTs { ...body, chatId, trigger, messageId, messages } as JSON to the api endpoint, with the headers and abort signal that useChat passes. sendMessages() returns the stream without waiting for the HTTP response, so useChat receives the response as the agent streams it, even if your backend keeps the request open until the agent finishes. Your backend should read these fields from the body:

JavaScript

1

2

3

4

5

// Agent code.
export async function POST(req) {
  const { chatId, trigger, messageId, messages } = await req.json();
  // chatId is useChat's id, which is the conversation's channel name.
}

Parameters

useChat passes an options object with the following properties:

triggerString
'submit-message' for a new message or a tool result, or 'regenerate-message' for regenerate().
chatIdString
The id you passed to useChat.
messageIdString or undefined
The id you pass to regenerate({ messageId }), the id of a user message you edit with sendMessage() or the id of the assistant message that a tool result or approval continues. undefined for a new message, and for regenerate() without a messageId.
messagesUIMessage[]
The conversation, as useChat holds it.
abortSignalAbortSignal or undefined
Fires when useChat stops the response. The transport attaches it to the request.
headersObject
Optional. Headers for the request, from the options of the call that sent the message: sendMessage(), regenerate(), addToolOutput(), or addToolApprovalResponse(). For a turn that useChat sends automatically after a resumed response, the headers come from the options of resumeStream().
bodyObject
Optional. Extra properties for the request's JSON body. The transport's chatId, trigger, messageId, and messages replace properties with the same names.
metadataUnknown
Optional. Not used.

Returns

Promise<ReadableStream<UIMessageChunk>>. A promise of the response's chunks. If the promise rejects, the transport has not posted the request. It rejects with an ErrorInfo:

  • InvalidArgument if the transport cannot build the request, such as for a header that is not valid, or a body or messages that cannot be serialized as JSON.
  • OperationCancelled if useChat stops the call, or the transport closes, before the transport posts the request.
  • The channel's error code and status, with the channel's error as cause, if the transport cannot attach the channel or read its history, such as when the token is missing a capability. An error without a code becomes InternalError.

The stream can also end with an error.

Resume a running turn

reconnectToStream(options): Promise<ReadableStream<UIMessageChunk> | null>

reconnectToStream() replays the response that is streaming on the channel from its start chunk, and then follows it live. useChat calls it when the component mounts with resume: true, and when you call resumeStream().

Parameters

useChat passes an options object with the following properties. The transport does not use its headers, body, or metadata, because resuming does not send a request.

chatIdString
The id you passed to useChat.
abortSignalAbortSignal
Optional. Fires when useChat stops the resumed response. useChat passes it in @ai-sdk/react 4.0.59 and 3.0.251, and in later releases.

Returns

Promise<ReadableStream<UIMessageChunk> | null>. A promise of the response's chunks, or of null if no response is streaming, or if the transport closes before the call finds one. It rejects with an ErrorInfo:

  • OperationCancelled if useChat stops the call before it returns the stream.
  • The channel's error code and status, with the channel's error as cause, if the transport cannot attach the channel or read its history. An error without a code becomes InternalError.

Close the chat transport

close(): void

close() stops the transport from reading the channel, and leaves the agent running. useChat does not close its transport, so your application should close it when the conversation goes away, such as in an effect cleanup:

JavaScript

1

2

// Client code, in a React component.
useEffect(() => () => transport.close(), [transport]);

A response that is still streaming ends in this tab, and the transport does not abort the turn's request. The transport unsubscribes from the channel. If the transport attached the channel, it also detaches the channel, and every listener on the channel stops receiving messages, including your application's listeners. If your application attached the channel first, the channel stays attached.

You can call close() more than once. The next sendMessages() or reconnectToStream() call reads the channel again, so React's development-mode double mount works. If a client-side tool finishes after the component unmounts, and sendAutomaticallyWhen makes useChat send the tool's result, the transport reads the channel again, and the channel stays attached because nothing closes the transport again.

Behavior

How a response ends

Your agent should publish each response to the channel with vercelAdaptor. A response runs from its start chunk to the first finish, abort, or error chunk after it. The stream that sendMessages() returns follows the next response that starts on the channel, and closes at the chunk that ends that response. toUIMessageStream writes the start chunk, and ends the response with:

  • finish when the model completes.
  • error if the model fails, sometimes followed by a finish.
  • abort if the abort signal that you pass to streamText fires.

If the agent exits any other way, it should end the response itself. If pipe() rejects, the agent should publish error with the adaptor's send(). The transport ignores a finish or abort that arrives while no response is streaming, so if the agent fails before it streams anything, only an error chunk or a failed request ends the turn. Without either, the tab that sent the turn stays submitted until your client calls stop() or the page reloads.

If the agent process dies, your backend should publish error for its turn, such as from the workflow that runs the agent. Until then, if the response has started, every tab that shows it stays streaming, unless the user presses stop, and every tab that loads the conversation resumes it.

Your agent should pass its abort signal to streamText only, so toUIMessageStream writes the abort chunk that ends the response. If pipe() also receives the signal, the pipe stops before toUIMessageStream writes that chunk, and an onEnd callback that you pass to toUIMessageStream to save the response does not run. The response then stays open on the channel, and other tabs stay streaming, unless the agent publishes abort itself, as the Temporal and Vercel WDK guides do.

A start or a finish in the middle of a turn ends the response. If several UI message streams make up one turn, pass sendStart: false to every stream except the first, and sendFinish: false to every stream except the last. useChat does not receive the chunks that arrive before a response's start chunk or after the chunk that ends it, except an error, which ends a response that is waiting to start. To send data parts after the model finishes, pass sendFinish: false for the model's stream, write the data parts and then write finish.

Overlapping turns

Keep in mind that the transport cannot differentiate two responses on one channel, so your backend should run one turn at a time for each conversation, across all of its clients.

The transport posts a new turn without waiting for the previous turn to end, such as just after the user stops a response. The new turn's response starts at the next start chunk on the channel. If the previous turn has not ended when that start chunk arrives, the transport ends the previous response, the chunks of both turns mix in the new response and the previous agent's finish, abort, or error ends the new response early.

An error that arrives while no response is streaming ends every response that is waiting to start. If the previous turn's agent died before its start chunk, the error that your backend publishes for that turn therefore also ends the response of a turn posted after it.

Stopping

stop() ends the response in this tab, and aborts the request that this tab posted for the turn. If the agent runs inside that 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, such as with a request to an endpoint of yours, or a cancel message on the conversation's channel:

JavaScript

1

2

3

4

5

// Client code.
const stopResponse = () => {
  void channel.publish('cancel', {});
  void stop();
};

If your Stop button publishes a cancel message, the agent should subscribe to cancel messages before it publishes anything, and your client should show the Stop button only once the response is streaming. A cancel message published before the agent subscribes does not reach the agent, and the agent runs the whole turn.

Tell the agent to stop only from the Stop button's handler. useChat fires the same abort signal when it replaces a response it resumed, and in @ai-sdk/react 4.0.101 and later when its component unmounts, so the transport cannot differentiate the user pressing stop from an unmount. If only the Stop button's handler tells the agent to stop, an unmount, a change of useChat's id, or a reload leaves an agent outside the request running, and the next mount resumes the response.

stop() ends the response in this tab before the agent stops. The agent can publish a few more chunks before your message to stop reaches it, and those chunks still reach the channel's history and other subscribers. A tab that resumed the response did not post the request, so from that tab, only your Stop button's handler can tell the agent to stop.

Resuming

reconnectToStream() reads the channel to find the response that is still streaming, and does not send a request to your backend. If the latest response on the channel has ended, or there is none, the call returns null, and the transport keeps reading the channel, so a later call finds a response that started in between.

A response is on the channel only once the agent publishes its start chunk. A tab that loads before then gets null, and receives the response when it next calls resumeStream(), such as from a channel subscription, or when it next loads. A tab that loads just as a response ends can miss the response until its next load, if your database does not hold the response yet.

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.

useChat handles a resumed response like any other response. Every tab that resumes a response runs onToolCall for its client-side tool calls, and sends the next turn when sendAutomaticallyWhen returns true, so if the user can open the conversation in several tabs, run tools on the server where possible. Resuming a response that continues a message after a tool result or an approval ends with an error in useChat, or leaves out that message's earlier tool calls, as it does with the AI SDK's resumable streams.

The channel

Your application should get the conversation's channel from its Ably client, with any channel options it needs, and pass the channel to the transport. On the first sendMessages() or reconnectToStream() call, the transport subscribes to the channel, attaches the channel if nothing has attached it yet and reads the channel's history back to the newest start chunk. The client's token needs the subscribe and history capabilities, and also publish if your application publishes on the channel, such as the cancel message from your Stop button.

Let the transport attach the channel. The transport reads history only back to the point where the channel attached, so if other code attaches the channel first, such as by subscribing, the transport misses the messages published between that point and its first call. A subscription in an effect of the component that calls useChat with resume: true is fine, such as the channel subscription that shows a turn started on another device. That subscription attaches the channel as the component mounts, and the transport subscribes before the channel finishes attaching, so the transport receives every message.

If your application's subscription attached the channel, close() leaves the channel attached, and your application should detach it when the conversation goes away. Keep one chat transport per channel on a client. If a transport attached the channel, closing it detaches the channel for every listener, and a response that another chat transport on the channel is streaming stops receiving chunks, until the user stops it or that transport's next call ends it as a stop.

Don't pass a rewind param on the channel, because the transport reads the channel's history itself, which would conflict with the rewound messages.

If the connection drops for up to about two minutes, Ably attempts to resume it, and if Ably resumes the connection, the transport receives the messages it missed. After a longer gap, a response can miss chunks. If the response misses the chunk that ends it, useChat stays streaming until the user presses stop, or until the next sendMessages() or reconnectToStream() call reads the channel again.

That call ends each response left open as a stop. If the transport attached the channel, the call detaches and re-attaches it, so your application's listeners on the channel also stop receiving messages until the channel re-attaches. The call then reads the channel's history again. The transport recovers a response that was streaming during a longer gap only after a page reload.

Versions

The transport works with useChat from @ai-sdk/react 4, which uses ai 7, and from @ai-sdk/react 3, which uses ai 6. Each @ai-sdk/react release depends on an exact ai release, so check which @ai-sdk/react release your app uses with npm ls @ai-sdk/react. @ai-sdk/react 4.0.141 and later releases have every behavior in this table:

Behavior@ai-sdk/react 4@ai-sdk/react 3
useChat passes its abort signal to reconnectToStream(), so stop() can end a resumed response.4.0.59 and later3.0.251 and later
A resumed response starts a new assistant message. Earlier releases append it to the previous assistant message.4.0.64 and later3.0.252 and later
useChat stops the response when its component unmounts, which also aborts the turn's request.4.0.101 and laterNo release
useChat reads resumeStreamIsReplay. In 4.0.125 to 4.0.140, and in 3.0.300 and later, resuming a response that useChat already holds, with a tool call still running, repeats that message's parts.4.0.141 and laterNo release
A Chat instance that you create with the chat transport reads resumeStreamIsReplay.4.0.138 and later3.0.307 and later
A Chat instance's dispose() stops the response, then closes the transport.4.0.138 and laterNo release

On ai 6, the agent should call result.toUIMessageStream() in place of toUIMessageStream({ stream: result.stream }). If the agent saves the response when the stream ends, it should pass onFinish in place of onEnd.

Errors

If useChat stops a response, or close() ends it, the stream ends with an OperationCancelled error named AbortError, the name that an aborted fetch uses, so useChat treats it as a stop. A response that a long disconnection left open ends with the same error when a later call reads the channel again. The stream can also end with these errors:

  • SessionSendFailed if the request fails, or your backend responds with a status outside 2xx, before the response ends. If the request fails after the response ends, the transport only logs the failure. The error's statusCode is the HTTP status, or 500 if the request got no response, such as on a network failure. Its message includes the first 200 characters of the response body, or the status text if the body is empty.
  • SessionMessageProcessingFailed if a message that arrives while the response streams cannot be decoded. If the message is replayed from history, the transport only logs the failure, and the response continues without the message.

Example

In this example, the agent's HTTP endpoint returns immediately, and runs the agent with Next.js after(), so a reload does not stop the agent. A cancel message on the channel aborts the model call:

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

38

39

40

41

42

43

44

// Agent code, in your route handler.
import { createRealtimeClient } from '@ably/pubsub-server';
import { after } from 'next/server';
import { anthropic } from '@ai-sdk/anthropic';
import { convertToModelMessages, streamText, toUIMessageStream } from 'ai';
import { vercelAdaptor } from '@ably/ai-transport/vercel';

export async function POST(req) {
  const { chatId, trigger, messages } = await req.json();
  // Answer 409 here while this conversation's previous turn is still running.
  after(() => respond(chatId, trigger, messages));
  return new Response(null, { status: 202 });
}

async function respond(chatId, trigger, messages) {
  const ably = createRealtimeClient({ key: process.env.ABLY_API_KEY });
  const channel = ably.channels.get(chatId);
  const agent = vercelAdaptor(channel);
  const controller = new AbortController();

  try {
    await channel.subscribe('cancel', () => controller.abort());

    // Publish the user's prompt, so other clients receive it. A tool result also arrives as
    // 'submit-message', with the assistant's message last.
    const prompt = messages.at(-1);
    if (trigger === 'submit-message' && prompt.role === 'user') {
      await agent.send({ type: 'user-message', message: prompt });
    }
    const result = streamText({
      model: anthropic('claude-sonnet-4-20250514'),
      messages: await convertToModelMessages(messages),
      abortSignal: controller.signal,
    });
    await agent.pipe(
      toUIMessageStream({ stream: result.stream, originalMessages: messages, generateMessageId: () => crypto.randomUUID() }),
    );
  } catch (error) {
    console.error(error);
    await agent.send({ type: 'error', errorText: 'The agent failed to respond.' });
  } finally {
    ably.close();
  }
}

The client passes the chat transport to useChat, and publishes the cancel message when the user presses stop:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

export function Chat({ ably, chatId }) {
  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]);

  // The Stop button: tell the agent to stop, then end the response in this tab.
  const stopResponse = () => {
    void channel.publish('cancel', {});
    void stop();
  };

  // Show messages, call sendMessage({ text }) to send and call stopResponse() to stop.
}

The quickstart has a full example, which also stores the conversation and runs one turn at a time.