Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Workflow recipe

RAG pipeline in a day with Postgres and pgvector

Ingest your documents, answer with citations and measure retrieval against 20 questions written first.

By Checked Intermediate1 day7 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

To build a RAG pipeline on Postgres, write 20 evaluation questions first, start Postgres with the pgvector extension, and ingest your documents by converting, chunking, embedding and storing them. Retrieve the closest passages for each question, have the model answer with citations, measure retrieval against your 20 questions and fix the biggest problem one change at a time.

Retrieval-augmented generation (RAG) means: find the passages that are relevant to a question, then ask a model to answer using only those passages. This recipe builds the simplest version that is worth keeping, on Postgres with the pgvector extension, so you do not need a separate vector database.

You will write the evaluation questions first. That sounds backwards, but it is the only way to know on Friday whether the changes you made on Thursday helped.

The code is Python. It uses Docling to read documents, OpenAI’s text-embedding-3-small for embeddings (1,536 dimensions), and Claude to write answers. Any embedding model and chat model will work if you change the two marked lines and the vector size.

Spreadsheet or editorAbout 60 min

1. Write 20 questions before you write any code

With someone who knows the documents, write 20 questions real users would ask, each with the file that contains the answer and a one-line correct answer. Mix easy lookups with a few that need two passages, and add two questions the documents cannot answer.

Save them as eval.jsonl, one JSON object per line:

{"question": "How many days of parental leave do new parents get?", "expected_source": "handbook/leave-policy.pdf", "expected_answer": "26 weeks for the primary carer, 4 weeks for the secondary carer."}
{"question": "Who approves expenses over 5,000 euros?", "expected_source": "finance/expenses.docx", "expected_answer": "The budget holder and the finance director."}
{"question": "What is the office wifi password?", "expected_source": "", "expected_answer": "Not in the documents."}

An empty expected_source marks a question that should get “I can’t find that”.

TerminalAbout 20 min

2. Start Postgres with pgvector and create the table

The pgvector project publishes Docker images with the extension already installed.

docker run --name rag-db -e POSTGRES_PASSWORD=rag -p 5432:5432 -d pgvector/pgvector:pg17
export DATABASE_URL="postgresql://postgres:rag@localhost:5432/postgres"

Save the schema as schema.sql and apply it:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS chunks (
  id          bigserial PRIMARY KEY,
  source      text NOT NULL,
  chunk_index int  NOT NULL,
  content     text NOT NULL,
  embedding   vector(1536) NOT NULL,
  UNIQUE (source, chunk_index)
);

-- Approximate nearest-neighbour index for cosine distance
CREATE INDEX IF NOT EXISTS chunks_embedding_idx
  ON chunks USING hnsw (embedding vector_cosine_ops);
docker exec -i rag-db psql -U postgres < schema.sql

The vector size must match your embedding model. If you switch models, change 1536 and re-ingest everything.

TerminalAbout 20 min

3. Set up the Python project

mkdir rag-day && cd rag-day
python -m venv .venv && source .venv/bin/activate
pip install docling "psycopg[binary]" pgvector numpy openai anthropic
export OPENAI_API_KEY=...      # embeddings
export ANTHROPIC_API_KEY=...   # answers

Shared helpers go in common.py:

import os

import numpy as np
import psycopg
from openai import OpenAI
from pgvector.psycopg import register_vector

EMBED_MODEL = "text-embedding-3-small"  # change here (and vector(1536)) to swap models
openai_client = OpenAI()


def connect() -> psycopg.Connection:
    conn = psycopg.connect(os.environ["DATABASE_URL"], autocommit=True)
    register_vector(conn)  # lets psycopg send and receive numpy arrays as vectors
    return conn


def embed(texts: list[str]) -> list[np.ndarray]:
    vectors: list[np.ndarray] = []
    for i in range(0, len(texts), 100):  # batch to stay well inside request limits
        resp = openai_client.embeddings.create(model=EMBED_MODEL, input=texts[i : i + 100])
        vectors.extend(np.array(d.embedding, dtype=np.float32) for d in resp.data)
    return vectors

TerminalAbout 90 min

4. Ingest: convert, chunk, embed, store

