16 min read
Lesson 2 of 6
Chains, Prompts & Structured Outputs
From the course LangChain & AI Orchestration Frameworks
Chains are the building blocks of LangChain applications — composable units that transform inputs to outputs, optionally calling LLMs along the way.
LCEL: LangChain Expression Language
Modern LangChain uses LCEL, a declarative way to compose chains using the pipe operator:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that translates {input_language} to {output_language}."),
("human", "{text}"),
])
model = ChatOpenAI(model="gpt-4o")
parser = StrOutputParser()
chain = prompt | model | parser
result = chain.invoke({
"input_language": "English",
"output_language": "French",
"text": "Hello, how are you?",
})
Structured Output
Force LLM responses into typed schemas using Pydantic:
from pydantic import BaseModel, Field
class MovieReview(BaseModel):
title: str = Field(description="Movie title")
rating: float = Field(description="Rating out of 10")
pros: list[str] = Field(description="What was good")
cons: list[str] = Field(description="What was bad")
structured_llm = model.with_structured_output(MovieReview)
review = structured_llm.invoke("Review the movie Inception")
# review.title → "Inception", review.rating → 9.2, etc.
Sequential Chains
Chain multiple steps where each uses the previous output:
outline_chain = outline_prompt | model | parser
draft_chain = draft_prompt | model | parser
edit_chain = edit_prompt | model | parser
full_chain = (
outline_chain
| (lambda outline: {"outline": outline})
| draft_chain
| (lambda draft: {"draft": draft})
| edit_chain
)
Parallel Chains
Run independent chains simultaneously with RunnableParallel:
from langchain_core.runnables import RunnableParallel
analysis = RunnableParallel(
sentiment=sentiment_chain,
summary=summary_chain,
keywords=keyword_chain,
)
results = analysis.invoke({"text": document})
This runs all three chains concurrently, dramatically reducing latency.
Key Takeaways
- •LCEL's pipe operator composes prompt → model → parser chains declaratively
- •Structured output with Pydantic guarantees typed, validated LLM responses
- •Sequential chains pass outputs between steps; parallel chains run concurrently
- •RunnableParallel reduces latency by executing independent chains simultaneously
0 of 6 lessons marked complete
Progress is kept in this browser only.