Skip to content

latent.wire.core.sse

SSE (Server-Sent Events) encoding for AI SDK UI data stream protocol.

This module provides functions to encode normalized events and AI SDK parts into SSE format for streaming to clients. The format follows the AI SDK UI protocol specification.

SSE Format: - Event: data: {JSON}

  • Termination: data: [DONE]

  • Ping: : ping

Functions

aiter_sse_blocks

aiter_sse_blocks(sse: AsyncIterator[bytes]) -> AsyncIterator[str]

Yield raw \n\n-delimited SSE records from a byte stream.

Tolerates records split across chunks (a record is held back until its terminating blank line arrives), including a multi-byte UTF-8 character split across the chunk boundary — the incremental decoder carries the partial bytes forward rather than raising. The buffer is capped so an unterminated record cannot grow without bound. Flushes a trailing record that arrives without a terminator. The per-record interpretation is the caller's (each wire codec parses its own event shape) — this only handles framing.

encode_done

encode_done() -> bytes

Encode the [DONE] termination marker.

This marker signals the end of the stream to the client. It MUST be emitted as the final event in every stream, regardless of success or failure. This ensures clients know the stream has completed and won't wait indefinitely for more events.

Returns: Bytes in SSE format for the [DONE] marker

Example: >>> done = encode_done() >>> assert done == b'data: [DONE]\n\n'

Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol

encode_ping

encode_ping() -> bytes

Encode a ping comment to keep the connection alive.

Ping events are SSE comments (lines starting with ":") that prevent timeouts on long-running streams with infrequent updates. They don't produce data on the client side, just keep the connection open.

Returns: Bytes in SSE format for a ping comment

Example: >>> ping = encode_ping() >>> assert ping == b': ping\n\n'

Comments (lines starting with ":") are ignored by EventSource clients but keep intermediaries from timing out an idle connection.

encode_sse

encode_sse(part: dict) -> bytes

Encode a single AI SDK part as SSE data event.

This function converts a dictionary representing an AI SDK part into SSE format. The output follows the format: data: {JSON}

Args: part: Dictionary representing an AI SDK part (e.g., text-delta, tool-input-start)

Returns: Bytes in SSE format ready to send over the wire

Example: >>> part = {"type": "text-delta", "textId": "txt_123", "delta": "Hello"} >>> encoded = encode_sse(part) >>> assert encoded == b'data: {"type":"text-delta","textId":"txt_123","delta":"Hello"}\n\n'