Project 1: Chat with Your PDFs

A complete PDF question-answering app with citations and a Streamlit UI.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 24 · Lesson 1 of 7 · Intermediate

Project 1: Chat with Your PDFs

A complete PDF question-answering app with citations and a Streamlit UI.

In this first capstone project you build a complete, interactive "chat with your PDFs" application. Users upload PDF files in a browser, the app indexes them, and users ask questions in a chat interface. Answers stream in with page-level citations, and the retrieved passages can be inspected. It combines loading (Module 2), chunking (Module 3), embeddings and search (Modules 4 to 6), and grounded, streamed generation (Module 9).

What you will build

  • A Streamlit web app with a sidebar for uploading PDFs and a chat area.
  • Per-page extraction, recursive chunking with overlap and contextual headers.
  • An in-memory vector index with the local BGE embedding model.
  • Streaming answers with citations in the form [file, p. 4], plus a "Sources" panel.
  • Conversation memory with query condensing for follow-up questions.
pip install streamlit pypdf sentence-transformers numpy anthropic

The complete application

pdf_chat_app.py
"""Chat with your PDFs: a complete RAG app in one file.  Run: streamlit run pdf_chat_app.py"""
import anthropic
import numpy as np
import streamlit as st
from pypdf import PdfReader
from sentence_transformers import SentenceTransformer

MODEL = "claude-opus-5-5"
QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
SYSTEM = """You answer questions about the user's uploaded PDF documents.
Use only the provided sources. After each statement, cite its source in square brackets
exactly as labelled, e.g. [report.pdf, p. 4]. If the sources do not contain the answer,
say so clearly. Be concise."""

st.set_page_config(page_title="Chat with your PDFs", page_icon="??")
client = anthropic.Anthropic()

@st.cache_resource
def get_embedder() -> SentenceTransformer:
    return SentenceTransformer("BAAI/bge-small-en-v1.5")

# ---------- Indexing ----------
def split(text: str, size: int = 900, overlap: int = 150) -> list[str]:
    chunks, start = [], 0
    while start < len(text):
        end = min(start + size, len(text))
        if end < len(text):
            cut = max(text.rfind("\n\n", start, end), text.rfind(". ", start, end))
            if cut > start + size // 2:
                end = cut + 1
        chunks.append(text[start:end].strip())
        if end >= len(text):
            break
        start = end - overlap
    return [c for c in chunks if len(c) > 40]

def build_index(files) -> dict:
    records = []
    for f in files:
        reader = PdfReader(f)
        for page_no, page in enumerate(reader.pages, start=1):
            for chunk in split(page.extract_text() or ""):
                records.append({"file": f.name, "page": page_no,
                                "text": f"[{f.name}, page {page_no}]\n{chunk}"})
    if not records:
        return {"records": [], "vectors": None}
    vectors = get_embedder().encode([r["text"] for r in records], normalize_embeddings=True,
                                    batch_size=64, show_progress_bar=False)
    return {"records": records, "vectors": vectors}

def search(index: dict, query: str, k: int = 5) -> list[dict]:
    q = get_embedder().encode(QUERY_PREFIX + query, normalize_embeddings=True)
    scores = index["vectors"] @ q
    return [{**index["records"][i], "score": float(scores[i])} for i in np.argsort(-scores)[:k]]

# ---------- Generation ----------
def condense(history: list[dict], question: str) -> str:
    if not history:
        return question
    convo = "\n".join(f"{m['role']}: {m['content'][:400]}" for m in history[-6:])
    msg = client.messages.create(
        model=MODEL, max_tokens=200, output_config={"effort": "low"},
        messages=[{"role": "user", "content":
            f"Conversation:\n{convo}\n\nRewrite this follow-up as a standalone search question. "
            f"Output only the question.\nFollow-up: {question}"}])
    return msg.content[0].text.strip()

def stream_answer(history: list[dict], question: str, hits: list[dict]):
    sources = "\n\n".join(f'<source label="{h["file"]}, p. {h["page"]}">\n{h["text"]}\n</source>'
                          for h in hits)
    messages = history[-6:] + [{"role": "user",
                                "content": f"<sources>\n{sources}\n</sources>\n\n{question}"}]
    with client.messages.stream(model=MODEL, max_tokens=2000, output_config={"effort": "low"},
                                system=SYSTEM, messages=messages) as stream:
        for text in stream.text_stream:
            yield text

# ---------- UI ----------
st.title("?? Chat with your PDFs")
with st.sidebar:
    files = st.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
    if st.button("Build index", disabled=not files):
        with st.spinner("Reading and indexing..."):
            st.session_state.index = build_index(files)
            st.session_state.messages = []
        n = len(st.session_state.index["records"])
        if n:
            st.success(f"Indexed {n} chunks from {len(files)} file(s)")
        else:
            st.error("No text found. Scanned PDFs need OCR.")

if "messages" not in st.session_state:
    st.session_state.messages = []

for m in st.session_state.messages:
    with st.chat_message(m["role"]):
        st.markdown(m["content"])

if question := st.chat_input("Ask a question about your documents"):
    index = st.session_state.get("index")
    with st.chat_message("user"):
        st.markdown(question)
    with st.chat_message("assistant"):
        if not index or not index["records"]:
            answer = "Please upload PDFs and click **Build index** first."
            st.markdown(answer)
        else:
            query = condense(st.session_state.messages, question)
            hits = search(index, query)
            answer = st.write_stream(stream_answer(st.session_state.messages, question, hits))
            with st.expander("Sources"):
                for h in hits:
                    st.markdown(f"**{h['file']}, page {h['page']}** (score {h['score']:.2f})")
                    st.caption(h["text"][:500])
    st.session_state.messages += [{"role": "user", "content": question},
                                  {"role": "assistant", "content": answer}]

Run it

streamlit run pdf_chat_app.py

Streamlit opens the app in your browser. Upload one or more PDFs (a product manual or an annual report works well), click Build index and start asking questions. Try a follow-up such as "and what about last year?" to see query condensing at work.

How it maps to the tutorial

FeatureLesson
Per-page PDF extractionLoading Documents
Chunking with overlap and contextual headersFixed-Size Chunking, Contextual Headers
Dense retrievalTop-k Search
Follow-up questionsQuery Condensing
Grounded, cited, streamed answersCitations, Streaming

Extensions

  1. Hybrid search: add BM25 and RRF so part numbers and names are found reliably.
  2. Reranking: retrieve 30 chunks and rerank to 5 with a cross-encoder.
  3. Scanned PDFs: when a page has no text, send the page to the vision model for transcription (Parsing Complex Documents).
  4. Persistence: store the index in Chroma so it survives restarts, keyed by file hash.
  5. Native citations: pass chunks as document blocks with citations enabled to show exact quotes.
  6. Evaluation: write 20 questions about your PDFs and measure hit rate and correctness.

Key takeaways

  • A useful PDF chat app needs only per-page extraction, chunking, embeddings, search and a grounded prompt.
  • Page-level labels in each chunk make citations precise and verifiable.
  • Query condensing makes multi-turn chat work; streaming makes it feel fast.