Runnable protocol hierarchy.
Objectives
- Build a basic chain connecting prompts, models, and string output parsers using the pipe (
|) operator. - Peek under the hood of LCEL by implementing chains using explicit
RunnableLambdaandRunnableSequenceconstructs. - Understand the core Runnable Hierarchy and the common methods shared across all LangChain components.
1. LCEL Chain Basics
LangChain Expression Language (LCEL) allows you to chain together multiple components. The pipe (|) operator streams inputs through components sequentially:
2. Under the Hood: Explicit Sequences
Under the hood, LCEL overloads the pipe operator (|) to implicitly create sequences. We can achieve the exact same behavior by wrapping code steps in RunnableLambda functions and combining them using a RunnableSequence.
3. The LangChain Runnable Hierarchy
Almost every component in LangChain—including Prompts, Chat Models, LLMs, Output Parsers, and helper classes—implements the Runnable protocol. This shared base class structure allows components to be seamlessly piped together.Core Hierarchy Classes
Runnable: The base protocol class defining the interface contract (invoke,stream,batch).RunnableSerializable: Inherits fromRunnable. It represents components that can be serialized or saved to disk (e.g. prompt templates, chat models, output parsers).RunnableLambda: Wraps a standard Python callable function or lambda so it behaves like a standard LangChain Runnable.RunnableSequence: Formed when chaining components using the pipe operator (|). Represents a pipeline where step feeds into step .RunnableParallel: Executes multiple branches concurrently on the same input, yielding a dictionary mapped to each branch’s output.RunnablePassthrough: Passes the input keys through unchanged or adds new keys dynamically. Commonly used withRunnableParallelto build RAG chains where you want to pass both the original question and retrieved context forward.
Regularly Used Component Runnables
BasePromptTemplate(e.g.ChatPromptTemplate): Takes a dictionary of arguments and formats it into prompts.BaseChatModel/LLM(e.g.ChatOpenAI): Takes prompts/messages and returns message outputs.BaseOutputParser(e.g.StrOutputParser,JsonOutputParser): Takes message outputs and parses them into strings or structured formats.
Practice & Exercises
To reinforce what you’ve learned in this section, practice with the interactive notebook:Practice & Exercises
Practice composing simple chains, using different invocation methods (batch, stream), and manually building sequences.💻 VS Code | 🚀 Colab | 📥 Download