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:
a custom Document Loader (BaseLoader + lazy_load)
a text splitting step (RecursiveCharacterTextSplitter)
an LCEL chainprompt | llm | parser
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.
Reuse the provider-agnostic setup from the demo: ChatOpenAI pointed at OpenRouter.
Hint
For factual, stable summaries you want a low temperature.
import osfrom dotenv import load_dotenvfrom langchain_openai import ChatOpenAIload_dotenv() # optional: reads .env if presentos.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 summarizationllm = 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 PdfReaderfrom langchain_core.documents import Documentfrom langchain_core.document_loaders import BaseLoaderclass 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"] == 1print("Metadata of first page:", documents[0].metadata)print("\n--- First 300 chars of page 1 ---")print(documents[0].page_content[:300])
Think — 2.4
Why is lazy_load() a generator instead of building the full list up front? What changes for a 10,000-page PDF?
You never wrote .load() yourself — who did, and from what?
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=Truesplitter = ____# TODO 3.2 — split the documents loaded in step 2chunks = ____
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) > 0assert "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
What did chunk_overlap=0 change? Why can overlap rescue ideas that span a boundary?
Where is start_index stored, and how could you use it to trace a summary back to its exact location in the source?
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 ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom 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 | parserchunk_chain = ____
Checkpoint
Smoke test on the first chunk — expect 2–3 bullet points:
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=4chunk_summaries = ____
Checkpoint
assert len(chunk_summaries) == 5for 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.
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 chainreduce_chain = ____# TODO 6.3 — compose: RunnableLambda(join) | reduce_chainfinal_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!)
a) Write final_summary to my_summary.pdf with fpdf2.
b) Prove the symmetry: re-load your own PDF with your ownMyPDFLoader.
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.pdfFONT = "/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 pathpdf.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 textpdf.output("my_summary.pdf")
# BONUS 8.2 — symmetry check: YOUR loader reads YOUR output PDFcheck = 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
In one sentence each, explain the role of: loader, splitter, prompt template, chain, output parser.
Which components of your pipeline would survive unchanged if the input were a Word file instead of a PDF? Why?
When would map-reduce be the wrong tool? (Think: chunks whose meaning depends on each other.)
What does .batch() buy you over a for loop of .invoke()?
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.1llm = ChatOpenAI(model="openai/gpt-oss-120b", temperature=0.2, base_url="https://openrouter.ai/api/v1")# 2.x — custom loaderclass 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 — splittingsplitter = RecursiveCharacterTextSplitter( chunk_size=4000, chunk_overlap=200, add_start_index=True)chunks = splitter.split_documents(documents)# 4.x — map chainchunk_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 — mapchunk_summaries = chunk_chain.batch( [{"text": c.page_content} for c in chunks[:5]], {"max_concurrency": 4})# 6.x — reducereduce_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 pipelinedef 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.