A long answer can take several seconds. If the website waits for all of it, the customer stares at a spinner. Streaming sends the text as it's written, so the customer starts reading straight away.
Model stream yields chunks as they're written. A generator pulls out the text of each chunk. Streaming response sends each piece to the client as soon as it's ready. The test client reads the response piece by piece, and we print a bar between pieces. Run it. The text arrives in several pieces, not all at the end.
stream_app.pypython
from fastapi import FastAPIfrom fastapi.responses import StreamingResponsefrom fastapi.testclient import TestClientfrom langchain.chat_models import init_chat_modelmodel = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)app = FastAPI()@app.get("/stream")def stream(q: str): pieces = (chunk.text for chunk in model.stream(q)) return StreamingResponse(pieces, media_type="text/plain")client = TestClient(app)q = "Describe a cosy bookshop in two short sentences."with client.stream("GET", "/stream", params={"q": q}) as r: for piece in r.iter_text(): print(piece, end=" | ")print()
Output
Sunlight | filters through towering oak shelves laden with worn leather classics,
casting a warm, golden | glow over the room. The rich scent of old paper and roasted
hazelnut coffee invites you to curl up in a plush velvet | armchair and stay awhile. |
On the website, JavaScript reads the stream, and adds each piece to the page. For agents, you can stream the steps too, like searching policies, so the customer knows something is happening. Many apps use server sent events, a simple standard for streaming text over HTTP.
A streaming response sends the model's text piece by piece, so customers read while it's written. Next, planning the course project, a full support bot.