LangChain Expression Language (LCEL) is a declarative approach to composing AI pipelines using the pipe (|) operator. Instead of writing verbose imperative code, developers can chain components like prompts, LLMs, retrievers, and parsers into clean, reusable sequences.
Key Concepts
- Pipe Operator (
|): Connects components where the output of one becomes the input of the next. - Runnable Interface: All LCEL components implement a standard interface (
invoke,stream,batch,ainvoke), allowing seamless integration. - Common Primitives:
RunnableParallelfor concurrent execution,RunnableLambdato wrap Python functions, andRunnablePassthroughto forward a step’s input unchanged.
Example: Prompt → Model → Parser
chain = prompt | model | output_parser
result = chain.invoke({"input": "Explain LCEL"})
This simple pipeline formats a prompt, sends it to an LLM, and parses the response into a structured output.
Advanced Use Cases
- RAG pipeline: Combine a retriever with a prompt and model.
- Streaming: Use
.stream()for real-time output. - Batch processing: Process multiple inputs in parallel with
.batch(). - Async execution: Use
.ainvoke()for non-blocking calls.
Best Practices
- Use LCEL for most new LangChain projects due to its composability and built-in optimization.
- Override
invokefor custom logic only when necessary. - Leverage
RunnableParallelto run independent steps concurrently.
By the end of this tutorial, you'll be equipped to build scalable, maintainable AI applications with ease.