Skip to main content
HB
RAG & AI Agents
Freelance client -- Upwork

Production RAG Pipeline with pgvector

Supabase · pgvector · LangChain · OpenAI · FastAPI

Hasan Iqbal Butt
By Hasan Iqbal ButtPublished: January 2025
95%Recall@5 on a Domain Golden Set
01

The Challenge

The client was paying eight hundred dollars per month for a dedicated Pinecone instance and still getting irrelevant results on domain-specific legal queries. The naive chunking strategy was splitting documents mid-paragraph, so the embeddings captured partial context that did not represent the actual meaning of the text. Retrieval accuracy sat around sixty percent. When the LLM received these fragmented chunks as context, it would hallucinate answers roughly forty percent of the time because the retrieved text was too incomplete to ground a reliable response. The client needed accurate answers to questions about specific contract clauses, regulatory requirements, and case law citations, all of which require full paragraphs of context to interpret correctly.

02

The Approach

The first decision was replacing Pinecone with pgvector on the client existing Supabase PostgreSQL instance. Since they were already paying for Supabase, adding the pgvector extension cost nothing extra. I created a vector column with 1536 dimensions to match the OpenAI text-embedding-ada-002 output and added an IVFFlat index for approximate nearest neighbor search. The chunking pipeline was rebuilt from scratch. Instead of splitting on a fixed token count, the system parses document structure first. It identifies headings, numbered clauses, paragraphs, and list items. Each chunk preserves its structural boundary, so a numbered clause is never split across two chunks. Chunks also carry metadata: the document category, section title, source file name, and page number. At query time, the pipeline runs in two stages. First, a metadata pre-filter narrows the search space to chunks from the relevant document category. This uses a standard PostgreSQL WHERE clause before the vector similarity search even begins. Second, pgvector performs cosine similarity on the filtered set and returns the top five chunks. LangChain orchestrates the full chain. It takes the query, calls OpenAI to generate the embedding, passes it to Supabase for retrieval, assembles the retrieved chunks into a structured prompt with source citations, and sends it to GPT-4. The system prompt instructs the model to cite which source each part of the answer came from and to explicitly state when the retrieved context does not contain enough information to answer. The FastAPI backend handles request validation, query preprocessing, and response formatting. It runs in a Docker container with structured logging for debugging retrieval quality over time.

03

System Architecture

Loading architecture diagram...
04

Pipeline Architecture

RAG Pipeline Infrastructure

Architecture for the Production RAG Pipeline. Click a node to view its configuration details.

QueryVectorizeSimilarity SearchTop ChunksContext PromptAnswerJSONClientNatural Language QueryFastAPIDocker ContainerOpenAI Embeddingsada-002 / 1536dSupabasepgvector + MetadataLangChainRetrieval ChainOpenAI GPT-4Answer GenerationJSON ResponseAnswer + Sources
Select a node to view infrastructure details
Primary data flow
05

Interactive Demo

Walk through the system design and data flow for this project step by step.

How the RAG Pipeline Works

Query"What are the GDPR consentrequirements for data processing?"FastAPI BackendValidate, normalize, preprocess

Step 1Natural Language Query Input

A user submits a domain-specific legal question in plain English through the FastAPI endpoint. The question could be anything from asking about a specific contract clause to requesting a summary of regulatory requirements. The backend validates the request payload, normalizes whitespace, and strips any special characters that could interfere with embedding quality.

Key Insight

Legal queries are particularly challenging for RAG systems because the same term can have different meanings in different legal contexts. A question about "consideration" in contract law means something completely different than in planning law. The query preprocessing step preserves these domain-specific nuances instead of aggressively stemming or lemmatizing the input.

1 of 6

06

Overview

Replaced a dedicated Pinecone vector database with pgvector on the client existing Supabase PostgreSQL instance, cutting infrastructure costs by eight hundred dollars per month. Built a custom chunking pipeline that preserves document structure and added metadata pre-filtering before cosine similarity search. LangChain orchestrates the retrieval chain while OpenAI text-embedding-ada-002 generates 1536-dimensional vectors. Retrieval accuracy improved from sixty percent to ninety five percent on a test set of two hundred domain-specific legal queries.

07

Business Impact

Retrieval accuracy jumped from sixty percent to ninety five percent on the client test set of two hundred domain-specific legal questions. Monthly infrastructure costs dropped from eight hundred dollars to zero additional spend because pgvector runs on the existing Supabase instance the client was already paying for. LLM hallucination rate fell from roughly forty percent of responses to under five percent because the retrieved chunks now contain complete, coherent context instead of fragmented text. Average query-to-answer latency is 1.8 seconds including embedding generation, vector search, and LLM response.

08

Technical Highlights

  • Replaced $800/month Pinecone with pgvector on existing Supabase at zero extra cost
  • Structure-aware chunking preserves headings, paragraphs, and numbered clauses
  • Metadata pre-filtering narrows search to the correct document category before vector similarity
  • Hybrid retrieval with cosine similarity plus metadata scoring pushed accuracy from 60% to 95%
  • OpenAI ada-002 embeddings with 1536 dimensions for semantic alignment
  • LangChain custom retrieval chain with source citation tracking
  • LLM hallucination rate dropped from 40% to under 5% with coherent context chunks
  • Query-to-answer latency averaging 1.8 seconds end to end
09

Frequently Asked Questions

Q: Why did you replace Pinecone with pgvector for this RAG pipeline?

The client was paying $800/month for Pinecone but getting poor retrieval performance due to naive chunking. Since they were already hosting their database on Supabase PostgreSQL, we enabled pgvector to eliminate additional hosting costs. We then built a custom, structure-aware chunking pipeline that pushed retrieval accuracy from 60% to 95% on their legal golden set.

Q: How does the custom chunking pipeline prevent LLM hallucinations?

Instead of splitting text arbitrarily by token counts, our chunking pipeline parses document structure to identify headings, numbered clauses, and list items. This ensures individual clauses are never broken across chunks. The chunks are indexed alongside rich metadata (document category, section name) for pre-filtering, reducing hallucinations from 40% to under 5%.

Q: What is the average latency of the production query pipeline?

The end-to-end latency averages 1.8 seconds. This includes creating the 1536-dimensional query embedding via OpenAI's API, executing a metadata-filtered cosine similarity query in Supabase, assembling the context prompt, and streaming the response from GPT-4.

Want results like this for your infrastructure?

I specialize in taking complex AI pipelines and cloud setups from concept to high-availability production. Let's discuss how to optimize your workloads, secure your environment, and reduce cloud costs.