Stream and AsyncStream are generic iterators over SSE (Server-Sent Event) responses that handle ping/error events, type-field injection, response cleanup, and backward-compatible isinstance checks via metaclasses. Stream.stream() silently skips pings, raises errors with parsed JSON or fallback text, injects missing type fields into events, and always closes the HTTP connection—either at iteration end or via context manager exit. SSE (Server-Sent Event) is a protocol in which a server pushes newline-delimited text events to the client over a single persistent HTTP connection; each event carries an event name, a data payload, and an optional id.
Stream in src/anthropic/_streaming.py provides the core interface to iterate over a synchronous SSE stream response and is generic over the yielded item type _T.[1] AsyncStream in the same file provides the core interface to iterate over an asynchronous SSE stream response and is likewise generic over _T.[1]
Stream.__stream__() silently skips SSE ping events and raises an API status error on error events — attempting to parse the error body as JSON first, falling back to the raw data string or a "Error code: {status_code}" message.[1] When a structured SSE event's JSON payload lacks a "type" key, Stream.__stream__() injects data["type"] = sse.event before forwarding the data to process_data.[1] Stream.__stream__() also yields completion events (the legacy text-completions API event type) alongside current Messages API events.[1]
Stream.__stream__() always closes the HTTP response in a finally block, releasing the connection even if the consumer exits the iterator early.[1] Stream also supports use as a context manager: __enter__ returns self and __exit__ calls self.close() to release the connection.[1]
Stream.raw_events() and AsyncStream.raw_events() are static methods that iterate raw ServerSentEvent objects directly from an httpx.Response, before any JSON parsing or event-name filtering, consuming the response body in the process.[1]
_SyncStreamMeta and _AsyncStreamMeta are metaclasses that preserve backward-compatible isinstance checks after MessageStream and AsyncMessageStream stopped inheriting from Stream and AsyncStream respectively.[1] Using isinstance(obj, Stream) to test whether a MessageStream is a Stream is deprecated and will be removed in the next major version; a DeprecationWarning is issued at check time.[1] Likewise, using isinstance(obj, AsyncStream) to test whether an AsyncMessageStream is an AsyncStream is deprecated and will be removed in the next major version, also raising a DeprecationWarning at check time.[1]
Sources