0
0
LangChainframework~5 mins

Pipe operator for chain composition in LangChain

Choose your learning style9 modes available
Introduction

The pipe operator helps you connect multiple steps in a chain easily. It makes your code cleaner and shows how data flows from one step to the next.

When you want to run several tasks one after another in a clear order.
When you want to pass the output of one function directly as input to the next.
When you want to build a readable flow of operations without nested code.
When you want to combine simple chains into a bigger process.
When you want to debug or understand how data moves through your program.
Syntax
LangChain
chain1 | chain2 | chain3
The pipe operator '|' connects chains so output flows from left to right.
Each chain receives the previous chain's output as input automatically.
Examples
This runs chainA first, then passes its output to chainB.
LangChain
chainA | chainB
This connects three chains in order, making a smooth flow of data.
LangChain
chain1 | chain2 | chain3
You can group chains with parentheses to control the order of composition.
LangChain
chainX | (chainY | chainZ)
Sample Program

This example shows two chains: one translates English text to French, the other summarizes the French text. Using the pipe operator, we connect them so the translation output goes directly to the summarizer. Finally, we run the combined chain with some input text.

LangChain
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate

# Create two simple chains
llm = OpenAI(temperature=0)
chain1 = LLMChain(llm=llm, prompt=PromptTemplate.from_template("Translate '{text}' to French."))
chain2 = LLMChain(llm=llm, prompt=PromptTemplate.from_template("Summarize the French text: '{text}'."))

# Compose chains using pipe operator
full_chain = chain1 | chain2

# Run the full chain
result = full_chain.run(text="Hello, how are you?")
print(result)
OutputSuccess
Important Notes

Make sure each chain's output matches the next chain's expected input format.

The pipe operator improves readability compared to nested calls.

Summary

The pipe operator connects chains so data flows smoothly from one to the next.

It helps write clear and simple chain compositions.

Use it when you want to build multi-step processes in LangChain.