Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Learn/LangChain Mastery/Part 3 · 2. LCEL & Prompt Architecture
Lesson 9 of 68

LCEL: Why LangChain Is a Composition Engine

Understanding chaining in AI workflows and how LangChain Expression Language (LCEL) simplifies it.

Derpx0610 Jan · 3 min read
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains
Contents
What "Chaining" Really Means1. Making Multiple LLM Calls2. Preparing the Input to the Model3. Using the Model's OutputWhy Chaining Feels So Natural with Language ModelsThe Early LangChain ApproachLangChain Expression Language (LCEL)Pipes Instead of Glue CodeTry It YourselfOne Interface, EverywhereSingle executionBatch executionStreamingAsyncEasy to Customize and ExtendA Real-World Example: Explanation vs RoastThe Mental Model to Remember
0% read · 3 min leftBack to top ↑
Course outline & contents0%
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains
Contents
What "Chaining" Really Means1. Making Multiple LLM Calls2. Preparing the Input to the Model3. Using the Model's OutputWhy Chaining Feels So Natural with Language ModelsThe Early LangChain ApproachLangChain Expression Language (LCEL)Pipes Instead of Glue CodeTry It YourselfOne Interface, EverywhereSingle executionBatch executionStreamingAsyncEasy to Customize and ExtendA Real-World Example: Explanation vs RoastThe Mental Model to Remember

When people first start using language models, they usually write code like this:

send a prompt → get a response → done

That works for demos. It does not work for real applications.

Real AI systems are workflows, not single calls.

Reliability in AI systems rarely comes from the model alone. It comes from the engineering system around it.

They often need to:

  • call a model more than once
  • prepare data before the model runs
  • do something useful with the model's output afterward

The idea that connects all of this is called chaining.


What "Chaining" Really Means

Chaining simply means:

taking multiple steps and connecting them so the output of one step becomes the input of the next.

With language models, this idea shows up in a few common ways.


1. Making Multiple LLM Calls

Language models are powerful, but they are not deterministic. They can make mistakes, hallucinate, or miss details.

Because of this, many applications use more than one model call.

Common patterns include:

  • breaking a big task into smaller steps
  • asking one model to generate an answer
  • asking another call to review, fix, or improve it

For example:

  • plan → execute → verify
  • draft → critique → rewrite
  • reason → answer → double-check

Chaining makes these multi-step processes clear and manageable.


2. Preparing the Input to the Model

Very often, the model cannot work with raw user input alone.

Before calling the LLM, applications may need to:

  • format a prompt template
  • fetch documents or database records
  • perform retrieval based on the user's query
  • combine multiple sources of information

This means the model call is only one step in a larger chain.

The data must be transformed and enriched before the LLM ever sees it.


3. Using the Model's Output

Chaining does not stop when the model responds.

In many systems, the LLM's output is used to:

  • generate Python code and then run it
  • generate SQL and execute it on a database
  • produce structured data for another service
  • drive business logic or automation

In these cases, the LLM is part of a pipeline, not the end of it.


Why Chaining Feels So Natural with Language Models

All of this could be done with traditional code. So why do people keep reaching for chaining abstractions?

Because text has become a universal interface.

Language models take text as input and produce text as output. Prompts, responses, SQL, code, JSON—everything is text.

When everything is text flowing between steps, chaining becomes the most natural way to think.

This is why visual tools like Flowwise and LangFlow became popular, built on top of LangChain.


The Early LangChain Approach

LangChain started with pre-built chains like LLMChain and ConversationalRetrievalChain. They helped get started but were hard to combine, customize, and lacked consistent async/batching/streaming support.

Developers wanted composable, consistent chains with built-in features. The old approach couldn't deliver cleanly.

So LangChain introduced LCEL.

Think of LCEL as a way to standardize "how" components talk to each other, so you can focus on "what" they do.


LangChain Expression Language (LCEL)

LangChain Expression Language (LCEL) is a declarative way to build chains using the pipe (|) operator.

Instead of large classes, compose small building blocks. Describe data flow, not execution control.


Pipes Instead of Glue Code

LCEL uses the pipe to connect components:

concept.py
prompt | model

This passes the prompt's output directly to the model.

Example:

simple_chain.py
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("tell me a joke about {foo}")

chain = prompt | model

# Run it
result = chain.invoke({"foo": "bears"})
print(result.content)

Try It Yourself

Install LangChain and try this simple chain:

install.sh
pip install langchain langchain-openai

Then run:

summarizer.py
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

# Set your OpenAI API key
import os
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("Summarize this text: {text}")

chain = prompt | model

# Test it
result = chain.invoke({"text": "LangChain makes building AI apps easy."})
print(result.content)

This creates a summarizer chain. Change the prompt or add more steps!


One Interface, Everywhere

Every LCEL chain supports:

Single execution

invoke.py
result = chain.invoke({"text": "Hello world"})

Batch execution

batch.py
results = chain.batch([{"text": "First"}, {"text": "Second"}])

Streaming

stream.py
for chunk in chain.stream({"text": "Long text"}):
  print(chunk.content, end="")

Async

async.py
result = await chain.ainvoke({"text": "Async call"})

All built-in—no extra code needed.


Easy to Customize and Extend

LCEL chains are composable. Add steps easily:

extend.py
from langchain.output_parsers import StrOutputParser

# Add output parsing
chain = prompt | model | StrOutputParser()

Swap models, add retrieval, or combine chains.


A Real-World Example: Explanation vs Roast

Here is a real chain that explains a concept, then roasts its own explanation, and finally compliments it.

First, choose your LLM provider:

Code

Now build the pipeline:

Code

This pipeline demonstrates LCEL's power:

  • Takes a topic input
  • Uses the explain prompt to generate an explanation
  • Feeds that explanation into both a roast and compliment prompt in parallel
  • Returns all three results in a structured dictionary

The pipeline runs automatically in parallel where possible, streaming results as they arrive.


The Mental Model to Remember

Think of LCEL as an expression language for AI workflows.

You write:

flow_concept.txt
input | transform | model | transform | output

The system handles execution, async, batching, streaming, tracing.

Once you think in flows, chaining becomes simple.

LCEL makes chaining clear, composable, and scalable.

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonYour First Chatbot: Talking to an LLMNext lesson →The Runnable Protocol (invoke, batch, stream)