Introduction
Welcome to the final lesson in our foundational module on structured LLM interaction. So far, we have engineered the key components for a coherent dialogue with a large language model. We've constrained its output to JSON, enabled it to call tools, managed conversation history, and, in our last lesson, crafted its "constitution" using system prompts to define its identity and objectives. We have essentially designed the content and rules of the conversation.
This lesson shifts our focus from the what to the how—specifically, how the LLM's response is delivered. We will move beyond the conventional, blocking request-response pattern and learn how to consume and process a streaming LLM response, yielding token-by-token content in real-time. For a user-facing application, this is the difference between a sluggish, delayed answer and the fluid, "live" typing experience of systems like ChatGPT. For an agentic system, it's the key to observing its thought process as it happens. Your background in event-driven architectures will be particularly useful here, as we'll essentially be building a real-time data pipeline from the LLM to the client.
The Problem with Blocking and the Power of Streaming
When you make a standard API call to an LLM, your application sends a request and then blocks, waiting for the entire response to be generated. For a complex query, this can take several seconds, or even longer. From a user's perspective, the application appears frozen and unresponsive.
Streaming solves this by changing the delivery model. Instead of one large payload, the server sends a sequence of small data chunks over a persistent HTTP connection. Each chunk typically contains a single token (or a small group of tokens). The client can process and display each chunk as it arrives, creating a real-time effect.
This flow is visualized below. The process is not one single round-trip, but a series of micro-transmissions for each token generated.

