useChatTransport

Open in

Read the ChatTransport adapter and its underlying ClientTransport from the nearest ChatTransportProvider. The ChatTransport is what you pass to Vercel's useChat as transport.

The hook is a thin context reader; it does not create transport state. Construction happens once inside ChatTransportProvider.

This hook must be used within a ChatTransportProvider.

React

1

2

3

4

5

6

7

8

import { useChatTransport } from '@ably/ai-transport/vercel/react';
import { useChat } from '@ai-sdk/react';

function Chat({ chatId }) {
  const { chatTransport } = useChatTransport();
  const { messages, sendMessage, stop } = useChat({ id: chatId, transport: chatTransport });
  // ...
}

Parameters

channelNameoptionalString
The channelName of the ChatTransportProvider to read from. Omit to use the nearest provider in the tree.
skipoptionalBoolean
When true, returns stub transports that throw on any access. Safe to hold in state before auth or other conditions are ready.

Returns

ChatTransportHandle

transportClientTransport<UIMessageChunk, UIMessage>
The underlying client transport. Also available via useClientTransport(). A throwing stub when skip is true, when no matching TransportProvider is found, or when transport construction failed. Check transportError before use.
chatTransportChatTransport
The chat transport adapter for use with Vercel's useChat hook. A throwing stub when skip is true, when no matching ChatTransportProvider is found, or when the underlying ClientTransport construction failed. Check both chatTransportError and transportError before use.
transportErrorAbly.ErrorInfo or Undefined
Set when no matching TransportProvider is found or transport construction failed and skip is false.
chatTransportErrorAbly.ErrorInfo or Undefined
Set when no matching ChatTransportProvider is found or transport construction failed and skip is false.

See Vercel AI SDK integration for the ChatTransport surface and ClientTransport for the underlying transport.

Example

React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import { useChatTransport } from '@ably/ai-transport/vercel/react';
import { useChat } from '@ai-sdk/react';

function Chat({ chatId }) {
  const { chatTransport, transport, chatTransportError, transportError } = useChatTransport();

  if (transportError) return <ErrorBanner error={transportError} />;
  if (chatTransportError) return <ErrorBanner error={chatTransportError} />;

  const { messages, sendMessage, stop } = useChat({ id: chatId, transport: chatTransport });

  return (
    <div>
      {messages.map((m) => <Message key={m.id} message={m} />)}
      <Composer onSend={(text) => sendMessage({ text })} onStop={stop} />
      <button onClick={() => transport.cancel({ all: true })}>Cancel everyone</button>
    </div>
  );
}