LM28 LangChain PDF Guided Exercise

How to use this exercise

  • Runnable version: langchain-pdf-exercice.ipynb (same content, with ____ blanks to fill in)
  • Reference sheet: LangChain Fundamentals · Worked demo: langchain_pdf.ipynb
  • Estimated time: ~60 min · Prerequisite: langchain_demo.ipynb completed
  • Replace # TODO n.n markers and ____ blanks with your code, run top-to-bottom, and check each Checkpoint.
  • Solutions are at the very bottom — expand only after trying.

Objectives

Write from scratch — no copy-paste from the demo:

  1. a custom Document Loader (BaseLoader + lazy_load)
  2. a text splitting step (RecursiveCharacterTextSplitter)
  3. an LCEL chain prompt | llm | parser
  4. a map-reduce summarization pipeline over a real EU regulation (OJ_L_202401689_EN_TXT.pdf)

0 · Setup

Install the slim packages. The monolithic langchain-community is deprecated and deliberately avoided — in step 2 you will write your own loader using only langchain-core + pypdf.

%pip install -q langchain langchain-openai langchain-core \
                langchain-text-splitters pypdf fpdf2 python-dotenv

1 · Configure the Model

Reuse the provider-agnostic setup from the demo: ChatOpenAI pointed at OpenRouter.

Hint

For factual, stable summaries you want a low temperature.

import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
 
load_dotenv()  # optional: reads .env if present
 
os.environ["OPENAI_API_KEY"] = os.getenv(
    "OPENAI_API_KEY",
    "[SECRET:openrouter-api-key]"
)
 
# TODO 1.1 — create the chat model:
#   model       = "openai/gpt-oss-120b"
#   base_url    = "https://openrouter.ai/api/v1"
#   temperature = pick a value suited to FACTUAL summarization
llm = ChatOpenAI(
    model="openai/gpt-oss-120b",
    temperature=____,
    base_url="https://openrouter.ai/api/v1",
)

Checkpoint

print(llm.invoke("Reply with the single word: ready").content) must print ready.

Think — 1.2

Why did you choose that temperature? What would go wrong with a high temperature when summarizing a legal text?

(write your answer here)


2 · Write Your Own Document Loader

A Document Loader turns any source into Document objects:

  • page_content → the extracted text
  • metadata → where it came from (source file, page number, …)

Subclass BaseLoader and implement lazy_load() — a generator that yields one Document per page. LangChain then derives .load(), .load_and_split() and streaming behavior from it automatically.

Hints

  • enumerate(reader.pages, start=1) gives you (page_number, page)
  • page.extract_text() may return None on empty pages — use or ""
from pypdf import PdfReader
from langchain_core.documents import Document
from langchain_core.document_loaders import BaseLoader
 
class MyPDFLoader(BaseLoader):
    """Custom LangChain Document Loader backed by pypdf (one Document per page)."""
 
    def __init__(self, path: str):
        self.path = path
 
    def lazy_load(self):
        # TODO 2.1 — create a PdfReader for self.path
        reader = ____
 
        # TODO 2.2 — yield ONE Document per page:
        #   page_content = page.extract_text() (or "" if None)
        #   metadata     = {"source": ..., "page": ..., "total_pages": ...}
        for i, page in ____(reader.pages, start=1):
            ____ Document(
                page_content=____,
                metadata={____},
            )
 
PDF_FILE = "OJ_L_202401689_EN_TXT.pdf"
 
# TODO 2.3 — instantiate YOUR loader and call .load()
documents = ____

Checkpoint

print(f"Loaded {len(documents)} pages")
assert len(documents) >= 1, "No documents loaded — check your loader"
assert documents[0].metadata["page"] == 1
print("Metadata of first page:", documents[0].metadata)
print("\n--- First 300 chars of page 1 ---")
print(documents[0].page_content[:300])

Think — 2.4

  1. Why is lazy_load() a generator instead of building the full list up front? What changes for a 10,000-page PDF?
  2. You never wrote .load() yourself — who did, and from what?
  3. Your loader only handles PDFs. What would you have to change downstream (splitter, chains) to process a .txt or a web page instead?

(write your answers here)


3 · Split the Document

LLMs have context limits — a full EU regulation neither fits nor is useful in one prompt. RecursiveCharacterTextSplitter splits on natural boundaries first (\n\n → \n → sentences → words), keeping chunks coherent.

Hints

  • chunk_overlap repeats a little text between consecutive chunks so that ideas spanning a boundary are not lost
  • add_start_index=True stores each chunk’s character offset in its metadata

Before running: predict roughly how many chunks ~300 pages with chunk_size=4000 will produce. Then compare with the actual number.

