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.
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_modelmodel = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)count = 0for chunk in model.stream("Write three short sentences about rainy days."): print(chunk.text, end="", flush=True) count += 1print(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
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.