AI Hints
Home›LangChain Tutorial›Settings, Streaming, Batches
LangChain · Lesson 8 of 120

Streaming

Word by word.

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

A long answer can take several seconds. Instead of staring at a blank screen, users like to see the answer appear piece by piece, the way chat apps do. That's streaming.

Streaming
From the video: Streaming
  • Long answers take time
  • Show pieces as they arrive
  • Streaming

Streaming chunks

Instead of invoke, we call stream. It returns the answer in small chunks, as soon as the model writes them. We print each chunk straight away, and also count them. Run it. The answer arrives in several chunks, instead of all at once at the end.

stream.pypython
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

count = 0
for chunk in model.stream("Write three short sentences about rainy days."):
    print(chunk.text, end="", flush=True)
    count += 1
print(f"\n\n{count} chunks")
Output
Raindrops tap softly against the windowpane.
Puddles form quickly on the quiet streets.
A warm blanket makes the chilly day cozy.

5 chunks

When to stream

Stream whenever a person is waiting for a long answer, in a chat window, for example. The total time is the same, but it feels much faster, because the first words appear in a fraction of a second. For background jobs, nobody is watching, so plain invoke is simpler.

keyvalue
Chat UIsstream
First wordsappear quickly
Total timethe same
Background jobsjust invoke

Summary

Stream returns the answer in chunks as it's written, so users see progress straight away. Next, sending many requests at once.

Key takeaways
  • model.stream(...)
  • Print each chunk
  • Feels faster
Next up: Batch Calls — many at once