Step 2 of 11· AI Customer Support Chatbot
Database
Create a Supabase project, connect with a connection pool, and create the tables for chunks, conversations, tickets and the request log.
Purpose#
Create the Postgres database that stores everything: the help center chunks with their vectors, conversations, tickets, ratings and the request log. Supabase provides hosted Postgres with the pgvector extension.
In this step:
- Create a Supabase project
- Write the schema
- Connect with a connection pool
- Create the tables
1. Supabase project#
- Sign in at supabase.com and click New project.
- Name:
support-desk. Set a database password and store it in your password manager. Choose the region closest to your server (step 11). - When the project is ready, click Connect at the top of the dashboard.
- Under Session pooler, copy the URI. Replace
[YOUR-PASSWORD]with the database password. - Set it in
.env:
DATABASE_URL=postgresql://postgres.abcdefghijkl:your-password@aws-0-eu-central-1.pooler.supabase.com:5432/postgres2. Schema#
-- AI Customer Support Chatbot schema for Supabase (Postgres with pgvector). Safe to run more than once.
create extension if not exists vector;
-- The knowledge base, split into chunks. One row per chunk.
create table if not exists chunks (
id bigint generated always as identity primary key,
doc text not null, -- file name without .md
title text not null,
heading text not null,
url text not null,
content text not null,
content_hash text not null unique, -- lets us skip chunks that did not change
fts tsvector generated always as (to_tsvector('english', title || ' ' || heading || ' ' || content)) stored,
embedding vector(1536) not null
);
create index if not exists chunks_fts_idx on chunks using gin (fts);
create index if not exists chunks_embedding_idx on chunks using hnsw (embedding vector_cosine_ops);
create table if not exists conversations (
id uuid primary key default gen_random_uuid(),
client text not null, -- hashed visitor address, never the raw IP
created_at timestamptz not null default now()
);
create table if not exists messages (
id bigint generated always as identity primary key,
conversation_id uuid not null references conversations on delete cascade,
role text not null check (role in ('user', 'assistant')),
content text not null,
sources jsonb not null default '[]',
outcome text, -- answered, small_talk, handoff, error (assistant messages)
cache_key text, -- answer_cache key of a cacheable answer
created_at timestamptz not null default now()
);
alter table messages add column if not exists cache_key text; -- for databases created before the cache
create index if not exists messages_conversation_idx on messages (conversation_id, id);
create table if not exists handoffs (
id bigint generated always as identity primary key,
conversation_id uuid not null references conversations on delete cascade,
reason text not null,
contact text,
status text not null default 'open',
created_at timestamptz not null default now()
);
create table if not exists feedback (
message_id bigint primary key references messages on delete cascade,
helpful boolean not null,
created_at timestamptz not null default now()
);
-- Answers to standalone questions, reused for the same question. No visitor data: only a hash of the question.
create table if not exists answer_cache (
key text primary key, -- sha256 of the normalized question and the settings
text text not null,
sources jsonb not null,
hits integer not null default 0,
created_at timestamptz not null default now(),
last_hit_at timestamptz,
expires_at timestamptz not null
);
-- One row per OpenAI request. No message content.
create table if not exists llm_calls (
id bigint generated always as identity primary key,
created_at timestamptz not null default now(),
kind text not null, -- embed, answer
model text not null,
input_tokens integer not null,
output_tokens integer not null,
cost numeric(12, 6) not null,
seconds real not null,
outcome text not null
);
create index if not exists llm_calls_created_idx on llm_calls (created_at);
-- Supabase exposes every table in the public schema through its REST API.
-- Row level security with no policies blocks that API. The server connects as the
-- database owner, which is not restricted by row level security.
alter table chunks enable row level security;
alter table conversations enable row level security;
alter table messages enable row level security;
alter table handoffs enable row level security;
alter table feedback enable row level security;
alter table answer_cache enable row level security;
alter table llm_calls enable row level security;3. Connection pool#
"""Connection pool and schema for the Supabase Postgres database.
Create or update the schema: python -m support_desk.db
"""
from pathlib import Path
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from support_desk import config
SCHEMA = (Path(__file__).parent / "schema.sql").read_text()
_pool: ConnectionPool | None = None
def pool() -> ConnectionPool:
global _pool
if _pool is None:
if not config.DATABASE_URL:
raise SystemExit("DATABASE_URL is not set. Locally: add it to .env (step 2). On a server or in GitHub Actions: set it as an environment variable or secret.")
_pool = ConnectionPool(
config.DATABASE_URL, min_size=1, max_size=5, open=True,
# check: test each connection before lending it out. Idle connections get closed by the
# database or the network; without the check, the next request would fail on a dead one.
check=ConnectionPool.check_connection,
timeout=10, # wait at most 10 seconds for a free connection, then raise an error
# dict_row: rows as dictionaries. prepare_threshold=None: required for Supabase's connection pooler.
kwargs={"row_factory": dict_row, "prepare_threshold": None},
)
return _pool
def connect():
"""Use as `with connect() as conn:`. Commits on success, rolls back on an error."""
return pool().connection()
def close() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
def init_schema() -> None:
with connect() as conn:
conn.execute(SCHEMA)
def to_vector(values: list[float]) -> str:
"""pgvector reads vectors as text: [0.1,0.2,...]."""
return "[" + ",".join(f"{v:.8f}" for v in values) + "]"
if __name__ == "__main__":
init_schema()
with connect() as conn:
tables = conn.execute(
"select table_name from information_schema.tables where table_schema = 'public' order by 1").fetchall()
print("Schema is up to date. Tables:", ", ".join(t["table_name"] for t in tables))A connection pool reuses database connections and checks each one before use, each with connect() block is one transaction, and values are always passed as parameters, so visitor text cannot change the SQL.
Checkpoint#
uv run python -m support_desk.dbExpected output:
Schema is up to date. Tables: answer_cache, chunks, conversations, feedback, handoffs, llm_calls, messagesIn the Supabase dashboard, open Table Editor. The six tables are listed. Each one shows no "RLS disabled" warning.
Troubleshooting#
connection refusedor timeout: check that you used the Session pooler URI and that the password is correct.password authentication failed: special characters in the password must be URL-encoded in the URI (@as%40,#as%23). Or reset the password to one with letters and numbers only (Project Settings → Database).type "vector" does not exist: the extension was not created. Runcreate extension vector;in the Supabase SQL Editor, then run the checkpoint again.Tenant or user not found: the user name in the pooler URI must include the project reference (postgres.abcdefghijkl).