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.

JavaScript

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_delta with a text_delta, thinking_delta or input_json_delta streams 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's content_block_stop ends the stream.
  • message_start is a plain publish with an empty message.content.
  • Every other event is a plain publish with the whole event as the message's data field, including a content_block_delta with a signature_delta or a citations_delta, and the error event. The input event is a plain publish with its messages as the message's data field.

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_start travels with message.content empty. The SDK's MessageStream keeps building the message it yields with message_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, so stop_reason and usage can already hold their final values. The message_delta that follows sets them again, so MessageStream builds the same message either way.
  • A signature_delta or a citations_delta is its own message, because MessageStream sets a signature and collects citations rather than joining text. A citation does not keep its place among the text deltas around it, and MessageStream adds it to its block either way.
  • A block that does not stream, such as redacted_thinking or a server tool's result, travels whole in its content_block_start. The codec does not check sizes, so a block larger than the Ably message size limit fails its publish, and pipe() rejects with PipeFailed.

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.

JavaScript

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.

JavaScript

1

2

3

import { anthropicAdaptor } from '@ably/ai-transport/anthropic';

const adaptor = anthropicAdaptor(channel);

Parameters

channelrequiredChannelWriter
The channel to publish on. A RealtimeChannel satisfies it. See createAgentAdaptor.
optionsoptionalAgentAdaptorOptions
Default headers and a logger. See createAgentAdaptor.

Returns

AgentAdaptor<AnthropicEvent>. The adaptor, for events of the following type:

AnthropicStreamEventRawMessageStreamEvent
Every stream event the Messages API produces, as the @anthropic-ai/sdk package declares it: message_start, message_delta, message_stop, content_block_start, content_block_delta and content_block_stop.
inputAnthropicInput
The messages a client sends: a user message to start a turn, or a user message whose tool_result blocks answer the tool calls of the reply before it.
errorAnthropicErrorEvent
A failed reply, as the Messages API's own error event. Publish it from the agent with send(), 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.

JavaScript

1

2

3

4

import { anthropicDecoder } from '@ably/ai-transport/anthropic';

const decoder = anthropicDecoder();
await channel.subscribe(decoder.receive);

Parameters

optionsoptionalDecoderOptions
A logger. See createDecoder.

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.

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

// 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 }) });
JavaScript

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 });
}