Module 4 Lesson 2: Single-Step Chains (LCEL Basics)
Piping the Brain. Learning how to use the | operator to create your first executable LangChain Expression Language chain.
LCEL: The Power of the Pipe
In this lesson, we build our first LangChain Expression Language (LCEL) chain. This is the "Industry Standard" way to write AI code. It is declarative, meaning you describe what you want to happen, and LangChain handles how it happens.
1. The Basic Chain Anatomy
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 1. Define Components
model = ChatOpenAI(model="gpt-4o-mini")
prompt = ChatPromptTemplate.from_template("Summarize this: {topic}")
parser = StrOutputParser()
# 2. CREATE THE PIPE
chain = prompt | model | parser
# 3. INVOKE
result = chain.invoke({"topic": "The history of the internet"})
print(result)
2. Breaking Down the Sequence
prompt: Receives{"topic": "..."}and creates aChatPromptValue.|: Passes that value to themodel.model: Receives the prompt, calls OpenAI, and returns anAIMessage.|: Passes that message to theparser.parser: Extracts the.contentstring and returns it.
3. The StrOutputParser
Why do we need this? Because model.invoke() returns a complex object (Module 1). If you just want the text, StrOutputParser is the "Cleaner" that strips away the metadata and returns a string.
4. Visualizing the Data Flow
graph LR
Dict[Dictionary: topic] --> P[ChatPromptTemplate]
P -->|Message List| M[ChatOpenAI]
M -->|AIMessage Object| S[StrOutputParser]
S -->|String| Done[Final Output]
5. Engineering Tip: Reusing Components
Because prompt, model, and parser are independent, you can reuse them in different chains.
summary_chain = prompt | model | parserexpanded_chain = other_prompt | model | parserYou don't need to re-initialize your model 50 times.
Key Takeaways
- LCEL uses the
|operator for a clean, readable syntax. - The input to a chain is usually a Python Dictionary.
StrOutputParseris essential for getting clean text results.- Chains are composable; you can build one and then pipe it into another.