Chains
A chain is a runnable assembled from smaller runnables — prompts, models, parsers, retrievers, custom functions. The same chain runs locally and exposes invoke, batch, stream, and async variants for free.
Build, branch, stream
EXAMPLE
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_core.runnables import RunnableParallel, RunnableLambda, RunnableBranch
from pydantic import BaseModel, Field
llm = ChatOpenAI(model='gpt-4o-mini')
# 1. Linear chain
translate = ChatPromptTemplate.from_template('Translate to {lang}: {text}') | llm | StrOutputParser()
print(translate.invoke({'lang': 'French', 'text': 'Hello'}))
# 2. Branching — pick a sub-chain based on input
classify = ChatPromptTemplate.from_template('One word: is this a question or a statement? {text}') | llm | StrOutputParser()
answer = ChatPromptTemplate.from_template('Answer: {text}') | llm | StrOutputParser()
echo = ChatPromptTemplate.from_template('Reword: {text}') | llm | StrOutputParser()
router = RunnableBranch(
(lambda x: 'question' in classify.invoke(x).lower(), answer),
echo,
)
# 3. Structured output
class User(BaseModel):
name: str = Field(description='Full name')
age: int = Field(description='Age in years')
extract = ChatPromptTemplate.from_template(
'Extract the user from: {text}\n{format_instructions}'
) | llm | JsonOutputParser(pydantic_object=User)
# 4. Stream tokens to the console
for chunk in translate.stream({'lang': 'Spanish', 'text': 'Streaming is fun'}):
print(chunk, end='', flush=True)
Why it matters
Build chains like UNIX pipes — each step has one job. When something gets messy, split, parameterise, and pipe.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
joke = ChatPromptTemplate.from_template('Tell me a one-liner about {topic}') | llm | StrOutputParser()
rate = ChatPromptTemplate.from_template('Rate this joke 1-10:\n{joke}') | llm | StrOutputParser()
pipeline = {'joke': joke} | rate
Try it Yourself »
Discussion
Loading…