Docling converts PDFs, Word, PowerPoint, HTML and Markdown into one document model, keeping headings and tables. Its HybridChunker splits along the document structure, and contextualize() prefixes each chunk with its headings, which helps retrieval a lot for policy-style documents.

import sys
from pathlib import Path

from docling.chunking import HybridChunker
from docling.document_converter import DocumentConverter

from common import connect, embed

SUFFIXES = {".pdf", ".docx", ".pptx", ".html", ".md"}


def main(folder: str) -> None:
    root = Path(folder)
    converter = DocumentConverter()
    chunker = HybridChunker()
    conn = connect()

    for path in sorted(p for p in root.rglob("*") if p.suffix.lower() in SUFFIXES):
        doc = converter.convert(str(path)).document
        texts = [chunker.contextualize(chunk=c) for c in chunker.chunk(dl_doc=doc)]
        texts = [t for t in texts if t.strip()]
        if not texts:
            print(f"skip {path}: no text found (scanned PDF without OCR?)")
            continue

        vectors = embed(texts)
        source = str(path.relative_to(root))
        with conn.transaction():  # replace this file's chunks atomically
            conn.execute("DELETE FROM chunks WHERE source = %s", (source,))
            with conn.cursor() as cur:
                cur.executemany(
                    "INSERT INTO chunks (source, chunk_index, content, embedding) VALUES (%s, %s, %s, %s)",
                    [(source, i, t, v) for i, (t, v) in enumerate(zip(texts, vectors))],
                )
        print(f"{source}: {len(texts)} chunks")


if __name__ == "__main__":
    main(sys.argv[1])
python ingest.py ./docs

The first run downloads Docling’s layout models, so it is slow. Re-running is safe: each file’s chunks are replaced. Open a few rows afterwards and read them; bad chunks are the most common cause of bad answers.

docker exec -it rag-db psql -U postgres -c "SELECT source, chunk_index, left(content, 120) FROM chunks ORDER BY random() LIMIT 5;"

TerminalAbout 60 min

5. Retrieve and answer with citations

Search embeds the question and returns the closest chunks by cosine distance (<=>). The answer step sends those chunks to the model as numbered sources and asks for citations.

import sys

import anthropic

from common import connect, embed

MODEL = "claude-opus-5-5"  # change here to swap the answering model
claude = anthropic.Anthropic()

SYSTEM = (
    "Answer the question using only the numbered sources. Cite sources inline like [2]. "
    "If the sources do not contain the answer, reply exactly: I can't find that in the documents. "
    "Do not use outside knowledge."
)


def search(conn, question: str, k: int = 5) -> list[dict]:
    [qvec] = embed([question])
    rows = conn.execute(
        """
        SELECT source, chunk_index, content, 1 - (embedding <=> %s) AS similarity
        FROM chunks
        ORDER BY embedding <=> %s
        LIMIT %s
        """,
        (qvec, qvec, k),
    ).fetchall()
    return [{"source": r[0], "chunk": r[1], "content": r[2], "similarity": float(r[3])} for r in rows]


def answer(question: str, k: int = 5) -> dict:
    hits = search(connect(), question, k)
    sources = "\n\n".join(f"[{i}] ({h['source']})\n{h['content']}" for i, h in enumerate(hits, 1))
    resp = claude.messages.create(
        model=MODEL,
        max_tokens=4000,
        system=SYSTEM,
        messages=[{"role": "user", "content": f"Sources:\n\n{sources}\n\nQuestion: {question}"}],
    )
    text = "".join(block.text for block in resp.content if block.type == "text")
    return {"answer": text, "hits": hits}


if __name__ == "__main__":
    result = answer(" ".join(sys.argv[1:]))
    print(result["answer"], "\n")
    for i, h in enumerate(result["hits"], 1):
        print(f"[{i}] {h['source']} #{h['chunk']}  similarity={h['similarity']:.3f}")
python ask.py "Who approves expenses over 5,000 euros?"

TerminalAbout 60 min

6. Measure retrieval against your 20 questions

Measure retrieval separately from answers. If the right passage is not retrieved, no prompt will fix the answer.

import json

from ask import search
from common import connect

