Study FAQ
How do I assemble a Claude Messages SSE stream into a complete response?
Also asked as 2
- Which Claude SSE events should I process to know that a streaming message is complete?
- How do I assemble Claude text and tool JSON deltas without corrupting content blocks?
Answer
Parse each Server-Sent Events (SSE) envelope and its JSON data, then advance message and block state in wire order. Consider the stream complete after a valid message_stop with the required blocks closed and no stream failure. The completed Message still needs stop-reason handling and application validation.
message_startinitializes the Message and its metadata. The content is empty and the stop reason can be null at this point.content_block_startopens a block at an index. Apply compatiblecontent_block_deltaevents only to that open block. Some blocks arrive whole. Close each one oncontent_block_stop.- Apply
message_deltato top-level fields such as stop metadata. Usage values there are cumulative, so update the corresponding counters instead of adding them across events. - On
message_stop, return the ordered assembled result. If the connection ends first or an error arrives, mark the attempt incomplete.
Text deltas append text within one block. A tool block's input_json_delta contains a JSON fragment. If fragments arrive, join and parse them when the block closes, or use the SDK accumulator. For a block that arrives complete, use its supplied typed data. Keep any tool action behind the application validation and authorization boundary. Handle pings and new ignorable event types without changing assembly state. Surface invalid transitions, unsupported required block data, and SSE errors explicitly. An error can arrive after HTTP 200, and a supported SDK can surface that error through the stream reader.
Official references
Full explanation
Reliable Claude API Streaming, Asynchronous Work, and Error Handling
Study guide · CCDV-F
Read the full explanation