Learning objectives
After reading this article you will be able to:
- Set up PostgreSQL with pgvector: table, vector column and HNSW index
- Chunk documents, create embeddings and search chunks by cosine distance
- Build the prompt with sources and test that the chatbot sticks to the context
A chatbot that answers questions about your docs, your catalog or your help center doesn't need a model trained on that data. It needs good retrieval and a well-built prompt. That is what RAG does, and PostgreSQL with the pgvector extension handles the retrieval without a new system to run.
This guide builds the whole flow in Python, in a single file: chunk the documents, create the embeddings, store and index them in PostgreSQL, fetch the chunks closest to the question and generate an answer with sources. If the concept is new to you, read what RAG is first.
What will you build, and what do you need?#
The system has two phases. Indexing runs once, and again whenever documents change: each file becomes chunks, and each chunk becomes a vector of numbers, its embedding. Querying runs on every question: the question also becomes an embedding, the database returns the chunks with the closest vectors and the LLM answers by reading them.
Before you start, have:
- A PostgreSQL server with the pgvector extension available. The project's README shows how to install it on each system.
- A supported Python version, plus the
psycopg(PostgreSQL driver) andopenailibraries. - An embeddings provider with an OpenAI-compatible endpoint. OpenAI itself works, and Ollama exposes
/v1/embeddingsif you want to run a model on your own machine. To understand what these vectors represent, see what embeddings are. - A chat model from any provider that accepts the OpenAI SDK. See what an OpenAI-compatible API is.
Create a requirements.txt:
psycopg[binary]
openaiAnd a .env with the variables. Model IDs come from each provider's model page:
# .env
DATABASE_URL=postgresql://user:password@host:5432/dbname
EMBEDDINGS_BASE_URL=https://api.openai.com/v1
EMBEDDINGS_API_KEY=your-embeddings-provider-key
EMBEDDING_MODEL=embedding-model-id
OPENAI_API_KEY=your-chat-provider-key
OPENAI_MODEL=chat-model-id
# OPENAI_BASE_URL=https://another-provider.example/v1 (optional)Embeddings and chat get separate variables because not every provider offers both. The OpenAI SDK reads OPENAI_API_KEY and OPENAI_BASE_URL on its own, so switching chat providers doesn't touch the code.
How do you set up the database with pgvector?#
Run this SQL once. Replace 1536 with the number of dimensions your embedding model outputs; the model's documentation lists it.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
source text NOT NULL,
content text NOT NULL,
embedding vector(1536) NOT NULL
);
-- approximate index for cosine distance
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
-- regular index to delete a file's chunks
CREATE INDEX ON chunks (source);Three decisions live here. The vector(1536) column rejects vectors of any other size, which catches a swapped model right away. The HNSW index trades a little accuracy for speed and can be created on an empty table. And the vector_cosine_ops class matches the <=> cosine distance operator the query uses: the index and the query must agree on the distance. For HNSW versus IVFFlat, and when to move off pgvector, see pgvector or a dedicated vector database.
How do you write the indexing and the query?#
Save this as rag.py:
import os
import sys
from pathlib import Path
import psycopg
from openai import OpenAI
CHUNK_SIZE = 1200 # characters per chunk, about 300 tokens
K = 5 # chunks sent to the model
MAX_DISTANCE = 0.6 # above this, a chunk is irrelevant: calibrate for your model
embeddings = OpenAI(
base_url=os.environ["EMBEDDINGS_BASE_URL"],
api_key=os.environ["EMBEDDINGS_API_KEY"],
)
chat = OpenAI() # reads OPENAI_API_KEY and, if set, OPENAI_BASE_URL
def to_vector(v: list[float]) -> str:
return "[" + ",".join(map(str, v)) + "]" # pgvector's text format
def embed(texts: list[str]) -> list[list[float]]:
r = embeddings.embeddings.create(model=os.environ["EMBEDDING_MODEL"], input=texts)
return [d.embedding for d in sorted(r.data, key=lambda d: d.index)]
def split(text: str) -> list[str]:
parts = []
for p in text.split("\n\n"):
p = p.strip()
# a paragraph longer than CHUNK_SIZE becomes CHUNK_SIZE-character pieces
parts += [p[i : i + CHUNK_SIZE] for i in range(0, len(p), CHUNK_SIZE)]
chunks, current = [], []
for p in parts:
if current and sum(map(len, current)) + len(p) > CHUNK_SIZE:
chunks.append("\n\n".join(current))
current = current[-1:] if len(current[-1]) + len(p) <= CHUNK_SIZE else [] # overlap, if it fits
current.append(p)
if current:
chunks.append("\n\n".join(current))
return chunks
def index(folder: str) -> None:
files = sorted(p for p in Path(folder).rglob("*") if p.suffix in {".md", ".txt"})
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
for file in files:
source = str(file.relative_to(folder))
chunks = split(file.read_text(encoding="utf-8"))
conn.execute("DELETE FROM chunks WHERE source = %s", (source,))
for i in range(0, len(chunks), 64): # 64 chunks per embeddings call
batch = chunks[i : i + 64]
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chunks (source, content, embedding) VALUES (%s, %s, %s::vector)",
[(source, c, to_vector(e)) for c, e in zip(batch, embed(batch))],
)
conn.commit() # each file goes in whole or not at all
print(f"{source}: {len(chunks)} chunks")
def search(question: str) -> list[tuple[str, str, float]]:
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
return conn.execute(
"""SELECT source, content, embedding <=> %(q)s::vector AS distance
FROM chunks ORDER BY embedding <=> %(q)s::vector LIMIT %(k)s""",
{"q": to_vector(embed([question])[0]), "k": K},
).fetchall()
def ask(question: str) -> str:
chunks = [c for c in search(question) if c[2] <= MAX_DISTANCE]
if not chunks:
return "I couldn't find that in the docs."
context = "\n\n".join(
f"[{i}] ({source})\n{content}" for i, (source, content, _) in enumerate(chunks, 1)
)
r = chat.chat.completions.create(
model=os.environ["OPENAI_MODEL"],
messages=[
{
"role": "system",
"content": "You answer questions about the company's documentation. "
"Use only the chunks provided and cite the source of each claim with its number "
"in brackets, like [1]. If the chunks don't contain the answer, say you couldn't find it.",
},
{"role": "user", "content": f"Chunks:\n{context}\n\nQuestion: {question}"},
],
)
return r.choices[0].message.content
if __name__ == "__main__":
command, argument = sys.argv[1], sys.argv[2]
if command == "index":
index(argument)
else:
print(ask(argument))What each part does:
splitbreaks the text into paragraphs and joins paragraphs up to about 1,200 characters. When a chunk closes, its last paragraph opens the next one if it fits: that overlap keeps an answer from being cut right at the border between two chunks.embedsends several chunks per call. OpenAI accepts up to 2,048 inputs and 300,000 tokens summed across them per request; other providers set their own limits, so the code sends batches of 64.indexdeletes each file's old chunks before inserting the new ones, in the same transaction. Running it again never duplicates anything.searchorders byembedding <=> vectorwith aLIMIT, the shape pgvector needs to use the index. Cosine distance ranges from 0 (same direction) to 2.askdrops chunks that are too far away and numbers the rest. If nothing passes the filter, it answers without calling the LLM, which saves tokens and avoids a made-up answer.
How does the prompt keep answers grounded?#
The model only knows what is in the prompt and in its training. The system instruction does three things: it limits the answer to the chunks, asks for the source of each claim and gives an honest way out ("I couldn't find it"). The bracketed numbers make the answer checkable: your front end can turn [2] into a link to the source file.
This reduces hallucination but doesn't remove it. The model can still combine two chunks the wrong way or ignore the instruction. The complementary techniques are in why chatbots make things up.
In a real chatbot, the question arrives with a conversation. Send the recent history along and search with the latest question, ideally rewritten to stand alone ("and the deadline?" becomes "what is the refund deadline?"). Chunks, history and question must fit in the model's context window, or the API rejects the call (on OpenAI, with context_length_exceeded). How to store and shorten the history is in how to give a chatbot memory.
How do you know it works?#
Load the variables, index a folder with a few .md files and ask:
pip install -r requirements.txt
set -a; source .env; set +a
python rag.py index ./docs
python rag.py ask "How many days do I have to request a refund?"Indexing prints how many chunks came out of each file. The answer should cite sources like [1]. Then run three tests:
- A question the docs answer in different words. If search finds the right chunk with no words in common, the embeddings are doing their job.
- An off-topic question. You should get "I couldn't find that in the docs." If the model answers anyway, lower
MAX_DISTANCE; if valid questions get filtered out, raise it. - The query plan. Run
EXPLAIN ANALYZEon the query with a real vector and look forIndex Scan using chunks_embedding_idx. On a small table, PostgreSQL may prefer a full scan, which the pgvector README describes as expected.
Keep a list of 20 to 30 real questions with their correct answers and rerun it after every change to chunk size, K or model. Tuning RAG is almost always tuning retrieval.
What are the common errors?#
| Error or symptom | Cause | Fix |
|---|---|---|
expected 1536 dimensions, not 768 |
The model outputs a different number of dimensions | Match the vector(n) column to the model and reindex everything |
type "vector" does not exist |
The extension wasn't created in this database | Run CREATE EXTENSION vector in the database that holds the table |
vector column cannot have more than 2000 dimensions for hnsw index |
A model with more than 2,000 dimensions | Index with halfvec, which goes up to 4,000, or ask the model for fewer dimensions if it supports that |
| The query doesn't use the index | ORDER BY with an expression, like 1 - (embedding <=> q) DESC |
Order by embedding <=> q ascending, with a LIMIT |
| Irrelevant chunks | Chunks too large, high K or a loose filter |
Shrink the chunk size and K, calibrate MAX_DISTANCE |
| Search gets worse after a model change | Vectors from different models in the same table | Use one model for indexing and querying; when you switch, reindex everything |
To estimate what embeddings, database and generation cost per month, see how much a RAG system costs.
How to do this on Square Cloud#
On Square Cloud, PostgreSQL hosting comes with the pgvector extension, so the chunks table and its HNSW index live in the same database as your documents and metadata. The platform has no dedicated vector database. You create the database in the dashboard (name, memory and engine), it is ready in seconds in the same datacenter as your applications, with about 1 ms of average latency, and the minimum for PostgreSQL is 1024 MB. Database hosting starts on the Standard plan, from R$44.99 a month; Hobby doesn't include databases.
The dashboard gives you the full connection URL, which you copy into the DATABASE_URL variable. TLS is mandatory: the client trusts the CA downloaded from the dashboard and, for PostgreSQL, also presents the certificate; the Python walkthrough is in connecting PostgreSQL to Python. Since the connection is external, you can run python rag.py index from your machine or from CI. Each database accepts up to 256 connections, with no pooler in front, and gets a daily automatic snapshot kept for 7 days; take a manual snapshot before a large reindex.
For generation, the AI Gateway, also from Standard, works with the OpenAI SDK: set OPENAI_BASE_URL=https://api.squarecloud.app/v2/ai, an account API key with the ai:chat scope in OPENAI_API_KEY and OPENAI_MODEL=cubic. The gateway doesn't generate embeddings, so the EMBEDDINGS_* variables keep pointing to another provider. Context goes up to 64k tokens on Standard and up to 128k on Pro: pick K and the chunk size with that in mind. See the details on PostgreSQL hosting.
AI
Host AI apps in always-on containers
FAQs
Which embedding model should I use with pgvector?
Any model works, as long as the column has the same number of dimensions the model outputs and indexing and queries use the same model. For HNSW indexing, the vector type takes up to 2,000 dimensions; halfvec goes up to 4,000.
How many chunks should I send to the model per question?
Start with 3 to 5 and tune with real questions. Too few leave the answer without context; too many burn tokens and mix topics.
Do I need LangChain to build RAG?
No. The whole flow fits in a few functions using the PostgreSQL driver and the provider's SDK. A framework helps when you need many document loaders or ready-made pipelines.
How do I update the index when a document changes?
Delete that document's chunks and embed only its new ones. The HNSW index follows INSERT and DELETE, so you don't rebuild it on every change.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- pgvector vs a dedicated vector database: which to usepgvector stores vectors in PostgreSQL, next to your data; a dedicated vector database focuses on scale and filtering. Compare indexes, operations and migration.