RAG on pgvector in FastAPI: an Ingest and an Ask Endpoint, a Supabase Login Token That Picks the Owner, and Answers With Citations
A librarian endpoint shelves documents as pgvector rows, a reader endpoint answers with citations, and the Supabase token's sub claim decides whose shelf you search. Three questions come back with scores like 0.6953, a call without a token gets 401, and 14 tests pass.
What you will learn
- Store chunks and 384-number embeddings in a Postgres table with a pgvector column and an HNSW index
- Build /ingest and /ask endpoints in FastAPI that answer with numbered citations
- Use the sub claim of a Supabase JWT as the owner so each user searches only their own documents
- Rebuild a help-centre knowledge base with a loader, a chunker and a reindex that runs in one transaction
Before you start
- Vector Databases Hands-On: The Same Search in Chroma and pgvector
- FastAPI for AI Services
- Supabase as a Backend
In this article we make a model answer questions from our own documents and tell us exactly where each answer came from. The documents live as vectors in Postgres with pgvector, FastAPI gets an /ingest and an /ask endpoint, and both are protected by the Supabase login token. At the end we look at a second project, the knowledge base of a support copilot, which shelves a whole help-centre folder with a loader, a chunker and a reindex.
No API key is needed. A stand-in test model answers, and the embedding model runs on your own machine.
A library for your documents
Two people work in a library. The librarian puts new books on the shelf, and the reader asks a question at the front desk.
- Our librarian is the
/ingestendpoint. It takes a document, like the returns policy, cuts it into chunks of whole paragraphs, and writes an index card for every chunk: 384 numbers that describe the meaning. The cards go on the shelf, a Postgres table with a pgvector column. - Our reader is the
/askendpoint. A question comes in with a login token, we search the cards closest in meaning, and the three best chunks go to the model, which answers only from them.
The answer comes back with citations: which document, which chunk, and how close it was.
The project and the database
The sample documents are three short markdown files: returns-policy.md, shipping-info.md and tent-care-guide.md. The database is the pgvector/pgvector:pg17 image (Postgres 17 with the vector extension) started by Docker Compose. The db service maps port 5434 on your machine to 5432 in the container, so it doesn't clash with another Postgres, and its health check runs pg_isready every two seconds.
docker compose up -d --wait db
The .env file holds DATABASE_URL (the local Docker database), SUPABASE_JWT_SECRET (a local test value that signs and checks login tokens) and two empty Anthropic settings. Empty means the stand-in test model answers, so everything runs for free.
store.py: one table, one index, one search
SCHEMA = """
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS chunks (
id bigserial PRIMARY KEY,
owner_id text NOT NULL,
source text NOT NULL,
chunk_index int NOT NULL,
content text NOT NULL,
embedding vector(384) NOT NULL
);
CREATE INDEX IF NOT EXISTS chunks_embedding_idx
ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX IF NOT EXISTS chunks_owner_idx ON chunks (owner_id);
"""
SEARCH_SQL = """
SELECT source, chunk_index, content, 1 - (embedding <=> %s) AS score
FROM chunks
WHERE owner_id = %s
ORDER BY embedding <=> %s
LIMIT %s
"""
Every row is one chunk: the owner, the source file, the chunk number, the text and a vector of 384 numbers. The HNSW index with vector_cosine_ops lets Postgres find the nearest vectors quickly, even with many rows. In the search, <=> is pgvector's cosine distance. We order by it, and 1 - distance becomes the score, so higher is better. WHERE owner_id = %s means every search only looks at your own documents.
The same file has a MemoryStore class with the same methods in a Python list, so most tests need no database. If pgvector itself is new to you, start with Vector Databases Hands-On.
Chunks and vectors
"""Cut a document into small pieces: whole paragraphs, merged up to a size limit."""
def chunk_text(text: str, max_chars: int = 420) -> list[str]:
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks: list[str] = []
current = ""
for paragraph in paragraphs:
if current and len(current) + len(paragraph) + 1 > max_chars:
chunks.append(current)
current = paragraph
else:
current = f"{current}\n{paragraph}".strip()
if current:
chunks.append(current)
return chunks
chunk_text splits on blank lines, so it always works with whole paragraphs, then merges paragraphs until the next one would pass 420 characters. No paragraph is cut in half. embedder.py wraps a SentenceTransformer for all-MiniLM-L6-v2 and calls encode(texts, normalize_embeddings=True), so every vector has length one and cosine distance works nicely. settings.py sets TOP_K = 3.
The login token decides the owner
A user logs in through Supabase with an email and a password. Supabase gives back an access token, a JWT that holds sub (the user id), the audience authenticated and an expiry time, signed with the project's JWT secret. Our API checks the token with the same secret. If it is valid, sub becomes the owner_id of every chunk we store and search.
import jwt
from fastapi import Header, HTTPException
from app import settings
def user_id_from_token(token: str, secret: str) -> str:
try:
claims = jwt.decode(token, secret, algorithms=["HS256"], audience="authenticated")
except jwt.ExpiredSignatureError:
raise HTTPException(401, "token expired")
except jwt.InvalidTokenError:
raise HTTPException(401, "invalid token")
return claims["sub"]
def current_user(authorization: str | None = Header(default=None)) -> str:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(401, "missing bearer token")
return user_id_from_token(authorization.removeprefix("Bearer "),
settings.SUPABASE_JWT_SECRET)
No token, a wrong secret, an expired token or the wrong audience all end in 401. Locally, 02_make_token.py signs a token with the same claims (sub, aud, exp one hour ahead) and the same secret, so we need no Supabase login to test.
llm.py: a prompt that asks for citations
def build_prompt(question: str, passages: list[dict]) -> str:
numbered = "\n\n".join(f"[{i}] ({p['source']})\n{p['content']}"
for i, p in enumerate(passages, start=1))
return ("Answer the question using only the numbered passages below. "
"Add the passage number in square brackets after each fact, like [1]. "
"If the passages do not contain the answer, say you do not know.\n\n"
f"Passages:\n{numbered}\n\nQuestion: {question}")
The stand-in TestModel needs no key. It takes the first sentence of the best passage, adds [1] and ends with [test model reply], so you always know who answered. get_model() returns a real Anthropic model only when both a key and a model name are set. Numbering and checking citations is covered in depth in RAG Prompt Assembly and Citations.
main.py: the two endpoints
class AskRequest(BaseModel):
question: str
top_k: int = settings.TOP_K
def create_app(store=None, embedder=None, model=None) -> FastAPI:
state = {}
@asynccontextmanager
async def lifespan(app):
state["store"] = store or PgStore()
state["store"].init_schema()
state["embedder"] = embedder or Embedder()
state["model"] = model or get_model()
yield
app = FastAPI(title="RAG on pgvector", lifespan=lifespan)
@app.post("/ingest")
def ingest(body: IngestRequest, user_id: str = Depends(current_user)):
chunks = chunk_text(body.text)
vectors = state["embedder"].embed(chunks)
stored = state["store"].replace_document(user_id, body.source, chunks, vectors)
return {"source": body.source, "chunks": stored}
@app.post("/ask")
def ask(body: AskRequest, user_id: str = Depends(current_user)):
vector = state["embedder"].embed([body.question])[0]
passages = state["store"].search(user_id, vector, body.top_k)
answer = state["model"].answer(body.question, passages)
citations = [{"n": i, "source": p["source"], "chunk_index": p["chunk_index"],
"score": round(p["score"], 4), "text": p["content"]}
for i, p in enumerate(passages, start=1)]
return {"answer": answer, "model": state["model"].name, "citations": citations}
return app
The lifespan function runs once at startup: it creates the table, loads the embedding model and picks the chat model. Both endpoints take user_id from Depends(current_user), so neither works without a valid token. replace_document deletes the old rows for that owner and source before inserting, so ingesting the same file twice replaces it. (The file also has a /health route.) Start it with python -m uvicorn app.main:app --port 8000.
Calling the API
03_try_it.py first calls /ask without a token, then ingests the three sample documents with the token, then asks three questions.
no token -> 401 {'detail': 'missing bearer token'}
ingest {'source': 'returns-policy.md', 'chunks': 2}
ingest {'source': 'shipping-info.md', 'chunks': 1}
ingest {'source': 'tent-care-guide.md', 'chunks': 2}
Q: How long do I have to send an item back?
A: You can return any unused item within 30 days of delivery for a full refund. [1] [test model reply]
[1] returns-policy.md #0 score 0.6953
[2] shipping-info.md #0 score 0.4216
[3] returns-policy.md #1 score 0.3878
Q: Can I get the parcel tomorrow?
A: Standard delivery takes 3 to 5 business days and costs 4.99 dollars. [1] [test model reply]
[1] shipping-info.md #0 score 0.4067
[2] returns-policy.md #0 score 0.3385
[3] returns-policy.md #1 score 0.3274
Q: How do I stop my tent from going mouldy?
A: Never pack a tent away wet. [1] [test model reply]
[1] tent-care-guide.md #0 score 0.5799
[2] tent-care-guide.md #1 score 0.5372
[3] returns-policy.md #1 score 0.0788
The door is locked without a token. Three ingests store 2 + 1 + 2 = 5 chunks. Each question finds the right file first. The parcel question is worth a second look: the best chunk is shipping-info.md #0, and the stand-in quotes its first sentence, about standard delivery. A real model would pick the express-delivery sentence from the same passage. The retrieval was right; the stand-in is simply naive.
Inside the database, \d chunks shows the embedding column as vector(384) and the HNSW index on it with vector_cosine_ops, just like store.py, and a SELECT on the table shows exactly five rows.
Users only see their own documents
def test_users_only_see_their_own_documents(loaded):
body = loaded.post("/ask", headers=auth("user-b"),
json={"question": "Can I return a tent?"}).json()
assert body["citations"] == []
assert body["answer"].startswith("I do not know")
User B logs in with a different sub, so the WHERE owner_id filter returns nothing and the answer starts with "I do not know". The other tests check no token, a wrong secret, an expired token and a wrong audience. With the database up, pytest prints 14 passed; with the database down, the one real pgvector round trip is skipped and you see 13 passed, 1 skipped.
The same code on Supabase
Only the settings change:
- In the Supabase SQL editor, run
create extension if not exists vector; - Copy the database connection string from the project settings into
DATABASE_URLin.env. - Copy the JWT secret into
SUPABASE_JWT_SECRET, so the API trusts real login tokens. - Start the API again. The lifespan function creates the
chunkstable by itself.
For a real model, pip install anthropic and put a key and a model name in .env. get_model() switches, and nothing else changes. When you are done locally, docker compose down -v removes the container, the network and the volume with all stored chunks.
A whole help centre: loader, chunker and reindex
The Support Copilot project uses the same idea for its knowledge base, but the documents are a folder of help-centre files, and only an admin can rebuild the shelf. This is a different project with a different table, so keep the two apart:
| RAG API above | Support Copilot knowledge base | |
|---|---|---|
| Table | chunks, with owner_id | kb_chunks, shared by everyone, UNIQUE (source, chunk_idx) |
| Input | One document per /ingest call | The whole data/help_center folder: 7 markdown files and a 2-page PDF |
| Chunking | Whole paragraphs, up to 420 characters | Whole sentences, up to 700 characters, with the title and heading in front |
| Rebuild | Replace one source for one owner | POST /api/admin/reindex, admin only |
The loader turns every file into Section objects with metadata. A markdown file is split by its ## headings, a PDF by its pages:
@dataclass
class Section:
source: str # file name, shown to the customer as the citation
title: str # page title, for markdown the "# ..." line
heading: str # the "## ..." heading the text sits under ("" for PDFs)
page: int | None # PDF page number, None for markdown
text: str
Eight files give 28 sections. The chunker packs whole sentences into pieces of at most 700 characters and puts the page title and heading in front, so a chunk still makes sense on its own (the "charged twice" chunk starts with "Returns and refunds - Charged twice:" and is 313 characters long). The longest section is 471 characters, so every section fits in one chunk: 28 in, 28 out.
The reindex replaces everything in one transaction:
def reindex(folder: Path | None = None) -> dict:
"""Read all docs, cut them, embed them and replace what is stored. Safe to run again and again."""
ensure_schema()
chunks = chunk_sections(load_folder(folder or Path(settings.kb_dir)))
vectors = embed([c.content for c in chunks])
with connect() as conn, conn.transaction():
conn.execute("TRUNCATE kb_chunks RESTART IDENTITY")
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO kb_chunks (source, title, page, chunk_idx, content, embedding) "
"VALUES (%s, %s, %s, %s, %s, %s::vector)",
[(c.source, c.title, c.page, c.chunk_idx, c.content, to_pgvector(v)) for c, v in zip(chunks, vectors)],
)
return {"chunks": len(chunks), "documents": len({c.source for c in chunks})}
Calling it returns {"chunks": 28, "documents": 8}, and calling it again gives exactly the same, because the table is replaced, not added to. If something fails halfway, the transaction rolls back and nothing is half-replaced. A customer who calls the reindex endpoint gets 403.
Searching works as before. "I was charged twice for one order" finds returns-and-refunds.md first with a score of 0.693, then payments and billing. "Which jacket size for chest 95 cm" finds the size guide PDF, page 2, with 0.786. The project's tests pass, all 16.
Common mistakes
- Taking the owner from the request body. The owner must come from the verified token's
sub, never from a field the client can type. - Forgetting the
WHERE owner_idfilter. Without it, one user's question can cite another user's documents. - Mixing embedding settings. The question and the chunks must use the same model and the same normalisation, and the column size (384) must match the model.
- Appending on reindex. Replace the old rows (per source, or the whole table in a transaction), or every rebuild doubles your chunks.
Quick recap
| Piece | Job |
|---|---|
/ingest | Chunk, embed and store a document for the signed-in user |
chunks table | vector(384) column, HNSW index with cosine ops |
/ask | Embed the question, search with <=> and owner_id, answer with numbered citations |
| Supabase JWT | HS256, audience authenticated, sub becomes the owner; anything else is 401 |
| Reindex | Load, chunk, embed, then TRUNCATE and INSERT in one transaction |
The in-memory version of the same pipeline is in RAG in LangChain. When the API is ready to go out, Deploy a RAG Service covers the next step.
Try it yourself
Put a markdown file of your own into sample_docs, run 03_try_it.py again and ask three questions in your own words. Then sign a second token for another user id with python 02_make_token.py user-b and check that this user sees none of your citations.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.
