Skip to main content

LangChain Expression Language (LCEL)

LangChain Expression Language (LCEL) is a declarative syntax designed to build complex, production-grade pipelines using the pipe operator (|).

Why LCEL?

LCEL pipelines automatically support streaming token delivery, async execution, parallel execution, and built-in observability tracking out of the box without changing code logic.


The Pipe Operator Syntax

In LCEL, components implementing the Runnable protocol are chained together seamlessly:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_template("Explain {topic} in 2 concise sentences.")
model = ChatChatOpenAI(model="gpt-4o")
output_parser = StrOutputParser()

# Construct the Runnable Chain using the Pipe Operator '|'
chain = prompt | model | output_parser

# Execute
result = chain.invoke({"topic": "Quantization in Edge AI"})
print(result)

Core Runnable Capabilities

Every LCEL component exposes standard invocation methods:

  • invoke(): Run the chain on a single input.
  • stream(): Stream back output chunks as they are generated by the model.
  • batch(): Execute the chain across a list of inputs in parallel.
  • ainvoke(): Asynchronous execution for high-concurrency web servers.
# Streaming example
for chunk in chain.stream({"topic": "HNSW Vector Indexes"}):
print(chunk, end="", flush=True)

Parallel Execution (RunnableParallel)

Run multiple branches of execution concurrently and combine their outputs:

from langchain_core.runnables import RunnableParallel, RunnablePassthrough

# Define sub-chains
summary_chain = ChatPromptTemplate.from_template("Summarize: {text}") | model | StrOutputParser()
keywords_chain = ChatPromptTemplate.from_template("Extract 3 tags: {text}") | model | StrOutputParser()

# Combine in parallel
combined_chain = RunnableParallel(
summary=summary_chain,
tags=keywords_chain,
original=RunnablePassthrough()
)

output = combined_chain.invoke({"text": "Retrieval Augmented Generation bridges vector databases with LLMs."})
# Returns: {"summary": "...", "tags": "...", "original": {...}}