Table of Contents


LangChain Fundamentals

What you will learn

By the end of this note you will be able to:

  1. Explain what LangChain is and why it exists
  2. Use a Chat Model through a provider-agnostic interface
  3. Build reusable Prompt Templates and compose them into LCEL chains
  4. Load, split and process long documents
  5. Apply the map-reduce pattern to summarize documents of any length

📓 Companion notebooks: langchain_demo.ipynb (basics) and langchain_pdf.ipynb (PDF → summary pipeline).


1. What is LangChain?

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 needPlain LLM limitationLangChain building block
Reusable, parameterized promptsCopy-paste strings in codeChatPromptTemplate
Connect to any providerEach API is differentUnified ChatModel interface
Read PDFs, web pages, databasesNo built-in accessDocument Loaders
Handle documents longer than the context windowContext limitText Splitters + map-reduce
Turn raw text into usable Python valuesOutput is free-form textOutput Parsers
Chain steps together cleanlyGlue code everywhereLCEL (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 package ecosystem (LangChain 0.3+)

flowchart LR
    LC[langchain] --> CORE[langchain-core<br/>Runnables, Prompts,<br/>Documents, Parsers]
    LC --> TEXT[langchain-text-splitters]
    CORE --> PO1[langchain-openai<br/>partner package]
    CORE --> PO2[langchain-anthropic]
    CORE --> PO3[langchain-community<br/>⚠️ being sunset]

Modern packaging

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 ChatOpenAI
from dotenv import load_dotenv
import os
 
load_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.

temperature

  • 0.0–0.2 → factual, stable output (summarization, extraction)
  • 0.7–1.0 → creative output (brainstorming, storytelling)

3. Prompt Templates

A prompt template is a parameterized, reusable prompt. Variables use the {curly_brace} syntax:

from langchain_core.prompts import ChatPromptTemplate
 
prompt = 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 StrOutputParser
 
chain = 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:

PrimitiveWhat 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
CompositionChains 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:

from langchain_core.runnables import RunnableLambda
final_chain = RunnableLambda(lambda s: {"summaries": "\n\n".join(s)}) | reduce_chain

5. Messages & Multi-turn Conversations

Chat models accept a list of typed messages, which is how context/history works:

from langchain_core.messages import HumanMessage, AIMessage
 
messages = [
    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:

from langchain_core.documents import Document
 
doc = Document(
    page_content="the extracted text…",
    metadata={"source": "sample.txt", "page": 1},
)
  • page_content → the text
  • 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 PdfReader
from langchain_core.documents import Document
from langchain_core.document_loaders import BaseLoader
 
class 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 same Document 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 RecursiveCharacterTextSplitter
 
splitter = 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”:

  1. Map — run the same summarization chain over every chunk
  2. 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 RunnableLambda
 
reduce_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_chain
final_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-loads summary.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

ConceptClass / toolOne-liner
Chat ModelChatOpenAIProvider-agnostic LLM interface
Prompt TemplateChatPromptTemplateParameterized, reusable prompt
Chain (LCEL)prompt \| llm \| parserComposable pipeline of Runnables
Runnable primitives.invoke() .batch() .stream()Uniform execution interface
MessagesHumanMessage, AIMessageTyped multi-turn history
Document LoaderBaseLoader subclassAny source → Document
Text SplitterRecursiveCharacterTextSplitterLong docs → coherent chunks
Output ParserStrOutputParserAIMessage → plain Python str
Map-reducetwo chainsSummarize 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

  1. Swap the model: change model= and temperature= in langchain_demo.ipynb. Does a low temperature make explanations more consistent?
  2. Extend the template: add a second variable {audience} to the explanation prompt (e.g. “explain for a 10-year-old”).
  3. Tune the splitter: change chunk_size / chunk_overlap on the EU PDF. How does chunk count change? Why?
  4. Full map-reduce: in langchain_pdf.ipynb, replace chunks[:5] with all chunks and compare the reduce output.
  5. 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
  • Sequential chains with memory for real chatbots
  • 📚 LangChain docs · Conceptual guide

TL;DR

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.