My prediction: __ chunks

from langchain_text_splitters import RecursiveCharacterTextSplitter
 
# TODO 3.1 — create the splitter:
#   chunk_size=4000, chunk_overlap=200, add_start_index=True
splitter = ____
 
# TODO 3.2 — split the documents loaded in step 2
chunks = ____

Checkpoint

total_chars = sum(len(c.page_content) for c in chunks)
print(f"{len(documents)} pages -> {len(chunks)} chunks ({total_chars:,} chars total)")
assert len(chunks) > 0
assert "start_index" in chunks[0].metadata, "add_start_index=True missing?"

Experiment 3.3

Set chunk_overlap to 0, re-run, note the chunk count, then set it back to 200. (No code to write — just observe.)

Think — 3.4

  1. What did chunk_overlap=0 change? Why can overlap rescue ideas that span a boundary?
  2. Where is start_index stored, and how could you use it to trace a summary back to its exact location in the source?
  3. Trade-offs: what do very small chunks cost you? What do very large chunks cost you?

(write your answers here)


4 · Build the Map Chain (LCEL)

This is the heart of the exercise. Compose components with the pipe operator:

chain = prompt | llm | output_parser

Each stage is a Runnable; the output of one flows into the next. Give the prompt one variable {text} — then the same chain can summarize a chunk, a page, or the whole document: the unit of work is data, not code.

Hint

StrOutputParser converts the AIMessage returned by the model into a plain str.

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from IPython.display import Markdown, display
 
# TODO 4.1 — write a prompt template with ONE variable {text}. It should instruct
#   a "legal assistant" to summarize an excerpt of an EU regulation in 2-3
#   concise bullet points, keeping article numbers when mentioned.
chunk_prompt = ChatPromptTemplate.from_template(
    ____
)
 
# TODO 4.2 — assemble the LCEL chain: prompt | llm | parser
chunk_chain = ____

Checkpoint

Smoke test on the first chunk — expect 2–3 bullet points:

display(Markdown(chunk_chain.invoke({"text": chunks[0].page_content})))

Think — 4.3

Your chain knows nothing about which chunk it receives. Explain why that indifference is exactly what makes .batch(), .stream() and map-reduce possible.

(write your answer here)


5 · Map — Summarize Chunks with .batch()

Map phase: run the same chain over many chunks. .batch() fans the inputs out concurrently and collects results in order — one of the reasons chains beat a plain for loop of llm.invoke(...).

The full regulation yields 200+ chunks — slow and costly to do in one go. For the exercise, process only the first 5 chunks: a cheap dry run that still exercises the whole pipeline.

Hint

.batch(inputs, config) takes a list of input dicts — one {"text": ...} per chunk — and a config such as {"max_concurrency": 4}.

# TODO 5.1 — batch-summarize the FIRST 5 chunks with max_concurrency=4
chunk_summaries = ____

Checkpoint

assert len(chunk_summaries) == 5
for i, s in enumerate(chunk_summaries, 1):
    display(Markdown(f"## Chunk {i}:"))
    display(Markdown(s))

6 · Reduce — Compose the Final Summary

Reduce phase: a second chain condenses all chunk summaries into one executive summary. This map-reduce pattern is how LangChain handles documents longer than the model’s context window.

You will also build a small nested chain: a RunnableLambda joins the list of summaries into one text, then feeds the reduce chain.

flowchart TB
    PDF[📄 Long document] --> SPLIT[Split]
    SPLIT --> M1["MAP: chunk_chain (batch)"]
    M1 --> R["REDUCE: reduce_chain"]
    R --> OUT[📝 Executive summary]

Hint

The lambda must return the input dict the prompt expects:
lambda s: {"summaries": "\n\n".join(s)}

from langchain_core.runnables import RunnableLambda
 
# TODO 6.1 — reduce prompt with ONE variable {summaries}: ask for a single,
#   well-structured executive summary (~3 short paragraphs) covering purpose,
#   scope, key obligations, and dates.
reduce_prompt = ChatPromptTemplate.from_template(____)
 
# TODO 6.2 — assemble the reduce chain
reduce_chain = ____
 
# TODO 6.3 — compose: RunnableLambda(join) | reduce_chain
final_chain = ____
 
final_summary = final_chain.invoke(chunk_summaries)

Checkpoint

display(Markdown(final_summary)) — one coherent summary, not five separate ones.


7 · Put It All Together

Package the pipeline into one reusable function. Reuse the chunk_chain, reduce_chain, final_chain and splitter built above — do not rebuild them.

