The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(docs-gpt): basic error handling
Greg Richardson524795113b6e
diff --git a/apps/docs/components/Clippy/ClippyModal.tsx b/apps/docs/components/Clippy/ClippyModal.tsxindex 72d7b0243c5..112fb545540 100644--- a/apps/docs/components/Clippy/ClippyModal.tsx+++ b/apps/docs/components/Clippy/ClippyModal.tsx@@ -8,7 +8,16 @@ import clippyImage from '../../public/img/clippy.png'import { useTheme } from 'common/Providers'import Image from 'next/image'-import { Button, IconAlertCircle, IconLoader, IconSearch, Input, Loading, Modal } from 'ui'+import {+ Button,+ IconAlertCircle,+ IconAlertTriangle,+ IconLoader,+ IconSearch,+ Input,+ Loading,+ Modal,+} from 'ui'import components from '~/components'type Props = {@@ -44,8 +53,9 @@ const ClippyModal: FC<Props> = ({ onClose }) => {const [answer, setAnswer] = useState('')const [isLoading, setIsLoading] = useState(false)const [isResponding, setIsResponding] = useState(false)+ const [hasError, setHasError] = useState(true)- const cantHelp = answer === "Sorry, I don't know how to help with that."+ const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."const status = isLoading? 'Clippy is searching...': isResponding@@ -55,6 +65,7 @@ const ClippyModal: FC<Props> = ({ onClose }) => {: undefinedconst handleConfirm = useCallback(async (query: string) => {+ setHasError(false)setAnswer(undefined)setIsLoading(true)@@ -69,6 +80,8 @@ const ClippyModal: FC<Props> = ({ onClose }) => {// TODO: display an error on the UIeventSource.addEventListener('error', (e) => {+ setIsLoading(false)+ setHasError(true)console.error(e)})@@ -99,6 +112,7 @@ const ClippyModal: FC<Props> = ({ onClose }) => {setQuery('')setAnswer(undefined)setIsResponding(false)+ setHasError(false)}return (@@ -140,7 +154,7 @@ const ClippyModal: FC<Props> = ({ onClose }) => {)}</div>- {!isLoading && !answer && (+ {!isLoading && !answer && !hasError && (<div className=""><div className="mt-2"><h2 className="text-sm text-scale-900">Not sure where to start?</h2>@@ -204,6 +218,16 @@ const ClippyModal: FC<Props> = ({ onClose }) => {<p className="text-lg text-center">Searching for results</p></div>)}+ {hasError && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4">+ <IconAlertTriangle strokeWidth={1.5} size={40} />+ <p className="text-lg text-center">Sorry, looks like Clippy is having a hard time!</p>+ <p className="text-sm text-center">Please try again in a bit.</p>+ <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}<div className="border-t border-scale-600 mt-4 text-scale-900"><div className="flex justify-between items-center py-2 text-xs"><div className="flex items-centerp gap-1 pt-3 pb-1">diff --git a/supabase/functions/clippy-search/errors.ts b/supabase/functions/clippy-search/errors.tsnew file mode 100644index 00000000000..0c8772c500a--- /dev/null+++ b/supabase/functions/clippy-search/errors.ts@@ -0,0 +1,7 @@+export class ApplicationError extends Error {+ constructor(message: string, public data: Record<string, any> = {}) {+ super(message)+ }+}++export class UserError extends ApplicationError {}diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.tsindex 47c5a924db4..19773944ab1 100644--- a/supabase/functions/clippy-search/index.ts+++ b/supabase/functions/clippy-search/index.ts@@ -3,6 +3,7 @@ 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, CreateCompletionRequest, OpenAIApi } from 'https://esm.sh/[email protected]'+import { ApplicationError, UserError } from './errors.ts'const openAiKey = Deno.env.get('OPENAI_KEY')const supabaseUrl = Deno.env.get('SUPABASE_URL')@@ -14,145 +15,98 @@ export const corsHeaders = {}serve(async (req) => {- // Handle CORS- if (req.method === 'OPTIONS') {- return new Response('ok', { headers: corsHeaders })- }+ try {+ // 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 (!openAiKey) {+ throw new ApplicationError('Missing environment variable OPENAI_KEY')+ }- if (!supabaseUrl) {- return new Response(- JSON.stringify({- error: 'Missing environment variable SUPABASE_URL',- }),- {- status: 400,- headers: { ...corsHeaders, 'Content-Type': 'application/json' },- }- )- }+ if (!supabaseUrl) {+ throw new ApplicationError('Missing environment variable SUPABASE_URL')+ }- if (!supabaseServiceKey) {- return new Response(- JSON.stringify({- error: 'Missing environment variable SUPABASE_SERVICE_ROLE_KEY',- }),- {- status: 400,- headers: { ...corsHeaders, 'Content-Type': 'application/json' },- }- )- }+ if (!supabaseServiceKey) {+ throw new ApplicationError('Missing environment variable SUPABASE_SERVICE_ROLE_KEY')+ }- const requestData = await req.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' },- }- )- }+ if (!requestData) {+ throw new UserError('Missing request data')+ }++ const { query } = requestData- const { query } = requestData+ if (!query) {+ throw new UserError('Missing query in request data')+ }- const sanitizedQuery = query.trim()+ const sanitizedQuery = query.trim()- const supabaseClient = createClient(supabaseUrl, supabaseServiceKey)+ const supabaseClient = createClient(supabaseUrl, supabaseServiceKey)- const configuration = new Configuration({ apiKey: openAiKey })- const openai = new OpenAIApi(configuration)+ 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 })+ // Moderate the content to comply with OpenAI T&C+ const moderationResponse = await openai.createModeration({ input: sanitizedQuery })- const [results] = moderationResponse.data.results+ const [results] = moderationResponse.data.results- if (results.flagged) {- return new Response(- JSON.stringify({- error: 'Flagged content',+ if (results.flagged) {+ throw new UserError('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: sanitizedQuery.replaceAll('\n', ' '),- })+ const embeddingResponse = await openai.createEmbedding({+ model: 'text-embedding-ada-002',+ input: sanitizedQuery.replaceAll('\n', ' '),+ })- if (embeddingResponse.status !== 200) {- console.log(- `Failed to create embedding for question. OpenAI response status ${embeddingResponse.status}`- )+ if (embeddingResponse.status !== 200) {+ throw new ApplicationError('Failed to create embedding for question', embeddingResponse)+ }- return new Response(- JSON.stringify({- error: 'Failed to process questions',- }),+ const [{ embedding }] = embeddingResponse.data.data++ const { error: matchError, data: pageSections } = await supabaseClient.rpc(+ 'match_page_sections',{- status: 500,- headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ embedding,+ match_threshold: 0.78,+ match_count: 10,+ min_content_length: 50,})- }-- 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) {+ throw new ApplicationError('Failed to match page sections', matchError)}- )- if (matchError) {- console.log(matchError.message)- throw matchError- }+ const tokenizer = new GPT3Tokenizer({ type: 'gpt3' })+ let tokenCount = 0+ let contextText = ''- 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- 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+ }- if (tokenCount >= 1500) {- break+ contextText += `${content.trim()}\n---\n`}- 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. 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."+ 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. 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}@@ -164,35 +118,61 @@ ${sanitizedQuery}Answer as markdown (including related code snippets if available):`- console.log(prompt)+ 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', {+ headers: {+ Authorization: `Bearer ${openAiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ body: JSON.stringify(completionOptions),+ })++ if (!response.ok) {+ const error = await response.json()+ throw new ApplicationError('Failed to generate completion', error)+ }- const completionOptions: CreateCompletionRequest = {- model: 'text-davinci-003',- prompt,- max_tokens: 512,- temperature: 0,- stream: true,- }+ // Proxy the streamed SSE response from OpenAI+ return new Response(response.body, {+ headers: {+ ...corsHeaders,+ 'Content-Type': 'text/event-stream',+ },+ })+ } 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' },+ }+ )+ }- const response = await fetch('https://api.openai.com/v1/completions', {- headers: {- Authorization: `Bearer ${openAiKey}`,- 'Content-Type': 'application/json',- },- method: 'POST',- body: JSON.stringify(completionOptions),- })-- // TODO: handle response errors- if (!response.ok) {- throw new Error('Failed to complete')- }+ // Print out unexpected errors to help with debugging+ console.error(err)- // Proxy the streamed SSE response from OpenAI- return new Response(response.body, {- headers: {- ...corsHeaders,- 'Content-Type': 'text/event-stream',- },- })+ // 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' },+ }+ )+ }})