RAG Knowledge Base
Build a searchable knowledge base from your own PDFs, text files, and Markdown. This end-to-end .NET demo extracts and chunks documents, creates real provider embeddings, persists vectors in SQLite, and grounds answers in the passages most relevant to each question.
Documents first. Questions after indexing.
Add your source files
Review the included public-domain book excerpts, upload PDF/TXT/MD files, or remove documents from the library.
Create the vector database
Extract text, split it into overlapping passages, embed in batches, and save vectors and citations beside the source files.
Ask about indexed content
Embed the question with the same model, retrieve the closest passages, and ask a chat model to answer with source citations.
The document library lives in wwwroot/rag-knowledge-base as requested. Files in this folder are
public website assets; do not upload private, confidential, or copyrighted material you are not allowed to
process. Text sent for embeddings and retrieved passages sent for answers go to the configured providers.
The browser's provider keys are transferred to this server for each operation and are not written to the
vector database. Production deployments should put private documents outside wwwroot, require
authentication, and use persistent writable storage.
Knowledge-base documents
Saved in src/BlazorWebApp/wwwroot/rag-knowledge-base/.
PDF, TXT, and MD files up to 10 MB each; maximum 50 files.
Create or rebuild the vector database
PDF pages are extracted with PdfPig. Text and Markdown use UTF-8. The app creates sentence-aware chunks
of about 1600 characters with overlap, embeds batches of 32 using
text-embedding-3-small, and stores the vectors, text, file names, and PDF page numbers in
rag-vector-store.sqlite3 in the same folder as the source files.
text-embedding-3-small.Built 31.10.2026 18:27Ask the indexed books
The question is embedded in the same vector space, cosine similarity selects the five closest passages,
and the configured default chat provider receives only those passages as evidence. Answers include
source markers such as [Source 1], with matching file and page references below.
From a file to a cited answer
| Stage | Implementation in this demo | Why it matters |
|---|---|---|
| Load | PDF page text with PdfPig; UTF-8 text and Markdown; fixed extension/size limits. |
Source file names and PDF page numbers stay attached for citations. Image-only scans need OCR, which is intentionally not included. |
| Chunk | Small, overlapping passages, split near sentence boundaries; each chunk retains its document and page metadata. | Retrieval uses precise evidence while overlap reduces context lost at a chunk boundary. |
| Embed | Microsoft.Extensions.AI IEmbeddingGenerator backed by text-embedding-3-small; batches contain at most 32 passages. |
Both documents and questions must use the same embedding model and vector dimensions. |
| Persist + search | Microsoft.Data.Sqlite stores passage text, metadata, and float vectors in a transaction. The app ranks a small collection with cosine similarity. |
This embedded, durable store is simple to run locally. Large or multi-user collections should use a dedicated vector engine. |
| Answer | The five closest passages are sent to the configured chat provider with instructions to treat document content as untrusted evidence and cite source markers. | The model is asked to say when the retrieved text does not support an answer; always verify high-stakes claims and citations. |
NuGet packages used
| Package | Purpose | Choice for this sample |
|---|---|---|
PdfPig | Extracts selectable text from PDF pages in managed .NET code. | Local parsing, no PDF upload service; scanned/image-only PDFs require a separate OCR step. |
Microsoft.Extensions.AI | Common IEmbeddingGenerator and IChatClient abstractions. | Keeps ingestion and answer logic separate from the provider SDK. |
Microsoft.Extensions.AI.OpenAI + OpenAI | Adapts OpenAI embeddings and chat to .NET AI interfaces. | OpenAI embeddings are fixed to text-embedding-3-small for a consistent index. |
Microsoft.Data.Sqlite | Persists vectors, source text, metadata, and index version to a local SQLite database. | No container or hosted vector database is needed for this small demonstration. |
Markdig | Optional Markdown parsing/rendering for applications that need to interpret Markdown structure. | Here, headings and Markdown text remain searchable as plain text; the package is already used elsewhere in this app. |
Install the core packages
dotnet add package PdfPig
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI
dotnet add package Microsoft.Data.Sqlite
The central .NET operations
using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;
using UglyToad.PdfPig;
using var pdf = PdfDocument.Open("handbook.pdf");
foreach (var page in pdf.GetPages())
{
Console.WriteLine($"Page {page.Number}: {page.Text}");
}
IEmbeddingGenerator<string, Embedding<float>> embeddings =
new OpenAIClient(new ApiKeyCredential(openAiKey))
.GetEmbeddingClient("text-embedding-3-small")
.AsIEmbeddingGenerator();
GeneratedEmbeddings<Embedding<float>> vectors =
await embeddings.GenerateAsync(["first passage", "second passage"]);
// Persist each text, vector, source file, and page number together.
// At query time, embed the question with this same generator,
// rank stored vectors by cosine similarity, then cite the retrieved sources.
Persist and retrieve vectors with SQLite
This compact example shows the same storage and ranking mechanism used by the playground. A dedicated vector engine can replace the linear scan when the collection becomes large.
using Microsoft.Data.Sqlite;
var storePath = Path.Combine(webRoot, "rag-knowledge-base", "rag-vector-store.sqlite3");
await using var database = new SqliteConnection($"Data Source={storePath}");
await database.OpenAsync();
await using (var schema = database.CreateCommand())
{
schema.CommandText = """
CREATE TABLE IF NOT EXISTS RagChunks (
Id TEXT PRIMARY KEY NOT NULL,
DocumentName TEXT NOT NULL,
PageNumber INTEGER NULL,
ChunkNumber INTEGER NOT NULL,
Content TEXT NOT NULL,
Embedding BLOB NOT NULL
);
""";
await schema.ExecuteNonQueryAsync();
}
float[] vector = (await embeddings.GenerateAsync([chunkText]))[0].Vector.ToArray();
byte[] vectorBytes = new byte[vector.Length * sizeof(float)];
Buffer.BlockCopy(vector, 0, vectorBytes, 0, vectorBytes.Length);
await using (var insert = database.CreateCommand())
{
insert.CommandText = """
INSERT INTO RagChunks
(Id, DocumentName, PageNumber, ChunkNumber, Content, Embedding)
VALUES ($id, $file, $page, $chunk, $content, $vector)
""";
insert.Parameters.AddWithValue("$id", Guid.NewGuid().ToString("N"));
insert.Parameters.AddWithValue("$file", fileName);
insert.Parameters.AddWithValue("$page", pageNumber is null ? DBNull.Value : pageNumber);
insert.Parameters.AddWithValue("$chunk", chunkNumber);
insert.Parameters.AddWithValue("$content", chunkText);
insert.Parameters.AddWithValue("$vector", vectorBytes);
await insert.ExecuteNonQueryAsync();
}
float[] queryVector = (await embeddings.GenerateAsync([question]))[0].Vector.ToArray();
var ranked = new List<(string File, int? Page, string Text, double Score)>();
await using (var search = database.CreateCommand())
{
search.CommandText = "SELECT DocumentName, PageNumber, Content, Embedding FROM RagChunks";
await using var reader = await search.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
byte[] storedBytes = reader.GetFieldValue<byte[]>(3);
float[] storedVector = new float[storedBytes.Length / sizeof(float)];
Buffer.BlockCopy(storedBytes, 0, storedVector, 0, storedBytes.Length);
var page = reader.IsDBNull(1) ? null : reader.GetInt32(1);
ranked.Add((reader.GetString(0), page, reader.GetString(2), Cosine(queryVector, storedVector)));
}
}
var topFive = ranked.OrderByDescending(item => item.Score).Take(5);
static double Cosine(float[] left, float[] right)
{
double dot = 0, leftNorm = 0, rightNorm = 0;
for (var i = 0; i < left.Length; i++)
{
dot += left[i] * right[i];
leftNorm += left[i] * left[i];
rightNorm += right[i] * right[i];
}
if (leftNorm == 0 || rightNorm == 0) return 0;
return dot / (Math.Sqrt(leftNorm) * Math.Sqrt(rightNorm));
}
IEmbeddingGenerator as the provider boundary and replace the
local SQLite cosine scan with a vector-store connector such as Qdrant, PostgreSQL/pgvector, or Azure AI
Search. Add authorization filters, ingestion queues, OCR where needed, idempotent document versions,
deletion propagation, and retrieval evaluation before using a production knowledge base.
Included sample books
Each checked-in PDF is a ten-page text excerpt from a well-known public-domain book:
- Alice's Adventures in Wonderland by Lewis Carroll.
- The Adventures of Sherlock Holmes by Arthur Conan Doyle.
- The Time Machine by H. G. Wells.