Skip to main content
Guides ••11 min read•

Build a PDF Chatbot Without a Vector Database

Build a PDF chatbot with in-memory RAG on free hosting. Learn the chunk limits, ZeroGPU cold-start costs, and guardrails that keep it honest.

An AI chatbot answering visitor questions from a PDF document, the core of building a PDF chatbot without a vector database.

Most PDF chatbot tutorials end where your problems begin. They hand you a working demo, a line of cosine similarity, and a deployment button, then leave you to discover the cold starts, the scanned pages, and the confidently wrong answers on your own. This is the decision-grade version of that build. You will build a PDF chatbot on free Hugging Face hosting that answers visitor questions from your own documents, and you will skip the vector database on purpose, because for a single site that complexity buys capabilities your traffic cannot yet exercise. The claim is precise and testable: brute-force cosine search over an in-memory MiniLM embedding matrix meets a sub-second latency budget well past tens of thousands of chunks, and the stack fails at extraction quality, sleeping hardware, and unguarded output long before it fails at retrieval. Knowing that order of failure is the entire engineering decision, because it tells you where to spend the complexity you just saved.

Stay in the loop.

Get the latest posts and exclusive content delivered to your inbox.

Join 18 readers. No spam. Unsubscribe in one click, anytime.

The Minimal Stack and Why It Skips the Vector Database

The complete parts list is short, and every piece of it is free:

  • Gradio, deployed as a Hugging Face Space, for the chat interface
  • all-MiniLM-L6-v2 (model card) for MiniLM embeddings: 384 dimensions per chunk, small enough to embed on CPU
  • numpy, for cosine similarity retrieval as one matrix-vector product per question
  • A hosted or ZeroGPU-backed model, for generation

A vector database earns its keep through approximate indexes, metadata filters, and disk persistence. At the scale of one corpus and a few thousand chunks, what it actually adds is a second service to configure, a schema to maintain, and a new class of deployment bugs, in exchange for capabilities your traffic cannot exercise yet. Skipping it is a bounded engineering decision rather than a demo shortcut, and the next two sections quantify the boundary. One warning before the build: the failure modes of this stack live outside the part everyone optimizes. Retrieval is the component that works. Extraction, hosting, and output discipline are where it breaks.

How to Build a PDF Chatbot Pipeline From Extraction to Answer

A chatbot conversation where visitors ask questions about a document, the Gradio chatbot interface layer that handles chat history and streaming.

The pipeline is five steps, and three of them hide the levers that actually determine answer quality.

  1. Extract text with pypdf. Plain per-page extraction (pypdf text extraction). Record each page's extracted character count while you are there; pages near zero characters are the early-warning signal for the scan problem below.

  2. Chunk at 200 to 400 tokens with 10 to 20 percent overlap. The model card documents a 256-token input limit, so chunks much larger than that silently lose their tails to truncation. A paragraph-aware splitter beats a fixed character window, because mid-sentence cuts produce chunks with no standalone meaning.

  3. Embed once at startup. One pass over the corpus takes seconds for a few thousand chunks on CPU. Keep the matrix and the chunk texts together in memory; that pair is your entire index.

  4. Normalize, then search with one product. Normalize embeddings at embed time and cosine similarity collapses into a plain dot product:

# E: (N, 384) matrix of normalized chunk embeddings
# q: (384,) normalized question embedding
scores = E @ q
top = np.argpartition(-scores, k)[:k]  # top-k without a full sort
  1. Assemble the prompt and generate. Top-k chunks into a context block, the visitor's question, then generation. A k of 4 to 6 chunks is a sensible starting range; tune it by watching which citations visitors actually use. Wrap the function in Gradio ChatInterface and the UI, chat history, and streaming are handled, which is most of why a Gradio chatbot is the right interface layer for this build.

