Get started with Anthropic
Build a chat app on the Anthropic Messages API where every subscribed client shows Claude's reply as it streams, and a client that reloads picks up where it left off. The same Ably channel can also carry the agent's status and artifacts.
What you build
A Next.js chat app where:
- Claude's reply streams to every connected client in realtime.
- A second tab shows the same conversation, because every subscribed client receives the same messages.
- Reloading the page reads the conversation from your database, then replays what arrived on the channel after it, so a reply that is still streaming carries on where it is.
- A reply that fails, for example because the API is overloaded, shows the error in every tab.
The conversation lives in your own database. AI Transport carries the live traffic over an Ably channel, and you build your own interface. The one below is an example.
Prerequisites
- Node.js 22 or later.
- An Ably account with an API key.
- An Anthropic API key, in the
ANTHROPIC_API_KEYenvironment variable, which the Anthropic SDK reads.
Install dependencies
Install the AI Transport SDK, the Ably Pub/Sub server and device SDKs, the Anthropic SDK, and Next.js, then add the scripts that run the app:
npm install @ably/ai-transport @ably/pubsub-server @ably/pubsub-device @anthropic-ai/sdk@^1 next react react-dom
npm pkg set scripts.dev="next dev" scripts.build="next build"AI Transport does not depend on Next.js. This guide uses it as an example.
Set up authentication
Create an auth endpoint at /api/auth/token that returns an Ably token to the browser, with the client id and the channel capabilities the user needs, as described in Set up authentication. The client needs the subscribe and history capabilities on the conversation channels.
The client below fetches its token with authUrl: '/api/auth/token'. The agent's HTTP endpoint runs on your own infrastructure, so it uses the API key directly.
Configure the channel rule
AI Transport streams a reply's text by appending each delta to a channel message. That needs the Message annotations, updates, deletes, and appends rule (mutableMessages: true in the Control API) on the channels your conversations use. Enable it once per Ably app through the dashboard, Control API, or CLI. The rule also persists the channel's messages, so a client that reloads can replay them.
Create the agent's HTTP endpoint
Create app/api/chat/route.js. The POST handler is the agent. It loads the stored conversation, publishes the new user message to the channel with send, calls the Messages API with the stored messages and the new one, and pipes the stream to the channel. The agent stores the user message with the serial that send returns, so a client that loads while the reply streams replays the whole reply. When the pipe resolves, the route reads the finished reply from finalMessage() and stores it, with the serial of the last message the pipe published.
When the reply fails, the route publishes the codec's error event with send, so every client ends the reply. The route catches the failure from finalMessage(), which rejects for every failed reply, even when the pipe resolved. See Handle a failed reply for more detail.
If the client closes the request, req.signal cancels both the model call and the pipe, and the route stores no reply for that turn.
The GET handler returns the stored messages and their serial to the page.
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
45
46
47
48
49
50
51
52
53
54
// Agent code. This runs on your own infrastructure, so it holds the API keys.
import Anthropic from '@anthropic-ai/sdk';
import { anthropicAdaptor } from '@ably/ai-transport/anthropic';
import { createRealtimeClient } from '@ably/pubsub-server';
import { loadConversation, recordMessages } from '../../store';
const ably = createRealtimeClient({ key: process.env.ABLY_API_KEY });
const client = new Anthropic();
// Build the Messages API's error event from what the model call or the pipe threw.
function errorEvent(error) {
const apiError = error instanceof Anthropic.APIError ? error : undefined;
return {
type: 'error',
error: { type: apiError?.type ?? 'api_error', message: apiError?.apiMessage ?? String(error?.message ?? error) },
request_id: apiError?.requestID ?? null,
};
}
export async function POST(req) {
const { channelName, messages } = await req.json();
const { messages: history } = loadConversation(channelName);
const adaptor = anthropicAdaptor(ably.channels.get(channelName));
// Publish the user's message to the channel, and store it with its serial.
const { serial: inputSerial } = await adaptor.send({ type: 'input', messages });
recordMessages(channelName, messages, inputSerial);
try {
const stream = client.messages.stream(
{ model: 'claude-sonnet-5-5', max_tokens: 4096, messages: [...history, ...messages] },
{ signal: req.signal },
);
const { serial } = await adaptor.pipe(stream, { signal: req.signal });
// Rejects for a reply that failed, even when the pipe resolved.
const reply = await stream.finalMessage();
recordMessages(channelName, [{ role: 'assistant', content: reply.content }], serial);
return new Response(null, { status: 204 });
} catch (error) {
// Tell every client the reply ended. The publish can fail for the same reason
// the pipe did, so it is best effort.
await adaptor.send(errorEvent(error)).catch(() => {});
// The client closed the request, so the model call or the pipe was cancelled.
if (req.signal.aborted) return new Response(null, { status: 204 });
throw error;
}
}
export function GET(req) {
const channelName = new URL(req.url).searchParams.get('channel');
return Response.json(loadConversation(channelName));
}Pass the stream to pipe as soon as you create it, without awaiting anything in between. The SDK's MessageStream starts its request when you create it, and only queues events for a reader once one is attached.
The codec sends each piece of streamed text once, so message_start travels with an empty content. The SDK builds the reply from the stream on the agent, before the codec encodes it, so the reply that finalMessage() returns keeps its text.
Create the chat component
Create app/chat.js. The component reads the stored conversation from the agent's HTTP endpoint, and gets the channel with a rewind to its serial. It subscribes an anthropicDecoder() to the channel. When the channel attaches, Ably replays the messages that arrived after the serial, in channel order, then delivers live messages. With no stored serial, nothing is stored yet, so the channel attaches without a rewind.
To send, the component wakes the agent with a POST that carries the user's message. The agent reads the prompt from the request body, and publishes it to the channel, so every subscribed client receives it.
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use client';
// Client code. The browser fetches a token, so it never holds an API key.
import { useCallback, useEffect, useState } from 'react';
import { anthropicDecoder } from '@ably/ai-transport/anthropic';
import { usePubSubClient } from '@ably/pubsub-device/react';
import { mergeEvent, toEntries } from './merge';
export function Chat({ channelName }) {
const client = usePubSubClient();
const [entries, setEntries] = useState([]);
const [input, setInput] = useState('');
const apply = useCallback(({ event }) => {
if (event !== undefined) setEntries((prev) => mergeEvent(prev, event));
}, []);
useEffect(() => {
let channel;
let decoder;
let cancelled = false;
(async () => {
const res = await fetch(`/api/chat?channel=${encodeURIComponent(channelName)}`);
const stored = await res.json();
if (cancelled) return;
setEntries(toEntries(stored.messages));
// Replay the messages after the stored serial. With no stored serial, nothing is stored yet.
channel = client.channels.get(channelName, stored.serial ? { params: { rewind: stored.serial } } : undefined);
decoder = anthropicDecoder();
decoder.onEvent(apply);
await channel.subscribe(decoder.receive);
})();
return () => {
cancelled = true;
if (!decoder) return;
channel.unsubscribe(decoder.receive);
// Detach, so the channel rewinds again when the effect runs again.
channel.detach().catch(() => {});
};
}, [client, channelName, apply]);
const send = async (e) => {
e.preventDefault();
const text = input.trim();
if (!text) return;
setInput('');
const messages = [{ role: 'user', content: text }];
await fetch('/api/chat', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ channelName, messages }) });
};
return (
<div>
{entries.map((entry) => (
<p key={entry.id}>
<strong>{entry.role}:</strong> {entry.text}
</p>
))}
<form onSubmit={send}>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button type="submit">Send</button>
</form>
</div>
);
}Merge the model output into conversation messages
Create app/merge.js. The agent publishes the Messages API's own stream events, and each client merges them into the entries its UI shows. A message_start opens an entry for the reply, and each text delta appends its text to the latest reply that is still streaming. message_stop ends the reply. An error ends the reply too, and adds an entry with the error's message, so a reply that fails before it starts still shows the error. toEntries turns messages into the same entries, for the stored messages when the page loads and for the messages of each input event.
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
// Client code.
const textOf = (content) =>
typeof content === 'string'
? content
: content
.filter((block) => block.type === 'text')
.map((block) => block.text)
.join('');
export function toEntries(messages) {
return messages
.map((message) => ({ id: crypto.randomUUID(), role: message.role, text: textOf(message.content) }))
.filter((entry) => entry.text !== '');
}
// Apply an update to the latest reply that is still streaming.
const updateReply = (entries, update) => {
const index = entries.findLastIndex((entry) => entry.streaming);
return index === -1 ? entries : entries.with(index, update(entries[index]));
};
export function mergeEvent(entries, event) {
switch (event.type) {
case 'input':
return [...entries, ...toEntries(event.messages)];
case 'message_start':
return [...entries, { id: event.message.id, role: 'assistant', text: '', streaming: true }];
case 'content_block_delta': {
const { delta } = event;
if (delta.type !== 'text_delta') return entries;
return updateReply(entries, (reply) => ({ ...reply, text: reply.text + delta.text }));
}
case 'message_stop':
return updateReply(entries, (reply) => ({ ...reply, streaming: false }));
case 'error':
return [
...updateReply(entries, (reply) => ({ ...reply, streaming: false })),
{ id: crypto.randomUUID(), role: 'error', text: event.error.message },
];
default:
return entries;
}
}A text delta carries the index of its content block, but not the id of its message, so the client applies it to the latest reply that is still streaming. This works because the agent pipes one reply at a time to each conversation's channel. To build the whole message instead, with thinking and tool use blocks, merge the events with the SDK's own MessageStream, as Anthropic Messages shows.
Integrate with your database
Create app/store.js. This Map stands in for the database your application already uses. The Messages API takes its history as a messages array, so the store keeps messages, and the next turn passes them to the model unchanged. It also keeps the serial of the last stored message.
1
2
3
4
5
6
7
8
9
10
11
// Stand-in for your own database. Replace both functions with real queries.
const conversations = new Map();
export function loadConversation(channelName) {
return conversations.get(channelName) ?? { messages: [] };
}
export function recordMessages(channelName, messages, serial) {
const current = loadConversation(channelName);
conversations.set(channelName, { messages: [...current.messages, ...messages], serial: serial ?? current.serial });
}Wire it together
Create app/page.js. The page creates the Ably client in the browser with createClient, and wraps the chat in PubSubClientProvider:
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
'use client';
// Client code.
import { useEffect, useState } from 'react';
import { createClient } from '@ably/pubsub-device';
import { PubSubClientProvider } from '@ably/pubsub-device/react';
import { Chat } from './chat';
const channelName = 'conversations:demo';
export default function Page() {
const [client, setClient] = useState();
useEffect(() => {
const ably = createClient({ authUrl: '/api/auth/token' });
setClient(ably);
return () => ably.close();
}, []);
if (!client) return null;
return (
<PubSubClientProvider client={client}>
<Chat channelName={channelName} />
</PubSubClientProvider>
);
}Create app/layout.js. Next.js needs a root layout to build the app:
1
2
3
4
5
6
7
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}Run the app
Start the dev server:
npm run devOpen http://localhost:3000 in two tabs and send a message from one. The reply streams into both. The agent publishes the prompt to the channel, so both tabs show it. Reload a tab while a reply is streaming, and the tab shows the stored conversation, then the reply so far, then the rest of it live.
What happens when you send a message
- The client POSTs the user's message to the agent's HTTP endpoint.
- The POST wakes the agent, and the agent reads the prompt from the request body. AI Transport does not send HTTP requests of its own. The agent publishes the prompt to the channel with
send, and stores the message with the serial thatsendreturns. - The agent calls the Messages API with the stored messages and the new one, and pipes the stream to the channel. Every subscribed client merges the text deltas into the reply.
- When the pipe resolves, the agent stores the reply with the serial of the last message. If the reply failed, the agent publishes an
errorevent instead, and every client ends the reply. A client that loads the page later replays the channel from the stored serial.
Understand the architecture
The Anthropic SDK owns the model call and the event stream. AI Transport carries that stream over one Ably channel, and the channel replays from the serial your database holds. Conversation covers who implements what.
Explore next
- History and replay: replay the channel from a stored serial, and read history backwards.
- Reconnection and recovery: what happens when a client loses its connection.
- Anthropic Messages: how the codec carries the Messages API's events, and how to run tools.
- Anthropic API reference:
anthropicAdaptor,anthropicDecoder, and the events the codec encodes and decodes. - Agent adaptor API reference: every method on the adaptor.