08F.7 Runnables and LCEL

Agents & multimodalLesson 7 of 1722,338 wordsReference11 parts
Module 08F · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17

If you have read any LangChain code, you have seen the pipe: prompt | model | parser. That one line is the most recognizable idiom of the library, and behind it sits a single, small, well-designed interface called the Runnable. Every prompt template, chat model, output parser, retriever and tool in LangChain is a Runnable, and so is every compiled LangGraph graph and every agent that create_agent returns. A Runnable can be called, batched, streamed, run asynchronously, retried, given a fallback, traced and composed with other Runnables, and it does all of that with the same handful of methods. The composition syntax is called LCEL, the LangChain Expression Language. This lesson teaches the interface and the syntax properly: how | really works, what the building blocks are (RunnableLambda, RunnableParallel, RunnablePassthrough, RunnableBranch), how configuration and callbacks flow through a chain, how streaming and astream_events work and what silently breaks them, how retries and fallbacks behave, how to test a chain with no API key, and, most importantly, when a chain is the right tool and when you should reach for create_agent or LangGraph instead.

In 2026 this is also a lesson about a quiet change of status. LCEL used to be the centre of LangChain. Since LangGraph became the recommended foundation (October 2024) and LangChain 1.0 replaced every chain and agent class with one agent abstraction (October 2025), LCEL is a small, stable, useful layer in langchain-core rather than the thing you build applications out of. The official documentation site no longer has a concept page for it. That makes a careful, source-verified lesson more important, not less: old tutorials are full of LCEL, and you will meet it in every LangChain codebase.

What you'll learn

  • What a Runnable is, the families of methods it exposes (invoke, batch, stream, events, transform), and what you get for free when your code is one (sync, async, batch, streaming, tracing, schemas)
  • How the pipe operator works: RunnableSequence, the coercion rules (dict to RunnableParallel, callable to RunnableLambda, generator to RunnableGenerator) and the traps in them
  • The building blocks: RunnableLambda, @chain, RunnableGenerator, RunnableParallel, RunnablePassthrough (with assign and pick), .map(), RunnableBranch, RouterRunnable and routing with a function
  • RunnableConfig: tags, metadata, run_name, callbacks, max_concurrency, recursion_limit, configurable, and how config is inherited by every step
  • Binding and configuration: bind, with_config, with_types, configurable_fields, configurable_alternatives, with_listeners, as_tool
  • Reliability: with_retry and with_fallbacks, their defaults, how they compose, why you retry the smallest unit, and the streaming trap (with_retry does not run under stream)
  • Streaming: why a chain streams, what blocks a stream (and what does not: routers, branches and assign), the astream_events v2 event schema, custom events, and the state of v1 (deprecated) and v3 (beta)
  • Callbacks, collect_runs and tracing
  • The legacy memory wrapper RunnableWithMessageHistory (deprecated) and how to read old LCEL tutorials (including itemgetter, RunnableMap and the old imports)
  • Testing chains with fake models and no key, including a pytest file that was run
  • When LCEL is right, when create_agent is right, when LangGraph is right, and how the three nest

What you don't need

  • An API key. Every sample in Parts 1 to 9 and 11 runs without a provider: the chains use fake chat models and plain-Python steps, and the outputs shown were produced by actually running them. The few samples that call a real provider are labelled illustrative.
  • Prompt templates and output parsers in depth. 08F.6 owns them; this lesson uses ChatPromptTemplate and StrOutputParser only as ordinary Runnables.
  • Chat models in depth. 08F.5 owns them (including max_retries, rate limiters and init_chat_model).
  • LangGraph. 08F.10 teaches it; Part 10 only shows how it relates to LCEL.

Setup

You need Python 3.11 or newer and uv; see 08F.4, Part 5 for the full project setup. Everything in this lesson needs only langchain-core (which langchain installs anyway), except the create_agent samples in 8.1 and 9.1 (they need langchain and langgraph) and Part 10 (it needs langgraph):

bash
uv init lcel-lab --bare --python 3.13 && cd lcel-lab   # first time only
uv add langchain-core
uv add --dev pytest                                     # for Part 9
uv add grandalf                                         # optional: ASCII drawings of chains (2.6)
uv add langchain                                        # for the create_agent samples in 8.1 and 9.1
uv add langgraph                                        # for those samples and Part 10
# or: pip install langchain-core pytest grandalf langchain langgraph

If you already have the project from 08F.4, you have all of this except grandalf and pytest (and any package you left out there). No .env file is needed. The few illustrative provider samples use the same keys as the earlier lessons; none of them is required to follow the lesson.

Versions (current at time of writing, read from PyPI on 14 November 2026; treat them as a snapshot): langchain-core 1.8.0, langchain 1.5.0, langgraph 1.2.22, langsmith 0.14.17, grandalf 0.8 and pydantic 2.14.3. Every sample marked "run" in this lesson was executed on 14 November 2026 (a few samples were added later and run on 15 and 17 November 2026, on the same versions; the one sample that uses a provider class, in 6.2, also used langchain-openai 1.8.0 and contacted only a server on 127.0.0.1) with Python 3.13.14 and exactly these versions, using uv run --no-project --with langchain-core python -I sample.py (plus --with langgraph and --with grandalf where needed). The output blocks are the real output of those runs.


What you must be able to do after this lesson#

  • Explain what a Runnable is and what you get for free
  • Compose steps with the pipe operator and RunnableParallel
  • Add retries and fallbacks to the smallest failing step
  • Decide when LCEL is the right tool and when it is not

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"What is a Runnable?" Part 1 and Part 2
"What does prompt | model | parser actually build?" 3.1 and 3.2
"Why does my chain give me a dict with the wrong keys?" 3.5
"How do I run two things at once in a chain?" 3.4
"How do I route to different chains?" 3.7
"Why are there no tokens streaming from my chain?" 7.2
"What is astream_events and which version do I use?" 7.3 and 7.5
"Where do I put tags and metadata so they show up in LangSmith?" 4.1
"Retry versus fallback versus the SDK's own retries?" Part 6
"My retry charged the customer's card three times." 6.3
"This tutorial uses ConversationChain or RunnableWithMessageHistory." Part 8
"How do I test a chain without calling the API?" Part 9
"Should this be a chain, an agent or a graph?" Part 10

Part 1: What a Runnable is, and what LCEL is#

1.1 One interface for every unit of work#

The Runnable base class in langchain-core describes itself in one line: "A unit of work that can be invoked, batched, streamed, transformed and composed." It is generic over its input and output types (Runnable[Input, Output]), and the whole idea is that very different things share one shape:

  • a prompt template is a Runnable from a dict of variables to a prompt value;
  • a chat model is a Runnable from messages (or a string, or a prompt value) to an AIMessage;
  • an output parser is a Runnable from a model output to a string, a dict or an object;
  • a retriever is a Runnable from a query string to a list of documents;
  • your own Python function becomes a Runnable by wrapping it in RunnableLambda;
  • and a chain of Runnables is itself a Runnable, so chains nest inside chains.

Because the shape is uniform, the library can write the hard parts once, in the base class, instead of once per component. The class docstring says so directly: "Any chain constructed this way will automatically have sync, async, batch, and streaming support." You write a function that handles one input; the interface gives you invoke for one, batch for many, ainvoke for async and stream for incremental output.

1.2 What is, and is not, a Runnable#

I checked each of these on langchain-core 1.8.0 by testing issubclass(..., Runnable):

Thing Runnable? Input to invoke Output
ChatPromptTemplate (and every prompt template) Yes a dict of variables (a bare value is accepted when there is exactly one variable) a prompt value
A chat model (BaseChatModel) or text model (BaseLLM) Yes a string, a list of messages or a prompt value an AIMessage (or a string for a text model)
An output parser (BaseOutputParser) Yes a model output a string, dict or object
A retriever (BaseRetriever, including the one from vectorstore.as_retriever()) Yes a query string list[Document]
A tool (BaseTool, including @tool functions) Yes a dict of arguments whatever the tool returns
A compiled LangGraph graph (CompiledStateGraph) Yes (checked in 10.4) the graph's state input the final state
An agent from create_agent Yes (it is a CompiledStateGraph, see 08F.4, 5.5) {"messages": [...]} the final state
Embeddings No (use embed_query and embed_documents; 08F.9)
A vector store (VectorStore) No (call as_retriever() to get a Runnable)
A Document or a message (HumanMessage) No (these are data, not units of work)

The last three rows catch people out. embeddings | something is a TypeError; you wrap the call in a RunnableLambda or get a retriever from the store first.

1.3 What "LCEL" means, and what it no longer means#

LCEL stands for the LangChain Expression Language. In the 0.1 to 0.3 era (before the 1.0 release of October 2025; see the timeline in 08F.4, 2.1) it was presented as the way to build everything: chains, retrieval pipelines and, with AgentExecutor, agents. The term has two meanings that are worth separating:

  1. The syntax. Composing Runnables with | (and, implicitly, dict literals and plain functions). This is alive and unchanged, and it is the subject of Part 3.
  2. The ecosystem pitch. "Build your whole application as one LCEL chain." This is the part that faded. The official history page records that in October 2024 LangGraph became the recommended way to build anything more than a single LLM call, with most chains and agents deprecated and migration guides written, and that LangChain 1.0 (October 2025) replaced all chains and agents with one abstraction, create_agent, built on LangGraph. The old chain classes live on in langchain-classic only as a migration bridge (08F.4, 3.8).

So the accurate 2026 statement is this: the Runnable protocol and the pipe syntax are the foundation of langchain-core, and LCEL is the right tool for short, stateless, fixed pipelines. What it is no longer is the main way to build agents or long-running workflows. Part 10 turns that into a decision procedure.

1.4 What you get for free#

Write a chain once and each of these works without extra code:

You get How it shows up
Sync, async, batch and streaming entry points invoke, ainvoke, batch, abatch, stream, astream (Part 2)
One tracing tree Every step is a run with inputs, outputs, timing and errors; LangSmith, collect_runs and your own callbacks see it (Part 4)
Uniform configuration Tags, metadata, a run name, callbacks and concurrency limits passed once at the call and inherited by every step
Reliability wrappers with_retry and with_fallbacks work on any step for invoke and batch; what they do when you stream is different (6.2, 6.4)
Streaming of partial results Works through any number of steps if they all cooperate (Part 7)
Introspection Input and output schemas, a drawable graph of the steps (2.6)
Composability A chain, a model, a tool, a compiled graph and an agent are interchangeable as steps

The price is a small amount of indirection: errors surface from inside langchain_core frames, and a type mismatch between two steps appears at run time, not at definition time. Part 11 collects the failures you will actually see.

1.5 Where the documentation is#

1.6 Import map#

Everything in this lesson comes from langchain_core. The verified public names of langchain_core.runnables (its __all__ on 1.8.0) include Runnable, RunnableSerializable, RunnableLambda, RunnableGenerator, RunnableParallel (alias RunnableMap), RunnablePassthrough, RunnableAssign, RunnablePick, RunnableBranch, RouterRunnable, RunnableSequence, RunnableBinding, RunnableWithFallbacks, RunnableWithMessageHistory, RunnableConfig, ConfigurableField (and the single and multi option variants), chain, ensure_config, patch_config, get_config_list and run_in_executor.

You need Import
The building blocks from langchain_core.runnables import RunnableLambda, RunnableParallel, RunnablePassthrough, RunnableBranch, chain
Config type from langchain_core.runnables import RunnableConfig
Prompts and parsers from langchain_core.prompts import ChatPromptTemplate and from langchain_core.output_parsers import StrOutputParser (08F.6)
Callbacks from langchain_core.callbacks import BaseCallbackHandler, dispatch_custom_event, adispatch_custom_event
Capture runs in-process from langchain_core.tracers.context import collect_runs
Fake models for tests from langchain_core.language_models import FakeListChatModel, GenericFakeChatModel

Old paths such as langchain.schema.runnable, langchain.prompts and langchain.schema.output_parser are gone from langchain 1.x (08F.4, 4.2); use langchain_core.*.


Part 2: The Runnable interface#

2.1 The Runnable interface: seven families of methods#

Every Runnable has the same core methods, in seven families (the table rows). Most sync methods come with an a-prefixed async twin (ainvoke, abatch, abatch_as_completed, astream, atransform); astream_events and astream_log exist only in async form.

Method Does Returns
invoke(input, config=None) / ainvoke One input in, one output out Output
batch(inputs, config=None, *, return_exceptions=False) / abatch Many inputs, run concurrently; results come back in input order list[Output]
batch_as_completed(...) / abatch_as_completed Many inputs; yields (index, output) as each finishes an iterator of tuples
stream(input, config=None) / astream One input; yields output chunks as they are produced an iterator of chunks
astream_events(input, config=None, *, version="v2", include_*=..., exclude_*=...) One input; yields an event for every start, chunk and end of every step (7.3) an async iterator of event dicts
astream_log(...) The older JSON-patch run log; astream_events replaced it (7.5) an async iterator of patches
transform(chunks) / atransform Chunks in, chunks out; how a sequence streams (7.1) an iterator of chunks

Around those sit the helpers, each of which returns a new Runnable wrapping the old one: pipe and | (Part 3), map, pick and assign (3.5 and 3.6), bind, with_config, with_types, configurable_fields, configurable_alternatives and with_listeners (Part 5), with_retry and with_fallbacks (Part 6), and as_tool, get_graph, get_prompts and the schema properties (2.6, 5.5).

Here is the first tour. It uses only langchain-core, no model and no key, and it was run on 14 November 2026. Read it once now; Parts 3 and 5 explain each construct in turn.

python
# tour.py: the Runnable interface and composition, no model and no key
from langchain_core.runnables import (
    Runnable, RunnableLambda, RunnableParallel, RunnablePassthrough, RunnableSequence,
)

add_then_double = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)
print(type(add_then_double).__name__)
print("invoke:", add_then_double.invoke(1))
print("batch :", add_then_double.batch([1, 2, 3]))
print("stream:", list(add_then_double.stream(1)))

# a dict literal on the right of | becomes a RunnableParallel
fan_out = RunnableLambda(lambda x: x + 1) | {
    "mul_2": RunnableLambda(lambda x: x * 2),
    "mul_5": RunnableLambda(lambda x: x * 5),
}
print(type(fan_out.last).__name__, fan_out.invoke(1))

# a plain callable on the right of | becomes a RunnableLambda
shout = RunnableLambda(lambda s: s.strip()) | str.upper
print(type(shout.last).__name__, shout.invoke("  hello "))

# RunnableParallel keeps the original input next to the computed value
both = RunnableParallel(origin=RunnablePassthrough(), modified=lambda x: x + 1)
print(both.invoke(1))

# assign adds keys to a dict input; pick selects keys
enrich = RunnablePassthrough.assign(total=lambda d: d["price"] * d["qty"])
print(enrich.invoke({"price": 4, "qty": 3}))
print((enrich | RunnablePassthrough().pick("total")).invoke({"price": 4, "qty": 3}))
print((enrich).pick(["price", "total"]).invoke({"price": 4, "qty": 3}))

# map applies the runnable to each element of a list
print(RunnableLambda(lambda x: x + 1).map().invoke([1, 2, 3]))

# pipe() with several steps, and naming
seq = RunnableLambda(lambda x: x + 1).pipe(lambda x: x * 2, lambda x: x - 3, name="my_seq")
print(seq.name, [s for s in seq.steps], seq.invoke(5))
print(isinstance(seq, Runnable), isinstance(seq, RunnableSequence))

# RunnableLambda that also takes config
def with_config_arg(x, config):
    return f"{x} tags={config.get('tags')}"
print(RunnableLambda(with_config_arg).invoke("hi", config={"tags": ["demo"]}))
Output14 lines
RunnableSequence
invoke: 4
batch : [4, 6, 8]
stream: [4]
RunnableParallel {'mul_2': 4, 'mul_5': 10}
RunnableLambda HELLO
{'origin': 1, 'modified': 2}
{'price': 4, 'qty': 3, 'total': 12}
12
{'price': 4, 'total': 12}
[2, 3, 4]
my_seq [RunnableLambda(...), RunnableLambda(...), RunnableLambda(...)] 9
True True
hi tags=['demo']

Walk through the output:

  • RunnableSequence: RunnableLambda(...) | RunnableLambda(...) built a RunnableSequence. invoke(1) ran (1 + 1) * 2 = 4.
  • batch([1, 2, 3]) returned [4, 6, 8]: one result per input, in input order.
  • stream(1) returned [4]: a single chunk. A RunnableLambda produces its whole output at once, so there is nothing to stream in pieces. That sounds like a detail and is in fact the most common reason a chain "does not stream" (7.2).
  • The dict literal on the right of | became a RunnableParallel (the printed type name), and both entries received the same input, 2.
  • The bare str.upper on the right of | became a RunnableLambda.
  • RunnableParallel(origin=RunnablePassthrough(), modified=...) kept the original input next to a computed value. assign added a total key to a dict and kept the others; pick selected keys.
  • .map() turned "one number to one number" into "list of numbers to list of numbers".
  • A RunnableLambda whose function takes a second parameter named config receives the run's RunnableConfig (here we passed tags=["demo"] and read it back).

2.2 invoke: one call, no memory#

invoke is a function call. A Runnable keeps no conversation state between calls: calling a chain twice with the same input runs it twice, and a chain that includes a chat model sends exactly the messages you built from that input, no more. If you want memory you must supply the history as part of the input or use a checkpointer (08F.11); the one Runnable-level exception, RunnableWithMessageHistory, is deprecated (Part 8). This is the same statelessness that 02.7 described for the model itself, now at the framework level.

The config argument is the second parameter of every method. It carries tags, metadata, callbacks, limits and run names, and it flows to every step; Part 4 covers it in full. Extra keyword arguments are forwarded to the implementation, which is how model.invoke(messages, stop=["###"]) works.

2.3 batch and batch_as_completed#

batch runs invoke once per input, concurrently. The official wording: by default batch "runs invoke() in parallel with a thread pool executor". Three things to know:

  1. Order is preserved: result[i] belongs to inputs[i], even though the calls finish in any order. (batch_as_completed is the variant that yields (index, output) in completion order, so you can start using early results.)
  2. Concurrency is the pool's default unless you limit it. For an LLM call, a pool-sized burst can trip the provider's rate limit. Pass config={"max_concurrency": 3} to cap it. The async twin abatch uses the same config key and starts all items at once otherwise (verified in 2.4).
  3. One failure fails the whole batch unless you pass return_exceptions=True, in which case each failed slot holds the exception object and the rest hold results.
python
# batch_demo.py: batch order, max_concurrency, return_exceptions, batch_as_completed
import threading
import time
from langchain_core.runnables import RunnableLambda

seen_threads = set()
def slow(x):
    seen_threads.add(threading.current_thread().name)
    time.sleep(0.05)
    return x

RunnableLambda(slow).batch(list(range(8)), config={"max_concurrency": 2})
print("worker threads used <= 2:", len(seen_threads) <= 2)

def boom(x):
    if x == 2:
        raise ValueError("bad 2")
    return x

print(RunnableLambda(boom).batch([1, 2, 3], return_exceptions=True))
print(list(RunnableLambda(boom).batch_as_completed([1, 2, 3], return_exceptions=True)))
try:
    RunnableLambda(boom).batch([1, 2, 3])
except ValueError as e:
    print("without return_exceptions the batch raises:", e)
Output4 lines
worker threads used <= 2: True
[1, ValueError('bad 2'), 3]
[(1, ValueError('bad 2')), (0, 1), (2, 3)]
without return_exceptions the batch raises: bad 2

The batch of [1, 2, 3] with return_exceptions=True returned [1, ValueError('bad 2'), 3]: the failure sits in its own slot. batch_as_completed returned (index, result) pairs in the order they finished, which is why the pairs are not in input order. Without return_exceptions the first failure is raised to the caller. The first line checks that max_concurrency=2 really limited a batch of eight items to two worker threads.

2.4 Async: ainvoke, abatch and astream#

Every async method has a default implementation that calls the sync method in asyncio's thread pool, so a chain made only of sync code still works with await. Components that do real async I/O (the provider chat models do) override the async methods natively. If you write your own step, give a RunnableLambda an afunc to provide a true coroutine implementation. This sample checks all of that:

