Server-Sent Events (Streaming)
Relevant source files
The following files were used as context for generating this wiki page:
Server-Sent Events (SSE) in the Anthropic Go SDK allow developers to receive incremental responses from Claude models. Instead of waiting for a complete message to be generated, the client receives a stream of events representing content deltas, metadata starts, and completion signals. This is critical for building responsive user interfaces and handling long-running model generations or tool executions.
Streaming is supported across various interfaces, including the standard Messages API, Beta Messages API (supporting features like MCP), and specialized Tool Helpers for automated conversation loops. Sources: examples/message-streaming/main.go, tools.md
Architecture and Data Flow
The streaming architecture relies on a persistent HTTP connection where the server pushes a sequence of structured events. The SDK provides a Stream object that abstracts the underlying network handling and provides an iterator-like interface for developers to process events as they arrive.
Event Lifecycle
A typical stream consists of a sequence of events starting with message metadata, followed by content block deltas, and ending with a final message summary.
The diagram above shows the standard progression of events received during a streaming session. Sources: toolrunner/testdata/cassettes/tool_runner_next_streaming.yaml, message_test.go:417-458
State Accumulation
The SDK includes an Accumulate method on message objects. This function takes a raw stream event and updates the internal state of a Message or BetaMessage struct. This allows developers to maintain a single object that represents the fully reconstructed response once the stream finishes.
Sources: message_test.go:538, betamessage_test.go:498, examples/tools-streaming/main.go:68
Implementation Patterns
Basic Message Streaming
To initiate a stream, users call NewStreaming on the client's Messages service. The return value is a stream iterator that provides access to the current event and error state.
stream := client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{...},
Model: anthropic.ModelClaudeSonnet4_5,
})
for stream.Next() {
event := stream.Current()
// Handle event variants
}
Sources: examples/message-streaming/main.go:17-27
Tool Runner Streaming
The BetaToolRunnerStreaming provides a high-level abstraction for streaming conversations that involve tool calls. It handles the complexity of parallel tool execution and automatically re-initiates streams when the model requires multiple turns.
| Method | Description |
|---|---|
NewToolRunnerStreaming | Initializes a runner capable of streaming both text and tool use blocks. |
AllStreaming(ctx) | Returns an iterator that yields eventsIterator for each turn in the conversation. |
NextStreaming(ctx) | Advances the conversation by a single turn, yielding events for that specific turn. |
Sources: tools.md:124-152
Event Types and Structures
The SDK categorizes events into several types, handled via type switches on the AsAny() representation of an event.
Key Event Categories
| Event Type | Purpose | Key Fields |
|---|---|---|
message_start | Indicates the beginning of a message response. | Message (metadata) |
content_block_start | Signals a new block of content (text or tool use). | Index, ContentBlock |
content_block_delta | Provides partial updates to the current block. | Index, Delta (text, json, or citations) |
message_delta | Updates message-level metadata like stop reason. | Delta (stop_reason, stop_sequence) |
ping | Keep-alive signal from the server. | N/A |
Sources: message_test.go:417-458, betamessage_test.go:377-418
Content Deltas
Deltas are the most frequent events in a stream. Depending on the content type, they contain different data:
- TextDelta: Contains the
Textstring segment. - InputJSONDelta: Contains
PartialJSONfor tool arguments. - CitationsDelta: Contains citation metadata for grounded responses.
- ThinkingDelta: Contains Claude's internal reasoning process (Beta).
Sources: examples/message-streaming/main.go:32-38, betamessage_test.go:454-469
Sequence of a Tool-Augmented Stream
When tools are involved, the stream sequence includes JSON deltas that must be accumulated and parsed.
Beta and Specialized Features
Streaming is also used for advanced features including:
- Model Context Protocol (MCP): Streams messages that can interact with external MCP servers for tool definitions. Sources: examples/message-mcp-streaming/main.go:33
- Extended Thinking: Streams
thinkingblocks, allowing users to see the model's reasoning process before the final output. Sources: betamessage_test.go:454-469 - Citations: Incremental delivery of source citations associated with text deltas. Sources: betamessage_test.go:401-412
Summary
Streaming via Server-Sent Events is a core component of the Anthropic Go SDK, integrated deeply into both standard and beta messaging services. By utilizing the event-based iterator and the state accumulation logic, developers can create interactive applications that provide immediate feedback while maintaining robust state management for complex, multi-turn tool-use conversations.