AI Hints
Home›LangChain Tutorial›Serving and the Project Plan
LangChain · Lesson 98 of 120

Streaming over HTTP

Text as it arrives.

⏱ 2 min read▶ Video at 1:51:55🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

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.

Streaming over HTTP
From the video: Streaming over HTTP
  • Long answers take time
  • Spinners feel slow
  • Stream the text

A streaming endpoint

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 FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from langchain.chat_models import init_chat_model

model = 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. |

Streaming in practice

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.

keyvalue
Browserappend each piece
Agentsstream steps too
Standardserver-sent events
Feelsmuch faster

Summary

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.

Key takeaways
  • model.stream
  • StreamingResponse
  • Read piece by piece
Next up: Project: Support Bot Plan — what we'll build