def summarize_pdf(path: str, max_chunks: int | None = None) -> str:
    """Load -> split -> map -> reduce. Returns the final summary as a string."""
    # TODO 7.1 — load the file with YOUR MyPDFLoader
    docs = ____
    # TODO 7.2 — split with the splitter from step 3
    chs = ____
    # TODO 7.3 — map: batch-summarize all chunks, or only the first max_chunks
    summaries = ____
    # TODO 7.4 — reduce: run final_chain on the summaries and return the result
    return ____
  • max_chunks=None → map over all chunks
  • otherwise → map over the first max_chunks (keep it small while testing!)

Checkpoint

Dry run on the regulation with 3 chunks only:

print(summarize_pdf(PDF_FILE, max_chunks=3)[:600], "…")

8 · Bonus — Export to PDF & Round-Trip

a) Write final_summary to my_summary.pdf with fpdf2.
b) Prove the symmetry: re-load your own PDF with your own MyPDFLoader.

Unicode gotcha

LLM output contains typographic characters (en-dashes –, curly quotes) that core PDF fonts (Helvetica, latin-1 only) cannot encode. Embed a Unicode TTF font (DejaVu Sans) and register it for both regular and bold styles.

from fpdf import FPDF
 
# BONUS 8.1 — fill in the blanks to export final_summary to my_summary.pdf
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"   # or the matplotlib copy:
# FONT = os.path.join(os.path.dirname(__import__("matplotlib").__file__),
#                     "mpl-data", "fonts", "ttf", "DejaVuSans.ttf")
 
pdf = FPDF()
pdf.add_page()
pdf.add_font("DejaVu", "", FONT)
pdf.add_font("DejaVu", "B", ____)              # bold variant path
pdf.set_font("DejaVu", "B", 16)
pdf.multi_cell(0, 10, "My summary of the EU regulation")
pdf.set_font("DejaVu", size=11)
pdf.ln(4)
pdf.multi_cell(0, 6, ____, markdown=True)      # the summary text
pdf.output("my_summary.pdf")

Checkpoint

print("my_summary.pdf:", os.path.getsize("my_summary.pdf"), "bytes")
assert os.path.getsize("my_summary.pdf") > 500
# BONUS 8.2 — symmetry check: YOUR loader reads YOUR output PDF
check = MyPDFLoader("my_summary.pdf").load()
print(f"my_summary.pdf: {len(check)} page(s)")
print(check[0].page_content[:400])

Checkpoint

The printed text should contain words from final_summary; len(check) >= 1.


9 · Reflection

  1. In one sentence each, explain the role of: loader, splitter, prompt template, chain, output parser.
  2. Which components of your pipeline would survive unchanged if the input were a Word file instead of a PDF? Why?
  3. When would map-reduce be the wrong tool? (Think: chunks whose meaning depends on each other.)
  4. What does .batch() buy you over a for loop of .invoke()?
  5. Name two things you would add for a production system. (Ideas: streaming, memory, RAG, structured output, retries/tracing.)

🙈 Solutions

Click to expand — try every TODO first!
# 1.1
llm = ChatOpenAI(model="openai/gpt-oss-120b", temperature=0.2,
                 base_url="https://openrouter.ai/api/v1")
 
# 2.x — custom loader
class MyPDFLoader(BaseLoader):
    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 = MyPDFLoader(PDF_FILE).load()
 
# 3.x — splitting
splitter = RecursiveCharacterTextSplitter(
    chunk_size=4000, chunk_overlap=200, add_start_index=True)
chunks = splitter.split_documents(documents)
 
# 4.x — map chain
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()
 
# 5.1 — map
chunk_summaries = chunk_chain.batch(
    [{"text": c.page_content} for c in chunks[:5]],
    {"max_concurrency": 4})
 
# 6.x — reduce
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 (about 3 short paragraphs) covering: purpose, scope, key "
    "obligations, and dates.\n\nSection summaries:\n{summaries}")
reduce_chain = reduce_prompt | llm | StrOutputParser()
final_chain = RunnableLambda(lambda s: {"summaries": "\n\n".join(s)}) | reduce_chain
 
# 7.x — full pipeline
def summarize_pdf(path: str, max_chunks: int | None = None) -> str:
    docs = MyPDFLoader(path).load()
    chs = splitter.split_documents(docs)
    selected = chs if max_chunks is None else chs[:max_chunks]
    summaries = chunk_chain.batch(
        [{"text": c.page_content} for c in selected],
        {"max_concurrency": 4})
    return final_chain.invoke(summaries)

TL;DR

Load (any source → Document) → split (context limits) → map (same chain per chunk, .batch()) → reduce (one final summary). Every stage is a Runnable, so the blocks stay interchangeable.