# Anthropic The Anthropic codec carries the [Anthropic Messages API](https://ably.com/docs/ai-transport/frameworks/anthropic.md)'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](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md), and the client reads with a [decoder](https://ably.com/docs/ai-transport/api/javascript/decoder.md). The codec works with the `@anthropic-ai/sdk` package at version 1. #### Javascript ``` 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()`](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md#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](https://ably.com/docs/ai-transport/frameworks/anthropic.md#errors) for why `pipe()` does not publish it. ### Javascript ``` // 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` Create an [agent adaptor](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md) that publishes Anthropic events on `channel`. ### Javascript ``` import { anthropicAdaptor } from '@ably/ai-transport/anthropic'; const adaptor = anthropicAdaptor(channel); ``` ### Parameters | Parameter | Required | Description | Type | | --- | --- | --- | --- | | channel | required | The channel to publish on. A `RealtimeChannel` satisfies it. See [`createAgentAdaptor`](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md#create-agent-adaptor-params). | `ChannelWriter` | | options | optional | Default headers and a logger. See [`createAgentAdaptor`](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md#create-agent-adaptor-params). | `AgentAdaptorOptions` |
### Returns `AgentAdaptor`. The adaptor, for events of the following type: | Event | Description | Type | | --- | --- | --- | | `AnthropicStreamEvent` | 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`. | `RawMessageStreamEvent` | | `input` | 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. |
| | `error` | A failed reply, as the Messages API's own error event. Publish it from the agent with `send()`, as in [Publish a failed reply](#error-event). |
|
| Property | Description | Type | | --- | --- | --- | | type | `'input'`. | String | | messages | The Messages API input messages, carried as the Ably message's data, so the agent passes them to the model unchanged. | `MessageParam[]` |
| Property | Description | Type | | --- | --- | --- | | type | `'error'`. | String | | error | The error's `type`, such as `overloaded_error` or `rate_limit_error`, and its `message`. An `APIError` carries both, as `type` and `apiMessage`. | `ErrorObject` | | request_id | The id of the request that failed, or `null`. An `APIError` carries it as `requestID`. | String or `null` |
## Create an Anthropic decoder `anthropicDecoder(options?: DecoderOptions): Decoder` Create a [decoder](https://ably.com/docs/ai-transport/api/javascript/decoder.md) that decodes what an Anthropic adaptor publishes. ### Javascript ``` import { anthropicDecoder } from '@ably/ai-transport/anthropic'; const decoder = anthropicDecoder(); await channel.subscribe(decoder.receive); ``` ### Parameters | Parameter | Required | Description | Type | | --- | --- | --- | --- | | options | optional | A logger. See [`createDecoder`](https://ably.com/docs/ai-transport/api/javascript/decoder.md#create-decoder-params). | `DecoderOptions` |
### Returns `Decoder`. The decoder, for the [events](#anthropic-adaptor-returns) 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 ``` // 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 ``` // 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 }); } ``` ## Related Topics - [Agent adaptor](https://ably.com/docs/ai-transport/api/javascript/agent-adaptor.md): API reference for the AI Transport agent adaptor: createAgentAdaptor, send, pipe, and pipeEach, and the options, results, and errors of each. - [Decoder](https://ably.com/docs/ai-transport/api/javascript/decoder.md): API reference for the AI Transport decoder: createDecoder, receive, decode, onEvent, and onError, and the Delivery each message becomes. - [Codec](https://ably.com/docs/ai-transport/api/javascript/codec.md): API reference for the AI Transport Codec: the encode and decode contract an adaptor and a decoder use, EncodedMessage, and how defineCodec builds a codec from a table of event rows. - [Vercel](https://ably.com/docs/ai-transport/api/javascript/vercel.md): API reference for the AI Transport codec for the Vercel AI SDK: vercelAdaptor, vercelDecoder, and the VercelEvent union of UIMessageChunk events and the user message. - [Vercel chat transport](https://ably.com/docs/ai-transport/api/javascript/vercel/chat-transport.md): API reference for createChatTransport, the AI Transport chat transport for the Vercel AI SDK's useChat hook: its options, its methods, and how it behaves. - [OpenAI](https://ably.com/docs/ai-transport/api/javascript/openai.md): API reference for the AI Transport codec for the OpenAI Responses API: openaiAdaptor, openaiDecoder, and the OpenAIEvent union of Responses stream events and client input. - [AG-UI](https://ably.com/docs/ai-transport/api/javascript/ag-ui.md): API reference for the AI Transport codec for AG-UI: agUiAdaptor, agUiDecoder, and the AGUIEvent union of AG-UI events and the run-input a client sends. ## Documentation Index To discover additional Ably documentation: 1. Fetch [llms.txt](https://ably.com/llms.txt) for the canonical list of available pages. 2. Identify relevant URLs from that index. 3. Fetch target pages as needed. Avoid using assumed or outdated documentation paths.