iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

LCEL (Expression Language)

LCEL (LangChain Expression Language) composes runnables with |. The result is a single runnable that streams, batches, and traces — for free.

Compose with |

EXAMPLE
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableParallel, RunnableLambda

llm = ChatOpenAI(model='gpt-4o-mini')

# 1. Linear pipeline
prompt = ChatPromptTemplate.from_template('Translate to {lang}: {text}')
chain  = prompt | llm | StrOutputParser()
print(chain.invoke({'lang': 'French', 'text': 'Hello, world'}))

# 2. Run two chains in parallel, merge the result
summarise = ChatPromptTemplate.from_template('Summarise in one sentence: {text}') | llm | StrOutputParser()
title     = ChatPromptTemplate.from_template('Suggest a title for: {text}')     | llm | StrOutputParser()

parallel = RunnableParallel(summary=summarise, title=title)
print(parallel.invoke({'text': 'PHP is a server-side scripting language…'}))

# 3. Inject a tiny custom step
shorten = RunnableLambda(lambda s: s.strip()[:60])
pipe = chain | shorten
print(pipe.invoke({'lang': 'German', 'text': 'How are you today?'}))

Why it matters

Every LCEL chain ships with .invoke, .batch, .stream, and .ainvoke. You don’t re-implement streaming or batching — you compose with | and the runtime handles them.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# LCEL — Runnables you pipe together with |.
chain = prompt | llm | StrOutputParser()
result = chain.invoke({'topic': 'rainbows'})
# Run in parallel
from langchain_core.runnables import RunnableParallel
parallel = RunnableParallel(joke=joke_chain, fact=fact_chain)
Try it Yourself »

Exercise

Pipe a prompt into an LLM.

chain = prompt llm

Discussion

Loading…