LangChain Expression Language (LCEL)
Relevant source files
The following files were used as context for generating this wiki page:
LangChain Expression Language (LCEL) is a declarative language for composing Runnable components into sequences or directed acyclic graphs (DAGs). It is designed to simplify the process of building complex applications with Large Language Models (LLMs) by providing a standard, interoperable interface for chaining together different components like models, prompts, and tools. LCEL is a core part of the langchain-core package.
LCEL provides an optimized execution plan for these compositions, offering automatic parallelization, streaming, and asynchronous support. This allows developers to build robust and efficient LLM-powered applications declaratively, while the framework handles the underlying execution complexity. It supports both a declarative syntax (LCEL) and an imperative approach of calling components directly, giving developers flexibility.
Sources: libs/core/README.md
Core Concepts
The Runnable Interface
The central abstraction in LCEL is the Runnable interface. Most components in LangChain Core, such as LLMs, Chat Models, Prompts, Retrievers, and Tools, implement this interface. It provides a unified invocation protocol, making components interchangeable and composable.
Sources: libs/core/README.md, libs/core/langchain_core/runnables/base.py
The Runnable class hierarchy includes several key implementations for building complex chains.
This diagram shows the basic inheritance structure for key Runnable components.
The Runnable interface defines a standard set of methods for execution:
| Method | Description |
|---|---|
invoke() | Executes the runnable on a single input. |
batch() | Executes the runnable on a batch of inputs, often in parallel. |
stream() | Streams the output of the runnable for a single input. |
ainvoke() | Asynchronously executes the runnable on a single input. |
abatch() | Asynchronously executes the runnable on a batch of inputs. |
astream() | Asynchronously streams the output of the runnable for a single input. |
Sources: libs/core/langchain_core/runnables/base.py:120-410, libs/core/README.md
Composition with the Pipe Operator
LCEL uses the pipe operator (|) to chain Runnable components together, creating a RunnableSequence. The output of one component is passed as the input to the next. This creates a clear and readable way to define complex data flows.
This flowchart illustrates a simple LCEL chain composition.
A typical invocation flow for a sequence might look like this:
Key Runnable Implementations
RunnablePassthrough
The RunnablePassthrough class is a utility that passes its input through unchanged. It is particularly useful when you need to supply the same input to multiple components in a parallel chain or to add new keys to a dictionary that is being passed through a sequence.
The assign method on RunnablePassthrough allows for adding new fields to the input dictionary by running other runnables.
Sources: libs/core/langchain_core/runnables/passthrough.py
RunnableBranch
RunnableBranch provides a mechanism for conditional execution within an LCEL chain. It takes a series of (condition, runnable) pairs and a default runnable. For a given input, it evaluates each condition in order. The first condition that returns True causes the corresponding runnable to be executed. If no conditions are met, the default runnable is executed.
This allows for creating dynamic, branching logic within a declarative chain.
This flowchart shows the logic of a RunnableBranch.
RunnableConfigurableFields
The RunnableConfigurableFields class allows for runtime configuration of a Runnable. By specifying fields as "configurable," their values can be dynamically set at invocation time using the config parameter. This is useful for creating flexible chains where parameters like model temperature or API keys can be changed without redefining the chain.
The configurable_fields method is used to define which attributes of a Runnable can be configured at runtime.
Sources: libs/core/langchain_core/runnables/configurable.py:22-68
Declarative vs. Imperative
LangChain Core allows developers to choose between a declarative and an imperative style. LCEL represents the declarative approach, where the framework manages execution details.
| Feature | Imperative | Declarative (LCEL) |
|---|---|---|
| Syntax | All of Python | LCEL |
| Tracing | ✅ – Automatic | ✅ – Automatic |
| Parallelism | ✅ – with threads or coroutines | ✅ – Automatic |
| Streaming | ✅ – by yielding | ✅ – Automatic |
| Async | ✅ – by writing async functions | ✅ – Automatic |
Sources: libs/core/README.md
Example Usage
The following example, adapted from a deprecation notice, shows how to build a modern, LCEL-based chain that interacts with an API. This demonstrates how prompts, models, and tools can be composed into a graph.
# This is a conceptual example based on the provided source code.
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langgraph.prebuilt.tool_node import ToolNode
# Assume 'tools' and 'api_spec' are defined
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
API_URL_PROMPT = ChatPromptTemplate.from_template("...") # Placeholder
# 1. Define the chain to decide on tool use
api_request_chain = (
API_URL_PROMPT.partial(api_docs=api_spec)
| llm.bind_tools(tools, tool_choice="any")
)
# 2. Define the graph states and nodes
class ChainState(TypedDict):
messages: Annotated[Sequence[BaseMessage], add_messages]
def call_request_chain(state: ChainState, config: RunnableConfig):
# ... implementation ...
return {"messages": [response]}
# 3. Build the graph
graph_builder = StateGraph(ChainState)
graph_builder.add_node("call_tool", call_request_chain)
graph_builder.add_node("execute_tool", ToolNode(tools))
graph_builder.add_node("call_model", llm) # Simplified
graph_builder.set_entry_point("call_tool")
graph_builder.add_edge("call_tool", "execute_tool")
graph_builder.add_edge("execute_tool", "call_model")
graph_builder.add_edge("call_model", END)
chain = graph_builder.compile()
Sources: libs/langchain/langchain/chains/api/base.py:112-200
Summary
LangChain Expression Language (LCEL) is a powerful, declarative framework for composing and executing LLM-powered applications. By standardizing component interactions through the Runnable interface and providing an optimized runtime, LCEL enables developers to build complex, stateful, and observable systems with clean, readable code. Its support for streaming, batching, and asynchronous execution, combined with flexible components for conditional logic and runtime configuration, makes it a cornerstone of the LangChain ecosystem.
Sources: libs/core/README.md, libs/core/langchain_core/runnables/base.py