Module 4 Lesson 2: Single-Step Chains (LCEL Basics)
·LangChain

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

  1. prompt: Receives {"topic": "..."} and creates a ChatPromptValue.
  2. |: Passes that value to the model.
  3. model: Receives the prompt, calls OpenAI, and returns an AIMessage.
  4. |: Passes that message to the parser.
  5. parser: Extracts the .content string 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 | parser
  • expanded_chain = other_prompt | model | parser You 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.
  • StrOutputParser is essential for getting clean text results.
  • Chains are composable; you can build one and then pipe it into another.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn