Lesson 5 of 9 · Composition
Chains With LCEL
Build LangChain chains with LCEL: the pipe operator, Runnables, RunnableParallel, RunnablePassthrough.assign, routing, batch and stream, retries and fallbacks.
- 7 min read
- Intermediate
- Reviewed
- Explain Runnables and how the | operator joins them into chains
- Run branches in parallel with RunnableParallel
- Add computed fields with RunnablePassthrough.assign and plain functions
- Route inputs to different chains with a function
- Make chains reliable with retries and fallbacks
Chains from parts
You've already seen prompt | model | StrOutputParser(). That pipe syntax is the LangChain Expression Language.
Because a chain is a Runnable, it can be piped into other chains, batched, streamed and traced like any single component.
How the pipe works
The | operator is ordinary Python: a class can define what a | b means. Here's a tiny version of LCEL. It turns dictionaries into parallel steps, functions into steps, and prints what flows between them:
# A tiny version of LCEL, to see how the | operator builds chains.
class Runnable:
name = "step"
def invoke(self, x):
raise NotImplementedError
def batch(self, xs):
return [self.invoke(x) for x in xs]
def __or__(self, other): # a | b -> a sequence: run a, then b
return Sequence([self, coerce(other)])
def __ror__(self, other): # lets a plain dict sit on the left of |
return Sequence([coerce(other), self])
class Lambda(Runnable):
def __init__(self, fn, name="lambda"): self.fn, self.name = fn, name
def invoke(self, x): return self.fn(x)
class Parallel(Runnable): # a dict of runnables: same input to each, dict out
name = "parallel"
def __init__(self, steps): self.steps = {k: coerce(v) for k, v in steps.items()}
def invoke(self, x): return {k: s.invoke(x) for k, s in self.steps.items()}
class Sequence(Runnable):
def __init__(self, steps): self.steps = steps
def __or__(self, other): # extending a sequence keeps it flat
return Sequence(self.steps + [coerce(other)])
def invoke(self, x):
for step in self.steps:
x = step.invoke(x)
print(f" {step.name:<9} -> {x!r}")
return x
def coerce(obj): # dicts and functions become runnables
if isinstance(obj, Runnable): return obj
if isinstance(obj, dict): return Parallel(obj)
if callable(obj): return Lambda(obj)
raise TypeError(obj)
prompt = Lambda(lambda d: f"Summarise ({d['chars']} chars): {d['text']}", "prompt")
model = Lambda(lambda p: "The charger failed after a week.", "model") # stands in for a chat model
parser = Lambda(lambda reply: reply.upper(), "parser")
chain = {"text": lambda d: d["text"].strip(), "chars": lambda d: len(d["text"].strip())} | prompt | model | parser
result = chain.invoke({"text": " The charger stopped working after a week of daily rides. "})
print("Result:", result)The dictionary at the start ran both of its functions on the same input and produced a dictionary, which the prompt step then used. Real LCEL does the same, with more features: parallel branches run concurrently, streaming passes pieces through the whole chain, and every step is traced.
Parallel branches and computed fields
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
model = init_chat_model("anthropic:MODEL_NAME")
summary = ChatPromptTemplate.from_template("Summarise in one sentence:\n{review}") | model | StrOutputParser()
reply = ChatPromptTemplate.from_template("Write a two-sentence reply to this review:\n{review}") | model | StrOutputParser()
pipeline = (
RunnablePassthrough.assign(words=RunnableLambda(lambda x: len(x["review"].split()))) # add a field
| RunnableParallel( # run both branches at the same time
summary=summary,
reply=reply,
words=lambda x: x["words"], # plain functions become RunnableLambdas
)
)
result = pipeline.invoke({"review": "The e-bike is great, but the charger stopped working after a week."})
for key, value in result.items():
print(f"{key}: {value}")summary: The customer likes the e-bike but its charger failed after a week. reply: Thank you, we're glad you like the bike! We're sorry about the charger; reply with your order number and we'll send a replacement today. words: 12
RunnablePassthrough.assign(...)passes the input dictionary through unchanged and adds new keys, here a word count.RunnableParallel(...)runs several Runnables on the same input at the same time and collects their outputs in a dictionary. The summary and the reply are two model calls, so running them in parallel roughly halves the waiting time.- Plain functions become
RunnableLambdas automatically inside a chain, or you can wrap them yourself withRunnableLambda(fn).
Routing, retries and fallbacks
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
model = init_chat_model("anthropic:MODEL_NAME")
backup = init_chat_model("openai:MODEL_NAME")
# Reliability: retry a failing call, then fall back to another provider
reliable_model = model.with_retry(stop_after_attempt=3).with_fallbacks([backup])
billing = ChatPromptTemplate.from_template("You handle billing. Answer briefly: {question}") | reliable_model | StrOutputParser()
technical = ChatPromptTemplate.from_template("You handle bike repairs. Answer briefly: {question}") | reliable_model | StrOutputParser()
def route(inputs): # a function that returns the chain to run next
words = ("refund", "invoice", "charge", "pay")
return billing if any(w in inputs["question"].lower() for w in words) else technical
support = RunnableLambda(route)
answers = support.batch([{"question": "Why was I charged twice?"},
{"question": "My brakes squeak. What should I do?"}])
for a in answers:
print(a)Sorry about that! A duplicate charge is usually a temporary hold; if it's still there in 3 days, we'll refund it. Clean the rims and brake pads with isopropyl alcohol; if they still squeak, the pads may need replacing.
- Routing: when a
RunnableLambda's function returns a Runnable, LCEL runs that Runnable with the same input. Here a simple keyword rule picks the billing or repair chain. (A model can do the routing instead, using structured output, as in the Agent Workflows course.) with_retryretries a failing call, for example after a timeout or rate-limit error.with_fallbackstries another Runnable if the first one fails. Falling back to a second provider keeps your application running during an outage.batchruns the chain on several inputs and returns the results in order.
Common mistakes
Implement the | operator that makes LCEL chains possible: joining two steps creates a new step that runs one after the other.
class Step:
def __init__(self, fn):
self.fn = fn
def invoke(self, x):
return self.fn(x)
def __or__(self, other):
# Return a new Step whose function runs self first, then other, on the result.
pass
strip = Step(lambda s: s.strip())
shout = Step(lambda s: s.upper() + "!")
count = Step(lambda s: f"{s} ({len(s)} chars)")
chain = strip | shout | count
print(chain.invoke(" ride safe "))
What does RunnablePassthrough.assign(words=...) do?
Summary
- LCEL joins Runnables with
|; a chain is itself a Runnable with invoke, batch and stream. - RunnableParallel runs branches at the same time; RunnablePassthrough.assign adds computed keys; functions become RunnableLambdas.
- A function that returns a Runnable routes to it.
- with_retry and with_fallbacks make chains reliable.
- Use LCEL for fixed pipelines; use agents or graphs when the model decides the next step.
Next: retrievers.
Finished reading? Tick it off to track your progress.