RAG practice project: build a RAG app on your own PDFs

Parse a PDF with Docling, chunk, embed, store in Qdrant, retrieve and answer with an OpenAI model, step by step with real output and a refusal test.

4 min read7 stepsReal lab output

By Verth Labs · Published

Retrieval-augmented generation (RAG) is the most common way to make a language model answer questions about documents it was never trained on: find the relevant passages first, then ask the model to answer from them. This RAG practice project builds the whole pipeline on a real PDF, step by step: parse, chunk, embed, store, retrieve, answer, and check that the model says "I don't know" when it should. Every output below was captured in GenAI Labs on 14 November 2026.

The document is the paper that introduced the name: "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks" (Lewis et al., arXiv 2005.11401), 19 pages with tables. Use any PDF of your own instead; the steps don't change.

The pipeline

StepTool used hereWhy
Parse the PDFDoclingKeeps headings and tables, not just raw text
ChunkLangChain RecursiveCharacterTextSplitterSplits on paragraphs first, so chunks stay readable
EmbedOpenAI text-embedding-3-smallTurns each chunk into a vector
Store and searchQdrantA vector database with cosine search
AnswerAn OpenAI chat modelWrites the answer from the retrieved chunks only

In GenAI Labs the OpenAI models are included: the standard OpenAI Python SDK is already configured (OPENAI_BASE_URL and OPENAI_API_KEY are set in the lab), so OpenAI() works with no key of your own. Outside the lab, the same code works with your own OpenAI API key.

Step 1: Step 1: parse the PDF with Docling

Plain text extraction loses structure: headings become ordinary lines and tables turn into word soup. Docling converts a PDF into Markdown with headings and tables intact.

import os, urllib.request, time
from docling.document_converter import DocumentConverter

pdf = os.path.expanduser("~/work/rag-demo/rag-paper.pdf")
os.makedirs(os.path.dirname(pdf), exist_ok=True)
req = urllib.request.Request("https://arxiv.org/pdf/2005.11401", headers={"User-Agent": "verth-genai-lab"})
open(pdf, "wb").write(urllib.request.urlopen(req, timeout=120).read())

t0 = time.time()
doc = DocumentConverter().convert(pdf).document
md = doc.export_to_markdown()
print(f"{time.time()-t0:.0f}s  pages={len(doc.pages)}  tables={len(doc.tables)}  chars={len(md)}")
Output
50s  pages=19  tables=7  chars=72447

Nineteen pages, seven tables found, about 72,000 characters of Markdown. The first conversion took 50 seconds on the lab's CPU (Docling runs layout and table models); running it again on the same file took 2 seconds. The Markdown starts with the paper's title as a heading, which is exactly what you want a chunk to carry.

Step 2: Step 2: chunk the text

Chunks that are too large dilute the match; too small and they lose context. 800 characters with 100 characters of overlap is a reasonable start:

from langchain_text_splitters import RecursiveCharacterTextSplitter

chunks = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100).split_text(md)
print(len(chunks), "chunks")
Output
134 chunks

Step 3: Step 3: embed the chunks

from openai import OpenAI

client = OpenAI()   # in GenAI Labs the base URL and key come from the lab
emb = client.embeddings.create(model="text-embedding-3-small", input=chunks, dimensions=384)
vectors = [e.embedding for e in emb.data]
print(len(vectors), "vectors of", len(vectors[0]), "dimensions")
Output
134 vectors of 384 dimensions

text-embedding-3-small produces 1,536 dimensions by default; the dimensions parameter shortens them. 384 dimensions keep storage and search small and are plenty for one paper.

Step 4: Step 4: store the vectors in Qdrant

Qdrant can run as a server or, for a single notebook, in local mode with its data in a folder:

from qdrant_client import QdrantClient
from qdrant_client.models import Distance, PointStruct, VectorParams

qdrant = QdrantClient(path=os.path.expanduser("~/work/rag-demo/qdrant"))
qdrant.create_collection("rag_paper", vectors_config=VectorParams(size=384, distance=Distance.COSINE))
qdrant.upsert("rag_paper", [PointStruct(id=i, vector=v, payload={"text": c})
                            for i, (v, c) in enumerate(zip(vectors, chunks))])
print(qdrant.count("rag_paper"))
Output
count=134

Step 5: Step 5: retrieve

Embed the question with the same model and ask Qdrant for the four closest chunks:

question = "What two RAG model variants does the paper compare, and how do they differ?"
qv = client.embeddings.create(model="text-embedding-3-small", input=[question], dimensions=384).data[0].embedding
hits = qdrant.query_points("rag_paper", query=qv, limit=4).points
for h in hits:
    print(round(h.score, 3), h.payload["text"][:70].replace("\n", " "))
Output
0.589 ## 2.1 Models  RAG-Sequence Model The RAG-Sequence model uses the same
0.588 1 Code to run experiments with RAG has been open-sourced as part of th
0.564 Table 1 shows results for RAG along with state-of-the-art models. On a
0.564 generation (RAG) - models which combine pre-trained parametric and non

The top hit is the right section, "2.1 Models". But look at the second hit: a footnote about where the code is published scores almost the same. Similarity scores are close together and noisy; that is why production RAG systems add hybrid search (keywords plus vectors) and a reranker, both good next steps for this project.

Step 6: Step 6: answer from the context only

The system prompt is the guardrail: answer only from the retrieved text, and say so when the text doesn't contain the answer.

SYSTEM = "Answer only from the context. If the context does not say, reply: not in the document."
context = "\n\n".join(h.payload["text"] for h in hits)
resp = client.chat.completions.create(model="gpt-6-luna", messages=[
    {"role": "system", "content": SYSTEM},
    {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
])
print(resp.choices[0].message.content)
Output
The paper compares RAG-Sequence and a variant that can use different retrieved passages for each
token. RAG-Sequence uses the same retrieved document throughout the generated sequence; the other
variant can condition each token on different passages. The document does not name the second
variant here.

This is a good answer and also a useful failure. The model correctly describes both approaches, but it can't name the second one (RAG-Token) because the chunk that names it wasn't among the four retrieved. The model followed the instruction instead of filling the gap from memory. Fix it on the retrieval side: retrieve more chunks, use larger chunks, or add a reranker, then ask again.

Step 7: Step 7: check that it refuses off-topic questions

q2 = "What is the population of Mumbai?"
# ... same retrieval and prompt as above ...
Output
not in the document

A RAG app that answers anything from the model's general knowledge isn't grounded. Test refusal on purpose, with questions the document can't answer.

Make it a project

  1. Your own PDFs. Replace the paper with five to ten documents you care about (course notes, product manuals, policies) and keep the source file name in each chunk's payload so answers can cite it.
  2. Better retrieval. Compare chunk sizes (400, 800, 1,600) and limit values on ten questions you write yourself, with known answers.
  3. Hybrid search and reranking. Add keyword search and a cross-encoder reranker and measure whether the right chunk moves into the top three.
  4. Evaluate. Score answer faithfulness and context relevance with RAGAS on your ten questions, and log the results to MLflow so you can compare versions.
  5. A user interface. Wrap the pipeline in a small Streamlit or Gradio app.

GenAI Labs has every tool above installed, OpenAI models included and ready-made notebooks for hybrid search, reranking, evaluation and agents. If you are building the operations side (tracking, serving, monitoring), see MLOps practice projects.