LCEL & ChainsLesson 1

LCEL (LangChain Expression Language)

In earlier scripts you called format_messages, then invoke, then read .content. That is fine for one-off tests. LCEL wires the same three steps with | so you call chain.invoke once and get back a plain string. Same ChatPromptTemplate as in Prompt Templates.

The pipe operator

LangChain calls each step a Runnable — prompt, model, or parser, as long as it has .invoke(). Put them in a row with |: output from the left side becomes input on the right.

One line, left to right:

prompt

ChatPromptTemplate

|

model

ChatOpenAI

|

parser

StrOutputParser

|

output

plain string

chain = prompt | model | parser
Prompt, model, parser — each step passes its result to the next.

Before and after

The chain does what you already did by hand. Add StrOutputParser at the end and you print the answer directly — no .content.

Before (manual)

messages = prompt.format_messages(
    question=q
)
reply = llm.invoke(messages)
print(reply.content)

With LCEL

chain = prompt | model | parser
answer = chain.invoke(
    {"question": q}
)
print(answer)
Fewer lines, and you keep a chain variable to reuse or extend.

What each step does

  • ChatPromptTemplate — takes {"question": "..."} and returns formatted messages.
  • ChatOpenAI — posts those messages and waits for OpenAI's reply.
  • StrOutputParser — reads the text out of the response object.

The demo script

lcel_demo.py sets up the chain, then asks two HTML questions in a loop.

lcel_demo.py
"""lcel_demo.py — prompt | model | parser"""
… imports, load_dotenv() …
prompt = ChatPromptTemplate.from_messages([…])
model = ChatOpenAI(…)
parser = StrOutputParser()
chain = prompt | model | parser
answer = chain.invoke({"question": q})

Download the code

lcel_demo.py

prompt | model | parser chain

Download .py
Save into your langchain-course folder. Needs venv, .env, and packages from Project Setup.

Run it

Activate the venv from Project Setup, then:

python lcel_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python lcel_demo.py
Q: What does the HTML <a> tag do?
A: The <a> tag marks a hyperlink to another page or file.
Q: What does the <title> tag do?
A: The <title> tag sets the text shown in the browser tab.
chain.invoke gives you a string — the parser handles .content for you.

Where this leads

  • The chain variable can sit in one file and get called from another — no copy-pasting the three steps.
  • Sequential chains, parallel branches, and streaming in this module all extend the same | pattern.
  • Official reference: LCEL concept.

What's Next

Next: Sequential Chains — two LLM steps in one pipe.