Event Streams for API Clients

Event Streams for API Clients

How server-sent event streams are framed, how to parse them from a raw HTTP body without losing text, and how the major model APIs lay out their streamed responses.

SectionCovers
The event stream formatServer-sent events are specified in the HTML Living Standard, maintained by WHATWG. The format is deliberately small: a UTF-8 text body, served as text/event-stream, made of lines. Knowing the exact rules matters,…
A parser that survives real networksAn HTTP library hands a streamed body over in reads of whatever size the network produced. A read can end in the middle of a line, in the middle of a multi-byte character, or between the carriage return and the line…
Decoding text that arrives in piecesUTF-8 spends one byte on ASCII characters and two to four bytes on everything else. The network does not know where one character ends and the next begins, so a read can stop after the first byte of a two-byte "é", or…
Streams that end earlyA streamed response can stop at any point: the client's own read timeout fires, the network drops, the server restarts, or the service reports an error after it had already started answering. The client has to tell a…
Three vendor stream formatsAll three formats below are carried over the same server-sent events framing, so one parser serves them all. What differs is the content of each event: where the text is, how tool calls are split, where usage numbers…