K = 5
conn = connect()
rows = [json.loads(line) for line in open("eval.jsonl", encoding="utf-8") if line.strip()]
answerable = [r for r in rows if r["expected_source"]]

hits, reciprocal_ranks = 0, []
for r in answerable:
    sources = [h["source"] for h in search(conn, r["question"], K)]
    if r["expected_source"] in sources:
        hits += 1
        reciprocal_ranks.append(1 / (sources.index(r["expected_source"]) + 1))
    else:
        reciprocal_ranks.append(0.0)
        print(f"MISS: {r['question']}\n  expected {r['expected_source']}, got {sources}")

print(f"\nhit@{K}: {hits}/{len(answerable)} = {hits / len(answerable):.0%}")
print(f"MRR: {sum(reciprocal_ranks) / len(reciprocal_ranks):.2f}")
python eval_retrieval.py

Then check the answers by hand for the same 20 questions: run ask.py on each and mark it correct, partly correct or wrong against expected_answer, and check that the two unanswerable questions got “I can’t find that”. Write the scores down as your baseline.

TerminalAbout 170 min

7. Fix the biggest problem, one change at a time

Read every miss before changing anything. The usual causes, in the order to try them:

  1. The text never made it in. Scanned PDFs without a text layer produce empty or garbage chunks. Check the rows for that source.
  2. Chunks lack context. A chunk that says “This applies to contractors” without its heading cannot be found. contextualize() helps; check that the heading text is present in the stored content.
  3. The question uses different words from the document (“parental leave” vs “maternity and paternity”). Add a keyword search alongside vectors (Postgres full-text search on content) and merge the two result lists.
  4. The right chunk is at rank 6 or 7. Try k = 8 and see if answers improve or get noisier.

After each change, re-run eval_retrieval.py and your answer check, and keep a short log of change, hit@5, MRR and answer score. Keep a change only if the numbers improve.

Check it worked

Verification checklist

0 of 6 done

When it goes wrong

If register_vector fails with an error about the vector type, the extension is missing in that database. Run the schema step again against the same DATABASE_URL.

If ingestion is very slow, it is usually Docling’s PDF pipeline on a CPU. Run it once overnight for large folders, or start with the Markdown and Word files to get the rest of the pipeline working.

If answers cite the wrong source numbers, check that the numbering in the prompt matches the list you print. The code above numbers from 1 in both places.

If the model answers from general knowledge instead of saying it cannot find something, make the refusal sentence exact (as in SYSTEM) and test the unanswerable questions every time you change the prompt.

Variations

To make the eval run automatically on every change, wire it into CI with the golden set recipe, which builds on these files.

To keep everything local, swap the embeddings for a local model served by Ollama and the answering model for a local chat model. Change EMBED_MODEL, the vector size and the two client calls.

If you already run a dedicated vector database such as Qdrant, keep the same steps and swap the SQL for its client. The eval set and the order of fixes do not change.

If your Postgres runs on Neon, the neon-postgres skill gives a coding agent current guidance on pooled versus direct connections and branching, which helps when you move the pipeline from a laptop database to a hosted one.

RAG fundamentals explains the idea step by step, and chunking strategies for RAG and hybrid search and reranking are the usual next fixes after step 7. pgvector vs vector databases covers when Postgres stops being enough. The RAG engineer learning path continues from here, and more recipes are in the AI workflow examples hub.

Outcome and tools

Outcome
A searchable Q&A over your docs, with a 20-question eval set to check answer quality.
For
Developers
Agent Skills
  • Evaluate RAG answers with a golden dataset

    Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.

    WorkflowIntermediate2 h6 steps

  • RAG fundamentals: retrieval before generation

    What RAG is and how retrieval-augmented generation works, when it beats long context or fine-tuning, and a minimal working pipeline in about 80 lines of Python.

    TutorialBeginner30 min

  • Embeddings and vector search, hands on

    Embed documents, store them in Postgres with pgvector, index them and run similarity and hybrid search.

    TutorialIntermediate45 min

  • Retrieval-augmented generation (RAG)

    Retrieving relevant documents and adding them to the prompt before the model generates an answer from them.

    Glossary

  • Embedding

    A vector representation of text or other data that places items with similar meaning close together, so they can be searched by similarity.

    Glossary

Back to top