Sub topic 1
Why Stream LLM Output, and How HTTP Streaming Works
Prerequisites
Assume you know basic Python async/await, HTTP requests, FastAPI routes, and Pydantic models. An LLM is a language model that generates text from a prompt.
Why Stream LLM Output, and How HTTP Streaming Works
A normal HTTP response waits until the server has the complete answer. LLM generation can take several seconds, so the user sees no progress during that time.
Streaming sends response pieces as soon as they are available. The user sees the first words quickly, which improves perceived latency. The total generation time may stay the same.
The server keeps one HTTP response open and writes several chunks to it:
The Endpoint and Request Model
FastAPI validates incoming data with a Pydantic model. The model below requires a non-empty prompt and limits its size.
Async Generators as the Source of a Stream
An async generator is a function that can pause and yield values over time. Each yield produces one chunk while allowing other asynchronous work to run.
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
async def count():
for i in range(5):
yield f"chunk {i}\n"
await asyncio.sleep(0.5)
@app.post("/chat")
async def chat(body: ChatRequest):
return StreamingResponse(count(), media_type="text/plain")The body parameter is validated before the route runs. In a real endpoint, count() would be replaced by an async generator that receives chunks from an LLM client.
Returning a Generator with StreamingResponse
StreamingResponse accepts an iterable or async iterable and sends each yielded value to the client. The response begins before the generator finishes. Later chapters will add event formatting and LLM client integration.
Exercise
Why does this endpoint need an async generator instead of returning one complete string?
Show answer
The generator produces chunks over time, so StreamingResponse can send each chunk before the full result exists.