Anthropic
The Anthropic codec carries the Anthropic Messages API's stream events over an Ably channel, plus an input event for the messages a client sends, and the API's error event for a reply that fails. The agent pipes the MessageStream from the @anthropic-ai/sdk package directly into the adaptor, which encodes the stream into Ably messages, and clients decode the messages back into the same stream events. A client can merge them with the SDK's own MessageStream.
Import anthropicAdaptor and anthropicDecoder from @ably/ai-transport/anthropic. The agent publishes with an agent adaptor, and the client reads with a decoder. The codec works with the @anthropic-ai/sdk package at version 1.
1
2
3
4
5
6
7
8
import { anthropicAdaptor, anthropicDecoder } from '@ably/ai-transport/anthropic';
// Agent code. channel is a channel from your Ably Pub/Sub client.
const adaptor = anthropicAdaptor(channel);
// Client code.
const decoder = anthropicDecoder();
await channel.subscribe(decoder.receive);The codec writes each event type in one of three ways:
- Streams: a
content_block_deltawith atext_delta,thinking_deltaorinput_json_deltastreams into one message for its content block, keyed by the block's index. The first delta of a block publishes the message, later deltas append to it, and the block'scontent_block_stopends the stream. message_startis a plain publish with an emptymessage.content.- Every other event is a plain publish with the whole event as the message's
datafield, including acontent_block_deltawith asignature_deltaor acitations_delta, and theerrorevent. Theinputevent is a plain publish with its messages as the message'sdatafield.
The codec does not write any headers.
Events that change on the wire
Some events reach a subscriber in a different form from the one the agent piped:
- History and a client that joins late read one delta event per content block, with the text joined. A client that catches up while a block is still streaming reads one delta with the text so far, then the deltas after it.
message_starttravels withmessage.contentempty. The SDK'sMessageStreamkeeps building the message it yields withmessage_start, so by the time the codec encodes the event, the message can hold content that the codec sends as events of their own. Its other fields travel as they are, sostop_reasonandusagecan already hold their final values. Themessage_deltathat follows sets them again, soMessageStreambuilds the same message either way.- A
signature_deltaor acitations_deltais its own message, becauseMessageStreamsets a signature and collects citations rather than joining text. A citation does not keep its place among the text deltas around it, andMessageStreamadds it to its block either way. - A block that does not stream, such as
redacted_thinkingor a server tool's result, travels whole in itscontent_block_start. The codec does not check sizes, so a block larger than the Ably message size limit fails its publish, andpipe()rejects withPipeFailed.
Publish a failed reply
When a reply fails, publish the codec's error event from the agent with send(), so every client ends the reply. Catch the failure from finalMessage(), which rejects for every failed reply, even when pipe() resolved. See Handle a failed reply for why pipe() does not publish it.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Agent code.
const stream = client.messages.stream(params);
try {
await adaptor.pipe(stream);
const reply = await stream.finalMessage();
} catch (error) {
const apiError = error instanceof Anthropic.APIError ? error : undefined;
await adaptor.send({
type: 'error',
error: { type: apiError?.type ?? 'api_error', message: apiError?.apiMessage ?? String(error?.message ?? error) },
request_id: apiError?.requestID ?? null,
});
}Create an Anthropic adaptor
anthropicAdaptor(channel: ChannelWriter, options?: AgentAdaptorOptions): AgentAdaptor<AnthropicEvent>Create an agent adaptor that publishes Anthropic events on channel.
1
2
3
import { anthropicAdaptor } from '@ably/ai-transport/anthropic';
const adaptor = anthropicAdaptor(channel);Parameters
channelrequiredChannelWriterRealtimeChannel satisfies it. See createAgentAdaptor.optionsoptionalAgentAdaptorOptionscreateAgentAdaptor.Returns
AgentAdaptor<AnthropicEvent>. The adaptor, for events of the following type:
AnthropicStreamEventRawMessageStreamEvent@anthropic-ai/sdk package declares it: message_start, message_delta, message_stop, content_block_start, content_block_delta and content_block_stop.inputAnthropicInputtool_result blocks answer the tool calls of the reply before it.errorAnthropicErrorEventsend(), as in Publish a failed reply.Create an Anthropic decoder
anthropicDecoder(options?: DecoderOptions): Decoder<AnthropicEvent>Create a decoder that decodes what an Anthropic adaptor publishes.
1
2
3
4
import { anthropicDecoder } from '@ably/ai-transport/anthropic';
const decoder = anthropicDecoder();
await channel.subscribe(decoder.receive);Parameters
optionsoptionalDecoderOptionscreateDecoder.Returns
Decoder<AnthropicEvent>. The decoder, for the events the adaptor publishes.
An input message whose data is not an array of objects fails to decode. It reaches a subscriber with event set to undefined.
Example
The client POSTs the user's message to the agent, which publishes it as an input event. The agent pipes the Messages stream, and the client merges each reply with the SDK's MessageStream, which it opens on message_start and closes on message_stop. An error fails the reply that is streaming.
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
// Client code.
import { MessageStream } from '@anthropic-ai/sdk/lib/MessageStream';
const encoder = new TextEncoder();
let reply;
decoder.onEvent(({ event }) => {
if (event === undefined || event.type === 'input') return;
if (event.type === 'error') {
if (reply) reply.error(new Error(event.error.message));
else showError(event.error);
reply = undefined;
return;
}
if (event.type === 'message_start') {
const stream = new ReadableStream({ start: (controller) => (reply = controller) });
MessageStream.fromReadableStream(stream)
.on('streamEvent', (_event, message) => render(message))
.on('error', (error) => showError(error));
}
reply?.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));
if (event.type === 'message_stop') {
reply?.close();
reply = undefined;
}
});
await channel.subscribe(decoder.receive);
const messages = [{ role: 'user', content: 'What is the weather?' }];
await fetch('/api/chat', { method: 'POST', body: JSON.stringify({ channelName: 'conversations:42', messages }) });1
2
3
4
5
6
7
8
9
10
11
12
13
// Agent code.
import Anthropic from '@anthropic-ai/sdk';
await adaptor.send({ type: 'input', messages });
const client = new Anthropic();
const stream = client.messages.stream({ model: 'claude-opus-5-5', max_tokens: 4096, messages }, { signal: req.signal });
try {
await adaptor.pipe(stream, { signal: req.signal });
await stream.finalMessage();
} catch (error) {
await adaptor.send({ type: 'error', error: { type: 'api_error', message: String(error?.message ?? error) }, request_id: null });
}