python
import asyncio
from langchain_core.runnables import RunnableLambda
active = 0; peak = 0
async def work(x):
    global active, peak
    active += 1; peak = max(peak, active)
    await asyncio.sleep(0.05)
    active -= 1
    return x * 2
r = RunnableLambda(work)
async def main():
    global peak
    print(await r.abatch(list(range(10))), "peak concurrent:", peak)
    peak = 0
    print(await r.abatch(list(range(10)), config={"max_concurrency": 3}), "peak concurrent:", peak)
    print(await r.ainvoke(5))
    async for c in r.astream(5): print("astream:", c)
    # sync function inside ainvoke: runs in a thread pool executor
    import threading
    def sync_work(x): return threading.current_thread() is threading.main_thread()
    print("sync func on main thread during ainvoke:", await RunnableLambda(sync_work).ainvoke(1))
    print("same func under invoke:", RunnableLambda(sync_work).invoke(1))
    # separate afunc
    both = RunnableLambda(lambda x: f"sync {x}", afunc=lambda x: asyncio.sleep(0, f"async {x}"))
    print(both.invoke(1), await both.ainvoke(1))
asyncio.run(main())
Output7 lines
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] peak concurrent: 10
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] peak concurrent: 3
10
astream: 10
sync func on main thread during ainvoke: False
same func under invoke: True
sync 1 async 1
  • abatch over ten items had a peak of 10 concurrent coroutines; with max_concurrency=3 the peak was 3. The cap works the same way as in the sync batch.
  • A plain synchronous function inside ainvoke ran off the main thread (False), so it did not block the event loop, whereas under invoke it ran on the main thread (True).
  • When both func and afunc are given, invoke runs func and ainvoke runs afunc.

2.5 stream and friends, briefly#

stream yields the output in chunks as the last step produces them, and a chain can stream through many steps if each one can pass chunks along. Streaming gets its own part (Part 7) because it is the place where "works on the first try" most often fails to be true.

2.6 Schemas and drawing a chain#

Every Runnable describes its input and output. They are inferred: the input type is what the first step accepts, the output type is what the last step produces. For a prompt-first chain the input is a dict whose keys are the prompt's variables. The properties and methods are input_schema, output_schema, get_input_schema(), get_output_schema(), get_input_jsonschema(), get_output_jsonschema() and config_schema(); with_types(input_type=..., output_type=...) overrides the inference when it is wrong (5.4).

get_graph() returns a drawable graph of the steps, with draw_mermaid(), draw_ascii(), print_ascii(), draw_png() and draw_mermaid_png(). The ASCII drawing needs the optional grandalf package (without it you get ImportError: Install grandalf to draw graphs). get_prompts() returns every prompt template inside a chain, which is how tools find the prompts to version.

python
# fake_chain.py: a prompt | model | parser chain with a fake chat model
from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([("system", "You are terse."), ("human", "{question}")])
chain = prompt | FakeListChatModel(responses=["Paris"]) | StrOutputParser()

print(type(chain).__name__, [type(s).__name__ for s in chain.steps])
print(chain.invoke({"question": "Capital of France?"}))
print(chain.batch([{"question": "a"}, {"question": "b"}]))
print(list(chain.stream({"question": "again"})))

# schemas
print(chain.input_schema.model_json_schema())
print(chain.output_schema.model_json_schema())
print(chain.get_input_jsonschema())
# graph
chain.get_graph().print_ascii()
# a bare value works when the prompt has exactly one variable
p1 = ChatPromptTemplate.from_template("Say hi to {name}")
print(p1.invoke("Ada").to_messages())
try:
    ChatPromptTemplate.from_template("{a} {b}").invoke("x")
except Exception as e:
    print(type(e).__name__, str(e)[:200])
Output37 lines
RunnableSequence ['ChatPromptTemplate', 'FakeListChatModel', 'StrOutputParser']
Paris
['Paris', 'Paris']
['P', 'a', 'r', 'i', 's']
{'properties': {'question': {'title': 'Question', 'type': 'string'}}, 'required': ['question'], 'title': 'PromptInput', 'type': 'object'}
{'title': 'StrOutputParserOutput', 'type': 'string'}
{'properties': {'question': {'title': 'Question', 'type': 'string'}}, 'required': ['question'], 'title': 'PromptInput', 'type': 'object'}
     +-------------+
     | PromptInput |
     +-------------+
            *
            *
            *
  +--------------------+
  | ChatPromptTemplate |
  +--------------------+
            *
            *
            *
  +-------------------+
  | FakeListChatModel |
  +-------------------+
            *
            *
            *
   +-----------------+
   | StrOutputParser |
   +-----------------+
            *
            *
            *
+-----------------------+
| StrOutputParserOutput |
+-----------------------+
[HumanMessage(content='Say hi to Ada', additional_kwargs={}, response_metadata={})]
TypeError Expected mapping type as input to ChatPromptTemplate. Received <class 'str'>.
For troubleshooting, visit: https://docs.langchain.com/oss/python/langchain/errors/INVALID_PROMPT_INPUT

What to take from it:

  • The chain is a RunnableSequence whose steps are the prompt, the model and the parser, as printed.
  • FakeListChatModel streams one character at a time (['P', 'a', 'r', 'i', 's']), which is a handy way to see streaming work without a provider.
  • The input schema is derived from the prompt: a required string field named question. A caller, or an API layer, can read this to validate input before running anything.
  • A bare string works as input when the prompt has exactly one variable. With two variables ({a} {b}) you get a TypeError that names the problem, and, in 1.8.0, a link to the official page for the error code (INVALID_PROMPT_INPUT). Pass a dict.

Part 3: Composition#

3.1 The pipe and RunnableSequence#

a | b is shorthand for RunnableSequence(a, b), and a.pipe(b, c) is the method form that accepts several steps (and an optional name). You can also build the sequence directly: RunnableSequence(a, b, c, name="my_chain"). A sequence is itself a Runnable, so (a | b) | c and a | (b | c) behave the same and a sequence can be a step of another sequence. The pieces are available as .first, .middle, .last and .steps (we printed .steps and .last in 2.1).

The rule of the pipe is one sentence: the output of each step is the input of the next. That makes the shape of the data between steps the thing you must always know. In the classic chain it changes like this:

Step Receives Produces
ChatPromptTemplate {"question": "..."} (a dict) a prompt value (a list of messages)
chat model the prompt value an AIMessage
StrOutputParser the AIMessage a str

If a step receives the wrong shape you get a run-time error from inside that step (a KeyError for a missing prompt variable, an AttributeError for .upper() on a message, a Pydantic validation error for a typed step). Nothing checks the connection when you write the |.

3.2 What the pipe coerces#

You rarely write RunnableLambda(...) or RunnableParallel(...) yourself, because the pipe converts some plain Python values for you. The rules, each confirmed by running 1.8.0:

You write (next to a Runnable) It becomes Example from the runs
A plain callable (function or lambda) RunnableLambda RunnableLambda(...) | str.upper printed type RunnableLambda
A dict whose values are Runnables or callables RunnableParallel RunnableLambda(...) | {"mul_2": ..., "mul_5": ...} printed RunnableParallel
A generator function (takes an iterator, yields) RunnableGenerator ... | upper_stream streamed piece by piece (3.3)
operator.itemgetter("key"), or any other callable, as a dict value or a pipe step RunnableLambda; it picks "key" out of the dict that arrives {"q": itemgetter("question")} | ... (the sample after this section's router sample)
RunnableMap(...) (the old name) The same class as RunnableParallel: RunnableMap is RunnableParallel prints True Old tutorials import it as from langchain.schema.runnable import RunnableMap (8.3)

Two traps live in this table.

  1. At least one operand must already be a Runnable. {"a": f} | RunnablePassthrough() works because the Runnable on the right implements the reflected operator (__ror__), but {"a": f} | {"b": g} is just Python's dict merge (Python 3.9 and later): it returned a plain dict holding two functions, not a Runnable. When in doubt, write RunnableParallel(...) explicitly.
  2. Coercion happens at composition time, not at call time. A typo such as a missing comma that turns your dict into something else shows up when you build the chain or call it, not in the editor.
python
# routing.py: RunnableBranch, RouterRunnable, routing with a function, dict coercion
from langchain_core.runnables import RunnableBranch, RunnableLambda, RouterRunnable, RunnablePassthrough, chain

branch = RunnableBranch(
    (lambda x: isinstance(x, str), lambda x: x.upper()),
    (lambda x: isinstance(x, int), lambda x: x + 1),
    lambda x: "goodbye",  # the last item is the default and has no condition
)
print(branch.invoke("hello"), branch.invoke(3), branch.invoke(None))
try:
    RunnableBranch(lambda x: 1)
except ValueError as e:
    print("ValueError:", e)

router = RouterRunnable({"double": RunnableLambda(lambda x: x * 2), "negate": RunnableLambda(lambda x: -x)})
print(router.invoke({"key": "double", "input": 21}))
print(router.batch([{"key": "negate", "input": 1}, {"key": "double", "input": 4}]))

# the idiomatic router: a function that returns the runnable to run next
@chain
def route(d):
    if d["kind"] == "len":
        return RunnableLambda(lambda x: len(x["q"]))
    return RunnableLambda(lambda x: x["q"].upper())

print(route.invoke({"kind": "len", "q": "hello"}), route.invoke({"kind": "up", "q": "hello"}))

# dict literals: coerced only when the other operand is a Runnable
print((RunnablePassthrough() | {"a": lambda x: x}).invoke(1))
print(({"a": lambda x: x} | RunnablePassthrough()).invoke(5))
two = {"a": 1} | {"b": 2}
print(type(two).__name__, two)  # two dicts are just Python's dict merge

Output (the last three lines show the coercion rules; the rest is explained in 3.7):

text
HELLO 4 goodbye
ValueError: RunnableBranch requires at least two branches
42
[-1, 8]
5 HELLO
{'a': 1}
{'a': 5}
dict {'a': 1, 'b': 2}

The itemgetter idiom. If you read 2023 to 2024 RAG tutorials, you will meet a dict of itemgetter calls at the head of a chain. It is not special LCEL machinery. itemgetter("question") is a plain Python callable that returns d["question"], so the rules above apply: next to a Runnable it becomes a RunnableLambda, and the dict that holds it becomes a RunnableParallel. Run on 1.8.0 (the names retriever and format are only there to make the step types readable):

python
# itemgetter_demo.py: the old-tutorial idiom, a dict of itemgetters, and what it becomes
from operator import itemgetter

from langchain_core.runnables import RunnableLambda, RunnableMap, RunnableParallel

retriever = RunnableLambda(lambda q: [f"doc about {q}"], name="retriever")

# the shape found in 2023 to 2024 RAG tutorials
inputs = {"context": itemgetter("question") | retriever, "question": itemgetter("question")}
step = inputs | RunnableLambda(lambda d: f"{d['question']!r} with {d['context']}", name="format")

print(type(step).__name__, [type(s).__name__ for s in step.steps])
print(step.invoke({"question": "refunds"}))

# itemgetter("question") is just a callable: it is coerced to a RunnableLambda
print(type((itemgetter("question") | retriever).first).__name__)
print(RunnableMap is RunnableParallel)
Output4 lines
RunnableSequence ['RunnableParallel', 'RunnableLambda']
'refunds' with ['doc about refunds']
RunnableLambda
True

Both entries of the dict receive the same input (the whole {"question": ...} dict), and each itemgetter picks out what its branch needs. Today you can write the same thing as lambda d: d["question"], or, when you only need to carry keys forward, with RunnablePassthrough.assign and .pick (3.5), which say what they mean.

3.3 RunnableLambda, @chain and RunnableGenerator#

RunnableLambda(func, afunc=None, name=None) turns any callable into a Runnable. Details that matter:

  • The signature. func may take (input) or (input, config). If the second parameter is named config, LangChain passes the run's RunnableConfig (the 2.1 sample read the tags back this way). Pass that config on when your function calls another Runnable or dispatches custom events (7.4). On Python 3.11 and later, nesting usually works without it (the @chain sample below nests plus_one with no config), but passing it is the portable form, and it is required when you hop threads or processes yourself.
  • A sync and an async implementation. afunc is the async version; invoke uses func and ainvoke uses afunc, or runs func in a thread when afunc is missing (2.4).
  • Returning a Runnable runs it. The class docstring: "if a RunnableLambda returns an instance of Runnable, that instance is invoked (or streamed)". This is the idiomatic way to route (3.7).
  • A name. Lambdas trace as <lambda>. Use def functions, or pass name=, so traces and get_graph() output are readable (the retrieval chain in 3.8 shows retrieve and format_docs in its graph for this reason).
  • A plain value does not stream; a returned Runnable does. The docstring says it is "best suited for code that does not need to support streaming". A RunnableLambda that returns a plain value receives its full input, computes, and emits the full output at once; for incremental output use a generator. A lambda that returns a Runnable streams through the Runnable it returns (shown in 7.2), so the routing pattern below does not cost you token streaming.

@chain (from langchain_core.runnables import chain) is a decorator that turns a function (sync, coroutine, generator or async generator) into a Runnable named after the function. Any Runnable you invoke inside such a function is recorded as a child run of it, so the nesting shows up in traces. That makes @chain the readable way to write a short piece of orchestration logic that is more than one expression:

python
# chain_decorator.py: @chain, nested tracing, partial JSON streaming, and the fake-model tool warning
import warnings
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.runnables import RunnableLambda, RunnablePassthrough, chain
from langchain_core.tracers.context import collect_runs

@chain
def count_words(text: str) -> int:
    return len(text.split())
print(type(count_words).__name__, count_words.name, count_words.invoke("a b c"))

@chain
def pipeline(x: int) -> int:
    y = RunnableLambda(lambda v: v + 1, name="plus_one").invoke(x)  # traced as a child
    return y * 2

with collect_runs() as cb:
    print(pipeline.invoke(3))
print(cb.traced_runs[0].name, [r.name for r in cb.traced_runs[0].child_runs])

fake = GenericFakeChatModel(messages=iter([AIMessage(content='{"city": "Paris", "pop": 2100000}')]))
for partial in (fake | JsonOutputParser()).stream("x"):
    print(partial)

print(RunnablePassthrough.assign(n=lambda d: d["a"] + 1).invoke({"a": 1}))

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    tool = RunnableLambda(lambda d: d["a"] + d["b"]).as_tool(name="adder", description="Add a and b", arg_types={"a": int, "b": int})
print(type(tool).__name__, tool.name, tool.invoke({"a": 1, "b": 2}))

try:
    GenericFakeChatModel(messages=iter([AIMessage(content="x")])).bind_tools([tool])
except NotImplementedError:
    print("GenericFakeChatModel.bind_tools: NotImplementedError")
Output9 lines
RunnableLambda count_words 3
8
pipeline ['plus_one']
{}
{'city': 'Paris'}
{'city': 'Paris', 'pop': 2100000}
{'a': 1, 'n': 2}
StructuredTool adder 3
GenericFakeChatModel.bind_tools: NotImplementedError
  • count_words is a RunnableLambda named count_words; the decorator did not change the function's behaviour.
  • pipeline calls plus_one inside its body, and the collected trace shows plus_one as a child of pipeline, so a trace of a @chain function is a tree even though you wrote a plain function.
  • JsonOutputParser streams partial JSON ({}, then {'city': 'Paris'}, then the full object): the parser, unlike a lambda, implements chunk-by-chunk processing.
  • RunnablePassthrough.assign(...) returns a RunnableAssign and adds keys to its dict input.
  • as_tool(...) turned the Runnable into a StructuredTool; it is a beta API (the run emitted a LangChainBetaWarning, suppressed here). Tools are 08F.8.
  • The last line is a warning that 08F.4 already flagged: GenericFakeChatModel.bind_tools raises NotImplementedError. That means a GenericFakeChatModel cannot back a tool-calling agent; Part 9 shows what to use.

RunnableGenerator wraps a function that takes an iterator of input chunks and yields output chunks. It is the way to write a custom streaming step: the function sees each upstream piece as it arrives and yields its own pieces immediately, so the chain keeps streaming through it. Section 7.2 runs one next to a lambda to show the difference.

3.4 RunnableParallel: fan-out and fan-in#

RunnableParallel (alias RunnableMap) is a dict of Runnables. The docstring: it "invokes Runnables concurrently, providing the same input to each". The output is a dict with the same keys holding each branch's output. You write it as a dict literal inside a pipe, or explicitly as RunnableParallel(a=..., b=...) or RunnableParallel({"a": ...}).

Two use cases cover most of it:

  1. Fan-out, fan-in. Run independent steps at once, for example two retrievers, or a retriever and a classifier, then pass the merged dict to a prompt.
  2. Carry the input forward. RunnableParallel(question=RunnablePassthrough(), context=retriever) keeps the original question next to the retrieved context, because the passthrough branch returns its input unchanged (the 2.1 sample did this with origin).
python
# parallel_demo.py: RunnableParallel runs branches concurrently, and one failure fails the whole step
import time
from langchain_core.runnables import RunnableLambda, RunnableParallel

def slow(tag):
    def run(x):
        time.sleep(0.2)
        return f"{tag}:{x}"
    return RunnableLambda(run)

par = RunnableParallel(a=slow("a"), b=slow("b"), c=slow("c"))
t = time.perf_counter()
result = par.invoke("q")
elapsed = time.perf_counter() - t
print(result)
print("three 0.2 s branches finished in under 0.5 s:", elapsed < 0.5)

def broken(x):
    raise ValueError("branch b failed")
bad = RunnableParallel(a=slow("a"), b=RunnableLambda(broken))
try:
    bad.invoke("q")
except ValueError as e:
    print("whole step failed:", e)
Output3 lines
{'a': 'a:q', 'b': 'b:q', 'c': 'c:q'}
three 0.2 s branches finished in under 0.5 s: True
whole step failed: branch b failed

Three branches of 0.2 s each finished in well under 0.5 s: they ran concurrently (the sample asserts a threshold rather than printing a timing, so the output is stable across machines). The second half shows the failure rule: if any branch raises, the whole step raises, and you get no partial dict. If you want partial results, catch inside each branch (a with_fallbacks per branch, 6.4) so that the failed branch returns a value.

3.5 RunnablePassthrough, assign and pick: carrying data forward#

Chains pass one value from step to step. Real prompts need several (the question, the retrieved context, the user's tier), so you end up carrying a dict. Three small Runnables manage that dict:

Runnable What it does Typical use
RunnablePassthrough() Returns its input unchanged A branch of a RunnableParallel that keeps the original value
RunnablePassthrough.assign(key=runnable_or_callable, ...) Returns the input dict plus new keys computed from it (returns a RunnableAssign) Add a computed field and keep everything already in the dict
.pick("key") or .pick(["a", "b"]) (a method on any Runnable; it pipes the result into a RunnablePick, so you get a RunnableSequence) Selects keys from a dict Return only what the caller needs

assign reads better than a RunnableParallel with a passthrough when you build up a dict in several stages, and it keeps every earlier key. Each assign can add one or more keys, and each new value can itself be a whole chain:

python
# assign_pattern.py: grow a dict step by step with assign, then pick what the caller needs
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnablePassthrough

KB = {
    "invoice": "Invoices are emailed on the 1st of each month.",
    "refund": "Refunds take 5 to 7 working days.",
}

def search(d: dict) -> list[str]:
    return [t for k, t in KB.items() if k in d["question"].lower()]

def fake_model(prompt_value) -> str:
    # stands in for a chat model: reports which context it was given
    return "Answer based on: " + prompt_value.to_messages()[-1].content.split("Context: ")[1].split("\n")[0]

prompt = ChatPromptTemplate.from_template("Question: {question}\nContext: {context}\nAnswer briefly.")

with_sources = (
    RunnablePassthrough.assign(docs=RunnableLambda(search))                       # adds "docs"
    .assign(context=lambda d: " ".join(d["docs"]))                                 # adds "context"
    .assign(answer=prompt | RunnableLambda(fake_model) | StrOutputParser())        # adds "answer"
)

result = with_sources.invoke({"question": "How long does a refund take?"})
print(sorted(result))
print(result["answer"])
print(with_sources.pick(["answer", "docs"]).invoke({"question": "When is my invoice sent?"}))
Output3 lines
['answer', 'context', 'docs', 'question']
Answer based on: Refunds take 5 to 7 working days.
{'answer': 'Answer based on: Invoices are emailed on the 1st of each month.', 'docs': ['Invoices are emailed on the 1st of each month.']}

The final dict holds question, docs, context and answer. That is the "return the sources with the answer" pattern from RAG tutorials, done with three assign calls, and pick trims the response to what an API would return. assign also streams: it emits the input keys first and then each new key as it becomes ready, so a UI can show the sources before the first token (the run is in 7.2). The model in the sample is a function that stands in for a real chat model so that the sample runs without a key; the structure is identical with a real one.

3.6 .map()#

runnable.map() returns a Runnable that applies the original to each element of a list (RunnableEach), so RunnableLambda(f).map().invoke([1, 2, 3]) gives [f(1), f(2), f(3)] (we saw [2, 3, 4] in 2.1). It is the same concurrency machinery as batch, but expressed inside a chain: use it when an earlier step produces a list (documents, chunks, tickets) and a later step must process each item, for example summarizing every retrieved document before combining them.

3.7 Routing: RunnableBranch, RouterRunnable and a function that returns a Runnable#

Three ways to choose a path at run time; they differ in how much they hide.

RunnableBranch(*branches) takes (condition, runnable) pairs and a final default. The first true condition wins. Verified rules: at least two branches are required (otherwise ValueError: RunnableBranch requires at least two branches); the conditions can be callables or Runnables; the last item is the default and has no condition. The 3.2 sample printed HELLO, 4 and goodbye for a string, an integer and None.

RouterRunnable({"key": runnable, ...}) picks a Runnable by key. Its input is a dict {"key": ..., "input": ...}: the sample called it with {"key": "double", "input": 21} and got 42, and batch of two keyed inputs returned [-1, 8]. Use it when the key is already computed (by a classifier, or from the request).

A function that returns a Runnable. If a RunnableLambda (or a @chain function) returns a Runnable, LangChain runs it with the same input. The sample's route function returned a length-counting Runnable for {"kind": "len"} and an upper-casing one otherwise (5 and HELLO). This is plain Python control flow, so it reads like ordinary code, nests without special syntax and traces cleanly. It is the pattern most current LangChain code uses, and it keeps streaming: the Runnable it returns streams to the caller (7.2), as does the branch a RunnableBranch picks. The official source docstring for RunnableLambda describes the behaviour, and I found no newer official guidance that prefers one router over another, so treat this as the author's recommendation, not official advice.

Need Reach for
Two or three fixed alternatives chosen by simple conditions RunnableBranch (declarative, visible in the graph drawing)
A route key already exists (from a classifier or a request field) RouterRunnable
Anything with more logic, nesting, or building the next chain from the input A function that returns a Runnable
Loops, or branches that need shared state across several steps LangGraph (Part 10)

A typical use of routing is classify then answer: a cheap model classifies the ticket (billing, shipping, other), and the router sends it to a different prompt. Remember what Module 08A taught in 08A.9, 3.2: that is a routing workflow, a fixed shape with an LLM choosing a branch, and LCEL is a fine way to write it as long as it stays one decision deep.

3.8 A complete chain: one-shot retrieval#

Here is the shape you will see in a thousand RAG tutorials, in a keyless version. A RunnableParallel builds the prompt's two variables, the prompt formats them, a model answers and a parser extracts the text. The "retriever" is a keyword lookup and the "model" is a function that reports how many context lines it received, so the output proves the plumbing without a provider. The full RAG treatment is 08F.9 and Module 07.

flowchart LR
    subgraph chain ["RunnableSequence: retrieval | prompt | model | parser"]
        direction LR
        inp(["question: str"]) --> par
        subgraph par ["RunnableParallel (dict literal)"]
            direction TB
            ctx["context: retrieve | format_docs"]
            q["question: RunnablePassthrough"]
        end
        par --> prompt["ChatPromptTemplate"]
        prompt --> model["chat model"]
        model --> parser["StrOutputParser"]
        parser --> out(["answer: str"])
    end
python
# retrieval_chain.py: a one-shot retrieval chain in LCEL with a fake retriever and a fake model
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnableParallel, RunnablePassthrough

POLICY = {
    "refund": "Refunds are issued within 14 days of purchase.",
    "shipping": "Standard shipping takes 3 to 5 working days.",
    "warranty": "Hardware carries a 24 month warranty.",
}

def retrieve(question: str) -> list[str]:
    # stand-in for a vector store retriever: keyword match
    return [text for key, text in POLICY.items() if key in question.lower()]

def format_docs(docs: list[str]) -> str:
    return "\n".join(f"- {d}" for d in docs) or "(nothing found)"

prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer only from the context.\nContext:\n{context}"),
    ("human", "{question}"),
])