This token-by-token delivery is fundamental not just for UI/UX, but for building observable agents. In future lessons, when we implement patterns like ReAct (Reasoning and Acting), we will stream the agent's internal "thoughts" to provide a real-time trace of its decision-making process.
The Underlying Technology: Server-Sent Events (SSE)
The mechanism that powers this real-time communication for most LLM APIs is Server-Sent Events (SSE). SSE is a web standard that allows a server to push data to a client unidirectionally over a single, long-lived HTTP connection. It's simpler and more lightweight than WebSockets, making it ideal for cases where you only need data flowing from the server to the client.
Given your interest in first-principles understanding, the following video provides an excellent technical deep dive into SSE.
Server-Sent Events Crash Course
This video by Hussein Nasser breaks down Server-Sent Events from the ground up, explaining the protocol, its implementation, and its trade-offs.
Please watch the following segments: What are SSE? This segment explains the core concept of SSE as a unidirectional channel over HTTP/1.1. Implementation: Watch the hands-on coding demo from here. Pay close attention to the server-side headers (Content-Type: text/event-stream) and the specific data format (data: ...\n\n) required. Also, note the client-side use of the EventSource API. Pros and Cons: Finally, review the pros and cons. The discussion on proxying, statefulness, and timeouts is highly relevant from a systems architecture perspective.
The key takeaway is that SSE is not a complex protocol; it's a clever use of standard HTTP features. The server sends a specific header, then keeps an HTTP connection open, writing specially formatted lines of text into the response body.
Implementing the Streaming Pipeline
Now, let's translate this theory into practice. We need to build two components: a backend that requests a stream from the LLM and forwards it in SSE format, and a client that consumes this stream.
The Backend: Proxying the LLM Stream
Our backend service will act as a proxy. It receives a request from our client, forwards it to the LLM provider's API with streaming enabled, and then relays the resulting chunks back to the client using the SSE format.
The article "Language Model Streaming With SSE" provides a clear and minimal implementation using Python and FastAPI.
Language Model Streaming With SSE - Thought Eddies
This article walks through building a simple but complete streaming application with a FastAPI backend and a vanilla JavaScript frontend.
Read through the following sections to understand the server and client implementation: A simple implementation: This shows the initial FastAPI code. Note the use of an async generator function and StreamingResponse. The key is setting stream=True in the OpenAI client call. SSE-compatible changes: This section covers the crucial modifications to make the server SSE-compliant: setting media_type="text/event-stream" and formatting each yielded chunk as data: {content}\n\n. The frontend client: Review the index.html file. The JavaScript code demonstrates how to use the EventSource API to connect to the backend and append incoming data to the UI.
The article also touches on a common issue: the EventSource API automatically reconnects, which might not be the desired behavior. A robust solution, as we'll see, involves the server sending an explicit termination signal.
The Client: Robustly Consuming the Stream
While EventSource is simple, building a production-grade client requires handling a critical detail that will be familiar from your work with distributed systems: buffering.
Network packets can arrive in arbitrary sizes. An SSE message like data: {"content": "Hello"}\n\n might be split across two separate chunks of data received by the client. If you process each chunk independently, you'll get parsing errors. The solution is to buffer incoming data until you have one or more complete lines (ending in a newline character) before attempting to parse them.
The "SSE Pattern" guide from Langwatch provides a fantastic, practical example of how to implement this robustly in Python.
SSE Pattern - Testing Agents with Server-Sent Events – Scenario
This guide demonstrates a production-ready pattern for consuming SSE streams, focusing on the details needed for reliable parsing.
Please review the following: SSE Format: Look at the simple examples under the SSE Format section. Notice the data: [DONE] message—this is the conventional way for a server to signal the end of the stream. Line Buffering: Read the explanation under Line Buffering. This is the core concept for robust client-side processing. Python Implementation: Carefully study the SSEAgentAdapter class in the complete working example. Pay attention to how it uses a buffer variable to accumulate decoded chunks, splits the buffer into lines, and processes only the complete lines while retaining any incomplete line for the next iteration. This pattern is essential for building a reliable client.
This implementation shows how to:
- Read chunks from the HTTP response stream.
- Decode and append them to a buffer.
- Process complete lines from the buffer.
- Check for the
data: [DONE]terminator. - Parse the JSON payload within the
data:prefix. - Extract the actual content from the provider-specific JSON structure (e.g.,
chunk['choices'][0]['delta']['content']for OpenAI).
This approach is far more resilient than naively assuming each received chunk is a complete message.
Finally, to see this all come together in a polished application, the following short video clip demonstrates streaming with the Anthropic API integrated into a Streamlit chat UI.
Claude 3.5 Sonnet API: Integrate The Best LLM into your App (Anthropic Python tutorial)
This video shows the practical application of streaming, from the SDK call to the final UI rendering.
Watch from we'll see how to stream this response to see the basic streaming code in action. Then, jump to the integration from this is the stream LM response, where the streaming logic is placed into a helper function. Finally, see the result in the UI at let's try now the CL 3.5.
Conclusion
In this lesson, we have moved from static, blocking interactions to dynamic, real-time data streams. By leveraging Server-Sent Events, we can build applications that provide a much better user experience and, as we'll soon see, offer a window into the agent's live execution process.
Here are your key takeaways from an engineering standpoint:
- Streaming is for Perceived Performance: Its primary purpose is to reduce perceived latency by displaying results token-by-token as they are generated.
- SSE is the Mechanism: Server-Sent Events is a simple, unidirectional, HTTP-based protocol that is the de-facto standard for LLM streaming.
- The Backend Proxies and Formats: A backend service is responsible for enabling streaming on the LLM API call, wrapping the resulting chunks in the
data: ...\n\nSSE format, and setting thetext/event-streamcontent type. - The Client Buffers and Parses: A robust client must implement line buffering to handle arbitrarily chunked network data, parse the SSE line protocol, and handle the stream termination signal (e.g.,
data: [DONE]).
This lesson concludes our first module. We have built a comprehensive toolkit for structured interaction with an LLM. We can now control its persona, define its tools, manage conversational memory, and stream its responses. We have all the foundational components.
In our next lesson, we will begin Module 2, "Core Engine: The Asynchronous Agent Loop." We will take these components and assemble them into the beating heart of our agent: the observe-think-act loop. This is where we transition from simple instruction-following to true autonomous behavior.