ChatGPT is great for casual, general-purpose question-answers but falls short when domain-specific knowledge is needed. Further, it makes up answers to fill its knowledge gaps and never cites its sources, so it can't really be trusted. This starter app uses embeddings coupled with vector search to solve this, or more specifically, to show how OpenAI's chat completions API can be used to create conversational interfaces to domain-specific knowledge.
Embeddings, as represented by vectors of floating-point numbers, measure the "relatedness" of text strings. These are super useful for ranking search results, clustering, classification, etc. Relatedness is measured by cosine similarity. If the cosine similarity between two vectors is close to 1, the vectors are highly similar and point in the same direction. In the case of text embeddings, a high cosine similarity between two embedding vectors indicates that the corresponding text strings are highly related.
This starter app uses embeddings to generate a vector representation of a document, and then uses vector search to find the most similar documents to the query. The results of the vector search are then used to construct a prompt. The response is then streamed to the user. Check out the Supabase blog posts on pgvector and OpenAI embeddings for more background.
Technologies used:
Creating and storing the embeddings:
Responding to queries:
The following set-up guide assumes at least basic familiarity developing web apps with React and Nextjs. Experience with OpenAI APIs and Supabase is helpful but not required to get things working.
Database
β Extensions
. You can also do this in SQL by running:create extension vector;
create table documents (
id bigserial primary key,
content text,
url text,
embedding vector (1536)
);
create or replace function match_documents (
query_embedding vector(1536),
similarity_threshold float,
match_count int
)
returns table (
id bigint,
content text,
url text,
similarity float
)
language plpgsql
as $$
begin
return query
select
documents.id,
documents.content,
documents.url,
1 - (documents.embedding <=> query_embedding) as similarity
from documents
where 1 - (documents.embedding <=> query_embedding) > similarity_threshold
order by documents.embedding <=> query_embedding
limit match_count;
end;
$$;
gh repo clone gannonh/chatgpt-pgvector
cd chatgpt-pgvector
code .
npm install
cp .env.local.example .env.local
Project
β API
. The API key should be stored in the SUPABASE_ANON_KEY
variable and project URL should be stored under NEXT_PUBLIC_SUPABASE_URL
.API Keys
. The API key should be stored in the OPENAI_API_KEY
variable.OPEAI_PROXY
be provide to enable your custom proxy of OPENAI api. Left it ""
to call official API directly.SPLASH_URL
be provide to enable your splash (Splash is a javascript rendering service. Itβs a lightweight web browser with an HTTP API, implemented in Python 3 using Twisted and QT5) api. Left it ""
to fetch url direct.npm run dev