# the fake model echoes how many context lines it saw, so the output proves the plumbing
def fake_model(prompt_value):
    system_text = prompt_value.to_messages()[0].content
    seen = system_text.count("\n- ")
    return AIMessage(content=f"[model saw {seen} context line(s)]")

chain = (
    RunnableParallel(context=RunnableLambda(retrieve) | format_docs, question=RunnablePassthrough())
    | prompt
    | RunnableLambda(fake_model)
    | StrOutputParser()
)
print(chain.invoke("What is the refund policy?"))
print(chain.invoke("Tell me about shipping and warranty"))
print(chain.invoke("Do you sell bicycles?"))
Output3 lines
[model saw 1 context line(s)]
[model saw 2 context line(s)]
[model saw 0 context line(s)]

The same chain with a real provider changes one line: the model step. This version needs a key and the langchain-openai package, so it was not run for this lesson (the model id follows the course's table; check the provider's page for current ids):

python
# retrieval_real.py: the same chain with a real model (illustrative: needs OPENAI_API_KEY)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnableParallel, RunnablePassthrough

load_dotenv()

POLICY = {"refund": "Refunds are issued within 14 days of purchase."}


def retrieve(question: str) -> list[str]:
    return [text for key, text in POLICY.items() if key in question.lower()]


def format_docs(docs: list[str]) -> str:
    return "\n".join(f"- {d}" for d in docs) or "(nothing found)"


prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer only from the context. If it is not there, say you do not know.\nContext:\n{context}"),
    ("human", "{question}"),
])
model = init_chat_model("openai:gpt-6-luna")  # a model string; see 08F.5 for provider prefixes

chain = (
    RunnableParallel(context=RunnableLambda(retrieve) | format_docs, question=RunnablePassthrough())
    | prompt
    | model
    | StrOutputParser()
)
print(chain.invoke("What is the refund policy?"))
Example output · illustrative1 line
Refunds are issued within 14 days of purchase.

3.9 Writing steps that compose well#

A short list of habits that make chains easy to read, test and trace:

  1. Name your functions (def format_docs, not lambda d: ...), or pass name=. Traces are the tool you will use to debug in production.
  2. Keep each step a pure function of its input where you can. A step that reads a global or mutates a closure counter behaves differently under batch and abatch (2.3, 2.4).
  3. Decide the data shape between steps and keep it boring. Strings and flat dicts with obvious keys. If you find yourself writing d["context"]["docs"][0]["text"], give the step a Pydantic model or a dataclass.
  4. Put the side-effecting step last, and alone. A step that sends an email or charges a card should not sit in the middle of something that retries (6.3).
  5. Pass config through when a step calls other Runnables.
  6. Test each step alone, then the chain with fake models (Part 9).

Part 4: Config, callbacks and tracing#

Deep-dive

4.1 RunnableConfig field by field#

Every method takes an optional config. It is a TypedDict (all keys optional) imported as from langchain_core.runnables import RunnableConfig, and it is how you talk to a whole chain at once: the config you pass to the outer call reaches every step.

Key Type Meaning Inherited by sub-calls?
tags list[str] Labels for filtering traces and events Yes (merged with each step's own tags)
metadata dict[str, Any] Key-value data attached to the run (user id, experiment name); values must be JSON-serializable Yes
callbacks handlers or a manager Handlers that receive start, end, error and token events Yes (request-time callbacks reach every child, see 4.2)
run_name str Name of this run in traces; defaults to the class name No
max_concurrency int or None Cap on parallel calls in batch, RunnableParallel and map; defaults to the thread pool's default Yes
recursion_limit int Cap on nested steps; 25 for plain Runnables, much higher in LangGraph (4.4) Yes
configurable dict[str, Any] Run-time values for configurable fields and alternatives (5.3); LangGraph also keeps thread_id here (08F.11) Yes
run_id uuid.UUID or None Fixes the id of the run, so you can correlate it with your own logs No

The helpers that manipulate configs are ensure_config, patch_config, merge_configs and get_config_list (you rarely need them), and with_config(...) (5.2) binds a config to a Runnable so every call has it.

This sample puts every inherited-versus-not rule on screen. A handler prints each chain start with its tags and metadata; the chain was given a run_name and a static tag with with_config and a call-time tag and metadata with config:

python
# config_inheritance.py: config inheritance, a callback handler and collect_runs
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.runnables import RunnableLambda
from langchain_core.tracers.context import collect_runs

class Printer(BaseCallbackHandler):
    def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None, tags=None, metadata=None, name=None, **kw):
        print(f"start {name!s:<18} tags={tags} meta={metadata} parent={'yes' if parent_run_id else 'no'}")

inner = RunnableLambda(lambda x: x + 1, name="inner")
outer = RunnableLambda(lambda x: x * 2, name="outer")
chain = (outer | inner).with_config(run_name="my_chain", tags=["static"])
chain.invoke(3, config={"tags": ["call"], "metadata": {"user": "u1"}, "callbacks": [Printer()]})

print("--- collect_runs ---")
with collect_runs() as cb:
    chain.invoke(3)
run = cb.traced_runs[0]
print(run.name, run.run_type, [c.name for c in run.child_runs], run.inputs, run.outputs)
Output5 lines
start my_chain           tags=['call', 'static'] meta={'user': 'u1'} parent=no
start outer              tags=['seq:step:1', 'call', 'static'] meta={'user': 'u1'} parent=yes
start inner              tags=['seq:step:2', 'call', 'static'] meta={'user': 'u1'} parent=yes
--- collect_runs ---
my_chain chain ['outer', 'inner'] {'input': 3} {'output': 7}

Read it line by line:

  • The outer run is named my_chain, the run_name we set with with_config. The two children keep their own names, outer and inner: run_name is not inherited.
  • The tags on the outer run are ['call', 'static']: the call-time tag and the one bound with with_config, merged. Both children carry them too, plus seq:step:1 and seq:step:2, tags that a RunnableSequence adds automatically to its steps by position.
  • The metadata {'user': 'u1'} reached both children: metadata is inherited.
  • The collect_runs half (4.3) shows the run tree: my_chain is a chain run with children outer and inner, input 3, output 7.

4.2 Callbacks#

A callback handler is an object whose methods LangChain calls at lifecycle events. Subclass BaseCallbackHandler (or AsyncCallbackHandler for async methods) and override what you need: on_chain_start, on_chain_end, on_chain_error, on_chat_model_start, on_llm_new_token, on_llm_end, on_tool_start, on_retriever_start, on_custom_event and so on. Handlers shipped in langchain_core.callbacks include StdOutCallbackHandler, StreamingStdOutCallbackHandler, FileCallbackHandler and UsageMetadataCallbackHandler (with the get_usage_metadata_callback context manager, used for token accounting in 08F.5).

There are two ways to attach a handler, and they have different reach:

  • At call time, in the config: chain.invoke(x, config={"callbacks": [handler]}). The handler is inherited by every step.
  • In a constructor: FakeListChatModel(..., callbacks=[handler]). The handler sees only that object's events.
python
# callbacks_scope.py: request-time callbacks reach every child, constructor callbacks only the object
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda

class Counter(BaseCallbackHandler):
    def __init__(self, label): self.label, self.events = label, []
    def on_chain_start(self, serialized, inputs, *, name=None, **kw): self.events.append(f"chain:{name}")
    def on_chat_model_start(self, serialized, messages, *, name=None, **kw): self.events.append(f"chat_model:{name}")
    def on_llm_end(self, response, **kw): self.events.append("llm_end")
    def on_custom_event(self, name, data, **kw): self.events.append(f"custom:{name}={data}")

from langchain_core.callbacks import dispatch_custom_event
def noisy(x, config):
    dispatch_custom_event("note", {"len": len(x.content)}, config=config)
    return x

req, ctor = Counter("request"), Counter("constructor")
model = FakeListChatModel(responses=["hello"], callbacks=[ctor])
chain = ChatPromptTemplate.from_template("{q}") | model | RunnableLambda(noisy) | StrOutputParser()
chain.invoke({"q": "hi"}, config={"callbacks": [req]})
print("request    :", req.events)
print("constructor:", ctor.events)
Output2 lines
request    : ['chain:RunnableSequence', 'chain:ChatPromptTemplate', 'chat_model:None', 'llm_end', 'chain:noisy', "custom:note={'len': 5}", 'chain:StrOutputParser']
constructor: ['chat_model:None', 'llm_end']

