Building Chains with LCEL
Use the pipe operator to chain a prompt template, an LLM, and an output parser into a Runnable sequence, invoke it synchronously and asynchronously, and inspect intermediate outputs.
What Is LCEL?
LCEL (LangChain Expression Language) is the declarative way to compose LangChain components into pipelines. Instead of instantiating verbose Chain classes, you connect Runnables with the | operator. LCEL chains support streaming, async, batching, and fallbacks automatically — you get all these capabilities for free just by using the pipe syntax.
Your First LCEL Chain
The simplest LCEL chain combines a PromptTemplate, a ChatModel, and an OutputParser. Each component is a Runnable, and the pipe operator connects them. When you call chain.invoke(), the input flows through each step in sequence, with the output of each becoming the input of the next.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_template(
'Write a product description for: {product}'
)
model = ChatOpenAI(model='gpt-4o-mini', temperature=0.7)
parser = StrOutputParser()
chain = prompt | model | parser
result = chain.invoke({'product': 'noise-cancelling headphones'})
print(result)