|) operator to create expressive, debuggable pipelines.
Initial chain
We start with a minimal chain that includes:- A prompt asking for a one-line description of a topic
- A ChatOpenAI model
- A string output parser
Adding a custom runnable to transform the output
Goal: convert the model output to title case by wrapping a simple Python function inRunnableLambda and appending it to the chain so it receives the parser output at runtime.
str.title() transforms "AI" into "Ai". That behavior is expected for title-casing with str.title().
When appending a Python function to an LCEL chain, pass the function reference (e.g.,
RunnableLambda(to_titlecase)), not a function call. LangChain invokes it at runtime as part of the pipeline.Adding a second runnable to inspect output length
Next, add a second runnable that logs the transformed text (for debugging) and returns its character length. This shows how to chain multiple custom runnables to both inspect and transform data.Putting it all together (concise example)
Use cases and rationale
Runnable lambdas let you inject arbitrary Python logic into LCEL pipelines to enrich, transform, validate, persist, or debug model outputs. Common use cases include:Inspecting the LCEL graph
For complex pipelines, visualizing the internal graph is helpful. Install a graph utility (e.g.,grandalf) to extract and visualize the chain graph.
print_ascii() might show):
Notes about runtime representations
- LCEL may convert some components (including wrapped functions) into internal Pydantic models or other runtime representations to enable type checking, validation, and serialization.
- These runtime conversions are primarily for inspection and validation; they don’t change how you write Python functions for
RunnableLambda. - Use the graph and runtime representations to debug inputs/outputs and to validate that components are wired as expected.
Quick reference
Summary
- LCEL pipelines are highly composable: prompts, models, parsers, and Python runnables can be combined using the pipe (
|) operator. RunnableLambdawraps Python functions so they can participate in LCEL chains.- Chain multiple runnables to transform, inspect, and persist outputs (e.g., title-casing, measuring length, calling external APIs).
- Use graph visualization (via
get_graph()andprint_ascii()) for debugging and understanding complex pipelines.