The request-level handler saw the whole tree: the sequence, the prompt, the model start (the chat model's name is None in the event, so identify models by serialized or by tags), llm_end, the lambda noisy, its custom event (note, dispatched with dispatch_custom_event) and the parser. The constructor-level handler saw only the model's own two events. Use call-time callbacks for anything that must watch the whole chain (logging, cost accounting, progress), and constructor callbacks only to instrument one component.

python
# handler_errors.py: what happens when a callback handler itself raises
import logging
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.runnables import RunnableLambda

logging.basicConfig(level=logging.WARNING, format="LOG %(name)s: %(message)s")

class Broken(BaseCallbackHandler):
    def on_chain_start(self, *args, **kwargs):
        raise RuntimeError("handler bug")

class Strict(Broken):
    raise_error = True

chain = RunnableLambda(lambda x: x + 1)
print("default handler :", chain.invoke(1, config={"callbacks": [Broken()]}))
try:
    chain.invoke(1, config={"callbacks": [Strict()]})
except RuntimeError as e:
    print("raise_error=True:", type(e).__name__, e)
Output4 lines
LOG langchain_core.callbacks.manager: Error in Broken.on_chain_start callback: RuntimeError('handler bug')
LOG langchain_core.callbacks.manager: Error in Strict.on_chain_start callback: RuntimeError('handler bug')
default handler : 2
raise_error=True: RuntimeError handler bug

The first call succeeded (2) and only a log line from langchain_core.callbacks.manager reported the handler's error; with raise_error = True the RuntimeError reached the caller. If you do not configure Python logging, the first case is close to invisible, so route the langchain_core logger to your logs.

Callbacks run in the background by default for tracing, so a short-lived process can exit before its traces are sent. In Python, call wait_for_all_tracers() (from langchain_core.tracers.langchain) in a finally block before a script, job or serverless function ends; it is the function the LangSmith page for Python recommends. The LangSmith docs also describe an environment variable, LANGCHAIN_CALLBACKS_BACKGROUND=false, in language-neutral prose; I searched langchain-core 1.8.0 and langsmith 0.14.17 and found no use of it in the Python source, so do not rely on it in Python: 11A.5, 2.9 measured it and found it changes nothing, and shows wait_for_all_tracers() and Client().flush() as the working fixes. Check the LangSmith page for current guidance.

4.3 collect_runs, tracing_v2_enabled and LangSmith#

Two context managers in langchain_core.tracers.context help in-process:

  • with collect_runs() as cb: records every run made inside the block in cb.traced_runs, each a Run object with name, run_type, inputs, outputs, error and child_runs (the 4.1 sample printed the tree). It is how you write a test that asserts "this step ran" without a network call.
  • tracing_v2_enabled(...) turns LangSmith tracing on for the block.

For ordinary use you need neither: set LANGSMITH_TRACING=true and LANGSMITH_API_KEY in the environment (08F.4, 5.7) and every chain you invoke is traced, with the run_name, tags and metadata from your config. The old LANGCHAIN_TRACING_V2 names appear in older tutorials; use the LANGSMITH_ names. Datasets, experiments and evaluators are 11A.5 and Module 10A.

4.4 max_concurrency and recursion_limit#

max_concurrency was shown for batch and abatch in 2.3 and 2.4. It also caps the branches of a RunnableParallel, which this sample confirms by measuring the peak number of simultaneously running branches:

python
# parallel_cap.py: does max_concurrency cap the branches of a RunnableParallel?
import threading, time
from langchain_core.runnables import RunnableLambda, RunnableParallel
active = 0; peak = 0; lock = threading.Lock()
def work(x):
    global active, peak
    with lock:
        active += 1; peak = max(peak, active)
    time.sleep(0.1)
    with lock:
        active -= 1
    return x
par = RunnableParallel({f"b{i}": RunnableLambda(work) for i in range(6)})
par.invoke(1)
print("peak without a cap:", peak)
peak = 0
par.invoke(1, config={"max_concurrency": 2})
print("peak with max_concurrency=2:", peak)
Output2 lines
peak without a cap: 6
peak with max_concurrency=2: 2

Six branches ran six at a time by default and two at a time with max_concurrency=2. recursion_limit needs a closer look because its default means different things in different places.

In plain Runnables the default is 25 (DEFAULT_RECURSION_LIMIT in langchain_core.runnables.config; printed in the sample below). It limits how deep Runnables can nest when a step returns another Runnable, as a recursive router would. This sample builds a chain of 100 nested Runnables, once with the default and once with a raised limit:

python
from langchain_core.runnables import RunnableLambda
def deep(n):
    if n == 0:
        return "done"
    return RunnableLambda(lambda _: deep(n - 1)).with_config()  # returns a runnable: invoked with the same input
r = RunnableLambda(deep)
print(r.invoke(3))
try:
    print(r.invoke(100))
except Exception as e:
    print(type(e).__name__, str(e)[:200])
print(r.invoke(100, config={"recursion_limit": 200}))
Output3 lines
done
RecursionError Recursion limit reached when invoking RunnableLambda(lambda _: deep(n - 1)) with input 100.
done

The error is a RecursionError whose message names the Runnable that hit the limit. Raising recursion_limit in the config fixed it.

LangGraph overrides the default. A compiled graph counts super-steps (one round of node execution) rather than nested Runnables, and its default is 10,007 in langgraph 1.2.22 (read from langgraph/_internal/_config.py: DEFAULT_RECURSION_LIMIT is 10007; the Graph API docs page agrees; the environment variable LANGGRAPH_DEFAULT_RECURSION_LIMIT changes it). It was 10,000 for langgraph 1.0.6 to 1.1.3. The error is GraphRecursionError. Part 10.4 runs a graph with a limit of 3 to show it.


Part 5: Binding and configuration#

Deep-dive

These helpers all return a new Runnable that wraps the old one; they never mutate it. Run the sample, then read the sections.

python
# bind_demo.py: bind, with_config, configurable
from langchain_core.language_models import FakeListChatModel
from langchain_core.runnables import ConfigurableField, RunnableLambda

r = RunnableLambda(lambda x: x)
b = r.bind(stop=["a"])
print(type(b).__name__, b.kwargs)

# bind on a chat model: kwargs reach _generate
fake = FakeListChatModel(responses=["hello world"])
print(type(fake.bind(stop=["###"])).__name__)
print(fake.bind(stop=["###"]).invoke("hi").content)

# configurable alternatives
a = FakeListChatModel(responses=["from A"])
b_ = FakeListChatModel(responses=["from B"])
sw = a.configurable_alternatives(ConfigurableField(id="which"), default_key="a", b=b_)
print(sw.invoke("x").content)
print(sw.invoke("x", config={"configurable": {"which": "b"}}).content)
print([ (s.id, s.default) for s in sw.config_specs])

# configurable_fields on a model field
m = FakeListChatModel(responses=["x"], sleep=None).configurable_fields(sleep=ConfigurableField(id="nap", name="Nap"))
print([s.id for s in m.config_specs])
print(m.with_config(configurable={"nap": 0.0}).invoke("hi").content)

# with_types
t = RunnableLambda(lambda x: x).with_types(input_type=int, output_type=int)
print(t.get_input_jsonschema().get("title"), t.get_input_jsonschema().get("type"))

# with_listeners
def on_start(run): print("listener start:", run.name)
def on_end(run): print("listener end  :", run.name, run.outputs)
def on_error(run): print("listener error:", run.error)
RunnableLambda(lambda x: x * 2, name="doubler").with_listeners(on_start=on_start, on_end=on_end, on_error=on_error).invoke(21)
Output11 lines
RunnableBinding {'stop': ['a']}
_ChatModelBinding
hello world
from A
from B
[('which', 'a')]
['nap']
x
RunnableLambdaInput integer
listener start: doubler
listener end  : doubler {'output': 42}

5.1 bind#

runnable.bind(**kwargs) fixes keyword arguments that are passed to the Runnable's invoke on every call. The result is a RunnableBinding (printed above, with .kwargs holding {'stop': ['a']}); for a chat model it is a binding specialised for models, so .invoke still returns an AIMessage. The source docstring's example is model.bind(stop=["three"]) | StrOutputParser(): a model that stops generating at a stop sequence, built once and reused. bind_tools on chat models is the specialised form for tool schemas (08F.8), and with_structured_output is another (08F.6).

Use bind when a parameter is a property of this use of a component, not of the component itself (a stop sequence for one chain, a response_format for another).

5.2 with_config#

with_config(config=None, **kwargs) binds a RunnableConfig so every call carries it: chain.with_config(run_name="triage", tags=["support"]) (used in 4.1). Call-time config is merged with it (tags are concatenated, as the 4.1 output showed).

5.3 configurable_fields and configurable_alternatives#

Sometimes a deployed chain should let the caller choose a model, a temperature or a whole sub-chain per request, without rebuilding the chain.

  • configurable_fields(**kwargs) exposes constructor fields. The sample made FakeListChatModel.sleep configurable under the id nap; config_specs listed it, and with_config(configurable={"nap": 0.0}) set it.
  • configurable_alternatives(ConfigurableField(id="which"), default_key="a", b=other) lets the caller swap an entire Runnable: with no config the default "a" answered from A, and config={"configurable": {"which": "b"}} answered from B. config_specs reported the field id and its default.

There are single- and multi-option variants (ConfigurableFieldSingleOption, ConfigurableFieldMultiOption) for fixed sets of values. init_chat_model with no model argument returns exactly such a configurable model, so init_chat_model(temperature=0).invoke(x, config={"configurable": {"model": "..."}}) selects the model per call (08F.5).

5.4 with_types#

with_types(input_type=..., output_type=...) overrides the inferred schema, for example when a RunnableLambda's first parameter has no annotation and the generated API schema is useless. The sample's lambda reported an integer input after with_types(input_type=int, ...). It changes the schema metadata only; it does not convert or validate values.

5.5 as_tool#

runnable.as_tool(name=..., description=..., arg_types=...) wraps a Runnable as a tool you can give to an agent. It is marked beta (the run emitted a LangChainBetaWarning), so treat the signature as subject to change; the normal route is the @tool decorator in 08F.8.

5.6 with_listeners#

with_listeners(on_start=..., on_end=..., on_error=...) (and with_alisteners for coroutines) attaches lifecycle hooks to one Runnable without writing a callback handler. Each hook receives the Run object, so you can read run.name, run.outputs or run.error. The sample's listeners printed listener start: doubler and listener end : doubler {'output': 42}. I also confirmed that on_error fires on an exception and that the exception still propagates; I left that out of the sample because the tracer prints the failure's traceback to the console, which makes the output noisy. Use with_listeners for small, local instrumentation (timing one step, counting calls) and callbacks (4.2) for cross-cutting ones.


Part 6: Reliability: retries and fallbacks#

6.1 Four layers, and which one you want#

LLM calls fail: rate limits, timeouts, overloaded servers, malformed output. Three earlier lessons already own most of what you need, so this part does not repeat them. 03.8 taught the error classes and the retry rules for raw API calls. 08F.5, Part 11 taught the layers on the model object (SDK retries, with_retry, with_fallbacks), the diagram of how they nest, the standard exception hierarchy with its is_retryable flag, and the rate limiter. 08F.6, Part 11 taught the ladder for parse failures. Read those first if you have not.

What this part adds is what is specific to Runnables and LCEL: how with_retry and with_fallbacks behave on a chain (and under stream), where in a chain to attach them, and how they compose.

Layer Where it is taught The one line to remember
SDK client retries (max_retries, timeout) 08F.5, 11.1 HTTP-level retries on connection errors, 429s and 5xx, inside one model call; the only retry layer that still works when you stream (6.2)
with_retry 6.2 and 6.3 here, and 08F.5, 11.2 Re-runs a whole Runnable on exceptions you choose; invoke and batch only
with_fallbacks 6.4 here Tries a different Runnable; a stream is rescued only before its first chunk
Agent middleware and graph retry policies 08F.8 (ModelRetryMiddleware, ToolRetryMiddleware, ModelFallbackMiddleware), 08F.12 The same ideas inside an agent loop or a graph node, where a retry must not redo the whole run

Layers multiply, so give retries one owner, as 08F.5 puts it: either leave max_retries at a small number and use no with_retry, or set max_retries=0 on the model and let with_retry (with a restricted exception list) own the policy. A model with max_retries=2 has up to three HTTP attempts; wrap it in with_retry(stop_after_attempt=3) as well and one logical call can make nine requests, each with its own backoff, while the user waits. Two things decide which owner you can pick, and both are easy to miss. The first is the call style: with_retry can own the policy only for invoke and batch, because a stream skips it (6.2). The second is the provider: the restricted exception list has to match what the integration really raises, and the table in 08F.5, 11.1 shows that this differs by integration.

6.2 with_retry#

text
Runnable.with_retry(*, retry_if_exception_type=(Exception,), wait_exponential_jitter=True,
                    exponential_jitter_params=None, stop_after_attempt=3) -> Runnable

It wraps the Runnable in a RunnableRetry (built on the tenacity library). The defaults, verified in the source and in the run below:

Parameter Default Meaning
stop_after_attempt 3 Total attempts, including the first
retry_if_exception_type (Exception,) A tuple of exception classes, or a predicate lambda exc: bool. The default retries every exception
wait_exponential_jitter True Wait exponentially longer between attempts, with random jitter
exponential_jitter_params None A dict with the keys initial, max, exp_base and jitter (seconds and factors) to tune the wait

When the last attempt fails, the last exception is raised to the caller.

python
# retry_fallback.py
from langchain_core.runnables import RunnableLambda

calls = {"n": 0}
def flaky(x):
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError(f"attempt {calls['n']} failed")
    return f"ok after {calls['n']} calls"

r = RunnableLambda(flaky).with_retry(stop_after_attempt=3, wait_exponential_jitter=False)
print(type(r).__name__, r.invoke("x"))

calls["n"] = 0
r2 = RunnableLambda(flaky).with_retry(stop_after_attempt=2, wait_exponential_jitter=False)
try:
    r2.invoke("x")
except Exception as e:
    print("gave up:", type(e).__name__, e)

# retry only on chosen exceptions: ValueError is not retried
n = {"c": 0}
def bad_value(x):
    n["c"] += 1
    raise ValueError("not retryable")
r3 = RunnableLambda(bad_value).with_retry(retry_if_exception_type=(ConnectionError,), stop_after_attempt=5, wait_exponential_jitter=False)
try: r3.invoke(1)
except ValueError as e: print("ValueError after", n["c"], "call(s)")

# predicate form
n["c"] = 0
r4 = RunnableLambda(bad_value).with_retry(retry_if_exception_type=lambda e: isinstance(e, ValueError), stop_after_attempt=3, wait_exponential_jitter=False)
try: r4.invoke(1)
except ValueError: print("predicate retried:", n["c"])

# fallbacks
def primary(x): raise TimeoutError("primary down")
def backup(x): return f"backup handled {x}"
fb = RunnableLambda(primary).with_fallbacks([RunnableLambda(backup)])
print(type(fb).__name__, fb.invoke("job"))

# exceptions_to_handle: other exceptions propagate
fb2 = RunnableLambda(primary).with_fallbacks([RunnableLambda(backup)], exceptions_to_handle=(ValueError,))
try: fb2.invoke("job")
except TimeoutError as e: print("not handled:", e)

# exception_key passes the error to the fallback
def show_error(d): return f"input={d['q']!r} error={d['error']!r}"
fb3 = RunnableLambda(lambda d: 1 / 0).with_fallbacks([RunnableLambda(show_error)], exception_key="error")
print(fb3.invoke({"q": "hi"}))

# batch + return_exceptions + fallbacks per item
def sometimes(x):
    if x % 2: raise RuntimeError("odd")
    return x
print(RunnableLambda(sometimes).with_fallbacks([RunnableLambda(lambda x: -x)]).batch([1, 2, 3]))

Output (the first half is retry, the second half is fallbacks and is explained in 6.4):

text
RunnableRetry ok after 3 calls
gave up: ConnectionError attempt 2 failed
ValueError after 1 call(s)
predicate retried: 3
RunnableWithFallbacks backup handled job
not handled: primary down
input='hi' error=ZeroDivisionError('division by zero')
[-1, 2, -3]

What each line shows:

  1. RunnableRetry ok after 3 calls: the function failed twice and succeeded on the third call, within stop_after_attempt=3.
  2. gave up: ConnectionError attempt 2 failed: with only two attempts allowed, the second failure was raised.
  3. ValueError after 1 call(s): with retry_if_exception_type=(ConnectionError,) a ValueError is not retried and is raised at once.
  4. predicate retried: 3: the predicate form retried a ValueError three times.

Retries inside a batch are per item, and the backoff is tunable:

python
# retry_params.py: backoff parameters, and retries inside a batch
import time
from langchain_core.runnables import RunnableLambda

attempts = {"n": 0}
def always_down(x):
    attempts["n"] += 1
    raise ConnectionError("service unavailable")

tuned = RunnableLambda(always_down).with_retry(
    stop_after_attempt=3,
    wait_exponential_jitter=True,
    # keys: initial, max, exp_base, jitter (seconds); tiny values here so the sample is fast
    exponential_jitter_params={"initial": 0.01, "max": 0.05, "exp_base": 2, "jitter": 0.01},
)
start = time.perf_counter()
try:
    tuned.invoke("x")
except ConnectionError:
    print("attempts:", attempts["n"], "| finished fast:", time.perf_counter() - start < 1)

# only the failing item is retried inside a batch
seen: dict[int, int] = {}
def flaky(x: int) -> int:
    seen[x] = seen.get(x, 0) + 1
    if x == 2 and seen[x] < 2:
        raise ConnectionError("first attempt for item 2 fails")
    return x

print(RunnableLambda(flaky).with_retry(wait_exponential_jitter=False).batch([1, 2, 3]))
print("calls per item:", seen)
Output3 lines
attempts: 3 | finished fast: True
[1, 2, 3]
calls per item: {1: 1, 2: 2, 3: 1}

Item 2 was called twice and the others once; the batch result is complete ([1, 2, 3]) because only the failing item retried.

python
# retry_stream.py: with_retry protects invoke but not stream
from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

calls = {"n": 0}


class FlakyModel(FakeListChatModel):
    """Fails twice with a connection error, then answers (on both the call and the stream path)."""

    def _call(self, *args, **kwargs):
        calls["n"] += 1
        if calls["n"] < 3:
            raise ConnectionError("blip")
        return "fine"

    def _stream(self, *args, **kwargs):
        calls["n"] += 1
        if calls["n"] < 3:
            raise ConnectionError("blip")
        return super()._stream(*args, **kwargs)


model = FlakyModel(responses=["fine"]).with_retry(stop_after_attempt=3, wait_exponential_jitter=False)
chain = ChatPromptTemplate.from_template("{q}") | model | StrOutputParser()

print("invoke:", chain.invoke({"q": "x"}), calls)

calls["n"] = 0
try:
    print("stream:", list(chain.stream({"q": "x"})), calls)
except ConnectionError:
    print("stream raised ConnectionError", calls)
Output2 lines
invoke: fine {'n': 3}
stream raised ConnectionError {'n': 1}

invoke retried twice and answered (three calls). stream made one call and raised. I measured the same bypass for astream and astream_events on 1.8.0, while ainvoke and abatch do retry, and the source of langchain_core/runnables/retry.py defines only invoke, ainvoke, batch and abatch. The repository wiki says the same in one line: stream() and transform() are "not retried because stream retry semantics are ambiguous" (once a chunk has reached the caller, re-running would send a second answer after the first). What to do instead for a streaming endpoint:

  1. Let the SDK client own retries on a streaming endpoint. max_retries on the model object retries the HTTP request that opens the stream, before any token exists. It lives inside the model call, not in a Runnable wrapper, so streaming cannot skip it (measured below).
  2. Or restart the whole stream yourself, before you have sent anything. Pull the first chunk, and on a transient error before that point start the stream again. After the first chunk has gone to the user, start over visibly (an error event, then a new request) and never splice two answers together. Exercise 9 builds this helper, and its answer has a version that was run.
  3. Add a fallback (6.4), which does work for a stream, but only before the first chunk.

Inside create_agent, the answer is different: ModelRetryMiddleware and ModelFallbackMiddleware are hooks around the model call, so they still apply when the agent is streamed (08F.8, 8.10).

The first option can be checked without a key and without contacting a provider. The next sample starts a tiny HTTP server on 127.0.0.1 that answers every request with a 503, points a real ChatOpenAI at it, and counts the requests that arrive. It compares the two retry owners of 6.1 under invoke and under stream (it needs langchain-openai; the key is a placeholder string, because nothing is sent to OpenAI):

python
# sdk_retry_stream.py: which retry layer still works when you stream? (local server, no provider, no key)
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

from langchain_core.exceptions import ModelAPIError
from langchain_openai import ChatOpenAI

hits = {"n": 0}


class Always503(BaseHTTPRequestHandler):
    """A stand-in for an overloaded provider: every request gets HTTP 503."""

    def do_POST(self):
        hits["n"] += 1
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        body = b'{"error": {"message": "overloaded"}}'
        self.send_response(503)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


server = HTTPServer(("127.0.0.1", 0), Always503)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_port}/v1"


def requests_made(model, method):
    hits["n"] = 0
    try:
        if method == "invoke":
            model.invoke("hi")
        else:
            list(model.stream("hi"))
    except ModelAPIError as exc:
        return f"requests={hits['n']}  raised {type(exc).__name__}"


sdk_owner = ChatOpenAI(model="gpt-6-luna", base_url=url, api_key="not-a-real-key", max_retries=2, timeout=5)
runnable_owner = ChatOpenAI(
    model="gpt-6-luna", base_url=url, api_key="not-a-real-key", max_retries=0, timeout=5
).with_retry(retry_if_exception_type=(ModelAPIError,), stop_after_attempt=3, wait_exponential_jitter=False)

for label, model in [("max_retries=2, no with_retry", sdk_owner), ("max_retries=0 + with_retry(3)", runnable_owner)]:
    for method in ("invoke", "stream"):
        print(f"{label:30} {method:6} -> {requests_made(model, method)}")
Output4 lines
max_retries=2, no with_retry   invoke -> requests=3  raised OpenAIAPIError
max_retries=2, no with_retry   stream -> requests=3  raised OpenAIAPIError
max_retries=0 + with_retry(3)  invoke -> requests=3  raised OpenAIAPIError
max_retries=0 + with_retry(3)  stream -> requests=1  raised OpenAIAPIError

Read the four lines as a table. With the SDK as owner (max_retries=2), invoke and stream both made three requests: the client retried the request that opens the stream. With with_retry as owner (max_retries=0), invoke made three requests and stream made one: the policy you wrote was skipped, and nothing took its place. The exception is OpenAIAPIError, the integration's subclass of ModelAPIError, so the except clause and the retry_if_exception_type tuple both name the standard class.

That gives the rule for choosing the owner:

The step is called with Give retries to Why
invoke, ainvoke, batch, abatch only Either owner (6.1) Both layers run
stream, astream or astream_events on the wrapped Runnable, or on a chain that contains it The SDK client (max_retries), plus a fallback with_retry is skipped; a fallback covers a failure before the first chunk
Both (the same model object serves a streaming endpoint and a batch job) The SDK client, or two model objects with different settings One object with max_retries=0 and with_retry is unprotected on its streaming path

What decides it is the method that reaches the wrapper, not whether tokens are flowing. A graph node that calls model.with_retry(...).invoke(...) is still protected when the graph is streamed with stream_mode="messages" or read through astream_events: the node calls invoke, so RunnableRetry.invoke runs, and the tokens reach the consumer by auto-streaming (7.2). I ran that with the flaky model above inside a LangGraph node: three attempts, and the answer's tokens arrived. (The two failed attempts failed before their first token; an attempt that fails after emitting tokens would already have sent them to the consumer, and I did not test that case.)

Two limits of this check. It covers a failure of the request, before the first token; no layer retries a connection that drops in the middle of an answer, which is the application's job (6.4, 7.6). And it was run on langchain-openai only: ChatOllama has no retry setting at all (08F.5, 11.2), so for a model like that the restart helper of option 2 is the only retry a stream can have.

6.3 Retry the smallest unit#

A retry re-runs everything inside the wrapped Runnable, including steps that already succeeded. Wrap a whole chain and a failure in the last step repeats the first step's work and, if that step has a side effect, repeats the side effect. This sample counts the side effects of a payment-like step in front of a flaky step:

python
# retry_scope.py: retry the smallest unit
from langchain_core.runnables import RunnableLambda

def make(fail_times):
    state = {"side_effects": 0, "flaky_calls": 0}
    def charge_card(x):
        state["side_effects"] += 1          # imagine a payment call
        return x
    def flaky(x):
        state["flaky_calls"] += 1
        if state["flaky_calls"] <= fail_times:
            raise ConnectionError("transient")
        return f"done {x}"
    return state, RunnableLambda(charge_card), RunnableLambda(flaky)

state, charge, flaky = make(2)
(charge | flaky).with_retry(stop_after_attempt=3, wait_exponential_jitter=False).invoke("order-1")
print("retry whole chain  :", state)

state, charge, flaky = make(2)
(charge | flaky.with_retry(stop_after_attempt=3, wait_exponential_jitter=False)).invoke("order-1")
print("retry only the step:", state)
Output2 lines
retry whole chain  : {'side_effects': 3, 'flaky_calls': 3}
retry only the step: {'side_effects': 1, 'flaky_calls': 3}

Retrying the whole chain executed the "payment" step three times for one order; retrying only the flaky step executed it once. The flaky step failed twice in both cases. This is the same at-least-once hazard that 08A.14 described for tool calls, now at the chain level, and the fixes are the same:

  1. Put with_retry on the smallest step that can fail transiently (the model call, the HTTP request).
  2. Make side-effecting steps idempotent (an idempotency key, "create if not exists") so that a repeat is harmless, and keep them outside retried sections.
  3. For a longer workflow, a checkpointed LangGraph graph is the right tool because it records which steps finished and does not redo them after a failure (08F.11).

6.4 with_fallbacks#

text
Runnable.with_fallbacks(fallbacks: Sequence[Runnable], *, exceptions_to_handle=(Exception,),
                        exception_key=None) -> RunnableWithFallbacks

with_fallbacks tries the original Runnable and, if it raises one of the handled exceptions, tries each fallback in order with the same input, returning the first success. In the sample from 6.2:

  • RunnableWithFallbacks backup handled job: the primary raised TimeoutError, the backup ran.
  • With exceptions_to_handle=(ValueError,) the TimeoutError was not handled and propagated (not handled: primary down). The default, as with with_retry, is every Exception: narrow it.
  • With exception_key="error" the exception is added to the fallback's input dict, so the fallback can see what went wrong (input='hi' error=ZeroDivisionError(...)). This is how you build a fallback that apologizes differently for a timeout than for a refusal.
  • In a batch, fallbacks apply per item ([-1, 2, -3]: only the odd inputs failed and fell back).

Fallbacks on chat models are the main use. The next sample defines a model that always times out (a subclass of the fake model whose _call raises) and falls back to a second model:

python
# fallback_model.py: model fallbacks, and where a fallback sits in a chain
from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

class DownModel(FakeListChatModel):
    def _call(self, *args, **kwargs):
        raise TimeoutError("provider timed out")

prompt = ChatPromptTemplate.from_template("Answer: {q}")
primary = DownModel(responses=["unused"])
backup = FakeListChatModel(responses=["answer from the backup model"])

robust = primary.with_fallbacks([backup])
chain = prompt | robust | StrOutputParser()
print(type(robust).__name__)
print(chain.invoke({"q": "hi"}))