The three quiet levers are chunk size, embedding normalization, and answer caching. The first two cost a line of code each and move answer quality more than swapping the generation model. The third is a lever with a failure mode bolted to it, which gets its own section.

Where In-Memory Search Stops Being Enough

The arithmetic behind RAG without a vector database is short enough to do in your head. MiniLM emits 384-dimensional vectors, so an in-memory index costs chunks times 384 times 4 bytes in float32, and every search is one matrix-vector product, N times 384 multiply-adds, executed by an optimized BLAS routine.

ChunksMatrix size (float32)Brute-force search
1,000~1.5 MBwell under 1 ms
10,000~15 MB~1 to 2 ms
50,000~77 MBa few ms
100,000~154 MBsingle-digit ms

These are order-of-magnitude figures on ordinary CPU hardware and will vary by machine, but the margin is not close. At 100,000 chunks, brute-force search costs single-digit milliseconds, roughly a thousand times inside a one-second budget, while even a fast model generating a short answer costs seconds. PDF question answering at this scale is generation-bound, and in-memory RAG's scaling limit is memory footprint and startup re-embedding time, not query latency.

That reframes the question of when to switch from in-memory search to a vector database. The real triggers are:

  • Corpus in the hundreds of thousands of chunks. Memory pressure and minutes-long re-embeds at every deploy break first, not search speed. An ANN index such as FAISS addresses the memory and latency side.
  • Incremental updates. When documents change hourly, re-embedding everything at restart stops being acceptable, and you need to insert new chunks without touching old ones.
  • Metadata filtering. Multi-document or multi-tenant corpora need "search only these documents" semantics, which a raw matrix cannot express.
  • Persistence across restarts. A restarted Space rebuilds from its container image, so an in-memory matrix re-embeds at boot; vector databases persist to disk.

None of those describe a single-site FAQ bot. All four describe the day the minimal stack stops being enough, and the final section maps the observable symptoms.

Silent Failures in Tables, Scans, and Cached Answers

Scanned pages with no text layer, the root cause of a scanned PDF RAG extraction failure where text extraction returns nothing.

Four failure modes masquerade as "the retrieval is bad". Diagnose them in this order, because each one is a specific fix, not a reason to change architecture.

Table-heavy PDFs

Reading-order extraction flattens a pricing table into "Basic 9.99 Pro 29.99", and the generation model confidently invents which plan costs what. No chunking scheme recovers structure that extraction discarded. Route table-heavy pages through pdfplumber's table extraction, or flatten tables into explicit "column: value" lines before chunking. Preserve the structure or the model will fabricate it.

Scanned pages with no text layer

A scanned PDF page is an image, so extraction returns nothing, and no embedding model can recover text that was never captured. The bot answers from whatever other pages it did find, which looks like selective ignorance and is the most common cause of "the answer is in the document but the bot does not know it". Watch the per-page character counts from the pipeline above, and run Tesseract OCR on near-empty page images before extraction.

Unlabeled multi-document corpora

Upload two PDFs with conflicting hours and no source labels, and the bot blends them into one confident answer. Prefix every chunk with a document label at embed time, "From the 2024 Service Catalog:", so provenance becomes part of what the embedding encodes and what the prompt states.

Stale cached answers

The most confidently wrong answer in a minimal build is a cached one that outlived the corpus it answered from. You update the PDF, the Space keeps running, and the cache serves the old hours indefinitely because nobody told it the document changed. Key the cache on a hash of the source files, so any document update invalidates every cached answer automatically. If you cache answers at all, this is the one detail that is not optional.

The ZeroGPU Cost and Cold-Start Math

Free hosting has two hidden line items: GPU quota and sleep.

Quota is metered per request

The Hugging Face Spaces ZeroGPU tier meters GPU time as each request consumes it (ZeroGPU documentation), so a small FAQ bot's monthly footprint is estimable before launch:

expected questions per month × seconds of generation per answer ≈ monthly GPU seconds

