Beril Tezcan workspace
Software Engineer & QA Engineer

Beril Tezcan

I'm a Software Test Engineer at i2i, where I focus on QA and test automation. I come from a software development background - building with ASP.NET Core and .NET - and I'm still learning, building and growing every day.

Software

What Is RAG?

Building Document-Grounded AI with a PDF Assistant
B
Beril Tezcan Software Engineer · QA Engineer 👁 121 views
What Is RAG?
Link copied!

Large language models can answer a wide range of questions, but they don't automatically know what's inside your private documents. One way to provide this information is to send the entire document to the model with every question. However, this approach quickly becomes inefficient.

Long documents consume the model's context window, increase API costs, and may introduce irrelevant information into the prompt.

Retrieval-Augmented Generation (RAG) solves this problem by combining information retrieval with language generation. Instead of sending an entire document to the model, a RAG application retrieves only the relevant sections and uses them as context to generate an answer.

RAG workflow illustration

In this article, I'll explain how RAG works and walk through the implementation of a PDF assistant built with ASP.NET Core, React, SQLite, and OpenRouter.

How Does RAG Work?

A RAG application follows two main stages: retrieving relevant information and generating an answer based on that information.

Before a user asks a question, the document is processed and its content is stored in a searchable format. When a question is submitted, the application searches for the most relevant parts of the document and sends them to the language model.

The model then generates an answer using the retrieved information.

RAG Pipeline

  • PDF → Text extraction
  • Text extraction → Chunking
  • Chunking → Embeddings
  • Embeddings → Vector storage
  • Question → Query embedding
  • Query embedding → Similarity search
  • Relevant chunks + question → LLM
  • LLM → Grounded answer

This approach allows the application to work with large documents without sending all their content to the model every time.

Why Not Send the Entire PDF to the Model?

Sending a complete document directly to a language model might work for small PDFs, but it introduces several problems as documents become larger.

  • Context window limitations: Large documents may exceed the model's context limit.
  • Higher costs: The same document content is sent repeatedly with every question.
  • Irrelevant information: Unrelated sections can make the prompt less focused.
  • Less accurate answers: Similar terms appearing in different sections may confuse the model.
  • Limited source traceability: Identifying which part of the document supports an answer becomes more difficult.

RAG addresses these issues by retrieving a small number of relevant text sections before generating a response.

The Two Main RAG Workflows

A RAG application can be divided into two independent workflows: document ingestion and retrieval with generation.

1. Document Ingestion

The ingestion process prepares the document for future searches.

It consists of four main steps:

  1. Extract text from the PDF.
  2. Split the extracted text into smaller chunks.
  3. Convert each chunk into an embedding.
  4. Store the chunks and their embeddings.

Once this process is complete, the document is ready to be searched.

2. Retrieval and Generation

When the user asks a question, the application performs the following steps:

  1. Convert the question into an embedding.
  2. Compare it with the stored document embeddings.
  3. Retrieve the most relevant chunks.
  4. Build a context using the retrieved content.
  5. Send the question and context to the language model.
  6. Return a document-grounded answer.

The important part is that the language model doesn't need to read the entire document. It receives only the information that is relevant to the current question.

Extracting Text from the PDF

The first step in the ingestion pipeline is extracting text from the PDF.

In this project, I use PdfPig to extract text page by page. Keeping the page number alongside the extracted text is important because it allows the application to reference the original source when generating answers.

using UglyToad.PdfPig;

using var document = PdfDocument.Open(filePath);

IReadOnlyList<PdfPageText> pages = document
    .GetPages()
    .Select(page => new PdfPageText(
        page.Number,
        page.Text))
    .ToList();

Each extracted page contains its page number and text content. This information is preserved throughout the pipeline and later included in the prompt.

For example, the model can reference its source as (Page 4) instead of generating an answer without any indication of where the information came from.

One limitation to keep in mind is that PDF parsers can extract only text that is available as text in the document. Scanned PDFs containing images require an additional OCR step, which is not included in this MVP.

Splitting the Document into Chunks

An entire PDF page may still contain too much information to be represented effectively by a single embedding. Therefore, the extracted text is divided into smaller pieces called chunks.

For this project, I use the following configuration:

  • Chunk size: 1,000 characters
  • Overlap: 150 characters

The overlap helps preserve context between consecutive chunks. Without it, a sentence or explanation could be split between two chunks, making it harder for the retrieval process to find the complete information.

Here's the chunking implementation:

public IReadOnlyList<TextChunk> Chunk(
    IReadOnlyList<PdfPageText> pages,
    int chunkSize = 1000,
    int overlap = 150)
{
    var chunks = new List<TextChunk>();

    foreach (var page in pages)
    {
        var text = page.Text;
        var start = 0;
        var chunkIndex = 1;

        while (start < text.Length)
        {
            var end = Math.Min(
                start + chunkSize,
                text.Length);

            if (end < text.Length)
            {
                var lastSpace = text.LastIndexOf(
                    ' ',
                    end - 1,
                    end - start);

                if (lastSpace > start + chunkSize * 0.7)
                {
                    end = lastSpace;
                }
            }

            var chunkText = text[start..end].Trim();

            if (!string.IsNullOrWhiteSpace(chunkText))
            {
                chunks.Add(new TextChunk(
                    chunkIndex,
                    page.PageNumber,
                    chunkText));
            }

            if (end >= text.Length)
            {
                break;
            }

            start = Math.Max(
                end - overlap,
                start + 1);

            chunkIndex++;
        }
    }

    return chunks;
}

Chunk size is an important design decision in RAG systems.

  • Smaller chunks may lack enough context to answer a question.
  • Larger chunks may contain unnecessary information and increase the amount of data sent to the model.
  • Too much overlap can result in duplicate retrieval results.
  • Too little overlap can break important information across chunk boundaries.

There isn't a single chunk size that works best for every document. The ideal configuration depends on the document structure and the type of questions users are expected to ask.

Generating Embeddings

An embedding is a numerical representation of text that captures aspects of its meaning.

Texts with similar meanings tend to have vectors that are closer to each other in the embedding

Explore the Project

Want to see how everything works in practice?

You can explore the complete source code, review the implementation, and follow the development of the project on GitHub.

View the complete project on GitHub →

Comments

No comments yet. Be the first!