LangChain is a framework for developing applications powered by Large Language Models (LLMs).
An LLM on its own is “just” a text-in → text-out function. Real applications need much more:
Application need
Plain LLM limitation
LangChain building block
Reusable, parameterized prompts
Copy-paste strings in code
ChatPromptTemplate
Connect to any provider
Each API is different
Unified ChatModel interface
Read PDFs, web pages, databases
No built-in access
Document Loaders
Handle documents longer than the context window
Context limit
Text Splitters + map-reduce
Turn raw text into usable Python values
Output is free-form text
Output Parsers
Chain steps together cleanly
Glue code everywhere
LCEL (prompt \| llm \| parser)
The one-sentence mental model
LangChain gives you standard, extendable interfaces (called Runnables) so that every component — model, prompt, parser, loader — plugs together like Lego.
The monolithic langchain-community package is deprecated / being sunset. The recommended approach is slim per-integration packages (e.g. langchain-openai) plus custom loaders built on langchain-core when no integration package is warranted. We follow this approach in langchain_pdf.ipynb.
Installation
pip install langchain langchain-openai langchain-core langchain-text-splitters python-dotenv# For the PDF exercise:pip install pypdf fpdf2
2. Chat Models — one interface, any provider
LangChain abstracts the provider away. ChatOpenAI works with any OpenAI-compatible API (OpenAI, OpenRouter, local servers, …):
from langchain_openai import ChatOpenAIfrom dotenv import load_dotenvimport osload_dotenv() # reads .env if present — never hard-code keys!llm = ChatOpenAI( model="google/gemma-4-26b-a4b-it", # any OpenRouter model id temperature=0.7, # creativity: 0 = factual, 1 = creative api_key=os.getenv("OPENAI_API_KEY"), base_url="https://openrouter.ai/api/v1", # swap providers here only)response = llm.invoke("Hello! How are you?")print(response.content) # AIMessage -> .content is the text
Why this matters
Model configuration lives in one place. You can swap providers or models without touching your chains — that decoupling is one of LangChain’s main benefits.
A prompt template is a parameterized, reusable prompt. Variables use the {curly_brace} syntax:
from langchain_core.prompts import ChatPromptTemplateprompt = ChatPromptTemplate.from_template( "Explain the concept of {concept} in simple terms.")formatted = prompt.format(concept="profit")# -> "Explain the concept of profit in simple terms."
The same template becomes a different prompt with different data — the unit of work is data, not code.
4. Chains — LCEL (LangChain Expression Language)
LCEL is the heart of LangChain. You compose components with the pipe operator|:
from langchain_core.output_parsers import StrOutputParserchain = prompt | llm | StrOutputParser()result = chain.invoke({"concept": "neural networks"})print(result) # plain string, thanks to StrOutputParser
flowchart LR
IN["{concept: 'neural net'}"] --> P[ChatPromptTemplate]
P --> LLM[ChatModel]
LLM --> O[StrOutputParser]
O --> OUT["'A neural net is…'"]
Why chains instead of plain function calls?
Every stage is a Runnable, which gives you for free:
Primitive
What it does
.invoke(input)
Run one input through the chain
.batch([inputs])
Fan out inputs concurrently, collect results in order
.stream(input)
Stream tokens as they arrive
Composition
Chains nest inside other chains
# .batch() in action — concurrency with one line:summaries = chunk_chain.batch( [{"text": c.page_content} for c in chunks[:5]], {"max_concurrency": 4}, # config accepted by any Runnable)
Glue for custom logic
RunnableLambda wraps any Python function into a Runnable so it can join a chain:
Chat models accept a list of typed messages, which is how context/history works:
from langchain_core.messages import HumanMessage, AIMessagemessages = [ HumanMessage(content="What is Python?"), AIMessage(content="Python is a programming language."), HumanMessage(content="What are its main features?"), # "it" resolves via history]response = llm.invoke(messages)
No memory by default
LLMs are stateless — “memory” is just you resending previous messages each turn. LangChain provides abstractions to manage that history.
6. Documents — the universal data format
A Document Loader converts any source (PDF, Word, web page, YouTube, DB…) into Document objects:
metadata → where it came from (tracing, filtering, citations)
Writing your own loader
Every loader implements lazy_load() — a generator yielding Documents one at a time (memory-friendly). LangChain derives load(), load_and_split() and streaming from it automatically:
from pypdf import PdfReaderfrom langchain_core.documents import Documentfrom langchain_core.document_loaders import BaseLoaderclass PDFLoader(BaseLoader): """Custom LangChain Document Loader backed by pypdf (one Document per page).""" def __init__(self, path: str): self.path = path def lazy_load(self): reader = PdfReader(self.path) for i, page in enumerate(reader.pages, start=1): yield Document( page_content=page.extract_text() or "", metadata={"source": self.path, "page": i, "total_pages": len(reader.pages)}, )documents = PDFLoader("OJ_L_202401689_EN_TXT.pdf").load()print(f"Loaded {len(documents)} pages")
The key insight
Because every loader returns the sameDocument type, the rest of your pipeline (splitting, prompting, retrieval) works unchanged regardless of the input format. Nothing downstream knows or cares where the text came from.
7. Text Splitting
LLMs have context limits — and long documents are rarely useful in one prompt anyway. Text Splitters cut documents into chunks.
RecursiveCharacterTextSplitter tries to split on natural boundaries first (\n\n → \n → sentences → words), keeping chunks coherent:
from langchain_text_splitters import RecursiveCharacterTextSplittersplitter = RecursiveCharacterTextSplitter( chunk_size=4000, # ~1k tokens: comfortably fits in a prompt chunk_overlap=200, # bridges ideas that span a boundary add_start_index=True, # stores each chunk's offset in metadata)chunks = splitter.split_documents(documents)
flowchart LR
DOC["📄 300-page PDF<br/>1 Document per page"] --> S[RecursiveCharacterTextSplitter]
S --> C1[chunk 1]
S --> C2[chunk 2]
S --> C3["…<br/>chunk N"]
Why chunk_overlap?
If a sentence is cut in half at a boundary, both halves lose context. Overlapping a little text between chunks means ideas spanning the boundary survive.
8. Map-Reduce Summarization — processing documents of any length
The classic pattern for “summarize a 300-page PDF with a 8k-token context model”:
Map — run the same summarization chain over every chunk
Reduce — a second chain condenses all chunk summaries into one final summary
# --- MAP: parameterized prompt, same chain for every chunk ---chunk_prompt = ChatPromptTemplate.from_template( "You are a legal assistant. Summarize the following excerpt of an EU regulation " "in 2-3 concise bullet points, keeping article numbers when mentioned:\n\n{text}")chunk_chain = chunk_prompt | llm | StrOutputParser()chunk_summaries = chunk_chain.batch( [{"text": c.page_content} for c in chunks[:5]], {"max_concurrency": 4},)# --- REDUCE: a second chain + a nested RunnableLambda ---from langchain_core.runnables import RunnableLambdareduce_prompt = ChatPromptTemplate.from_template( "You are a legal assistant. The following are summaries of consecutive sections " "of an EU regulation. Write a single, well-structured executive summary " "covering: purpose, scope, key obligations, and dates.\n\n" "Section summaries:\n{summaries}")reduce_chain = reduce_prompt | llm | StrOutputParser()final_chain = RunnableLambda(lambda s: {"summaries": "\n\n".join(s)}) | reduce_chainfinal_summary = final_chain.invoke(chunk_summaries)
flowchart TB
PDF[📄 Long document] --> SPLIT[Split]
SPLIT --> M1[MAP: summarize chunk 1]
SPLIT --> M2[MAP: summarize chunk 2]
SPLIT --> M3[MAP: summarize chunk N]
M1 --> R[REDUCE: final summary chain]
M2 --> R
M3 --> R
R --> OUT[📝 Executive summary]
The full pipeline, end to end
langchain_pdf.ipynb runs: custom PDF loader → splitter → map chain (batch) → reduce chain → export summary.pdf with fpdf2 — and then re-loadssummary.pdf with the same loader to prove the round-trip.
Unicode gotcha when exporting
LLM output often contains typographic characters (–, curly quotes) that core PDF fonts (Helvetica, latin-1 only) cannot encode. Embed a Unicode TTF font (e.g. DejaVu Sans) in fpdf2 — see notebook §8.
9. Concept cheat sheet
Concept
Class / tool
One-liner
Chat Model
ChatOpenAI
Provider-agnostic LLM interface
Prompt Template
ChatPromptTemplate
Parameterized, reusable prompt
Chain (LCEL)
prompt \| llm \| parser
Composable pipeline of Runnables
Runnable primitives
.invoke().batch().stream()
Uniform execution interface
Messages
HumanMessage, AIMessage
Typed multi-turn history
Document Loader
BaseLoader subclass
Any source → Document
Text Splitter
RecursiveCharacterTextSplitter
Long docs → coherent chunks
Output Parser
StrOutputParser
AIMessage → plain Python str
Map-reduce
two chains
Summarize docs of any length
10. Common pitfalls
Check yourself
❌ Hard-coding API keys → use .env + load_dotenv()
❌ Calling llm.invoke in a loop → use .batch() for concurrency
❌ chunk_overlap=0 on related text → ideas get cut at boundaries
❌ Feeding a whole PDF to the model → context limit; split + map-reduce
❌ Assuming the model “remembers” → resend message history every turn
11. Exercises
Swap the model: change model= and temperature= in langchain_demo.ipynb. Does a low temperature make explanations more consistent?
Extend the template: add a second variable {audience} to the explanation prompt (e.g. “explain for a 10-year-old”).
Tune the splitter: change chunk_size / chunk_overlap on the EU PDF. How does chunk count change? Why?
Full map-reduce: in langchain_pdf.ipynb, replace chunks[:5] with all chunks and compare the reduce output.
New loader: write a TXTLoader for sample.txt following the BaseLoader recipe — which parts of the pipeline can you reuse unchanged?
12. Where to go next
RAG — retrieval-augmented generation: embeddings + vector store over this very PDF
.stream() — token-by-token streaming for chat UIs
with_structured_output() — get JSON/pydantic objects instead of free text
LangChain = standard interfaces for LLM apps. Models, prompts, loaders, splitters and parsers are all Runnables you compose with | into pipelines that handle any provider and any document size.