SupabasegregnrTutorial
Storing OpenAI embeddings in Postgres with pgvector
Summary
Post describes how embeddings represent semantic relatedness as vectors and how OpenAI’s text-embedding-ada-002 model produces 1536-dimensional embeddings for text. It addresses storing and searching large or dynamically changing collections that may not fit comfortably in memory, using PostgreSQL and the pgvector extension instead of a small CSV-and-NumPy workflow. The implementation enables the vector extension, creates a documents table with a vector(1536) column, and defines match_documents() with cosine distance, thresholds, counts, and ordering. It also shows JavaScript code for generating embeddings, a search flow that retrieves matching documents for prompt context, and token limiting before a completion request, while noting that documents can be chunked. For larger tables, the post recommends an ivfflat index with vector_cosine_ops and gives 4 * sqrt(table_rows) as a starting point for lists.
Context
Small-scale embedding storage and similarity calculations can use CSV files, Python, and NumPy, but the post identifies challenges when collections exceed available memory or embeddings need to be created, updated, and deleted dynamically. It presents PostgreSQL as a way to manage larger embedding collections and support applications that do not use Python.
Approach / What changed
Enable pgvector in PostgreSQL, store document text or references alongside vector(1536) embeddings, and define a match_documents() SQL function using cosine distance, a similarity threshold, and a match count. Generate embeddings with OpenAI’s text-embedding-ada-002 model, query the function for relevant documents, limit injected context by tokens, and add an ivfflat vector_cosine_ops index as the table grows.
Takeaways
pgvector adds a vector data type and three distance operators: Euclidean distance, negative inner product, and cosine distance. The example uses cosine distance because OpenAI recommends cosine similarity for its embeddings.
The search flow generates one embedding for the user’s query, calls match_documents() with a threshold of 0.78 and a maximum of 10 matches, then limits combined context to 1500 tokens before sending it to a completion model.
For cosine-distance ordering, the example uses an ivfflat index with vector_cosine_ops; 4 * sqrt(table_rows) is given as a starting value for the number of lists.
Source and freshness
- Source
- supabase.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.