useTransport
The useTransport hook returns the transport from the nearest TransportProvider, or from the provider for a channel name you pass. Use it to send messages, pipe events, or subscribe with history replay from a component.
OpenAI
Vercel AI SDK
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useTransport } from '@ably/ai-transport/react';
function Composer({ channelName }) {
const { transport, error } = useTransport();
if (error) return <p>Transport unavailable: {error.message}</p>;
const send = async (text) => {
if (!transport) return;
const requestId = crypto.randomUUID();
await transport.send({ type: 'input', items: [{ role: 'user', content: text }] }, { headers: { requestId } });
// Wake the agent. It reads the prompt from the channel.
await fetch('/api/chat', { method: 'POST', body: JSON.stringify({ channelName, requestId }) });
};
return <button onClick={() => send('Hello')} disabled={!transport}>Send</button>;
}This hook must be used within a TransportProvider.
Parameters
channelNameoptionalStringThe channel name of the provider to read. Omit it to read the nearest provider.
The hook throws an ErrorInfo with InvalidArgument when no matching TransportProvider encloses the component.
Returns
transportTransport<E> or undefinedThe provider's transport.
undefined on the first render, before the provider has created it, and when creating it failed.errorErrorInfo or undefinedThe error that stopped the provider creating the transport, or
undefined when the transport exists.Example
A component subscribes with history replay from the serial your server stored with the conversation. useDeliveries has no history option, so the component calls transport.subscribe in an effect and unsubscribes when the effect cleans up.
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useEffect } from 'react';
import { fromSerial } from '@ably/ai-transport';
import { useTransport } from '@ably/ai-transport/react';
function Conversation({ storedSerial, onDelivery }) {
const { transport } = useTransport();
useEffect(() => {
if (!transport) return;
const unsubscribe = transport.subscribe(onDelivery, {
history: storedSerial ? { replay: fromSerial(storedSerial) } : undefined,
});
return () => unsubscribe();
}, [transport, storedSerial, onDelivery]);
return null;
}