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
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)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.
Download the code
lcel_demo.py
prompt | model | parser chain
langchain-course folder. Needs venv, .env, and packages from Project Setup.Run it
Activate the venv from Project Setup, then:
python lcel_demo.pychain.invoke gives you a string — the parser handles .content for you.Where this leads
- The
chainvariable 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.