Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(docs-search): search edge function

Greg Richardsoned1fd8804b8f
diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.ts
index 8a80354e429..e2c52a51d89 100644
--- a/supabase/functions/clippy-search/index.ts
+++ b/supabase/functions/clippy-search/index.ts
@@ -4,7 +4,7 @@ import { createClient } from 'https://esm.sh/@supabase/[email protected]'
import { oneLine, stripIndent } from 'https://esm.sh/[email protected]'
import GPT3Tokenizer from 'https://esm.sh/[email protected]'
import { Configuration, CreateCompletionRequest, OpenAIApi } from 'https://esm.sh/[email protected]'
-import { ApplicationError, UserError } from './errors.ts'
+import { ApplicationError, UserError } from '../common/errors.ts'
const openAiKey = Deno.env.get('OPENAI_KEY')
const supabaseUrl = Deno.env.get('SUPABASE_URL')
diff --git a/supabase/functions/clippy-search/errors.ts b/supabase/functions/common/errors.ts
similarity index 100%
rename from supabase/functions/clippy-search/errors.ts
rename to supabase/functions/common/errors.ts
diff --git a/supabase/functions/search/index.ts b/supabase/functions/search/index.ts
new file mode 100644
index 00000000000..93cb0812c9b
--- /dev/null
+++ b/supabase/functions/search/index.ts
@@ -0,0 +1,157 @@
+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 { Configuration, OpenAIApi } from 'https://esm.sh/[email protected]'
+import { ApplicationError, UserError } from '../common/errors.ts'
+
+const openAiKey = Deno.env.get('OPENAI_KEY')
+const supabaseUrl = Deno.env.get('SUPABASE_URL')
+const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')
+
+export const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+}
+
+serve(async (req) => {
+ try {
+ // Handle CORS
+ if (req.method === 'OPTIONS') {
+ return new Response('ok', { headers: corsHeaders })
+ }
+
+ if (!openAiKey) {
+ throw new ApplicationError('Missing environment variable OPENAI_KEY')
+ }
+
+ if (!supabaseUrl) {
+ throw new ApplicationError('Missing environment variable SUPABASE_URL')
+ }
+
+ if (!supabaseServiceKey) {
+ throw new ApplicationError('Missing environment variable SUPABASE_SERVICE_ROLE_KEY')
+ }
+
+ const requestData = await req.json()
+
+ if (!requestData) {
+ throw new UserError('Missing request data')
+ }
+
+ const { query } = requestData
+
+ if (!query) {
+ throw new UserError('Missing query in request data')
+ }
+
+ const sanitizedQuery = query.trim()
+
+ const supabaseClient = createClient(supabaseUrl, 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: sanitizedQuery })
+
+ const [results] = moderationResponse.data.results
+
+ if (results.flagged) {
+ throw new UserError('Flagged content', {
+ flagged: true,
+ categories: results.categories,
+ })
+ }
+
+ const embeddingResponse = await openai.createEmbedding({
+ model: 'text-embedding-ada-002',
+ input: sanitizedQuery.replaceAll('\n', ' '),
+ })
+
+ if (embeddingResponse.status !== 200) {
+ throw new ApplicationError('Failed to create embedding for question', embeddingResponse)
+ }
+
+ 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 || !pageSections) {
+ throw new ApplicationError('Failed to match page sections', matchError)
+ }
+
+ const uniquePageIds = pageSections
+ .map<number>(({ page_id }) => page_id)
+ .filter((value, index, array) => array.indexOf(value) === index)
+
+ const { error: fetchPagesError, data: pages } = await supabaseClient
+ .from('page')
+ .select()
+ .in('id', uniquePageIds)
+
+ if (fetchPagesError || !pages) {
+ throw new ApplicationError(`Failed to fetch pages`, fetchPagesError)
+ }
+
+ const combinedPages = pages
+ .map((page) => {
+ const sections = pageSections
+ .filter(({ page_id }) => page_id === page.id)
+ .map(({ content: _, ...pageSection }) => pageSection)
+
+ const score = sections.reduce((sum, section) => sum + section.similarity, 0)
+
+ return {
+ ...page,
+ sections,
+ score,
+ }
+ })
+ .sort((a, b) => b.score - a.score)
+
+ return new Response(JSON.stringify(combinedPages), {
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json',
+ },
+ })
+ } catch (err: unknown) {
+ if (err instanceof UserError) {
+ return new Response(
+ JSON.stringify({
+ error: err.message,
+ data: err.data,
+ }),
+ {
+ status: 400,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ }
+ )
+ } else if (err instanceof ApplicationError) {
+ // Print out application errors with their additional data
+ console.error(`${err.message}: ${JSON.stringify(err.data)}`)
+ } else {
+ // Print out unexpected errors as is to help with debugging
+ console.error(err)
+ }
+
+ // TODO: include more response info in debug environments
+ return new Response(
+ JSON.stringify({
+ error: 'There was an error processing your request',
+ }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ }
+ )
+ }
+})
diff --git a/supabase/migrations/20230217032716_page_hierarchy_function.sql b/supabase/migrations/20230217032716_page_hierarchy_function.sql
new file mode 100644
index 00000000000..df34f9f053f
--- /dev/null
+++ b/supabase/migrations/20230217032716_page_hierarchy_function.sql
@@ -0,0 +1,53 @@
+drop function match_page_sections;
+
+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
+ page_section.id,
+ page_section.page_id,
+ page_section.slug,
+ page_section.heading,
+ page_section.content,
+ (page_section.embedding <#> embedding) * -1 as similarity
+ from page_section
+
+ -- 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;
+$$;
+
+create or replace function get_page_parents(page_id bigint)
+returns table (id bigint, parent_page_id bigint, path text, meta jsonb)
+language sql
+as $$
+ with recursive chain as (
+ select *
+ from page
+ where id = page_id
+
+ union all
+
+ select child.*
+ from page as child
+ join chain on chain.parent_page_id = child.id
+ )
+ select id, parent_page_id, path, meta
+ from chain;
+$$;