Summarize Documents with LangChain, No Chroma Needed

Summarize PDFs of any length with LangChain and OpenAI using a single pass or map-reduce, and why a vector store like Chroma is the wrong tool for it.

In my previous post, I summarized short pieces of text. Long documents need a different approach, because a 200-page report won't fit in one prompt, and even when it does, you'll incur significant cost and quality penalties. This post covers how the Summarize tool in my LangChain examples app handles PDFs of any length, and why it doesn't use a vector database to do it.

Why a Vector Store Is the Wrong Tool for Summaries

Many older LangChain examples split a PDF into pages, embed them into a vector store such as Chroma, run a similarity search, and summarize the results. The search returns only the chunks closest to the query, four by default. With an empty or generic query, those chunks are close to arbitrary, so the "summary" covers a few pages and ignores the rest.

Embeddings help you find the parts of a document that relate to a question. A summary has to cover every part, so retrieval leaves gaps. Vector stores like Chroma work well for answering questions about documents, which I covered in Generative Q&A over Your Documents. To summarize, send the full text to the model.

Extract Text from a PDF

The app reads each page's text layer with pypdf and reports password-protected or unreadable files as clear errors instead of stack traces. Scanned PDFs have no text layer, so they come back empty. Run them through OCR first.

def pdf_text(data: bytes) -> list[str]:
    try:
        return [page.extract_text() or "" for page in PdfReader(BytesIO(data)).pages]
    except FileNotDecryptedError:
        raise FetchError("This PDF is password-protected. Remove the password and try again.") from None
    except PdfReadError:
        raise FetchError("Could not read this PDF.") from None

Single Pass or Map-Reduce

Current models accept long inputs, so most documents are summarized in one call. Above 120,000 characters, roughly 30,000 tokens, the app switches to map-reduce: it splits the text into 60,000-character chunks with some overlap, summarizes each chunk in parallel, then summarizes those summaries in the style you picked:

def summarize(text: str, style: str = "Short") -> str:
    text = text.strip()
    if not text:
        raise ValueError("There is no text to summarize.")
    model = chat_model()
    if len(text) <= SINGLE_PASS_CHARS:
        return model.invoke(_prompt(text, style)).text
    chunks = RecursiveCharacterTextSplitter(chunk_size=60_000, chunk_overlap=1_000).split_text(text)
    partials = model.batch([_prompt(chunk, "Detailed") for chunk in chunks], config={"max_concurrency": 4})
    combined = "\n\n".join(p.text for p in partials)
    return model.invoke(_prompt(combined, style)).text

The chunk summaries always use the detailed style, even if you asked for a short one. That keeps enough of each section for the final pass to work with; condensing twice to 100 words would lose most of the document. The 1,000-character overlap stops a sentence that straddles two chunks from being cut in half.

Long PDFs cost more to summarize. A 400,000-character document takes eight model calls: one for each of its seven chunks and one to combine them.

Deploy the App on Railway

My LangChain Apps template on Railway deploys the app with Postgres and pgvector. Set OPENAI_API_KEY and APP_PASSWORD, so strangers can't spend your credits through the public URL.

Deploy on Railway

Summarize a PDF

Open Summarize, choose PDF, upload a file and pick Short, Detailed or Bullets. A typical report comes back in seconds; a book-length PDF takes longer because of the extra chunk calls.

Summarize tool showing a bullet-point summary of an uploaded PDF
Summarize tool showing a bullet-point summary of an uploaded PDF

Frequently Asked Questions

Do I need a vector database to summarize documents? No. Vector databases retrieve the parts of a document that match a question. A summary needs the whole document, so you send the text to the model directly, in chunks if it's long.

How does LangChain summarize a document that's too long for the model? Split it into chunks, summarize each chunk, then summarize the combined summaries. This is called map-reduce.

Can I summarize a scanned PDF? Not without OCR first. The app reads the PDF's text layer, and scanned pages don't have one.

Subscribe to alphasec

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe