Building a RAG Pipeline with LangChain and Supabase Vector
Step-by-step guide to building a production-grade Retrieval-Augmented Generation pipeline — embedding documents, storing vectors in pgvector, and streaming answers via a Next.js API.
Retrieval-Augmented Generation solves a specific problem: language models answer confidently from training data they may not have, and they cannot cite anything. RAG fixes both by retrieving relevant passages first, then asking the model to answer from those passages.
This post walks through the pipeline we built for the chapter's internal docs search — roughly 400 pages of workshop notes.
The shape of the problem
A RAG pipeline has four stages, and each one can independently ruin your results:
- Chunking — splitting documents into retrievable units
- Embedding — turning chunks into vectors
- Retrieval — finding the right chunks for a question
- Generation — answering from what was retrieved
Most people jump straight to step 4 and blame the model. In practice, bad answers almost always trace back to steps 1 and 3.
Setting up pgvector
Supabase ships Postgres with the pgvector extension available. Enable it and
create the table:
create extension if not exists vector;
create table documents (
id bigserial primary key,
content text not null,
metadata jsonb default '{}'::jsonb,
embedding vector(1536)
);
-- IVFFlat trades a little recall for a lot of speed.
-- Build the index AFTER inserting data so it can learn the distribution.
create index on documents
using ivfflat (embedding vector_cosine_ops)
with (lists = 100);
A note on
lists: the usual starting point isrows / 1000. Too few and every query scans most of the table; too many and recall drops because neighbouring vectors land in different lists.
Chunking that respects structure
The naive approach splits every N characters. That cuts sentences in half and separates a heading from the paragraph it introduces.
Split on structure first, and only fall back to length:
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
// Tried in order — paragraphs before lines before words
separators: ["\n## ", "\n### ", "\n\n", "\n", " "],
});
const chunks = await splitter.createDocuments([rawText]);
The overlap matters more than people expect. Without it, a fact that straddles a chunk boundary becomes unretrievable — it exists in neither chunk in full.
Embedding and storing
import { OpenAIEmbeddings } from "@langchain/openai";
import { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";
const store = await SupabaseVectorStore.fromDocuments(
chunks,
new OpenAIEmbeddings({ model: "text-embedding-3-small" }),
{ client: supabase, tableName: "documents", queryName: "match_documents" },
);
match_documents is a Postgres function that does the similarity search:
create or replace function match_documents (
query_embedding vector(1536),
match_count int default 5
) returns table (id bigint, content text, similarity float)
language sql stable
as $$
select id, content, 1 - (embedding <=> query_embedding) as similarity
from documents
order by embedding <=> query_embedding
limit match_count;
$$;
The <=> operator is cosine distance. We return 1 - distance so that higher
means more similar, which is what everyone expects when they read the number.
Retrieval is where the wins are
Two changes moved our answer quality more than any prompt tuning:
- Over-fetch, then rerank. Retrieve 20 candidates, rerank them with a cross-encoder, keep the top 5. Bi-encoder similarity is fast but coarse.
- Filter before you search. If the user is asking about a specific workshop, a metadata filter narrows the space before the vector comparison runs at all.
Streaming the answer
Retrieved context goes into the prompt, and the response streams back so the page fills in as tokens arrive rather than after a ten-second pause:
export async function POST(req: Request) {
const { question } = await req.json();
const docs = await store.similaritySearch(question, 5);
const context = docs.map((d) => d.pageContent).join("\n\n---\n\n");
const result = streamText({
model: openai("gpt-4o-mini"),
system:
"Answer using only the context provided. " +
"If the context does not contain the answer, say so plainly.",
prompt: `Context:\n${context}\n\nQuestion: ${question}`,
});
return result.toDataStreamResponse();
}
That system prompt is doing real work. Without the second sentence the model fills gaps with plausible invention, which is the exact failure RAG exists to prevent.
What we would do differently
Chunk quality compounds through every later stage, so it deserves the most attention and usually gets the least. Build an evaluation set of thirty real questions with known answers before tuning anything — otherwise you are guessing about whether a change helped.