Skip to content

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

feat(cmdk): exclude integrations from clippy search

Greg Richardson2be06af7688c
diff --git a/packages/ui/src/components/Command/AiCommand.tsx b/packages/ui/src/components/Command/AiCommand.tsx
index 8065096fe3f..21971713c55 100644
--- a/packages/ui/src/components/Command/AiCommand.tsx
+++ b/packages/ui/src/components/Command/AiCommand.tsx
@@ -1,8 +1,7 @@
-import * as React from 'react'
import type {
ChatCompletionResponseMessage,
+ CreateChatCompletionResponse,
CreateChatCompletionResponseChoicesInner,
- CreateCompletionResponse,
} from 'openai'
import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
@@ -176,8 +175,12 @@ const AiCommand = () => {
setIsResponding(true)
- const completionResponse: CreateCompletionResponse = JSON.parse(e.data)
- const [{ text: content }] = completionResponse.choices
+ const completionResponse: CreateChatCompletionResponse = JSON.parse(e.data)
+ const [
+ {
+ delta: { content },
+ },
+ ] = completionResponse.choices as CreateChatCompletionResponseChoicesInnerDelta[]
const text = content ?? ''
diff --git a/packages/ui/src/components/Command/DocsSearch.tsx b/packages/ui/src/components/Command/DocsSearch.tsx
index 64225778084..24df475b590 100644
--- a/packages/ui/src/components/Command/DocsSearch.tsx
+++ b/packages/ui/src/components/Command/DocsSearch.tsx
@@ -57,9 +57,12 @@ const DocsSearch = () => {
setHasSearchError(false)
setIsLoading(true)
- const { error, data: pageSections } = await supabaseClient.functions.invoke('search', {
- body: { query },
- })
+ const { error, data: pageResults } = await supabaseClient.functions.invoke<PageResult[]>(
+ 'search',
+ {
+ body: { query },
+ }
+ )
setIsLoading(false)
@@ -71,14 +74,14 @@ const DocsSearch = () => {
return
}
- if (!Array.isArray(pageSections)) {
+ if (!Array.isArray(pageResults)) {
setIsLoading(false)
setHasSearchError(true)
console.error('Malformed response')
return
}
- setResults(pageSections)
+ setResults(pageResults)
},
[supabaseClient]
)
diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.ts
index de86010809b..061844941ba 100644
--- a/supabase/functions/clippy-search/index.ts
+++ b/supabase/functions/clippy-search/index.ts
@@ -85,15 +85,15 @@ serve(async (req) => {
const [{ embedding }] = embeddingResponse.data.data
- const { error: matchError, data: pageSections } = await supabaseClient.rpc(
- 'match_page_sections',
- {
+ const { error: matchError, data: pageSections } = await supabaseClient
+ .rpc('match_page_sections', {
embedding,
match_threshold: 0.78,
- match_count: 10,
min_content_length: 50,
- }
- )
+ })
+ .not('page.path', 'like', '/guides/integrations/%')
+ .select('content,page!inner(path)')
+ .limit(10)
if (matchError) {
throw new ApplicationError('Failed to match page sections', matchError)
@@ -116,26 +116,6 @@ serve(async (req) => {
contextText += `${content.trim()}\n---\n`
}
- 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}
-
- Question: """
- ${sanitizedQuery}
- """
-
- Answer as markdown (including related code snippets if available):
- `
-
const messages: ChatCompletionRequestMessage[] = [
{
role: ChatCompletionRequestMessageRoleEnum.System,
diff --git a/supabase/functions/common/database-types.ts b/supabase/functions/common/database-types.ts
index bf0addcb2cc..aa213cf6e17 100644
--- a/supabase/functions/common/database-types.ts
+++ b/supabase/functions/common/database-types.ts
@@ -118,16 +118,16 @@ export interface Database {
Args: {
embedding: unknown
match_threshold: number
- match_count: number
min_content_length: number
}
Returns: {
+ content: string | null
+ embedding: unknown | null
+ heading: string | null
id: number
page_id: number
- slug: string
- heading: string
- content: string
- similarity: number
+ slug: string | null
+ token_count: number | null
}[]
}
vector_avg: {
@@ -178,7 +178,10 @@ export interface Database {
Tables: {
buckets: {
Row: {
+ allowed_mime_types: string[] | null
+ avif_autodetection: boolean | null
created_at: string | null
+ file_size_limit: number | null
id: string
name: string
owner: string | null
@@ -186,7 +189,10 @@ export interface Database {
updated_at: string | null
}
Insert: {
+ allowed_mime_types?: string[] | null
+ avif_autodetection?: boolean | null
created_at?: string | null
+ file_size_limit?: number | null
id: string
name: string
owner?: string | null
@@ -194,7 +200,10 @@ export interface Database {
updated_at?: string | null
}
Update: {
+ allowed_mime_types?: string[] | null
+ avif_autodetection?: boolean | null
created_at?: string | null
+ file_size_limit?: number | null
id?: string
name?: string
owner?: string | null
diff --git a/supabase/functions/search/index.ts b/supabase/functions/search/index.ts
index 3d5c91c2904..e6c21816d78 100644
--- a/supabase/functions/search/index.ts
+++ b/supabase/functions/search/index.ts
@@ -77,15 +77,14 @@ serve(async (req) => {
}
const [{ embedding }] = embeddingResponse.data.data
- const { error: matchError, data: pageSections } = await supabaseClient.rpc(
- 'match_page_sections',
- {
+ const { error: matchError, data: pageSections } = await supabaseClient
+ .rpc('match_page_sections', {
embedding,
match_threshold: 0.78,
- match_count: 10,
min_content_length: 50,
- }
- )
+ })
+ .select('slug, heading, page_id')
+ .limit(10)
if (matchError || !pageSections) {
throw new ApplicationError('Failed to match page sections', matchError ?? undefined)
@@ -97,7 +96,7 @@ serve(async (req) => {
const { error: fetchPagesError, data: pages } = await supabaseClient
.from('page')
- .select()
+ .select('id, type, path, meta')
.in('id', uniquePageIds)
if (fetchPagesError || !pages) {
@@ -107,18 +106,19 @@ serve(async (req) => {
const combinedPages = pages
.map((page) => {
const sections = pageSections
+ .map((pageSection, index) => ({ ...pageSection, rank: index }))
.filter(({ page_id }) => page_id === page.id)
- .map(({ content: _, ...pageSection }) => pageSection)
- const score = sections.reduce((sum, section) => sum + section.similarity, 0)
+ // Rank this page based on its highest-ranked page section
+ const rank = sections.reduce((min, { rank }) => Math.min(min, rank), Infinity)
return {
...page,
sections,
- score,
+ rank,
}
})
- .sort((a, b) => b.score - a.score)
+ .sort((a, b) => a.rank - b.rank)
return new Response(JSON.stringify(combinedPages), {
headers: {
diff --git a/supabase/migrations/20230403222943_reusable_match_function.sql b/supabase/migrations/20230403222943_reusable_match_function.sql
new file mode 100644
index 00000000000..9d2d4556d84
--- /dev/null
+++ b/supabase/migrations/20230403222943_reusable_match_function.sql
@@ -0,0 +1,27 @@
+drop function match_page_sections;
+
+-- Return a setof page_section so that we can use PostgREST resource embeddings (joins with other tables)
+create or replace function match_page_sections(embedding vector(1536), match_threshold float, min_content_length int)
+returns setof page_section
+language plpgsql
+as $$
+#variable_conflict use_variable
+begin
+ return query
+ select *
+ 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;
+end;
+$$;