The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(docs-gpt): end-to-end gpt-3 completion using context injection
Greg Richardson607c981be065
diff --git a/apps/docs/components/Clippy/ClippyModal.tsx b/apps/docs/components/Clippy/ClippyModal.tsxindex 3fb6f26e774..3edb3dce4b1 100644--- a/apps/docs/components/Clippy/ClippyModal.tsx+++ b/apps/docs/components/Clippy/ClippyModal.tsx@@ -1,4 +1,5 @@-import { FC, useState } from 'react'+import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { FC, useCallback, useState } from 'react'import { Input } from '~/../../packages/ui'type Props = {@@ -7,6 +8,26 @@ type Props = {const ClippyModal: FC<Props> = ({ onClose }) => {const [query, setQuery] = useState('')+ const [answer, setAnswer] = useState<string>()+ const [isLoading, setIsLoading] = useState(false)+ const supabaseClient = useSupabaseClient()++ const handleConfirm = useCallback(async () => {+ setAnswer(undefined)+ setIsLoading(true)++ const response = await supabaseClient.functions.invoke('clippy-search', { body: { query } })++ setIsLoading(false)++ // TODO: display an error on the UI+ if (response.error) {+ console.error('Clippy search failed', response.error)+ return+ }++ setAnswer(response.data.answer)+ }, [query, supabaseClient])return (<div@@ -14,7 +35,8 @@ const ClippyModal: FC<Props> = ({ onClose }) => {onClick={onClose}><div- className={`mx-auto flex rounded-lg p-6 w-full max-w-2xl shadow-2xl overflow-hidden border text-left border-scale-500 dark:bg-scale-300 cursor-auto`}+ className={`mx-auto flex flex-col gap-6 rounded-lg p-6 w-full max-w-2xl shadow-2xl overflow-hidden border text-left border-scale-500 dark:bg-scale-300 cursor-auto`}+ onClick={(e) => e.stopPropagation()}><InputclassName="w-full"@@ -23,7 +45,18 @@ const ClippyModal: FC<Props> = ({ onClose }) => {placeholder="What can I help you with?"value={query}onChange={(e) => setQuery(e.target.value)}+ onKeyDown={(e) => {+ switch (e.key) {+ case 'Enter':+ handleConfirm()+ return+ default:+ return+ }+ }}/>+ {isLoading && 'Loading'}+ {answer && <div>{answer}</div>}</div></div>)diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjsindex bf98d6d34fd..003bb8c1340 100644--- a/apps/docs/next.config.mjs+++ b/apps/docs/next.config.mjs@@ -84,6 +84,6 @@ const nextConfig = {// next.config.jsexport default () => {// const plugins = [withMDX]/- const plugins = [withTM(['ui', 'common']), withMDX, withYaml]+ const plugins = [withTM(['ui', 'common', '@supabase/auth-helpers-nextjs']), withMDX, withYaml]return plugins.reduce((acc, next) => next(acc), nextConfig)}diff --git a/apps/docs/package.json b/apps/docs/package.jsonindex 47e4c83c8b3..059b6fdd05f 100644--- a/apps/docs/package.json+++ b/apps/docs/package.json@@ -40,6 +40,8 @@"@mdx-js/react": "^1.6.22","@next/mdx": "^12.0.4","@radix-ui/react-accordion": "^1.0.1",+ "@supabase/auth-helpers-nextjs": "^0.5.4",+ "@supabase/auth-helpers-react": "^0.3.1","@supabase/supabase-js": "^2.4.1","algoliasearch": "^4.14.2","babel": "^6.23.0",diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsxindex 0736cff9c2b..9243f33e133 100644--- a/apps/docs/pages/_app.tsx+++ b/apps/docs/pages/_app.tsx@@ -1,21 +1,24 @@+import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'+import { SessionContextProvider } from '@supabase/auth-helpers-react'+import { ThemeProvider } from 'common/Providers'import { DefaultSeo } from 'next-seo'import { useRouter } from 'next/router'-import { useEffect } from 'react'+import { useEffect, useState } from 'react'import { AppPropsWithLayout } from 'types'import { SearchProvider } from '~/components/DocSearch'import Favicons from '~/components/Favicons'-import { ThemeProvider } from 'common/Providers'import SiteLayout from '~/layouts/SiteLayout'+import { post } from '~/lib/fetchWrappers'import '../styles/algolia-search.scss'import '../styles/ch.scss'import '../styles/docsearch.scss'import '../styles/main.scss?v=1.0.0'import '../styles/new-docs.scss'import '../styles/prism-okaidia.scss'-import { post } from '~/lib/fetchWrappers'function MyApp({ Component, pageProps }: AppPropsWithLayout) {const router = useRouter()+ const [supabase] = useState(() => createBrowserSupabaseClient())function telemetry(route: string) {return post(`https://api.supabase.io/platform/telemetry/page`, {@@ -81,13 +84,15 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {cardType: 'summary_large_image',}}/>- <ThemeProvider>- <SearchProvider>- <SiteLayout>- <Component {...pageProps} />- </SiteLayout>- </SearchProvider>- </ThemeProvider>+ <SessionContextProvider supabaseClient={supabase}>+ <ThemeProvider>+ <SearchProvider>+ <SiteLayout>+ <Component {...pageProps} />+ </SiteLayout>+ </SearchProvider>+ </ThemeProvider>+ </SessionContextProvider></>)}diff --git a/package-lock.json b/package-lock.jsonindex 3f1717ce89b..2449a500bc1 100644--- a/package-lock.json+++ b/package-lock.json@@ -47,6 +47,8 @@"@mdx-js/react": "^1.6.22","@next/mdx": "^12.0.4","@radix-ui/react-accordion": "^1.0.1",+ "@supabase/auth-helpers-nextjs": "^0.5.4",+ "@supabase/auth-helpers-react": "^0.3.1","@supabase/supabase-js": "^2.4.1","algoliasearch": "^4.14.2","babel": "^6.23.0",@@ -9577,6 +9579,33 @@"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.44.1.tgz","integrity": "sha512-DKj3U6tS+sCNsSXsoZbOl5gDrAVD3cAZ9QCiVSykLC3iJo085kkmw/3BAACRH54Bq2bN34yySuH6G1SLh2xHXA=="},+ "node_modules/@supabase/auth-helpers-nextjs": {+ "version": "0.5.4",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-nextjs/-/auth-helpers-nextjs-0.5.4.tgz",+ "integrity": "sha512-Xm3BMDOYPbNyuh8UXDRgBDc3JkeM5S2PfuC1jFJ73CCay4YiH1YxTz06Cvtp+vLH432qdjnqH+49ehVvUehPnQ==",+ "dependencies": {+ "@supabase/auth-helpers-shared": "0.2.4"+ },+ "peerDependencies": {+ "@supabase/supabase-js": "^2.0.4"+ }+ },+ "node_modules/@supabase/auth-helpers-react": {+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-react/-/auth-helpers-react-0.3.1.tgz",+ "integrity": "sha512-g3SFv08Dz9FapNif/ZY1b7qKGlMJDyTLSayHBz3kb3FuYxg7aLWgQtydDhm5AGbc0XtvpIBuhGTIOVevwpdosA==",+ "peerDependencies": {+ "@supabase/supabase-js": "^2.0.4"+ }+ },+ "node_modules/@supabase/auth-helpers-shared": {+ "version": "0.2.4",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-shared/-/auth-helpers-shared-0.2.4.tgz",+ "integrity": "sha512-c+hi3N6DhjPTzjXGOokre4gmMZOqt0f1ORrwZwi2s07pk3cbkmn77DwwVtlYMNi3oZNYRQqAfxJu83UzpJrrmg==",+ "peerDependencies": {+ "@supabase/supabase-js": "^2.0.4"+ }+ },"node_modules/@supabase/auth-ui-react": {"version": "0.1.8","resolved": "https://registry.npmjs.org/@supabase/auth-ui-react/-/auth-ui-react-0.1.8.tgz",@@ -44519,6 +44548,26 @@"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.44.1.tgz","integrity": "sha512-DKj3U6tS+sCNsSXsoZbOl5gDrAVD3cAZ9QCiVSykLC3iJo085kkmw/3BAACRH54Bq2bN34yySuH6G1SLh2xHXA=="},+ "@supabase/auth-helpers-nextjs": {+ "version": "0.5.4",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-nextjs/-/auth-helpers-nextjs-0.5.4.tgz",+ "integrity": "sha512-Xm3BMDOYPbNyuh8UXDRgBDc3JkeM5S2PfuC1jFJ73CCay4YiH1YxTz06Cvtp+vLH432qdjnqH+49ehVvUehPnQ==",+ "requires": {+ "@supabase/auth-helpers-shared": "0.2.4"+ }+ },+ "@supabase/auth-helpers-react": {+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-react/-/auth-helpers-react-0.3.1.tgz",+ "integrity": "sha512-g3SFv08Dz9FapNif/ZY1b7qKGlMJDyTLSayHBz3kb3FuYxg7aLWgQtydDhm5AGbc0XtvpIBuhGTIOVevwpdosA==",+ "requires": {}+ },+ "@supabase/auth-helpers-shared": {+ "version": "0.2.4",+ "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-shared/-/auth-helpers-shared-0.2.4.tgz",+ "integrity": "sha512-c+hi3N6DhjPTzjXGOokre4gmMZOqt0f1ORrwZwi2s07pk3cbkmn77DwwVtlYMNi3oZNYRQqAfxJu83UzpJrrmg==",+ "requires": {}+ },"@supabase/auth-ui-react": {"version": "0.1.8","resolved": "https://registry.npmjs.org/@supabase/auth-ui-react/-/auth-ui-react-0.1.8.tgz",@@ -49585,6 +49634,8 @@"@mdx-js/react": "^1.6.22","@next/mdx": "^12.0.4","@radix-ui/react-accordion": "^1.0.1",+ "@supabase/auth-helpers-nextjs": "^0.5.4",+ "@supabase/auth-helpers-react": "^0.3.1","@supabase/supabase-js": "^2.4.1","@types/node": "^17.0.12","@types/react": "17.0.39",diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.tsnew file mode 100644index 00000000000..9fa200524bf--- /dev/null+++ b/supabase/functions/clippy-search/index.ts@@ -0,0 +1,196 @@+import { serve } from 'https://deno.land/[email protected]/http/server.ts'+import 'https://deno.land/x/[email protected]/mod.ts'+import { createClient } from 'https://esm.sh/@supabase/[email protected]'+import GPT3Tokenizer from 'https://esm.sh/[email protected]'+import { Configuration, OpenAIApi } from 'https://esm.sh/[email protected]'++const openAiKey = Deno.env.get('OPENAI_KEY')+const supabaseUrl = Deno.env.get('DOCS_SEARCH_SUPABASE_URL')+const supabaseServiceKey = Deno.env.get('DOCS_SEARCH_SUPABASE_SERVICE_KEY')++export const corsHeaders = {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',+}++serve(async (req) => {+ // Handle CORS+ if (req.method === 'OPTIONS') {+ return new Response('ok', { headers: corsHeaders })+ }++ if (!openAiKey) {+ return new Response(+ JSON.stringify({+ error: 'Missing environment variable OPENAI_KEY',+ }),+ {+ status: 400,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ if (!supabaseUrl) {+ return new Response(+ JSON.stringify({+ error: 'Missing environment variable DOCS_SEARCH_SUPABASE_URL',+ }),+ {+ status: 400,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ if (!supabaseServiceKey) {+ return new Response(+ JSON.stringify({+ error: 'Missing environment variable DOCS_SEARCH_SUPABASE_SERVICE_KEY',+ }),+ {+ status: 400,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ const requestData = await req.json()++ if (!requestData) {+ return new Response(+ JSON.stringify({+ error: 'Missing request data',+ }),+ {+ status: 400,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ const { query } = requestData++ console.log(supabaseUrl, supabaseServiceKey)++ const supabaseClient = createClient('http://supabase_kong_docs:8000', supabaseServiceKey)++ const configuration = new Configuration({ apiKey: openAiKey })+ const openai = new OpenAIApi(configuration)++ // Moderate the content to comply with OpenAI T&C+ const moderationResponse = await openai.createModeration({ input: query })++ const [results] = moderationResponse.data.results++ if (results.flagged) {+ return new Response(+ JSON.stringify({+ error: 'Flagged content',+ flagged: true,+ categories: results.categories,+ }),+ {+ status: 400,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ const embeddingResponse = await openai.createEmbedding({+ model: 'text-embedding-ada-002',+ input: query.replaceAll('\n', ' '),+ })++ if (embeddingResponse.status !== 200) {+ console.log(+ `Failed to create embedding for question. OpenAI response status ${embeddingResponse.status}`+ )++ return new Response(+ JSON.stringify({+ error: 'Failed to process questions',+ }),+ {+ status: 500,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+ }++ const [{ embedding }] = embeddingResponse.data.data++ const { error: matchError, data: pageSections } = await supabaseClient.rpc(+ 'match_page_sections',+ {+ embedding,+ match_threshold: 0.78,+ match_count: 10,+ min_content_length: 50,+ }+ )++ if (matchError) {+ console.log(matchError.message)+ throw matchError+ }++ const tokenizer = new GPT3Tokenizer({ type: 'gpt3' })+ let tokenCount = 0+ let contextText = ''++ for (let i = 0; i < pageSections.length; i++) {+ const pageSection = pageSections[i]+ const content = pageSection.content+ const encoded = tokenizer.encode(content)+ tokenCount += encoded.text.length++ if (tokenCount >= 1500) {+ break+ }++ contextText += `${content.trim()}\n---\n`+ }++ const prompt = `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. Include multiline code snippets when available. 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}++Question: """+${query}+"""++Answer as markdown:+`++ console.log(prompt)++ const completionResponse = await openai.createCompletion({+ model: 'text-davinci-003',+ prompt,+ max_tokens: 512,+ })++ if (completionResponse.status !== 200) {+ throw new Error('Failed to complete')+ }++ // TODO: handle response errors+ const {+ id,+ choices: [{ text: answer }],+ } = completionResponse.data++ console.log(completionResponse.data)++ return new Response(+ JSON.stringify({+ id,+ answer,+ }),+ {+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ }+ )+})diff --git a/supabase/migrations/20230128004504_embedding_similarity_search.sql b/supabase/migrations/20230128004504_embedding_similarity_search.sqlnew file mode 100644index 00000000000..7999cd07581--- /dev/null+++ b/supabase/migrations/20230128004504_embedding_similarity_search.sql@@ -0,0 +1,31 @@+create or replace function match_page_sections(embedding vector(1536), match_threshold float, match_count int, min_content_length int)+returns table (path text, content text, similarity float)+language plpgsql+as $$+#variable_conflict use_variable+begin+ return query+ select+ page.path,+ page_section.content,+ (page_section.embedding <#> embedding) * -1 as similarity+ from page_section+ join page+ on page_section.page_id = page.id++ -- We only care about sections that have a useful amount of content+ where length(page_section.content) >= min_content_length++ -- The dot product is negative because of a Postgres limitation, so we negate it+ and (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 page_section.embedding <#> embedding++ limit match_count;+end;+$$;