Understanding Chains
Relevant source files
The following files were used as context for generating this wiki page:
In LangChain, Chains are fundamental components that encode a sequence of calls, not just to LLMs, but to a variety of other utilities. They provide a simplified and standardized interface for creating applications that go beyond a single LLM call. This composability allows developers to build complex, stateful, and observable applications by linking together different components, including other chains.
The core abstraction that powers Chains is the Runnable interface. This interface is central to the LangChain Expression Language (LCEL), which provides a declarative way to compose these components into sequences or graphs. Common applications of chains include Retrieval Augmented Generation (RAG), interacting with APIs, creating chatbots, and extracting structured data.
Sources: libs/langchain/README.md, libs/langchain/langchain/chains/init.py:3-12, libs/core/README.md:18-26
The Runnable Interface
The Runnable class is the base abstraction for most components in LangChain, including Chains. It provides a standard interface for invocation, batching, streaming, and composition.
Sources: libs/core/langchain_core/runnables/base.py:100-103
Core Runnable Methods
The Runnable interface defines a set of methods for execution, ensuring a consistent API across all components.
| Method | Description |
|---|---|
invoke() / ainvoke() | Transforms a single input into an output, synchronously or asynchronously. |
batch() / abatch() | Efficiently transforms multiple inputs into outputs, typically in parallel. |
stream() / astream() | Streams output from a single input as it's produced. |
transform() / atransform() | Transforms a stream of inputs into a stream of outputs. |
astream_log() | Streams output and selected intermediate results for tracing and debugging. |
astream_events() | Generates a stream of events providing real-time progress information. |
Sources: libs/core/langchain_core/runnables/base.py:105-111, libs/core/langchain_core/runnables/base.py:466-476, libs/core/langchain_core/runnables/base.py:598-608, libs/core/langchain_core/runnables/base.py:730-745
Runnable Class Diagram
This diagram shows the abstract Runnable class with its generic types and key invocation methods.
Composition with LCEL
LangChain Expression Language (LCEL) is a declarative way to compose Runnable components. The primary composition operator is the pipe (|), which creates a RunnableSequence. This sequence chains runnables together, where the output of one step becomes the input for the next.
This flowchart illustrates a simple RunnableSequence composition.
Types of Chains
LangChain provides a wide variety of pre-built chains for common applications. These chains are all built on the Runnable interface and can be composed with other components. The langchain.chains module serves as an entry point for many of these implementations.
Sources: libs/langchain/langchain/chains/init.py:14-63
APIChain
The APIChain is designed to interact with APIs. It first constructs a valid API URL based on a user's question and API documentation, then makes a request to that URL, and finally, summarizes the API response to answer the original question.
It is composed of two internal LLMChains:
api_request_chain: Predicts the API URL to call.api_answer_chain: Summarizes the response from the API call.
A critical security feature is limit_to_domains, which restricts the chain to call only specified domains, preventing arbitrary API requests.
Sources: libs/langchain/langchain/chains/api/base.py:71-87, libs/langchain/langchain/chains/api/base.py:202-215
APIChain Execution Flow
The following sequence diagram shows the internal process of the APIChain's _call method.
Document Chains
LangChain offers specialized chains for processing documents, which are crucial for tasks like Retrieval Augmented Generation (RAG) and summarization. These chains often use LangGraph to manage their execution flow.
StuffDocumentsChain
The create_stuff_documents_chain function creates a chain that "stuffs" all provided documents into a single context window for processing by an LLM. It's a straightforward approach but is limited by the model's context window size. This chain can process all documents in one request or refine an existing result with new documents.
The chain's state is managed by the ExtractionState TypedDict.
class ExtractionState(TypedDict):
"""State for extraction chain."""
documents: list[Document]
result: NotRequired[Any]
Sources: libs/langchain_v1/langchain/chains/documents/stuff.py:61-67, libs/langchain_v1/langchain/chains/documents/stuff.py:382-396
The flow is managed by a StateGraph from LangGraph.
MapReduceDocumentsChain
The create_map_reduce_chain function implements the map-reduce pattern for document processing. This is highly effective for large document sets that do not fit into a single context window.
- Map Phase: Each document is processed independently and in parallel. The
map_promptis used to generate an intermediate result for each document. - Reduce Phase (Optional): The intermediate results from the map phase are combined into a final result. This can be done using an LLM with a
reduce_prompt, a custom function, or it can be skipped entirely.
The process is managed by a StateGraph that uses the Send API to dispatch map operations for parallel execution.
Sources: libs/langchain_v1/langchain/chains/documents/map_reduce.py:141-155, libs/langchain_v1/langchain/chains/documents/map_reduce.py:340-350
Map-Reduce Flow
This diagram shows the map-reduce execution graph.