# exceptions_to_handle narrows what triggers the fallback
narrow = primary.with_fallbacks([backup], exceptions_to_handle=(ConnectionError,))
try:
    (prompt | narrow | StrOutputParser()).invoke({"q": "hi"})
except TimeoutError as e:
    print("TimeoutError escaped:", e)
Output3 lines
RunnableWithFallbacks
answer from the backup model
TimeoutError escaped: provider timed out

Observations: with_fallbacks returned a RunnableWithFallbacks; the chain answered from the backup; and a fallback list that handles only ConnectionError let the TimeoutError escape. In the drawn graph of the chain the fallback wrapper appears as a single WithFallbacks node between the prompt and the parser (observed on 1.8.0): the fallback chain counts as one step in the drawing.

Where you attach the fallback matters:

Pattern Fallback receives Typical use
prompt | model.with_fallbacks([model_b]) | parser The same prompt value Swap the model, keep the prompt. The prompt must work for both models
(prompt_a | model_a).with_fallbacks([prompt_b | model_b]) The original input dict Different prompts per model (for example different system prompt style or output format)
chain.with_fallbacks([RunnableLambda(canned_reply)]) The original input dict A last-resort deterministic answer
model.with_structured_output(Schema).with_fallbacks([...]) The same input Bind tools or schemas before wrapping, so the wrapper sees a Runnable that already has them

