Streaming, Callbacks and Async
Streaming cuts time to first token, not total latency, and a chain streams end to end only if every step after the model can transform a stream. Know the three ways to watch a run (stream/astream output chunks, astream_events for every component, agent stream modes), how callback handlers hook into it, and how the async methods behave when a component has no native async code.
Key points
- 1
Every Runnable has
invoke,batch,streamand async twinsainvoke,abatch,astream, plusbatch_as_completed/abatch_as_completedandastream_events.astreamis an async generator: iterate it withasync for, neverawaitit. - 2
streamyields the last step's output chunk by chunk: a chat model yieldsAIMessageChunks, andStrOutputParserturns each into a string. A plain function (RunnableLambda) needs its whole input, so placed after the model it holds back the output until the end; placed before the model it costs nothing. - 3
To keep streaming through custom code, pipe a generator function that takes an iterator of chunks; it is coerced to a
RunnableGenerator. Wrapping the same generator inRunnableLambdafirst collects the whole input, then calls it. - 4
astream_eventsdefaults toversion="v2"in langchain-core 1.x. Events are namedon_<type>_<start|stream|end>:on_chat_model_streamcarriesdata["chunk"], parsers emiton_parser_*, tools and retrievers emit only start and end. Inner model tokens appear even when a later step blocks the final output. - 5
Filter events with
include_names,include_types(chat_model,llm,parser,prompt,retriever,tool,chain) andinclude_tags; include filters combine with OR, andexclude_*filters remove matches. Tags are inherited by child runs. - 6
Chat models auto-stream: when a streaming-aware handler is attached (
astream_events, LangGraphmessagesmode),invokeuses the streaming API internally and still returns oneAIMessage.disable_streaming=Truemakesstreamreturn a single chunk;"tool_calling"disables it only when tools are bound. - 7
create_agentagents stream withstream_mode:updatesgives per-step dicts keyed by node (model,tools),messagesgives(token, metadata)tuples withmetadata["langgraph_node"],customgives whatever tools send throughget_stream_writer(),valuesgives full state. A list of modes yields(mode, chunk)tuples;version="v2"yieldsStreamPartdicts. The docs recommendstream_events(version="v3")for new apps. - 8
Callback handlers subclass
BaseCallbackHandler(orAsyncCallbackHandler) and override hooks such ason_chat_model_start,on_llm_new_token(token, **kwargs),on_llm_end,on_chain_*,on_tool_*,on_retriever_*andon_custom_event. Ifon_chat_model_startis not implemented, chat models fall back toon_llm_startwith stringified messages. - 9
Handler errors are logged and swallowed unless the handler sets
raise_error = True. In async runs, sync handlers run in a thread executor (unlessrun_inline = True) and async handlers are awaited on the loop. One handler instance serves concurrent runs, so key per-call state byrun_id. - 10
dispatch_custom_event(name, data)(oradispatch_custom_event) inside a Runnable or tool surfaces ason_custom_eventinastream_eventsv2 and in handlers'on_custom_event; outside a run it raisesRuntimeError. - 11
Default async methods run the sync code in asyncio's thread pool, so a sync-only component still works under
awaitwithout blocking the loop.max_concurrencyin the config caps parallel calls forbatch/abatch;return_exceptions=Truereturns failures in place;abatch_as_completedyields(index, result)out of order. - 12
LangChain passes config through context variables. Before Python 3.11, asyncio tasks cannot carry a context, so in async code pass
configexplicitly toainvoke/astream/adispatch_custom_event, and take awriterparameter instead of callingget_stream_writer(). In Jupyter use top-levelawait, notasyncio.run.
Common traps
Streaming does not reduce total generation time or token cost; it only shows the first tokens sooner.
A post-processing
RunnableLambdaat the end of a chain silently turns a token stream into one chunk at the end.Calling sync
chain.invokeor iteratingchain.streaminside anasync defFastAPI endpoint blocks the event loop and prevents cancellation on disconnect; useainvoke/astream.SSE frames end at a blank line, so a raw newline in a token breaks the frame; JSON-encode payloads. Clients must buffer across network chunks, because one chunk can hold part of a frame.
A tool that calls
get_stream_writer()fails when invoked directly outside a LangGraph run, which breaks naive unit tests.Naming the token parameter anything other than
tokenin a syncon_llm_new_tokenmakes every call fail, and the error is only logged.Storing per-call state such as a start time on
selfin a handler gives wrong numbers underabatchor concurrent requests.
Read the source
Further reading
Suggest a resourceNo extra reading for Streaming, Callbacks and Async yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Streaming, Callbacks and Async
Ten questions, with the answer and explanation after each one.