Overview

3 Summarizing text using LangChain

This chapter moves from concepts to practice by building summarization engines with LangChain’s Expression Language (LCEL). It frames summarization as a pragmatic first step for LLM applications and focuses on real-world scenarios: documents that exceed a model’s context window, summarization across multiple sources, and cases involving structured data. The chapter emphasizes how chains—ordered, composable steps—let you automate summarization reliably and lay the groundwork for more advanced systems later.

For single documents that don’t fit in the context window, the chapter adopts a map-reduce pattern. The text is tokenized and split into overlapping chunks, each chunk is summarized (map), and the resulting summaries are condensed into a final synthesis (reduce). LCEL makes this composition explicit and reusable: text splitting via a RunnableLambda, prompting with PromptTemplate, inference through an LLM, output parsing with StrOutputParser, and parallelization with RunnableParallel. Practical guidance includes choosing chunk sizes, managing overlaps, and accounting for token limits, latency, costs, and rate limiting.

For multiple documents, the same map-reduce idea can be applied across a list of LangChain Document objects created with loaders (e.g., for Wikipedia, Word, PDF, and text). The chapter also introduces the refine technique, which incrementally updates a running summary by combining it with each document in turn—useful when you want high fidelity to every source. A simple decision flow emerges: if your material fits in the context window, “stuff” it into one prompt; if not, use map-reduce for scale and throughput, and prefer refine when preserving the essence of each part is critical. Together, these patterns demonstrate how to orchestrate summarization across large, diverse inputs and prepare for structured-data scenarios explored later.

Summarizing a document bigger than the LLM’s context window: this involves splitting the document into smaller chunks, summarizing each chunk, and then summarizing the combined chunk summaries.
Summarizing across documents using the Map-Reduce technique seen earlier: in this method, each document chunk undergoes a map operation to generate a summary. These individual summaries are then further condensed into a single summary through the reduce operation.
Summarizing across documents using the Refine technique: with this approach, a final summary is constructed incrementally by iteratively summarizing the combination of the current final summary and one of the document chunks. This process continues until all document chunks have been processed, resulting in the completion of the final summary.
Summarization flowchart This flowchart guides you in selecting the right summarization approach based on whether you need to summarize multiple unrelated documents and whether the input text fits within the context window

Summary

  • Summarization is a great starting point for building LLM applications due to its straightforwardness.
  • The choice of technique depends on whether you're summarizing a single document or multiple documents and if the text fits within the context window.
  • Typically, the first step in summarization involves loading each raw text source into a LangChain Document object.
  • For many summarization tasks, a map-reduce approach is effective. This method summarizes each document or chunk individually in the "map" stage, then combines these summaries in the "reduce" stage to create a final summary.
  • When summarizing multiple documents, load each document with the appropriate loader, summarize them individually, and progressively refine the summary by integrating each document’s summary until all are included.
  • Map-reduce is suited for large text summaries where some content loss is acceptable to handle the processing load, while the refine technique ensures the essence of each part is fully retained in the final summary.

FAQ

What is an LLM “context window,” and why does it matter for summarization?The context window is the maximum amount of text (instructions + context) an LLM can receive in a single prompt. Different models support different token limits (roughly word-like units): GPT-3.5 up to 16K, GPT-4 and Claude 3 up to 100K, and newer models such as GPT-5 and Gemini can exceed 1M. If your input exceeds this window, you must chunk or use techniques like map-reduce or refine.
How do I summarize a document that’s larger than the model’s context window?Use a map-reduce approach: split the document into manageable chunks (e.g., with TokenTextSplitter), run a summarization prompt on each chunk (map), then combine those chunk summaries and summarize them again (reduce) to produce a final summary.
Which LangChain/LCEL components are used to build these summarization chains?Key pieces include Runnable (the interface for chainable components), RunnableLambda (wrap any Python callable as a chain step), RunnableParallel (process sequences in parallel), PromptTemplate (build prompts), the pipe operator “|” (compose steps), and StrOutputParser (convert model output to plain text).
How is the “map” step implemented for chunk summarization?You create a prompt like “Write a concise summary of the following text...” with a {chunk} variable, pipe it into the LLM, then into StrOutputParser. Use RunnableParallel (and .map()) to apply this per chunk so each chunk is summarized in parallel.
How is the “reduce” step implemented to combine chunk summaries?Collect the per-chunk summaries, join them (e.g., with newlines) into a single string, then feed that string into a second prompt that asks the LLM to produce a concise summary of the summaries. Parse the result to get the final summary.
How do I execute the end-to-end map-reduce chain?Compose three parts: a chunking chain, a map chain (summarize each chunk), and a reduce chain (summarize the summaries). Invoke the composed chain on your source text (e.g., map_reduce_chain.invoke(moby_dick_book)) and print the resulting summary. Be mindful of potential 429 rate-limit errors on free tiers.
How can I manage cost and rate limits when summarizing large texts?Use shorter inputs or fewer documents, reduce chunk size and number of runs, and choose cost-effective models. Example from the chapter: the full Moby Dick (~350K tokens) costs about $0.37 at $1.25/million tokens (GPT-5) or ~$0.015 at $0.05/million (GPT-5-nano). Ensure you have sufficient billing credit to avoid 429 quota errors.
How do I summarize content across multiple sources (Wikipedia, Word, PDF, TXT)?Load content into Document objects using loaders like WikipediaLoader, Docx2txtLoader, PyPDFLoader, and TextLoader. Merge all documents into a single list and then apply either a map-reduce or refine summarization workflow.
When should I use map-reduce vs. refine?Use map-reduce for very large volumes where some information loss is acceptable to scale processing. Use refine when you want to ensure each document’s essence is preserved—building the final summary progressively by iteratively incorporating each document.
How does the refine workflow operate in practice?Summarize a document, then iteratively feed the current refined summary plus the next document’s content to a refine prompt. Repeat for all documents. The function returns both the final summary and the intermediate steps so you can see how the summary evolved.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free