At 1,000 questions a month with roughly 5 seconds of generation each, that comes to about 83 GPU-minutes a month, spread across daily allowances. The number that kills small bots is the spike, not the monthly average: one busy day can exhaust the daily allowance and leave the bot failing for every visitor until the window resets.

Sleep is billed to the first visitor

Free Spaces sleep after a documented inactivity window (Space runtime documentation), currently 48 hours as of this writing. The first visitor after sleep pays the full restart: container boot, model load, and corpus re-embedding, often tens of seconds before the first token of the first answer. That wait frequently dominates the perceived cost of the entire answer, because a 2-millisecond search is invisible next to a 30-second boot.

Mitigations, cheapest first:

  1. Run generation on plain CPU. For an FAQ bot, a small model generating short answers on CPU is slow but adequate, and it removes the quota failure mode entirely. Spending scarce GPU quota on a small model is often the worse trade.
  2. Set expectations in the interface. A one-line "the first answer after idle can take a minute" note converts a mysterious hang into an explained wait.
  3. Pay for persistent hardware only once the bot is load-bearing for the business.

Minimal Guardrails for a Bot Left Unattended

An unattended customer-facing chatbot needs four guardrails before it faces the public alone, and I would not ship without any one of them.

  1. A retrieval-score threshold that refuses. Compute the best cosine score for each question. Below a threshold tuned on your own corpus, where the tuning method is feeding the bot questions the PDF cannot answer and watching where good answers become guesses, respond with an explicit refusal and a contact route instead of generating from weak context. This one guardrail removes most hallucinations in an FAQ bot, because the model is never asked to answer questions it has no grounds for.

  2. Inline citations. Attach the source document and page to every answer. Citations let visitors verify claims, and they convert silent retrieval failures into visible ones, because when the citation is wrong, you hear about it.

  3. PDF text as untrusted input. Retrieved chunks are injected into the prompt, which means anyone who can edit the source PDF can steer the model. Wrap chunk text in delimiters, instruct the model to treat delimited content as data rather than instructions, and keep system-level rules out of the corpus. Prompt injection is listed in the OWASP Top 10 for LLM Applications, and document content deserves the same suspicion as input from an anonymous visitor.

  4. A human escalation path. Every refusal should end with an email address or contact link. A bot that refuses and dead-ends converts a safety feature into a lost customer.

This is the guardrail set sized for an unattended small-business FAQ bot. Rate limiting, moderation layers, and PII scrubbing are for bots with real adversaries, and a local business document rarely attracts them.

When to Graduate Off the Minimal Stack

Symptoms, not calendar dates, trigger the move. Match what you observe to the smallest fix that addresses it:

SymptomWhat it actually meansSmallest sufficient action
Answers creep past a secondcorpus well past 100,000 chunks, or a model too large for CPUANN index such as FAISS, or a smaller model
Every deploy re-embeds for minutescorpus growth made restart the bottlenecka vector database with disk persistence
Requests to search only certain documentsmulti-document or multi-tenant needmetadata filtering in a vector database
Stale answers after a document updatecache invalidation failurehash-keyed cache first, a database only if updates are constant
First visitors wait, busy days error outcold starts and quota spikes are business costspersistent hardware

The compressed decision rule: build a PDF chatbot this way when one site, one corpus, and questions a normal document can answer describe your problem. The in-memory approach is the correct architecture for that shape of problem, not a stepping stone to apologize for, and it degrades loudly, in the symptoms above, instead of silently. When those symptoms arrive, graduate one component at a time, and only the component the symptom names.

Stay in the loop.

Get the latest posts and exclusive content delivered to your inbox.

Join 18 readers. No spam. Unsubscribe in one click, anytime.

About the author

David Moreno

Applied AI Strategist

David helps teams put AI to work in real businesses. He writes teardowns of how companies actually deploy models: the architectures, the trade-offs, and the results that survive contact with the real world.

Related Posts