The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: add detailed guide.
thorwebdevb015cca0df7c
diff --git a/apps/docs/pages/guides/getting-started/quickstarts/openai-vector-search.mdx b/apps/docs/pages/guides/getting-started/quickstarts/openai-vector-search.mdxindex 3b8ff2d2c5d..ca152a95844 100644--- a/apps/docs/pages/guides/getting-started/quickstarts/openai-vector-search.mdx+++ b/apps/docs/pages/guides/getting-started/quickstarts/openai-vector-search.mdx@@ -3,138 +3,354 @@ import StepHikeCompact from '~/components/StepHikeCompact'export const meta = {title: 'Supabase with OpenAI',- subtitle: 'Learn how to create a Supabase project, enable a database extension, and create some embeddings for your openai project.',- breadcrumb: 'OpenAI'+ subtitle:+ 'Learn how to build your own custom ChatGPT style doc search powered by Next.js, OpenAI, and Supabase.',+ breadcrumb: 'OpenAI',}-<StepHikeCompact>+Some time ago we've built [Supabase Clippy](https://supabase.com/blog/chatgpt-supabase-docs) a ChatGPT for the Supabase Docs. In this tutorial we'll look at how you can build your own custom ChatGPT experience based on your own knowledge base.- <StepHikeCompact.Step step={1}>+We assume that you have a Next.js project with a collection of `.mdx` files nested inside your `pages` directory. We will start developing locally with the Supabase CLI and then push our local database changes to our hosted Supabase project.- <StepHikeCompact.Details title="Create Supabase project">+You can find the complete code, ready to be deployed to Vercel, [on GitHub](https://github.com/supabase-community/nextjs-openai-doc-search).- To create a project with Supabase, navigate to [Supabase](https://supabase.com/?ref=supabaseforai), click `Sign In` and authenticate with GitHub to login or register a new account.+## Configure the Database- From the Supabase dashboard, click `New project` and select an organization.+<StepHikeCompact>- > Note: You may need to create an organization first.+ <StepHikeCompact.Step step={1}>- Give your project a `name`, `password`, select a `region` close to your potential users and click `Create new project`.+ <StepHikeCompact.Details title="Set up Supabase locally">- Supabase will take a couple of minutes to configure the infrastructure.+ Make sure you have the latest version of the [Supabase CLI installed]().++ Initialize Supabase in the root directory of your app.</StepHikeCompact.Details><StepHikeCompact.Details>- + ```bash+ supabase init+ ```</StepHikeCompact.Details></StepHikeCompact.Step><StepHikeCompact.Step step={2}>- <StepHikeCompact.Details title="Add PG-vector extension">+ <StepHikeCompact.Details title="Enable the pgvector extension">- So PgVector is a great fit to store those and compare for similarity. To enable the `pgvector` extension, you can use the following code right from your Supabase Project's SQL Editor:+ To make changes to our local database, we need to create a new migration. This will create a new `.sql` file in our `supabase/migrations` folder, where we can write SQL that will be applied to our local database when starting Supabase locally.</StepHikeCompact.Details><StepHikeCompact.Code>+ ```bash+ supabase migration new init+ ```++ Copy the following SQL line into the newly created migration file to enable the pgvector extension.++```sql- create extension if not exists pgvector with schema extensions;+ -- Enable pgvector extension+ create extension if not exists vector with schema public;```</StepHikeCompact.Code>- <StepHikeCompact.Details title="">+ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={3}>+ <StepHikeCompact.Details title="Create the database schema">++ Next, we will set up two tables:++ 1. `nods_page`: we use this to store the checksum of our pages to make sure we only regenerate the embeddings when the page content has changed.+ 2. `nods_page_section`: here we store the actual embeddings with some metadata.- Or go to [Database > Extensions](https://app.supabase.com/project/_/database/extensions) and enable the Vector extension.+ To do so, copy these SQL queries to your init migration file.</StepHikeCompact.Details>+<StepHikeCompact.Code>++ ```sql+ -- Create tables+ create table "public"."nods_page" (+ id bigserial primary key,+ parent_page_id bigint references public.nods_page,+ path text not null unique,+ checksum text,+ meta jsonb,+ type text,+ source text+ );+ alter table "public"."nods_page" enable row level security;++ create table "public"."nods_page_section" (+ id bigserial primary key,+ page_id bigint not null references public.nods_page on delete cascade,+ content text,+ token_count int,+ embedding vector(1536),+ slug text,+ heading text+ );+ alter table "public"."nods_page_section" enable row level security;+ ```+</StepHikeCompact.Code></StepHikeCompact.Step>- <StepHikeCompact.Step step={3}>- <StepHikeCompact.Details title="Create OpenAI account">+ <StepHikeCompact.Step step={4}>+ <StepHikeCompact.Details title="Create similarity search database function">++ Anytime the user sends us a query, we want to find the content that's relevant to their questions. We can do this using pgvector's similarity search.++ As these are quite complex SQL operations, we wrap them in database functions that we can then easily call from our frontend using [RPC](https://supabase.com/docs/reference/javascript/rpc).++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```sql+ -- Create embedding similarity search functions+ create or replace function match_page_sections(embedding vector(1536), match_threshold float, match_count int, min_content_length int)+ returns table (id bigint, page_id bigint, slug text, heading text, content text, similarity float)+ language plpgsql+ as $$+ #variable_conflict use_variable+ begin+ return query+ select+ nods_page_section.id,+ nods_page_section.page_id,+ nods_page_section.slug,+ nods_page_section.heading,+ nods_page_section.content,+ (nods_page_section.embedding <#> embedding) * -1 as similarity+ from nods_page_section++ -- We only care about sections that have a useful amount of content+ where length(nods_page_section.content) >= min_content_length++ -- The dot product is negative because of a Postgres limitation, so we negate it+ and (nods_page_section.embedding <#> embedding) * -1 > match_threshold++ -- OpenAI embeddings are normalized to length 1, so+ -- cosine similarity and dot product will produce the same results.+ -- Using dot product which can be computed slightly faster.+ --+ -- For the different syntaxes, see https://github.com/pgvector/pgvector+ order by nods_page_section.embedding <#> embedding++ limit match_count;+ end;+ $$;+ ```++ </StepHikeCompact.Code>- OpenAI is a research organization that aims to create safe and beneficial artificial general intelligence (AGI) that can benefit all of humanity. [OpenAI](https://openai.com) also offers various products and services that use its AI models, such as ChatGPT, Codex, and Playground.+ </StepHikeCompact.Step>- And we will use it to create embeddings, and generate text to answer users' queries.+ <StepHikeCompact.Step step={5}>+ <StepHikeCompact.Details title="Start Supabase Locally">- To create an OpenAI account, you can follow these steps:+ Start Supabase locally. At this point all files in `supabase/migrations` will be applied to your database and you're ready to go.</StepHikeCompact.Details>- <StepHikeCompact.Details>+ <StepHikeCompact.Code>++ ```bash+ supabase start+ ```- - Visit the [OpenAI sign up](https://platform.openai.com/signup) page in your web browser.- - Click the **sign up** link.- - You can use your e-mail to sign up, or an existing Google or Microsoft account.- - After signing up, you can view your API keys by clicking on your profile in the top-right corner and selecting **View API keys**.- - You can use your API keys to access the OpenAI services and products, such as ChatGPT, Codex, and Playground.+ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={6}>+ <StepHikeCompact.Details title="Push changes to your Supabase database">++ Once ready, you can link your local project to your cloud hosted Supabase project and push the local changes to your hosted instance.</StepHikeCompact.Details>+ <StepHikeCompact.Code>++ ```bash+ supabase link --project-ref=your-project-ref++ supabase db push+ ```++ </StepHikeCompact.Code>+</StepHikeCompact.Step>- <StepHikeCompact.Step step={4}>- <StepHikeCompact.Details title="Create embeddings">+</StepHikeCompact>- To search through your texts base (like documentation or a book that you really like) you should create embeddings for it. Wonderful **[Greg Richardson](https://twitter.com/ggrdson)** already made a script to do that. The only thing left to do is to collect your documents as a bunch of Markdown files and pass them to it.+## Pre-process the knowledge base at build time- You can find the full code here: [Embeddings Generation Code](https://github.com/supabase/supabase/blob/6acc7332c6909030c1a2c69c561c27c39ff1f1ff/apps/docs/scripts/generate-embeddings.ts)+Now that our database is set up, we will write a script to process all `.mdx` files in the `pages` directory. You can find the full script [here](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/lib/generate-embeddings.ts).- What it does is:+<StepHikeCompact>++ <StepHikeCompact.Step step={1}>+ <StepHikeCompact.Details title="Generate Embeddings">++ We can now write a script to pre-process our `.mdx` files at build time and generate the embeddings. Create a new file `lib/generate-embeddings.ts` and copy the code over from [GitHub](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/lib/generate-embeddings.ts)</StepHikeCompact.Details>- <StepHikeCompact.Details>+ </StepHikeCompact.Step>- 1. Searches for all the Markdown files in the provided Path.- 2. Parsing markdown files to split it into text blocks. It just uses headings for that.- 3. Parsing these blocks by the type of the text and removes some additional blocs like JS components (Yes, you can pass MDX as well).- 4. Uses `openai.createEmbedding` to actually generate embeddings from text blocks.- 5. Saves the source page links, raw text blocks and embeddings to the Supabase Database using `supabase-js` library.+ <StepHikeCompact.Step step={2}>+ <StepHikeCompact.Details title="Set up environment variables">++ We will need a couple environment variables to run the script. Add them to your `.env` file and make sure your `.env` file is not committed to source control!</StepHikeCompact.Details>- <StepHikeCompact.Details title="">+ <StepHikeCompact.Code>++ ```txt+ NEXT_PUBLIC_SUPABASE_URL=+ NEXT_PUBLIC_SUPABASE_ANON_KEY=+ SUPABASE_SERVICE_ROLE_KEY=++ # Get your key at https://platform.openai.com/account/api-keys+ OPENAI_KEY=+ ```++ You can get your local Supabase credentials by running- Don't forget to specify `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY` and `OPENAI_KEY` environment variables.+ ```bash+ supabase status+ ```++ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={3}>+ <StepHikeCompact.Details title="Run script at build time">++ Include the script in your `package.json` script commands to enable Vercel to automaticall run it at build time.</StepHikeCompact.Details>+ <StepHikeCompact.Code>++ ```json+ "scripts": {+ "dev": "next dev",+ "build": "pnpm run embeddings && next build",+ "start": "next start",+ "embeddings": "tsx lib/generate-embeddings.ts"+ },+ ```++ </StepHikeCompact.Code>+</StepHikeCompact.Step>- <StepHikeCompact.Step step={5}>- <StepHikeCompact.Details title="Answering the User's Query">+</StepHikeCompact>- We are all prepared now. The next thing is the actual user interface. The idea here is to find the most similar text blocks from our knowledge to the query entered by a user. How to do that? Here is the time for the real superpower of PgVector.+## Create Text Completion with OpneAI API- We can use the same OpenAI API `openai.createEmbedding` to vectorise users's query and create an embedding from it. And then use PgVector to compare its vectorized representation with all the knowledge base to find the most similar text blocks.+Anytime the user asks a question, we will need to create an embedding for their question, perform a similarity search, and then send a text completion request to the OpenAI API with the query and then context content merged together into a prompt.- To do so you can use the following Postgres Function also provided by **[Greg Richardson](https://twitter.com/ggrdson)**:+All of this is glued together in a [Vercel Edge Function](https://vercel.com/docs/concepts/functions/edge-functions), the code for which can be found on [GitHub](https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/pages/api/vector-search.ts).- [Embedding Similarity Search SQL](https://github.com/supabase/supabase/blob/6acc7332c6909030c1a2c69c561c27c39ff1f1ff/supabase/migrations/20230128004504_embedding_similarity_search.sql)+<StepHikeCompact>- After you get Top-10 results, for example, you need to extract the real text blocks for these and put it into GPT-3.5 (a.k.a. ChatGPT) with the initial User's query and the following Prompt to get the comprehensive answer form your personal AI assistant. The current implementation uses the `text-davinci-003` model (but we have plans to switch to gpt-3.5-turbo/gpt-4 in the future).+ <StepHikeCompact.Step step={1}>+ <StepHikeCompact.Details title="Create Embedding for Question">- And don't forget to use OpenAI `openai.createModeration` to verify that User's query not violates any policies.+ In order to perform similarity search we need to turn the question into an embedding.</StepHikeCompact.Details><StepHikeCompact.Code>- ```sh- You are a very enthusiastic assistant who loves to help people!- Given the following sections from the documentation, answer the- question using only that information, outputted in markdown format.- If you are unsure and the answer is not explicitly written in the- documentation, say "Sorry, I don't know how to help with that."+ ```ts+ const embeddingResponse = await fetch('https://api.openai.com/v1/embeddings', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${openAiKey}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ model: 'text-embedding-ada-002',+ input: sanitizedQuery.replaceAll('\n', ' '),+ }),+ })++ if (embeddingResponse.status !== 200) {+ throw new ApplicationError('Failed to create embedding for question', embeddingResponse)+ }++ const {+ data: [{ embedding }],+ } = await embeddingResponse.json()+ ```++ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={2}>+ <StepHikeCompact.Details title="Perform similarity search">++ Using the `embeddingResponse` we can now perform similarity search by performing an remote procedure call (RPC) to the database function we created earlier.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```ts+ const { error: matchError, data: pageSections } = await supabaseClient.rpc(+ 'match_page_sections',+ {+ embedding,+ match_threshold: 0.78,+ match_count: 10,+ min_content_length: 50,+ }+ )+ ```++ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={3}>+ <StepHikeCompact.Details title="Perform text completion request">++ With the relevant content for the user's question identified, we can now build the prompt and make a text completion request via the OpenAI API.++ If succesful, the OpenAI API will respond with a `text/event-stream` response that we can simply forward to the client where we'll process the event stream to smoothly print the answer to the user.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```ts+ const prompt = codeBlock`+ ${oneLine`+ You are a very enthusiastic Supabase representative who loves+ to help people! Given the following sections from the Supabase+ documentation, answer the question using only that information,+ outputted in markdown format. If you are unsure and the answer+ is not explicitly written in the documentation, say+ "Sorry, I don't know how to help with that."+ `}Context sections:${contextText}@@ -144,6 +360,36 @@ export const meta = {"""Answer as markdown (including related code snippets if available):+ `++ const completionOptions: CreateCompletionRequest = {+ model: 'text-davinci-003',+ prompt,+ max_tokens: 512,+ temperature: 0,+ stream: true,+ }++ const response = await fetch('https://api.openai.com/v1/completions', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${openAiKey}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(completionOptions),+ })++ if (!response.ok) {+ const error = await response.json()+ throw new ApplicationError('Failed to generate completion', error)+ }++ // Proxy the streamed SSE response from OpenAI+ return new Response(response.body, {+ headers: {+ 'Content-Type': 'text/event-stream',+ },+ })```</StepHikeCompact.Code>@@ -152,5 +398,91 @@ export const meta = {</StepHikeCompact>+## Show the answer on the frontend++In a last step, we need to process the event stream from the OpenAI API and print the answer to the user. The full code for this can be found on [GitHub]().++```tsx+const handleConfirm = React.useCallback(+ async (query: string) => {+ setAnswer(undefined)+ setQuestion(query)+ setSearch('')+ dispatchPromptData({ index: promptIndex, answer: undefined, query })+ setHasError(false)+ setIsLoading(true)++ const eventSource = new SSE(`api/vector-search`, {+ headers: {+ apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',+ Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,+ 'Content-Type': 'application/json',+ },+ payload: JSON.stringify({ query }),+ })++ function handleError<T>(err: T) {+ setIsLoading(false)+ setHasError(true)+ console.error(err)+ }++ eventSource.addEventListener('error', handleError)+ eventSource.addEventListener('message', (e: any) => {+ try {+ setIsLoading(false)++ if (e.data === '[DONE]') {+ setPromptIndex((x) => {+ return x + 1+ })+ return+ }++ const completionResponse: CreateCompletionResponse = JSON.parse(e.data)+ const text = completionResponse.choices[0].text++ setAnswer((answer) => {+ const currentAnswer = answer ?? ''++ dispatchPromptData({+ index: promptIndex,+ answer: currentAnswer + text,+ })++ return (answer ?? '') + text+ })+ } catch (err) {+ handleError(err)+ }+ })++ eventSource.stream()++ eventSourceRef.current = eventSource++ setIsLoading(true)+ },+ [promptIndex, promptData]+)+```++## Learn More++Want to learn more about the awesome tech that is powering this?++- Read the blogpost on how we built [ChatGPT for the Supabase Docs](https://supabase.com/blog/chatgpt-supabase-docs).+- [[Docs] pgvector: Embeddings and vector similarity](https://supabase.com/docs/guides/database/extensions/pgvector)+- Watch [Greg's](https://twitter.com/ggrdson) "How I built this" [video](https://youtu.be/Yhtjd7yGGGA) on the [Rabbit Hole Syndrome YouTube Channel](https://www.youtube.com/@RabbitHoleSyndrome):++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/Yhtjd7yGGGA"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>+export const Page = ({ children }) => <Layout meta={meta} children={children} hideToc={true} />export default Pagediff --git a/apps/docs/public/img/supabase-new.png b/apps/docs/public/img/supabase-new.pngdeleted file mode 100644index 2a3bf98f3c1..00000000000Binary files a/apps/docs/public/img/supabase-new.png and /dev/null differ