A common production composition retries the transient errors on the primary, then falls back to a different provider for the rest. It follows the "one owner" rule of 6.1, in two variants, because the owner depends on how the model is called (6.2). The exception tuple is the one from 08F.5, 11.2: the standard retryable family plus the transport errors that some integrations do not map. A tuple of Python built-ins would never match a real provider failure, because the SDKs' own timeout and rate-limit classes are not subclasses of TimeoutError or ConnectionError. Written with the course's provider order, this is illustrative (it needs langchain-openai, langchain-anthropic, langchain-google-genai and the matching keys; check each provider's page for current model ids; the google_genai prefix is the name in the init_chat_model registry):

python
# resilient_model.py: one retry owner, then fall back across providers (illustrative)
import importlib

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.exceptions import (
    ModelAPIError, ModelConnectionError, ModelRateLimitError, ModelTimeoutError,
)

load_dotenv()

# The standard retryable family, plus the raw transport errors that the Google and Ollama
# integrations let through unmapped (08F.5, 11.1 and 11.2): collect whichever is installed.
transport = []
for name in ("httpx", "httpx2"):
    try:
        transport.append(importlib.import_module(name).TransportError)   # includes timeouts
    except ImportError:
        pass
TRANSIENT = (ModelRateLimitError, ModelAPIError, ModelConnectionError, ModelTimeoutError, *transport)

second = init_chat_model("anthropic:claude-haiku-5-5", max_retries=1, timeout=30)
third = init_chat_model("google_genai:gemini-3.8-flash", max_retries=1, timeout=30)

# Variant A, for invoke and batch: the SDK layer is off on the primary and with_retry owns the policy.
primary = init_chat_model("openai:gpt-6-luna", max_retries=0, timeout=30).with_retry(
    retry_if_exception_type=TRANSIENT, stop_after_attempt=2
)
# fall back only on transient failures; a 400 or a bad key would fail the same way elsewhere
model = primary.with_fallbacks([second, third], exceptions_to_handle=TRANSIENT)  # an OpenRouter model can be a fourth entry
print(model.invoke("Reply with the single word: ready").content)

# Variant B, for stream and astream: with_retry would be skipped, so the SDK client owns the retries.
streaming_primary = init_chat_model("openai:gpt-6-luna", max_retries=2, timeout=30)
streaming_model = streaming_primary.with_fallbacks([second, third], exceptions_to_handle=TRANSIENT)
for chunk in streaming_model.stream("Reply with the single word: ready"):
    print(chunk.text, end="")
print()
Example output · illustrative2 lines
ready
ready

Do not call model.stream(...) on variant A: it runs, and its retry policy silently does nothing. In variant B the fallback still only helps before the first chunk (the next sample). The transport errors are in the tuple for the fallback models as much as for the primary: OpenAI and Anthropic raise subclasses of the standard classes, but a Google model raises the transport library's exception for a connection failure, and a tuple without it would neither retry nor fail over. For any provider you add, provoke one error and check the class you get, as 08F.5 does with a dead port. A context-overflow fallback to a larger-window model is a separate, narrower with_fallbacks(..., exceptions_to_handle=(ContextOverflowError,)), as 08F.5, 11.2 shows.

Fallbacks and streaming. with_fallbacks does implement stream and astream, but it can only switch models before the first chunk. Once a chunk has been yielded to the caller, a later error propagates and the fallback is not tried: the caller would otherwise receive the first model's half answer glued to the second model's whole answer. Both cases, run on 1.8.0 (the fake models stream a character at a time, which is why the backup's reply arrives as single letters):

python
# fallback_stream.py: a fallback rescues a stream only if the primary fails before its first chunk
from langchain_core.language_models import FakeListChatModel, GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("{q}")
backup = FakeListChatModel(responses=["backup"])


class DownModel(FakeListChatModel):
    """Fails before it yields anything."""

    def _stream(self, *args, **kwargs):
        raise TimeoutError("down")


class MidStreamModel(GenericFakeChatModel):
    """Yields two chunks, then fails."""

    def _stream(self, messages, stop=None, run_manager=None, **kwargs):
        for i, chunk in enumerate(super()._stream(messages, stop, run_manager, **kwargs)):
            if i == 2:
                raise TimeoutError("died mid-stream")
            yield chunk


early = prompt | DownModel(responses=["x"]).with_fallbacks([backup]) | StrOutputParser()
print("fails before the first chunk:", list(early.stream({"q": "x"})))

mid = MidStreamModel(messages=iter([AIMessage(content="one two three four")]))
late = prompt | mid.with_fallbacks([backup]) | StrOutputParser()
seen = []
try:
    for piece in late.stream({"q": "x"}):
        seen.append(piece)
except TimeoutError as e:
    print("fails mid-stream: TimeoutError", repr(str(e)), "after", seen)
Output2 lines
fails before the first chunk: ['b', 'a', 'c', 'k', 'u', 'p']
fails mid-stream: TimeoutError 'died mid-stream' after ['one', ' ']

A provider outage or a rate limit usually fails at the request, before any token, so a fallback does cover the common streaming failure. A connection that drops half way is the case it cannot cover. For that, decide in your application what the user should see (an error event and a "retry" button, or a silent restart if nothing has been displayed yet), and log it (7.6).

6.5 Putting reliability in the right place#

A short rule set that follows from this part, with the model-side rules left to 08F.5, Part 11:

  1. Timeouts first. No retry policy rescues a call that hangs for five minutes; set the model's timeout (08F.5).
  2. One owner of retries. Either the client (max_retries, small, no with_retry) or with_retry (max_retries=0), never both unplanned (6.1). A streaming endpoint cannot use with_retry at all, so there the owner is the client (6.2).
  3. Restrict what you retry to transient classes, and check that the classes you name are the ones your integration raises (08F.5, 11.1). Never retry deterministic errors: a missing prompt variable or a schema bug in your own code fails the same way every time. Retrying a model's malformed output is different: it is a cost decision you make on purpose, as 08F.6, Part 11 shows, and it needs a chain without side effects.
  4. Retry small, fall back wide. Retry the model call (or any single step that can fail transiently); fall back at the model (or chain) level.
  5. Remember the stream. with_retry is bypassed under stream, astream and astream_events, the client's max_retries is not, and a fallback rescues a stream only before its first chunk.
  6. Make side effects idempotent or keep them out of retried sections (6.3).
  7. Observe it. Retries and fallbacks are invisible to users and expensive; they show up in traces and metrics only if you look (11A.5, Module 11A).

Part 7: Streaming and astream_events#

Deep-dive

Streaming itself (why it matters for latency, how providers send chunks, what to do on the client) is Module 03.3. This part is about what is specific to Runnables: how a chain streams, what silently stops it, and how to observe a whole chain's progress.

7.1 How a chain streams#

Every Runnable has stream (sync) and astream (async). A RunnableSequence implements them by passing chunks through each component's transform method: step 1 yields a chunk, step 2 transforms that chunk and yields its own, and so on, so the first output reaches the caller after the first chunk has made it through every step, not after the model has finished.

sequenceDiagram
    participant C as Caller
    participant S as RunnableSequence
    participant M as Chat model
    participant P as StrOutputParser
    participant L as RunnableLambda
    C->>S: stream(input)
    S->>M: transform(input)
    M-->>P: chunk 1, chunk 2, chunk 3
    P-->>L: text pieces
    Note over L: a plain lambda waits for the end of its input
    L-->>S: one big output
    S-->>C: one chunk, at the very end

The official models page states the rule: "Streaming only works if all steps in the program know how to process a stream of chunks." Components that implement chunk-wise processing include chat models, StrOutputParser, JsonOutputParser (which streams partial JSON, as 3.3 showed) and the list parsers. Components that cannot, such as a plain RunnableLambda, wait for their whole input.

7.2 What blocks a stream#

python
# streaming_blocks.py: what streams through a chain and what blocks
from typing import Iterator
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda, RunnableGenerator

def model():
    return GenericFakeChatModel(messages=iter([AIMessage(content="one two three four")]))

print("stream through parser:", list((model() | StrOutputParser()).stream("x")))
print("stream through lambda:", list((model() | StrOutputParser() | RunnableLambda(str.upper)).stream("x")))

def upper_stream(chunks: Iterator[str]) -> Iterator[str]:
    for c in chunks:
        yield c.upper()
print("stream through generator:", list((model() | StrOutputParser() | RunnableGenerator(upper_stream)).stream("x")))

# a generator function is coerced into RunnableGenerator when piped
print("coerced:", list((model() | StrOutputParser() | upper_stream).stream("x")))
Output4 lines
stream through parser: ['one', ' ', 'two', ' ', 'three', ' ', 'four']
stream through lambda: ['ONE TWO THREE FOUR']
stream through generator: ['ONE', ' ', 'TWO', ' ', 'THREE', ' ', 'FOUR']
coerced: ['ONE', ' ', 'TWO', ' ', 'THREE', ' ', 'FOUR']

The same fake model that said "one two three four" was streamed through four different tails:

  1. Through the parser alone, the text arrived piece by piece.
  2. After a RunnableLambda(str.upper) (a lambda that returns a plain value) it arrived as one chunk at the end: the lambda swallowed the stream. This is what the diagram above shows, and it is the most common reason "my chain does not stream".
  3. After a RunnableGenerator (a function from an iterator of chunks to an iterator of chunks) it streamed again, upper-cased piece by piece.
  4. A bare generator function piped with | was coerced into a RunnableGenerator automatically ("coerced").

So the fix for a post-processing step that must not break streaming is to write it as a generator over chunks. Be aware of the cost: a step that needs the whole text (counting words, parsing a complete JSON document, checking a policy) cannot stream and should not pretend to; run it after the stream ends, or accept the buffering.

Other cases from the runs:

  • RunnableParallel streams a dict, one key per chunk. Each chunk carries one branch's piece, and chunks from different branches interleave in arrival order, so the order between keys is not fixed. The sample below groups the pieces by key, which gives a stable result.
  • Wrappers that change what a stream does. with_retry is bypassed when you stream, so no retry happens unless the model's own max_retries is on (6.2), and with_fallbacks can switch models only before the first chunk (6.4). Neither blocks the stream; both silently change what protects it.
  • A chat model called with invoke inside a step streams tokens only when a streaming consumer is attached to the outer call, such as astream_events or a graph's stream_mode="messages" (the last sample in this section). LangChain then uses the model's streaming internals even though your code called invoke (auto-streaming; see also 08F.5). A plain stream on a lambda that calls model.invoke does not.
python
# streaming_parallel.py: what a RunnableParallel streams, and astream_events filters
import asyncio
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableParallel

def m(text): return GenericFakeChatModel(messages=iter([AIMessage(content=text)]))
par = RunnableParallel(a=m("x y") | StrOutputParser(), b=m("p q") | StrOutputParser())
# chunks arrive as one-key dicts; the order between keys is not fixed, so group them per key
grouped: dict[str, list[str]] = {}
for chunk in par.stream("go"):
    for key, piece in chunk.items():
        grouped.setdefault(key, []).append(piece)
print(grouped)

async def main():
    chain = (m("alpha beta") | StrOutputParser()).with_config(run_name="answer_chain")
    names = [e["name"] for e in [e async for e in chain.astream_events("go", version="v2", include_names=["StrOutputParser"])]]
    print(sorted(set(names)), len(names))
    tagged = m("alpha beta").with_config(tags=["final"]) | StrOutputParser()
    evs = [e["event"] async for e in tagged.astream_events("go", version="v2", include_tags=["final"])]
    print(sorted(set(evs)))
    # collect only the streamed text, by event type
    text = "".join([e["data"]["chunk"].content async for e in (m("hello there") | StrOutputParser()).astream_events("go", version="v2") if e["event"] == "on_chat_model_stream"])
    print(repr(text))
asyncio.run(main())

Output (the first line is the grouped parallel chunks; the rest belongs to 7.3):

text
{'b': ['p', ' ', 'q'], 'a': ['x', ' ', 'y']}
['StrOutputParser'] 5
['on_chat_model_end', 'on_chat_model_start', 'on_chat_model_stream']
'hello there'

Routers, branches and assign while streaming. The lambda rule above is about lambdas that return a plain value. Three patterns that this lesson recommends do keep streaming, which is the question people ask first about 3.5 and 3.7:

python
# stream_routes.py: assign, a lambda that returns a Runnable, and a branch all keep streaming
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnablePassthrough


def model():
    return GenericFakeChatModel(messages=iter([AIMessage(content="one two")]))


prompt = ChatPromptTemplate.from_template("{question}")

# assign: input keys first, then each new key as it is ready
chain = RunnablePassthrough.assign(docs=lambda d: ["d1"]).assign(
    answer=prompt | model() | StrOutputParser()
)
for chunk in chain.stream({"question": "q"}):
    print(chunk)

# a lambda that returns a Runnable streams through the returned Runnable
router = RunnableLambda(lambda x: model() | StrOutputParser())
print(list(router.stream("x")))

# a branch streams the branch it picked
branch = RunnableBranch(
    (lambda x: True, model() | StrOutputParser()),
    RunnableLambda(lambda x: "default"),
)
print(list(branch.stream("x")))

# a lambda that returns a plain value emits it at once
print(list((model() | StrOutputParser() | RunnableLambda(str.upper)).stream("x")))
Output8 lines
{'question': 'q'}
{'docs': ['d1']}
{'answer': 'one'}
{'answer': ' '}
{'answer': 'two'}
['one', ' ', 'two']
['one', ' ', 'two']
['ONE TWO']
  • assign streams the dict as it grows. The input keys arrive first ({'question': 'q'}), then docs as soon as it is computed, then answer piece by piece. This is the "stream the answer and return the sources" RAG pattern of 3.5: a UI can show the sources before the first token, and a client that merges the one-key chunks ends up with the same dict that invoke returns.
  • A lambda (or @chain function) that returns a Runnable streams through it, so the router of 3.7 does not break token streaming. A RunnableBranch streams the branch it chose in the same way.
  • The last line is the contrast: a lambda that returns a plain value, placed after the parser, still collapses the stream into one chunk.

The sample above shows what a streaming consumer is, but not what a plain invoke inside a step does. This sample, which needs langgraph as well, runs one model.invoke call inside a step under three different outer calls:

python
# auto_streaming.py: a model.invoke inside a step streams only when a streaming consumer is attached
import asyncio

from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda
from langgraph.graph import END, START, MessagesState, StateGraph


def make_model():
    return GenericFakeChatModel(messages=iter([AIMessage(content="one two three")]))


class TokenLog(BaseCallbackHandler):
    def __init__(self):
        self.tokens = []

    def on_llm_new_token(self, token, **kwargs):
        self.tokens.append(token)


# 1. a plain stream() on a lambda that calls model.invoke: no tokens reach the handler
model, log = make_model(), TokenLog()
list(RunnableLambda(lambda x: model.invoke(x)).stream("hi", config={"callbacks": [log]}))
print("plain stream, handler tokens:", log.tokens)

# 2. a graph node that calls model.invoke, streamed with stream_mode="messages"
model = make_model()
graph = StateGraph(MessagesState)
graph.add_node("n", lambda state: {"messages": [model.invoke(state["messages"])]})
graph.add_edge(START, "n")
graph.add_edge("n", END)
app = graph.compile()
chunks = app.stream({"messages": [("user", "hi")]}, stream_mode="messages")
print("graph messages mode:", [chunk.content for chunk, _meta in chunks])

# 3. the same lambda under astream_events: the model's token events appear
model = make_model()
step = RunnableLambda(lambda x: model.invoke(x))


async def main():
    events = [e["event"] async for e in step.astream_events("hi", version="v2")]
    print("astream_events:", events.count("on_chat_model_stream"), "token events")


asyncio.run(main())
Output3 lines
plain stream, handler tokens: []
graph messages mode: ['one', ' ', 'two', ' ', 'three']
astream_events: 5 token events

A plain stream on the lambda sent no tokens to the handler; the graph's messages mode and astream_events did receive them. The switch to the model's streaming internals happens when a streaming consumer is attached, not merely because the outer call is called stream.

7.3 astream_events v2: the event schema#

stream gives you the final output as it grows. When you also want to know what happened inside (which step started, which model is producing tokens, which tool is running), use astream_events:

text
Runnable.astream_events(input, config=None, *, version="v2",
    include_names=None, include_types=None, include_tags=None,
    exclude_names=None, exclude_types=None, exclude_tags=None, **kwargs)
    -> AsyncIterator[StreamEvent]

It is async only on a generic Runnable (7.5), and it yields a dict for every start, chunk and end of every step. Every event has the same keys (the sample prints them):

Key Meaning
event The event name, on_[type]_(start|stream|end)
name The name of the Runnable (its class, run_name or function name)
run_id A unique id for this run
parent_ids The ids of the runs above it (v2 only); its length is the depth in the tree
tags The run's tags (inherited ones included)
metadata The run's metadata
data The payload: input on start events, chunk on stream events, output on end events

The event names verified on 1.8.0 and in the source docs: on_chat_model_*, on_llm_* (text models), on_chain_*, on_prompt_*, on_parser_*, on_tool_start and on_tool_end, on_retriever_start and on_retriever_end, and on_custom_event (7.4). Here is the event stream of a prompt, a fake model and a parser:

python
# event_stream.py: the astream_events (v2) event stream of a prompt | model | parser chain
import asyncio
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

def make_chain():
    model = GenericFakeChatModel(messages=iter([AIMessage(content="one two")]))
    return ChatPromptTemplate.from_template("{q}") | model | StrOutputParser()

async def main():
    async for event in make_chain().astream_events({"q": "hi"}, version="v2"):
        data = event["data"]
        shown = data.get("chunk", data.get("output", ""))
        shown = getattr(shown, "content", shown)  # an AIMessageChunk shows its text
        print(f"{event['event']:<22} {event['name']:<20} depth={len(event['parent_ids'])} {shown!r}")
    print("keys of one event:", sorted(event))
    print("-- include_types=['chat_model'] --")
    async for event in make_chain().astream_events({"q": "hi"}, version="v2", include_types=["chat_model"]):
        print(event["event"])
    print("-- include_types=['prompt', 'parser'] --")
    async for event in make_chain().astream_events({"q": "hi"}, version="v2", include_types=["prompt", "parser"]):
        print(event["event"], event["name"])

asyncio.run(main())
Output32 lines
on_chain_start         RunnableSequence     depth=0 ''
on_prompt_start        ChatPromptTemplate   depth=1 ''
on_prompt_end          ChatPromptTemplate   depth=1 ChatPromptValue(messages=[HumanMessage(content='hi', additional_kwargs={}, response_metadata={})])
on_chat_model_start    GenericFakeChatModel depth=1 ''
on_chat_model_stream   GenericFakeChatModel depth=1 'one'
on_parser_start        StrOutputParser      depth=1 ''
on_parser_stream       StrOutputParser      depth=1 'one'
on_chain_stream        RunnableSequence     depth=0 'one'
on_chat_model_stream   GenericFakeChatModel depth=1 ' '
on_parser_stream       StrOutputParser      depth=1 ' '
on_chain_stream        RunnableSequence     depth=0 ' '
on_chat_model_stream   GenericFakeChatModel depth=1 'two'
on_parser_stream       StrOutputParser      depth=1 'two'
on_chain_stream        RunnableSequence     depth=0 'two'
on_chat_model_end      GenericFakeChatModel depth=1 'one two'
on_parser_end          StrOutputParser      depth=1 'one two'
on_chain_end           RunnableSequence     depth=0 'one two'
keys of one event: ['data', 'event', 'metadata', 'name', 'parent_ids', 'run_id', 'tags']
-- include_types=['chat_model'] --
on_chat_model_start
on_chat_model_stream
on_chat_model_stream
on_chat_model_stream
on_chat_model_end
-- include_types=['prompt', 'parser'] --
on_prompt_start ChatPromptTemplate
on_prompt_end ChatPromptTemplate
on_parser_start StrOutputParser
on_parser_stream StrOutputParser
on_parser_stream StrOutputParser
on_parser_stream StrOutputParser
on_parser_end StrOutputParser

Reading it:

  • The outermost run is the RunnableSequence at depth 0. Everything else is its child at depth 1.
  • The model's on_chat_model_stream events carry AIMessageChunks; the parser's on_parser_stream events carry the strings; and the sequence's own on_chain_stream events carry the final chunks. You can pick any layer to listen to.
  • on_chat_model_end carries the aggregated message ('one two'), and on_prompt_end the prompt value, so you can log exactly what was sent without a callback handler.
  • The filters work by type (include_types=["chat_model"] left only the model's events) and by name or tag (include_names, include_tags, and the exclude_ forms). The type strings are the middle of the event name: chat_model, llm, chain, prompt, parser, tool, retriever.

The tag filter is the important one in practice. A real chain often contains more than one model (a classifier and an answerer, or a query rewriter and a generator), and each emits on_chat_model_stream events. If you forward every one to the user's screen, they see the classifier's "billing" appear before the answer. Tag the model whose tokens the user should see, and filter on the tag. The previous sample (streaming_parallel.py) did exactly that. Its second output line used include_names=["StrOutputParser"] and got only the parser's five events (start, three chunks, end); the third line is the tag filter: a model tagged final was selected with include_tags=["final"], and only its events came back (they are all on_chat_model_* events, because tags are inherited by children of the tagged Runnable, not by its siblings, so the downstream parser, which is a sibling, did not carry the tag). The last line collects only the text of the on_chat_model_stream events, which is the standard way to build a token stream out of events.

7.4 Custom events#

A step can emit its own events, which is how you report progress from inside a long step. dispatch_custom_event(name, data, *, config=None) (sync) and adispatch_custom_event (async) are in langchain_core.callbacks. They appear in astream_events as on_custom_event and reach callback handlers' on_custom_event method (the 4.2 sample captured one):

python
# custom_events.py
import asyncio
from langchain_core.callbacks import adispatch_custom_event
from langchain_core.runnables import RunnableLambda, RunnableConfig

async def step(x: int, config: RunnableConfig) -> int:
    await adispatch_custom_event("progress", {"message": "half way"}, config=config)
    return x + 1

async def main():
    async for e in RunnableLambda(step).astream_events(1, version="v2"):
        if e["event"] == "on_custom_event":
            print("CUSTOM:", e["name"], e["data"], e["tags"])
        else:
            print(e["event"], e["name"])
    # without config in py3.11+
    async def no_cfg(x):
        await adispatch_custom_event("progress", {"n": 1})
        return x
    try:
        out = [e["event"] async for e in RunnableLambda(no_cfg).astream_events(1, version="v2")]
        print("no config ->", out)
    except Exception as ex:
        print("no config error:", type(ex).__name__, ex)
asyncio.run(main())
Output5 lines
on_chain_start step
CUSTOM: progress {'message': 'half way'} []
on_chain_stream step
on_chain_end step
no config -> ['on_chain_start', 'on_custom_event', 'on_chain_stream', 'on_chain_end']
  • The event arrives as CUSTOM: progress {'message': 'half way'} []: its name, its data and its tags.
  • Pass the step's config to the dispatch call: the docs say the call must receive the running Runnable's config. The sample's second half (a step with no config argument) emitted the event anyway on Python 3.13, because the config travels in a context variable in async code on 3.11 and later. Treat that as a convenience of recent Pythons, not a guarantee: the documented, portable form passes config=config. Omitting config also worked for a sync dispatch_custom_event inside a RunnableLambda (under invoke and under astream_events, on Python 3.13). It fails when the call is made outside any run, for example from a thread you started yourself: that raises RuntimeError: Unable to dispatch an adhoc event without a parent run id, and its message tells you to pass the config explicitly (passing config=config into the thread worked). Custom events exist in astream_events v2 and v3 only, not v1.
  • Keep the payload small and JSON-serializable: it is copied into events and traces.

7.5 Versions: v1 is deprecated, v3 is beta#

version= Status in langchain-core 1.8.0 Notes
"v1" Deprecated since 1.3.3, removal in 2.0.0 Emits astream_events version='v1' is deprecated. Use version='v2' or astream instead. Built on the older astream_log. No parent_ids, no custom events
"v2" The default and the one to use The schema in 7.3
"v3" Beta A typed, content-block-centred protocol supported only by chat models (BaseChatModel) and compiled LangGraph graphs. On a generic Runnable it raises NotImplementedError
python
# event_versions.py: astream_events versions, and the sync stream_events
import asyncio, warnings
from langchain_core.runnables import RunnableLambda

async def main():
    r = RunnableLambda(lambda x: x)
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        async for _ in r.astream_events(1, version="v1"):
            pass
    print("v1:", [str(w.message) for w in caught])
    try:
        # on a generic Runnable, v3 is an awaitable that raises when awaited
        await r.astream_events(1, version="v3")
    except NotImplementedError as e:
        print("v3:", str(e)[:130])

asyncio.run(main())
try:
    RunnableLambda(lambda x: x).stream_events(1, version="v2")
except NotImplementedError as e:
    print("sync:", e)
Output3 lines
v1: ["astream_events version='v1' is deprecated. Use version='v2' or astream instead."]
v3: astream_events(version='v3') is only supported on Runnable subclasses that implement the v3 streaming protocol (BaseChatModel, Com
sync: stream_events(version='v2') is not supported. Use astream_events() for v1/v2, or stream_events(version='v3') on a supported subclass.

Two surprises are visible. First, astream_events(version="v3") on a plain Runnable does not raise when you call it; it returns an awaitable, and the NotImplementedError is raised when you await it. Second, there is a sync stream_events method in 1.8.0, but for v1 and v2 it raises NotImplementedError and tells you to use astream_events; only stream_events(version="v3") on a supporting subclass works. So: for v2 events you must be in async code. The old astream_log (a stream of JSON-patch operations) still exists, and the docs prefer astream_events v2 or plain astream.

LangGraph graphs are Runnables, so agent.astream_events(...) works too, and create_agent renamed the graph's model node from agent (0.x) to model (1.x), which breaks old event filters written as include_names=["agent"] (08F.4). LangGraph also has its own stream modes (values, updates, messages, custom, debug), which are usually the better fit for graphs and agents: 08F.14.

7.6 Streaming a chain to a browser#

The common production shape is an async web endpoint that turns astream into server-sent events. This is illustrative (it needs fastapi and a provider key); the chain is the one from 3.8 with a streaming parser, and the endpoint maps chunks to SSE lines instead of forwarding raw events:

python
# sse_endpoint.py: stream a chain's text to a browser (illustrative: needs fastapi, a key)
import json
import logging

from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

load_dotenv()

logger = logging.getLogger(__name__)
app = FastAPI()
chain = (
    ChatPromptTemplate.from_messages([("system", "You are terse."), ("human", "{question}")])
    # this endpoint streams, so the SDK client owns retries: a with_retry here would be skipped (6.2)
    | init_chat_model("openai:gpt-6-luna", max_retries=2, timeout=30)
    | StrOutputParser()
).with_config(run_name="answer_chain", tags=["api"])


@app.get("/ask")
async def ask(q: str) -> StreamingResponse:
    async def sse():
        try:
            async for piece in chain.astream({"question": q}):
                yield f"data: {json.dumps({'token': piece})}\n\n"
            yield "event: done\ndata: {}\n\n"
        except Exception:  # log the real error server-side; send the client a generic one
            logger.exception("stream failed")
            yield "event: error\ndata: {\"message\": \"generation failed\"}\n\n"

    # no-cache keeps proxies from storing the stream; X-Accel-Buffering is nginx's "do not buffer" switch
    return StreamingResponse(
        sse(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )
Example output · illustrative8 lines
data: {"token": "Refunds"}

data: {"token": " take"}

data: {"token": " 5 to 7 days."}

event: done
data: {}

Details that matter in production: send errors as an event (once the response has started, you can no longer change the HTTP status; the sample logs the real exception and sends the client a generic message), and put Cache-Control: no-cache on SSE responses, as the sample does, with the buffering switch your proxy needs (X-Accel-Buffering: no is nginx's; check yours). Stop the model call when the client disconnects, otherwise you pay for tokens nobody reads: Starlette (the layer under FastAPI) cancels the generator when the connection drops, which raises asyncio.CancelledError inside the async for at the next await, so that is the place to stop upstream work (put cleanup in a finally, and do not swallow the cancellation; the details depend on your server, so test it). The retry policy of this endpoint is the client's max_retries=2, set explicitly on the model: with_retry would not apply to chain.astream, while the client's retries do (both measured in 6.2). They cover the request that opens the stream. A failure after the first token reaches the except branch, which is why the endpoint sends an error event; add a fallback model (6.4) if you need another provider for outages. The browser side is Module 13A.

7.7 Which streaming method when#

You want Use
The final text as it grows, from a chain chain.astream (or stream in sync code)
Intermediate steps, tool starts, tokens from one specific model, progress astream_events(version="v2") with filters
Streaming from a LangGraph graph or an agent The graph's stream modes (08F.14)
Typed content-block streaming from a chat model astream_events(version="v3") on the model (beta), or the model's own streaming API (08F.5)
Something that works on every version astream

Part 8: Memory wrappers and legacy chains (how to read old LCEL code)#

Reference

This is the legacy part of the lesson. Nothing here is the recommended way to build new code; it exists so that you can read the tutorials, blog posts and codebases written between 2023 and 2025 and translate them.

8.1 RunnableWithMessageHistory#

In the LCEL era, memory was added to a chain by wrapping it in RunnableWithMessageHistory(runnable, get_session_history, input_messages_key=..., history_messages_key=...). You supply a factory that returns a chat-message-history object for a session id; the wrapper loads the history into the prompt's MessagesPlaceholder before each call and appends the new turn afterwards. The session id travels in the config, under configurable.

python
import warnings
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory

prompt = ChatPromptTemplate.from_messages([("system", "Be brief."), MessagesPlaceholder("history"), ("human", "{input}")])
model = GenericFakeChatModel(messages=iter([AIMessage(content="Hi Ada"), AIMessage(content="Your name is Ada")]))
stores = {}
def get_history(session_id: str):
    return stores.setdefault(session_id, InMemoryChatMessageHistory())
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    chain = RunnableWithMessageHistory(prompt | model, get_history, input_messages_key="input", history_messages_key="history")
    get_history("warm-up")
for w in caught:
    print("WARNING:", w.category.__name__, "-", str(w.message)[:110])
cfg = {"configurable": {"session_id": "s1"}}
print(chain.invoke({"input": "I am Ada"}, config=cfg).content)
print(chain.invoke({"input": "Who am I?"}, config=cfg).content)
print([ (m.type, m.content) for m in stores["s1"].messages])
try:
    chain.invoke({"input": "x"})
except Exception as e: print(type(e).__name__, str(e)[:200])
Output6 lines
WARNING: LangChainDeprecationWarning - RunnableWithMessageHistory is deprecated. Use LangGraph's built-in persistence instead.
WARNING: LangChainDeprecationWarning - The class `InMemoryChatMessageHistory` was deprecated in LangChain 1.6.4 and will be removed in 2.0.0 See the
Hi Ada
Your name is Ada
[('human', 'I am Ada'), ('ai', 'Hi Ada'), ('human', 'Who am I?'), ('ai', 'Your name is Ada')]
ValueError Missing keys ['session_id'] in config['configurable'] Expected keys are ['session_id'].When using via .invoke() or .stream(), pass in a config; e.g., chain.invoke({'input': 'foo'}, {'configurable': {'

What it shows:

  • It is deprecated. Importing and constructing it on 1.8.0 raised a LangChainDeprecationWarning: "RunnableWithMessageHistory is deprecated. Use LangGraph's built-in persistence instead." The history class it is normally paired with, InMemoryChatMessageHistory, is deprecated too, with a pointer to the short-term memory docs (the version number inside that warning, 1.6.4, is printed exactly as the library emits it; check the changelog if it matters to you).
  • It still works: the second call knew the name from the first, because the history was loaded from the store for session s1.
  • Forgetting the session id is a clear error: Missing keys ['session_id'] in config['configurable'] (the wrapper "must always be called with a config that contains the appropriate parameters for the chat message history factory").

What replaces it. Memory is now a checkpointer passed when the agent or graph is compiled, plus a thread_id in the call config. The same two-turn conversation, current style (this one was run too; it needs langchain and langgraph, and a fake model stands in for a provider):

python
# checkpointer.py: the current replacement for RunnableWithMessageHistory (no key)
from langchain.agents import create_agent
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langgraph.checkpoint.memory import InMemorySaver

fake = GenericFakeChatModel(messages=iter([AIMessage(content="Hi Ada"), AIMessage(content="Your name is Ada")]))
agent = create_agent(model=fake, checkpointer=InMemorySaver())

cfg = {"configurable": {"thread_id": "s1"}}
agent.invoke({"messages": [{"role": "user", "content": "I am Ada"}]}, cfg)
result = agent.invoke({"messages": [{"role": "user", "content": "Who am I?"}]}, cfg)
print([(m.type, m.content) for m in result["messages"]])
Output1 line
[('human', 'I am Ada'), ('ai', 'Hi Ada'), ('human', 'Who am I?'), ('ai', 'Your name is Ada')]

The state of the thread (all four messages) comes back from the checkpointer on each call, and the checkpointer is swappable (in-memory here; SQLite or Postgres in production) without touching the chain. Checkpointers, threads, time travel and the long-term Store are 08F.11; the general memory design space (buffer, summary, retrieval) is 08B.2.

8.2 The legacy chain classes and what replaced them#

Before LCEL, and for a while alongside it, LangChain had chain classes: objects such as LLMChain with their own run, predict and __call__ methods. LangChain 1.0 removed them from langchain; they live in langchain-classic (08F.4, 3.8), and importing the common ones from there works (checked on this install: LLMChain, create_retrieval_chain and create_history_aware_retriever import from langchain_classic.chains; create_stuff_documents_chain is not exported there and is imported from langchain_classic.chains.combine_documents). The deprecation markers verified in the source carry the replacement advice:

Legacy class (in langchain_classic.chains, except as noted) Marked deprecated Replace with
LLMChain since 0.1.17, removal 2.0.0; its notice says "RunnableSequence, e.g., prompt | llm" prompt | model | parser
SequentialChain, SimpleSequentialChain (legacy) a | b | c, with RunnablePassthrough.assign for the multi-key plumbing
TransformChain (legacy) A RunnableLambda
ConversationChain since 0.2.7 A model plus a checkpointer and a thread_id (08F.11)
ConversationBufferMemory and the other memory classes (in langchain_classic.memory) since 0.3.1 A checkpointer, message trimming and summarization (08B.2, 08F.11)
RetrievalQA since 0.1.17 (the class that carries the create_agent notice, with a pointer to the RAG docs) A retrieval chain (3.8) for one-shot RAG, or create_agent with a retrieval tool (08F.9)
ConversationalRetrievalChain since 0.1.17; its notice points to create_history_aware_retriever together with create_retrieval_chain (both still in langchain_classic) The same pair for a chain that rewrites follow-up questions from the history, or an agent with a retrieval tool (08F.9)

The rows marked "(legacy)" are from the course's own mapping rather than a verified deprecation marker, so check the class's docstring if you need to cite one. Exact imports for the two that trip people up: from langchain_classic.chains.combine_documents import create_stuff_documents_chain and from langchain_classic.memory import ConversationBufferMemory. The rule behind all of them is the one from 08F.4: learn the Runnable form and you can translate any chain class.

8.3 Reading an old LCEL tutorial: a translation table#

Most old tutorials fail for one of a small set of reasons. This table lists them with what each does on langchain 1.5 and langchain-core 1.8:

In the tutorial On a current install Use instead
from langchain.schema.runnable import RunnablePassthrough ModuleNotFoundError from langchain_core.runnables import RunnablePassthrough
from langchain.prompts import ChatPromptTemplate ModuleNotFoundError from langchain_core.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser ModuleNotFoundError from langchain_core.output_parsers import StrOutputParser
from langchain.chat_models import ChatOpenAI (or the langchain_community variant) ImportError for the first; the second comes from langchain-community, which is sunset and archived (08F.4, 3.7): it may still import, but nothing in it is maintained from langchain_openai import ChatOpenAI, or init_chat_model("openai:...") (08F.5)
from langchain.schema.runnable import RunnableMap or RunnableMap({...}) ModuleNotFoundError for the import from langchain_core.runnables import RunnableParallel (RunnableMap is only an alias of it, and still importable from langchain_core.runnables)
{"context": itemgetter("question") | retriever, "question": itemgetter("question")} at the head of a chain Works: a dict next to a Runnable becomes a RunnableParallel, and itemgetter(...) is a callable that becomes a RunnableLambda (3.2) lambda d: d["question"], or RunnablePassthrough.assign(...) and .pick(...) (3.5)
model.bind(stop=["\n"]) | parser, bind in the middle of a pipe Works (bind returns a Runnable, Part 5) Unchanged; bind is current
chain.run("text"), chain.predict(q="text") AttributeError: 'RunnableSequence' object has no attribute 'run' chain.invoke(...)
chain({"q": "text"}) (calling the object) TypeError: 'RunnableSequence' object is not callable chain.invoke({"q": "text"})
LLMChain(llm=..., prompt=...) not in langchain; in langchain_classic prompt | model
RunnableWithMessageHistory(...) Works, deprecated Checkpointer and thread_id (8.1)
chain.astream_events(..., version="v1") Works, deprecation warning version="v2" (7.5)
AgentExecutor plus | pipes gone from langchain create_agent (08F.8)
hub.pull("...") from langchain.hub gone from langchain The LangSmith prompt hub through the langsmith client (08F.6)

The run, predict and call-the-object rows are real output from this sample:

python
# legacy_calls.py: old call styles do not exist on Runnables
from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

chain = ChatPromptTemplate.from_template("{q}") | FakeListChatModel(responses=["ok"]) | StrOutputParser()
print("invoke:", chain.invoke({"q": "hi"}))
for label, call in [
    ("chain.run('hi')", lambda: chain.run("hi")),
    ("chain.predict(q='hi')", lambda: chain.predict(q="hi")),
    ("chain({'q': 'hi'})", lambda: chain({"q": "hi"})),
]:
    try:
        call()
    except Exception as e:
        print(f"{label:<24} -> {type(e).__name__}: {e}")
Output4 lines
invoke: ok
chain.run('hi')          -> AttributeError: 'RunnableSequence' object has no attribute 'run'
chain.predict(q='hi')    -> AttributeError: 'RunnableSequence' object has no attribute 'predict'
chain({'q': 'hi'})       -> TypeError: 'RunnableSequence' object is not callable

The old call styles belong to the chain classes, not to Runnables. If a tutorial uses them, you are reading pre-LCEL code, and the safe translation is to rebuild the pipeline as prompt | model | parser and call .invoke.


Part 9: Testing chains without a provider#

Deep-dive

A chain is a function, and you test it like one: no network, no key, deterministic. The rules from 03.10 (mock at the boundary, test the plumbing and not the model) apply, and LCEL makes the boundary easy to cut, because the model is one Runnable in a pipe and any other Runnable can stand in for it.

9.1 The fake models#

langchain_core.language_models ships fake chat models for exactly this:

Class Behaviour Good for
FakeListChatModel(responses=[...]) Returns the responses in order and cycles when it runs out; streams one character at a time The simplest "the model says X" test
GenericFakeChatModel(messages=iter([...])) Returns the next message from an iterator you supply (AIMessage objects, which can carry tool_calls); streams word by word Scripted multi-turn conversations and streaming tests
FakeMessagesListChatModel(responses=[...]) Returns message objects in order, cycling (a third call returned the first response again) Tests that need exact message objects
ParrotFakeChatModel Echoes the input message back Tests where you want to see exactly what reached the model

Two warnings from the runs:

python
# tool_fake.py: a fake chat model that supports tool calls, for testing agents without a key
from langchain.agents import create_agent
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.tools import tool


class ToolFakeChatModel(GenericFakeChatModel):
    """GenericFakeChatModel raises NotImplementedError in bind_tools; this subclass accepts it."""

    def bind_tools(self, tools, **kwargs):
        return self  # the scripted replies already say which tool to call


@tool
def order_status(order_id: str) -> str:
    """Look up an order."""
    return f"order {order_id}: shipped"


script = iter([
    AIMessage(content="", tool_calls=[{"name": "order_status", "args": {"order_id": "A-1042"}, "id": "call_1"}]),
    AIMessage(content="Your order A-1042 has shipped."),
])
agent = create_agent(model=ToolFakeChatModel(messages=script), tools=[order_status])
result = agent.invoke({"messages": [{"role": "user", "content": "Where is A-1042?"}]})
print([(m.type, m.content) for m in result["messages"]])
Output1 line
[('human', 'Where is A-1042?'), ('ai', ''), ('tool', 'order A-1042: shipped'), ('ai', 'Your order A-1042 has shipped.')]

The four messages are the user turn, the scripted tool call (empty content, a call to order_status), the tool's result, and the scripted final answer. 11A.5 covers testing agents and graphs in depth, including other test doubles.

9.2 A test file that was run#

This file uses plain pytest and asyncio.run (so there is no async plugin to install). It tests the chain's output, the prompt that reaches the model, streaming, the events, retries, fallbacks and the run tree. All of it ran on 14 November 2026 with langchain-core 1.8.0 and pytest 9.2.0:

python
# test_lcel.py: keyless tests for an LCEL chain (run with: uv run pytest -q)
import asyncio

import pytest
from langchain_core.language_models import FakeListChatModel, GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda
from langchain_core.tracers.context import collect_runs


def build_chain(model):
    prompt = ChatPromptTemplate.from_messages([("system", "You are terse."), ("human", "{question}")])
    return prompt | model | StrOutputParser()


def test_chain_returns_model_text():
    chain = build_chain(FakeListChatModel(responses=["Paris"]))
    assert chain.invoke({"question": "Capital of France?"}) == "Paris"


def test_missing_variable_is_an_error():
    chain = build_chain(FakeListChatModel(responses=["x"]))
    with pytest.raises(KeyError):
        chain.invoke({"wrong": "?"})


def test_prompt_contains_the_question():
    seen = []
    spy = RunnableLambda(lambda prompt_value: seen.append(prompt_value.to_messages()) or prompt_value)
    prompt = ChatPromptTemplate.from_messages([("system", "You are terse."), ("human", "{question}")])
    chain = prompt | spy | FakeListChatModel(responses=["ok"]) | StrOutputParser()
    chain.invoke({"question": "Where is my order?"})
    assert [m.type for m in seen[0]] == ["system", "human"]
    assert seen[0][1].content == "Where is my order?"


def test_streaming_yields_several_chunks():
    model = GenericFakeChatModel(messages=iter([AIMessage(content="one two three")]))
    chunks = list(build_chain(model).stream({"question": "?"}))
    assert len(chunks) > 1 and "".join(chunks) == "one two three"


def test_events_include_model_tokens():
    model = GenericFakeChatModel(messages=iter([AIMessage(content="hello there")]))

    async def collect():
        return [e async for e in build_chain(model).astream_events({"question": "?"}, version="v2")]

    events = asyncio.run(collect())
    text = "".join(e["data"]["chunk"].content for e in events if e["event"] == "on_chat_model_stream")
    assert text == "hello there"


def test_retry_recovers():
    calls = {"n": 0}

    def flaky(x):
        calls["n"] += 1
        if calls["n"] < 2:
            raise ConnectionError("blip")
        return x

    step = RunnableLambda(flaky).with_retry(stop_after_attempt=2, wait_exponential_jitter=False)
    assert step.invoke("ok") == "ok" and calls["n"] == 2


def test_fallback_used():
    bad = RunnableLambda(lambda _: 1 / 0)
    assert bad.with_fallbacks([RunnableLambda(lambda _: "safe")]).invoke(None) == "safe"


def test_run_tree_has_the_expected_steps():
    chain = build_chain(FakeListChatModel(responses=["x"]))
    with collect_runs() as cb:
        chain.invoke({"question": "?"})
    assert [r.name for r in cb.traced_runs[0].child_runs] == ["ChatPromptTemplate", "FakeListChatModel", "StrOutputParser"]
Output · of uv run pytest -v (the progress percentages are removed for width)9 lines
test_lcel.py::test_chain_returns_model_text PASSED
test_lcel.py::test_missing_variable_is_an_error PASSED
test_lcel.py::test_prompt_contains_the_question PASSED
test_lcel.py::test_streaming_yields_several_chunks PASSED
test_lcel.py::test_events_include_model_tokens PASSED
test_lcel.py::test_retry_recovers PASSED
test_lcel.py::test_fallback_used PASSED
test_lcel.py::test_run_tree_has_the_expected_steps PASSED
============================== 8 passed in 0.06s ===============================

Techniques in this file worth copying:

  1. The spy step. RunnableLambda(lambda pv: seen.append(...) or pv) sits between two steps, records what passed through, and returns it unchanged. It tests "the right prompt reached the model" without a model.
  2. collect_runs. Assert on the run tree: the names and order of the steps. A refactor that drops a step fails the test.
  3. Stream and events tests with a fake model. Check that more than one chunk arrives and that joining the chunks gives the text. Streaming regressions (a lambda inserted in front of the parser) show up here, not in production.
  4. Retry and fallback tests with counters. Count the calls to a function that fails on demand.

Part 10: When LCEL is the right tool, and when it is not#

10.1 What the official sources say#

There is no official LCEL-versus-LangGraph decision page, so here is what the official sources do state, and where this lesson goes beyond them.

  • The history page says that in October 2024 LangGraph became the preferred way to build any application that is more than a single LLM call, and that most chains and agents were marked deprecated in LangChain with guides to migrate them to LangGraph.
  • For 1.0 (October 2025) the same page says all chains and agents were replaced by one high-level abstraction, an agent built on top of LangGraph, with the old chains kept in langchain-classic.
  • The products page describes LangGraph as the runtime (durable execution, streaming, human-in-the-loop, persistence, low-level control) and LangChain as the framework (abstractions and integrations).
  • The LangGraph overview describes workflows built from shared state, nodes and edges that "mix deterministic steps with LLM-driven steps".

Nothing in those sources says LCEL is deprecated, and nothing says to stop using it: the Runnable protocol is the substrate that models, tools, prompts and graphs all share. What they say is that applications beyond a single call are built on LangGraph, usually through create_agent. The decision rule below is this lesson's synthesis of that guidance with how the pieces behave when you run them; it is not an official quote.

10.2 A decision procedure#

flowchart TD
    start(["I need to build an LLM feature"]) --> q1{"Does the model choose<br/>tools or loop?"}
    q1 -- yes --> agent["create_agent (08F.8)"]
    q1 -- no --> q2{"Need persistence, approvals,<br/>resume, or shared state<br/>across many steps?"}
    q2 -- yes --> lg["LangGraph StateGraph (08F.10)"]
    q2 -- no --> q3{"Fixed steps, no loop,<br/>one or two decisions?"}
    q3 -- yes --> lcel["LCEL chain (this lesson)"]
    q3 -- no --> lg
    agent -. "inside a node" .-> lcel
    lg -. "inside a node" .-> lcel
Your situation Use Why
One model call with a prompt and a parser prompt | model | parser (or the provider SDK, Module 03) A chain is the lightest form; no loop, no state
A fixed pipeline: classify, then one of two prompts; or retrieve, then answer LCEL with at most one RunnableBranch or routing function Each step runs once, in a known order, and the shape is visible
Fan-out and fan-in over independent calls (two retrievers, three summaries) RunnableParallel This is what it is for
Pre- and post-processing around a model, or around an agent LCEL steps Small, testable, composable
The model decides which tool to call, possibly many times create_agent (08F.8) A loop with a stop condition: LCEL has no loop
A workflow with a loop (draft, check, redraft until it passes) LangGraph Cycles and loop limits are first-class there
Human approval, pause and resume, or recovery after a crash LangGraph with a checkpointer (08F.11, 08F.12) Persistence and interrupts are the runtime's job
Several steps that share and update state, and that you must inspect step by step LangGraph Typed state with reducers, instead of a dict threaded by hand
Multiple cooperating agents LangGraph subgraphs (08F.13) Composition with isolated state

10.3 The signs that a chain has outgrown LCEL#

Chains age badly in predictable ways. Each of these is a symptom, and each has a LangGraph answer:

Symptom in your chain What is really going on LangGraph answer
A second RunnableBranch inside the first, then a third You are encoding a state machine in nested expressions Conditional edges between named nodes
RunnablePassthrough.assign with six or more keys, and step 5 reads a key step 2 wrote Hidden, untyped shared state A typed state schema with reducers
A retry wrapped around three steps, one of which sends an email At-least-once side effects (6.3) Per-node retry policies and checkpointed steps
"If the check fails, call the model again" implemented by recursion or by a Python while around chain.invoke A loop with no visibility or limit A cycle in the graph, with a recursion limit
"Wait for the manager to approve, then continue" You need to pause a run and resume it later, maybe days later interrupt and a checkpointer
You want to see which step the run was on when it crashed LCEL has no durable record of progress Checkpoints and state history
RunnableWithMessageHistory Deprecated memory wrapper A checkpointer and thread ids

10.4 LCEL inside LangGraph, and LangGraph inside LCEL#

The two are not alternatives, they nest. A compiled graph is a Runnable (checked below), so it can be a step in a chain, and a node of a graph is an ordinary function that can call a chain. Run both directions:

python
from typing import TypedDict
from langchain_core.runnables import Runnable, RunnableLambda
from langchain_core.runnables.config import DEFAULT_RECURSION_LIMIT
from langgraph.graph import StateGraph, START, END
from langgraph.errors import GraphRecursionError

class S(TypedDict):
    n: int

def inc(s: S) -> S: return {"n": s["n"] + 1}
g = StateGraph(S)
g.add_node("inc", inc)
g.add_edge(START, "inc")
g.add_conditional_edges("inc", lambda s: END if s["n"] >= 5 else "inc")
app = g.compile()
print("graph is a Runnable:", isinstance(app, Runnable), type(app).__name__)
print(app.invoke({"n": 0}), app.batch([{"n": 3}, {"n": 4}]))
print("DEFAULT_RECURSION_LIMIT (core):", DEFAULT_RECURSION_LIMIT)
try:
    app.invoke({"n": 0}, config={"recursion_limit": 3})
except GraphRecursionError as e:
    print("GraphRecursionError:", str(e)[:120])
# LCEL chain as a node, graph as a step in an LCEL chain
shout = RunnableLambda(lambda d: {"n": d["n"] * 10})
print((RunnableLambda(lambda x: {"n": x}) | app | shout).invoke(0))
Output5 lines
graph is a Runnable: True CompiledStateGraph
{'n': 5} [{'n': 5}, {'n': 5}]
DEFAULT_RECURSION_LIMIT (core): 25
GraphRecursionError: Recursion limit of 3 reached without hitting a stop condition. You can increase the limit by setting the `recursion_limi
{'n': 50}
  • graph is a Runnable: True CompiledStateGraph: the compiled graph passes isinstance(app, Runnable).
  • app.invoke(...) and app.batch(...) work with the same interface as any chain; batch ran the two inputs through the loop independently (both ended at n = 5).
  • The graph has a loop (inc routes back to itself until n >= 5), the thing LCEL cannot express. recursion_limit=3 made it stop with a GraphRecursionError that tells you how to raise the limit. The core default printed on line three, 25, is for plain Runnables; the graph's own default is far higher (4.4).
  • (RunnableLambda(...) | app | shout).invoke(0) returned {'n': 50}: the graph is the middle step of a pipe; a lambda turned the number into the graph's input state, and another post-processed its output.

The other direction, a chain used inside a node, is the everyday pattern. The node is an ordinary function that takes the state (and, optionally, the config), calls an LCEL chain and returns a state update. A handler passed at call time sees the whole nested tree:

python
# node_with_chain.py: an LCEL chain inside a LangGraph node, and the config that links them
from typing import TypedDict

from langchain_core.language_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_core.callbacks import BaseCallbackHandler
from langgraph.graph import END, START, StateGraph

draft_chain = (
    ChatPromptTemplate.from_template("Draft a reply about: {topic}")
    | FakeListChatModel(responses=["Thanks for writing; your refund is on its way."])
    | StrOutputParser()
)

class State(TypedDict):
    topic: str
    draft: str

def draft_node(state: State, config: RunnableConfig) -> dict:
    # pass config on, so the chain's runs nest under this node in the trace
    return {"draft": draft_chain.invoke({"topic": state["topic"]}, config)}

builder = StateGraph(State)
builder.add_node("draft", draft_node)
builder.add_edge(START, "draft")
builder.add_edge("draft", END)
graph = builder.compile()

class Tree(BaseCallbackHandler):
    def __init__(self): self.depth = {}; self.lines = []
    def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None, name=None, **kw):
        d = self.depth.get(parent_run_id, -1) + 1
        self.depth[run_id] = d
        self.lines.append("  " * d + str(name))
print(graph.invoke({"topic": "refund"}))

h = Tree()
graph.invoke({"topic": "refund"}, config={"callbacks": [h]})  # a call-time handler sees every nested run
print("\n".join(h.lines))
Output6 lines
{'topic': 'refund', 'draft': 'Thanks for writing; your refund is on its way.'}
LangGraph
  draft
    RunnableSequence
      ChatPromptTemplate
      StrOutputParser

The tree is LangGraph, then the draft node, then the chain's RunnableSequence with its prompt and parser (the fake model appears as a chat-model event, which this handler does not print). In the runs here the nesting also appeared without passing config into the chain, because the context carries it on Python 3.11 and later; the node above passes it anyway so the code does not depend on that.

The practical lesson: use LCEL for the pieces and LangGraph for the control flow. Prompts, parsers, retrievers and fan-out stay as chains; the loop, the approval and the persistence belong to the graph, and a create_agent agent is itself such a graph (08F.4, 7.2).

10.5 Translating a chain to a graph#

When a chain does outgrow itself, the translation is mechanical. This is the map you will use in 08F.10:

In the chain In the graph
RunnableLambda step A node (a function from state to a state update)
The dict threaded through assign A state schema (TypedDict or Pydantic) with reducers
RunnableBranch, a routing function Conditional edges (add_conditional_edges)
RunnableParallel Parallel branches from one node, merged by a reducer
.with_retry(...) A node-level RetryPolicy (08F.12)
RunnableWithMessageHistory A checkpointer and thread_id (08F.11)
astream_events The graph's stream modes (08F.14)
with_config(run_name=..., tags=...) The same config on the compiled graph
collect_runs, callbacks The same; the graph is a Runnable

The framework-neutral questions of 08F.1's checklist apply to this choice as to any other: would a plain function do, and what does the abstraction cost you? 08F.15 collects the production patterns and the 0.x to 1.x migration steps.

10.6 Anti-patterns#

  1. One giant chain. Twelve steps joined with |, three dicts, two branches. Nobody can see which step is wrong. Split it into named sub-chains, test each, and compose; if it still needs a diagram to read, it is a graph.
  2. RunnableLambda for everything. A lambda breaks streaming (7.2), hides step names in traces and is untyped. Use real functions with names, RunnableGenerator where streaming matters, and the typed building blocks (prompts, parsers) where they exist.
  3. Hidden state in closures or globals. A counter, a cache or a client captured by a step behaves differently under batch and across async tasks (2.3, 2.4).
  4. Retrying across side effects (6.3).
  5. Unbounded loops by recursion. Use a graph cycle with a limit, or create_agent with ModelCallLimitMiddleware.
  6. Routing on unconstrained model text (3.7).
  7. Using a chain where one SDK call would do. 08F.4, 7.4 is honest about what a framework costs; a single client.responses.create(...) (Module 03) is sometimes the right answer, and the price of LCEL is a dependency tree and one more abstraction to learn.
  8. Treating LCEL tutorials as current. Date them (8.3), then translate.

10.7 A note on JavaScript#

The JavaScript package @langchain/core has the same Runnable vocabulary (RunnableLambda, RunnableSequence, RunnableParallel) under @langchain/core/runnables, with .pipe() for composition. The | operator does not exist in JavaScript, so prompt.pipe(model) is the form there. This course is Python only; check the JavaScript docs for parity of features such as astream_events.


Part 11: Debugging a chain#

Deep-dive

11.1 The checklist#

When a chain misbehaves, work from the outside in:

  1. Run each step alone. prompt.invoke(x), then model.invoke(<result>), then parser.invoke(<result>). The step whose output surprises you is the culprit. (Fresher habit number one: this works because every step is a Runnable.)
  2. Print the shapes. The most common bug is a step receiving a different type than you thought: a message where you expected a string, a dict where you expected a list.
  3. Inspect the schema and the graph. chain.input_schema.model_json_schema() and chain.get_graph().print_ascii() (2.6) show what the chain thinks it is.
  4. Look at the trace. collect_runs locally (4.3), LangSmith in a deployed service. Every step's input and output, and where the time went, are there.
  5. Spy. Insert a pass-through RunnableLambda that prints or records what flows by (9.2).
  6. Isolate the model. Swap the real model for a fake one; if the bug stays, it is your plumbing.

11.2 Real error messages#

All five of these were produced by running the code on 1.8.0 (only the first line of each message is shown):

python
# chain_errors.py: the errors you will actually meet, with their real messages
from langchain_core.language_models import FakeListChatModel
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda

model = FakeListChatModel(responses=["hello there"])
prompt = ChatPromptTemplate.from_template("Say {word}")

def attempt(label, fn):
    try:
        print(f"{label}: {fn()!r}")
    except Exception as e:
        print(f"{label}: {type(e).__name__}: {str(e).splitlines()[0]}")

attempt("1 missing variable   ", lambda: (prompt | model).invoke({"wrong": "x"}))
attempt("2 forgot the parser  ", lambda: (prompt | model | RunnableLambda(lambda s: s.upper())).invoke({"word": "hi"}))
attempt("3 bare str, 2 vars   ", lambda: ChatPromptTemplate.from_template("{a} {b}").invoke("x"))
attempt("4 dict into a lambda ", lambda: (RunnableLambda(lambda d: d["name"])).invoke("Ada"))
attempt("5 wrong key in dict  ", lambda: (RunnableLambda(lambda d: d["name"])).invoke({"nmae": "Ada"}))
Output5 lines
1 missing variable   : KeyError: "Input to ChatPromptTemplate is missing variables {'word'}.  Expected: ['word'] Received: ['wrong']\nNote: if you intended {word} to be part of the string and not a variable, please escape it with double curly braces like: '{{word}}'.\nFor troubleshooting, visit: https://docs.langchain.com/oss/python/langchain/errors/INVALID_PROMPT_INPUT "
2 forgot the parser  : AttributeError: 'AIMessage' object has no attribute 'upper'
3 bare str, 2 vars   : TypeError: Expected mapping type as input to ChatPromptTemplate. Received <class 'str'>.
4 dict into a lambda : TypeError: string indices must be integers, not 'str'
5 wrong key in dict  : KeyError: 'name'
Message Cause Fix
KeyError: "Input to ChatPromptTemplate is missing variables {'word'}..." (1) The input dict lacks a prompt variable; the message lists expected and received keys and links to the official INVALID_PROMPT_INPUT page Pass the right keys. If you meant a literal {word}, write {{word}}
AttributeError: 'AIMessage' object has no attribute 'upper' (2) A step after the model expected a string, but nothing converted the message Add StrOutputParser() after the model
TypeError: Expected mapping type as input to ChatPromptTemplate (3) A bare string was passed to a prompt with more than one variable Pass a dict
TypeError: string indices must be integers (4) A step that expects a dict received a string Check what the previous step returned
KeyError: 'name' (5) A dict key is misspelt or missing between steps Print the dict; consider a Pydantic model for the step boundary
ValueError: RunnableBranch requires at least two branches A branch with only a default Use at least one condition and a default, or just call the function
RecursionError: Recursion limit reached when invoking ... Nested Runnables deeper than recursion_limit (25) Raise it, or switch to a graph cycle (4.4)
ValueError: Missing keys ['session_id'] in config['configurable'] RunnableWithMessageHistory called without its session id Pass config={"configurable": {"session_id": ...}}; better, migrate (8.1)
ImportError: Install grandalf to draw graphs print_ascii needs an optional package uv add grandalf, or use draw_mermaid()
NotImplementedError: astream_events(version='v3') is only supported on ... v3 on a plain Runnable Use version="v2" (7.5)
NotImplementedError from bind_tools on a fake model GenericFakeChatModel has no tool binding The subclass in 9.1
No streaming, one chunk at the end A non-streaming step (a RunnableLambda, a parser that needs the whole text) in the chain Convert it to a generator, or move it after the stream (7.2)
An event stream full of tokens from the wrong model Several chat models in the chain Tag the one you want and filter with include_tags (7.3)
Three payments for one order A with_retry around a side-effecting step Retry the smallest unit and make the effect idempotent (6.3)
Retry never fires when streaming; the first transient error reaches the caller with_retry is bypassed by stream, astream and astream_events Set max_retries on the model (it does apply to a stream), or restart the stream yourself before sending anything (6.2)
A fallback did not help after the answer had started with_fallbacks switches only before the first chunk Handle a mid-stream error in the application (6.4, 7.6)
A StopIteration with no message from a fake model The scripted replies ran out One reply per expected call, or FakeListChatModel (9.1)

Common misconceptions#

Misconception Reality
"LCEL is deprecated, so I should never use |." The Runnable protocol and the pipe are the foundation of langchain-core and are not deprecated. What was retired is building whole applications and agents out of chains, and the old chain classes (LLMChain, ConversationChain, ...). prompt | model | parser is current (1.3).
"LCEL is the same as LangChain." It is one layer of one package (langchain-core). LangChain 1.x, create_agent and LangGraph sit above it, and every compiled graph is itself a Runnable (1.2, 10.4).
"A Runnable is a chat model." A model is one kind of Runnable. Prompts, parsers, retrievers, tools, your functions and graphs are Runnables too. Embeddings and vector stores are not (1.2).
"{...} | {...} builds a parallel step." Two dict literals are Python's dict merge. At least one operand must already be a Runnable, or write RunnableParallel(...) (3.2).
"Chains stream automatically." Only if every step handles chunks. One RunnableLambda that returns a plain value buffers everything after it into a single chunk; a lambda that returns a Runnable, a RunnableBranch and assign all keep streaming (7.2).
"batch is sequential invoke in a loop." It runs the calls concurrently, preserves input order, and fails as a whole unless you pass return_exceptions=True; cap it with max_concurrency (2.3).
"run_name, tags and metadata all propagate to sub-steps." Tags and metadata do; run_name does not (4.1).
"A callback in a model's constructor sees the whole chain." Only call-time callbacks in the config are inherited by every step (4.2).
"The recursion limit is 25." For plain Runnables, yes. A compiled LangGraph graph, and therefore an agent from create_agent, defaults to 10,007 super-steps (4.4).
"with_retry retries network errors." By default it retries every exception, including your bugs and validation errors, three times in total. Restrict it (6.2).
"Wrapping the whole chain in with_retry is safest." It re-runs steps that already succeeded, including side effects. Retry the smallest unit (6.3).
"with_retry protects my streaming endpoint." It does not: RunnableRetry implements invoke, ainvoke and batch only, so stream, astream and astream_events skip it and the first transient error reaches the caller. The model's own max_retries does still apply (three requests under stream in the 6.2 run), and a fallback rescues a stream only before its first chunk (6.2, 6.4).
"A fallback model gives the same answer quality." It is a different model: another dialect, window and refusal behaviour. Evaluate the fallback path (6.4).
"astream_events v1, v2 and v3 are interchangeable." v1 is deprecated, v2 is the default and the one to use, v3 is beta and works only on chat models and compiled graphs (7.5).
"RunnableWithMessageHistory is the way to add memory." It is deprecated (the run shows the warning). Use a checkpointer and a thread_id (8.1).
"GenericFakeChatModel can stand in for any model in tests." Not for tool calling: bind_tools raises NotImplementedError (9.1).
"I can build any workflow as a long enough chain." Loops, approvals, resume after a crash and shared state are where chains stop and graphs start (Part 10).

Key takeaways#

  1. A Runnable is one interface (invoke, batch, stream and their async twins, astream_events, transform) shared by prompts, models, parsers, retrievers, tools, your functions and compiled graphs. Write a step once and you get sync, async, batch, streaming and tracing.
  2. LCEL is the pipe syntax over Runnables: a | b is a RunnableSequence; a dict becomes a RunnableParallel; a callable becomes a RunnableLambda; a generator function becomes a streaming RunnableGenerator. The data shape between steps is yours to keep straight; nothing checks it until run time.
  3. The building blocks: RunnableLambda and @chain for your code, RunnableParallel for fan-out, RunnablePassthrough with assign and pick for carrying a dict, .map() for lists, and RunnableBranch, RouterRunnable or a function that returns a Runnable for routing.
  4. Config (tags, metadata, callbacks, max_concurrency, recursion_limit, configurable) flows to every step; run_name and run_id do not. Call-time callbacks reach every step; constructor callbacks reach one object.
  5. Binding: bind fixes call kwargs, with_config fixes config, configurable_fields and configurable_alternatives let the caller choose at run time (never from untrusted input), with_types fixes the schema.
  6. Retry and fallback are one-liners with sharp defaults: with_retry makes three attempts and retries every exception; with_fallbacks handles every exception and passes the same input. Restrict both, retry the smallest unit, make side effects idempotent, and give retries one owner (the SDK's max_retries or with_retry, not both). with_retry does not run under stream (the client's max_retries does, so it owns retries on a streaming endpoint), and a fallback rescues a stream only before its first chunk. Name exception classes your integration really raises: the standard Model... family, plus transport errors for the integrations that do not map them.
  7. Streaming works only if every step cooperates. A RunnableLambda that returns a plain value buffers; a RunnableGenerator streams; routers (a lambda that returns a Runnable, RunnableBranch) and assign stream too. astream_events v2 reports every step; filter by tag, name or type, and tag the model whose tokens users should see. v1 is deprecated, v3 is beta, and v2 needs async code.
  8. Custom events report progress from inside a step; pass the step's config to the dispatch call.
  9. RunnableWithMessageHistory and the legacy chain classes are legacy; the replacements are prompt | model, a checkpointer with a thread_id, and create_agent.
  10. Test chains with fake models, spy steps, collect_runs and counters; subclass GenericFakeChatModel to support tool binding; leave real-model quality to evals.
  11. Choose by shape: a short, stateless, fixed pipeline is a chain; a model-driven tool loop is create_agent; loops, approvals, persistence and shared state are LangGraph. They nest: chains inside nodes, graphs inside chains.

Terms introduced in this lesson#

Term One-line definition
Runnable The base interface of langchain-core: any unit of work with invoke, batch, stream and their async forms, composable and traceable
LCEL The LangChain Expression Language: composing Runnables with | (and implicit coercions) into chains
RunnableSequence The Runnable that a | b builds: runs steps in order, each output feeding the next input
RunnableLambda A Runnable wrapping a plain Python function (optionally with an async twin and a config argument)
RunnableParallel A dict of Runnables that run concurrently on the same input and return a dict of outputs
RunnablePassthrough A Runnable that returns its input unchanged; .assign adds computed keys to a dict input, .pick selects keys
RunnableBranch A Runnable that runs the first branch whose condition is true, or a default
RunnableGenerator A Runnable that wraps a function from an iterator of chunks to an iterator of chunks, so a custom step can stream
RunnableConfig The per-call dictionary of tags, metadata, callbacks, run_name, max_concurrency, recursion_limit and configurable values
Callback handler An object whose methods LangChain calls on lifecycle events (start, end, error, new token, custom event)
astream_events The async method that yields an event for every start, chunk and end of every step of a Runnable; version "v2" is the one to use
Custom event An event your own step emits with dispatch_custom_event or adispatch_custom_event, delivered through the callback system
Binding Fixing keyword arguments, config or types on a Runnable (bind, with_config, with_types), returning a new Runnable
Configurable alternatives A Runnable whose parts (fields or whole sub-Runnables) the caller can swap per call through config["configurable"]
with_retry The Runnable method that re-runs a step on exceptions you choose (three attempts by default, every exception by default); applies to invoke and batch (and their async forms), not to stream, astream or astream_events
Fallback A second Runnable that with_fallbacks tries, with the same input, when the first raises a handled exception
Fake chat model A test double such as FakeListChatModel or GenericFakeChatModel that returns scripted replies without a provider

Exercises#

  1. Tour the interface. In a scratch project with only langchain-core, build RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2) | {"double": lambda x: x * 2, "square": lambda x: x * x}. Predict the output of invoke(3) and batch([1, 2]), run them, then print the type of each step in .steps and of the last element. Which coercions happened?
  2. Keep the stream alive. Take model | StrOutputParser() with a GenericFakeChatModel that replies with a sentence. Add a step that redacts digits. First write it as a RunnableLambda and print list(chain.stream(...)); then rewrite it as a RunnableGenerator and compare. What would still go wrong if a phone number were split across two chunks?
  3. Retry safely. Build charge | send_receipt where charge records a payment in a dict and send_receipt fails twice before succeeding. Wrap the whole chain in with_retry and count the payments. Then make charge idempotent (keyed by order id) so that retrying the whole chain is harmless, and restrict the retry to ConnectionError.
  4. Route without guessing. Build a ticket triage chain: a fake classifier returns "Billing.", "shipping" and "refund?" for three tickets; normalize the label, route to one of two answer Runnables, and make an unknown label raise a clear error instead of falling to a default.
  5. Tag the right model. A chain contains a classifier model and an answering model. Using astream_events(version="v2"), print only the answering model's tokens. Do it once with include_tags and once with include_names, and say which is more robust when you rename a class.
  6. Translate an old tutorial. Rewrite the snippet below with the current API, and list every import that fails on langchain 1.5 and what each is replaced by. Use 8.3.
python
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from langchain_community.chat_models import ChatOpenAI

memory = ConversationBufferMemory()
prompt = PromptTemplate.from_template("History: {history}\nUser: {input}\nReply:")
chain = LLMChain(llm=ChatOpenAI(), prompt=prompt, memory=memory)
print(chain.run("My order A-1042 is late."))
  1. Extend the test file. Add three tests to the file of 9.2: one that asserts max_concurrency=1 makes a RunnableParallel of three slow branches take at least three times one branch's time (assert a threshold, not an exact time), one that checks a RunnableBranch falls through to its default, and one that uses return_exceptions=True to check that a failed item does not hide the others.
  2. Chain, agent or graph? For each, choose and justify: (a) summarize an uploaded document into three bullets; (b) answer questions from a policy handbook, retrieving first and answering once; (c) a support assistant that looks up orders, issues refunds and may call tools several times; (d) a refund workflow that needs a human manager to approve amounts over a threshold, possibly a day later; (e) draft an email, check it against a style checklist and redraft until it passes, at most three times.
  3. Retry the stream. Reproduce the model from 6.2 (fails twice, then answers) inside prompt | model.with_retry(...) | StrOutputParser(). Show that invoke answers and stream raises. Then write a small helper stream_with_restart(chain, inputs, attempts=3) that buffers until the first chunk arrives, restarts the stream on a ConnectionError raised before that point, and re-raises after the last attempt. Why is it only safe to restart before the first chunk?
Answers and hints
  1. invoke(3) gives {'double': 16, 'square': 64}: 3 + 1 = 4, 4 * 2 = 8, and then 8 (not the original 3) is the input of the dict, so double is 16 and square is 64. batch([1, 2]) gives [{'double': 8, 'square': 16}, {'double': 12, 'square': 36}]. .steps is ['RunnableLambda', 'RunnableLambda', 'RunnableParallel']: the dict literal became a RunnableParallel, and its two lambdas were coerced into RunnableLambdas as well. If you predicted that the dict sees the original input, you hit the trap of 3.1: each step gets the previous step's output.

  2. The generator version streams token by token; the lambda version returns one chunk at the end. With a generator that works chunk by chunk, a number split across chunks ("555 " then "0199") is handled correctly only if each digit is replaced independently, as here; but a rule that needs to see the whole number (for example a regular expression for phone numbers) would miss it. For such rules, buffer a small window in the generator, or run the redaction on the finished text and accept that you cannot stream the raw tokens to the user. When I ran such a generator over a model reply of call 555 0199 now, the stream came out as ['call', ' ', '###', ' ', '####', ' ', 'now']: still one piece per upstream chunk.

  3. Wrapping the whole chain runs charge once per attempt (three payments for three attempts) unless charge is idempotent. With the key check (if key not in charged) the dict holds one payment and the receipt step still takes three attempts. My run printed receipt for order-1 and charges recorded: {'order-1': 40} | receipt attempts: 3. Better still, retry only send_receipt and keep charge outside.

  4. Normalize with .strip().strip(".").lower(), route with a @chain function that returns the Runnable from a dict and raises ValueError for an unknown label. In my run the first two tickets were routed ([billing team] ..., [shipping team] ...) and the third, whose label was refund?, raised ValueError: classifier returned an unknown label: 'refund?'. In production, make the classifier return an enum through structured output so that unknown labels are rare, and decide whether an unknown label should escalate to a human.

  5. include_tags=["answer"] after with_config(tags=["answer"]) on the answering model returned only Your invoice is attached. in my run; with no filter the output was billingYour invoice is attached. (both models' tokens). A tag survives renames of the class and of the model, whereas include_names depends on the class or function name, so tags are the more robust choice.

  6. Failing imports: langchain.chains (LLMChain), langchain.prompts, langchain.memory, and langchain_community.chat_models.ChatOpenAI (it comes from langchain-community, which is sunset and archived, so even if the import still works it is a migration task; 08F.4, 3.7). The current version builds prompt | model with ChatPromptTemplate, uses init_chat_model("openai:...") or langchain_openai.ChatOpenAI, replaces the memory class by a checkpointer and a thread_id (an create_agent with checkpointer=..., or a graph; 08F.11), and calls .invoke, not .run. The prompt's {history} becomes a MessagesPlaceholder or the agent's message state.

  7. (a) Use sleeping branches and time.perf_counter; assert elapsed >= 0.25 for three 0.1 s branches under max_concurrency=1 (a threshold with margin). (b) RunnableBranch((cond, f), default).invoke(value_that_fails_cond) returns the default's result. (c) RunnableLambda(f).batch(inputs, return_exceptions=True) then assert that the failing index holds an exception instance and the others hold values, as in the 2.3 sample.

  8. (a) A chain (prompt | model | parser), or a single SDK call. (b) A chain (the 3.8 retrieval chain), since retrieval happens once in a fixed order; an agent only if the model must decide whether and what to retrieve (08F.9). (c) create_agent: the model chooses tools and loops. (d) LangGraph with a checkpointer and interrupt: the run must pause for a day and resume. (e) A LangGraph cycle with a counter (or an explicit loop around a chain if it is truly one process and you accept no persistence): a loop with a check is exactly what chains do not express.

  9. Inside the helper, call chain.stream(inputs), pull the first chunk with next(...) in a try block, and loop up to attempts times on ConnectionError; once the first chunk exists, yield it and the rest of the stream without catching anything. This version was run on 1.8.0:

    python
    # stream_restart.py: restart a stream on a transient error, but only before the first chunk
    from langchain_core.language_models import FakeListChatModel
    from langchain_core.output_parsers import StrOutputParser
    from langchain_core.prompts import ChatPromptTemplate
    
    calls = {"n": 0}
    
    
    class FlakyModel(FakeListChatModel):
        """Fails twice with a connection error, then answers."""
    
        def _call(self, *args, **kwargs):
            calls["n"] += 1
            if calls["n"] < 3:
                raise ConnectionError("blip")
            return "fine"
    
        def _stream(self, *args, **kwargs):
            calls["n"] += 1
            if calls["n"] < 3:
                raise ConnectionError("blip")
            return super()._stream(*args, **kwargs)
    
    
    def stream_with_restart(chain, inputs, attempts=3, retry_on=(ConnectionError,)):
        for attempt in range(1, attempts + 1):
            stream = iter(chain.stream(inputs))
            try:
                first = next(stream)          # nothing has reached the caller yet
            except StopIteration:
                return                        # an empty stream is not an error
            except retry_on:
                if attempt == attempts:
                    raise
                continue                      # production code sleeps here, with backoff and jitter
            yield first
            yield from stream                 # after the first chunk, errors propagate
            return
    
    
    model = FlakyModel(responses=["fine"]).with_retry(stop_after_attempt=3, wait_exponential_jitter=False)
    chain = ChatPromptTemplate.from_template("{q}") | model | StrOutputParser()
    
    print("invoke:", chain.invoke({"q": "x"}), calls)
    
    calls["n"] = 0
    try:
        print("stream:", list(chain.stream({"q": "x"})), calls)
    except ConnectionError:
        print("stream raised ConnectionError", calls)
    
    calls["n"] = 0
    print("stream_with_restart:", list(stream_with_restart(chain, {"q": "x"})), calls)
    
    calls["n"] = 0
    try:
        list(stream_with_restart(chain, {"q": "x"}, attempts=2))
    except ConnectionError:
        print("attempts=2: raised ConnectionError", calls)
    Output4 lines
    invoke: fine {'n': 3}
    stream raised ConnectionError {'n': 1}
    stream_with_restart: ['f', 'i', 'n', 'e'] {'n': 3}
    attempts=2: raised ConnectionError {'n': 2}

    The helper made three calls and delivered one answer; with attempts=2 it gave up and re-raised. A restart before the first chunk is invisible to the caller, because nothing was delivered. After the first chunk, a restart would deliver a second answer after the first (the reason RunnableRetry leaves stream alone, and why with_fallbacks also switches only before the first chunk). The async form is the same with chain.astream and anext. The client's max_retries is the simpler option when you can use it (6.2).


Check yourself#

  1. What is a Runnable, and name five different kinds of object in LangChain that are Runnables.
  2. Which two common LangChain objects are not Runnables, and how do you use them in a chain?
  3. What does a | b build, and what happens to a dict literal or a plain function next to a Runnable in the pipe?
  4. What is the output of {"a": f} | {"b": g}, and why?
  5. What does batch do about concurrency, ordering and failures, and how do you cap it?
  6. Why does RunnableLambda break streaming, and what are two ways to fix it?
  7. Which RunnableConfig keys are inherited by sub-steps and which are not?
  8. What is the difference between a callback handler passed at call time and one passed to a model's constructor?
  9. What is the default recursion_limit for a plain Runnable, what is it for a compiled LangGraph graph, and why does this matter for agents?
  10. What are the defaults of with_retry, and why is the default dangerous?
  11. Why should you retry the smallest unit, and what two measures make a retried side effect safe?
  12. What does with_fallbacks pass to the fallback, and what does exception_key add?
  13. What are the three versions of astream_events, and which should you use? What is surprising about calling v3 on a plain Runnable?
  14. How do you stream only one model's tokens out of a chain that contains two models?
  15. When is a chain the right tool, and what are three signs it should become a LangGraph graph?
  16. Does with_retry protect a chain that you call with stream or astream? What does with_fallbacks do in the same situation?

Further resources#

Official sources only. This lesson is built from the source of langchain-core and from running it, because the current docs site has no concept page for Runnables or LCEL; where the official reference is more complete than this lesson (it is, for every class), read it. 08F.17 is the closing lesson that says how.


← 08F.6: Prompts, Output Parsers and Structured Output | Module 08F overview | 08F.8: Tools and create_agent →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close