Skip to content

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

feat(docs-gpt): completion streaming

Greg Richardsonbd83e9ba2f72
diff --git a/apps/docs/components/Clippy/ClippyModal.tsx b/apps/docs/components/Clippy/ClippyModal.tsx
index c1c1bf8b650..1356b4469fb 100644
--- a/apps/docs/components/Clippy/ClippyModal.tsx
+++ b/apps/docs/components/Clippy/ClippyModal.tsx
@@ -1,7 +1,8 @@
-import { useSupabaseClient } from '@supabase/auth-helpers-react'
-import { FC, useCallback, useEffect, useState } from 'react'
+import type { CreateCompletionResponse } from 'openai'
+import { FC, useCallback, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
+import { SSE } from 'sse.js'
import clippyImageDark from '../../public/img/clippy-dark.png'
import clippyImage from '../../public/img/clippy.png'
@@ -26,56 +27,72 @@ const questions = [
const ClippyModal: FC<Props> = ({ onClose }) => {
const { isDarkMode } = useTheme()
const [query, setQuery] = useState('')
- const [status, setStatus] = useState('')
const [answer, setAnswer] = useState('')
- const [cantHelp, setCantHelp] = useState(false)
const [isLoading, setIsLoading] = useState(false)
- const supabaseClient = useSupabaseClient()
-
- const handleConfirm = useCallback(async () => {
+ const [isResponding, setIsResponding] = useState(false)
+
+ const cantHelp = answer === "Sorry, I don't know how to help with that."
+ const status = isLoading
+ ? 'Clippy is searching...'
+ : isResponding
+ ? 'Clippy is responding...'
+ : cantHelp
+ ? 'Clippy has failed you'
+ : undefined
+
+ const handleConfirm = useCallback(async (query: string) => {
setAnswer(undefined)
setIsLoading(true)
- setStatus('Clippy is searching...')
-
- const response = await supabaseClient.functions.invoke('clippy-search', { body: { query } })
- setIsLoading(false)
- setStatus('')
+ const eventSource = new SSE(
+ `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/clippy-search`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ payload: JSON.stringify({ query }),
+ }
+ )
// TODO: display an error on the UI
- if (response.error) {
- console.error('Clippy search failed', response.error)
- return
- }
-
- if (response.data.answer.includes('Sorry, I don')) {
- setCantHelp(true)
- setStatus('Clippy has failed you')
- } else {
- setStatus('')
- setCantHelp(false)
- }
-
- setAnswer(response.data.answer)
- }, [query, supabaseClient])
-
- useEffect(() => {
- if (query) {
- handleConfirm()
- }
- }, [query, handleConfirm])
+ eventSource.addEventListener('error', (e) => {
+ console.error(e)
+ })
+
+ eventSource.addEventListener('message', (e) => {
+ setIsLoading(false)
+
+ if (e.data === '[DONE]') {
+ setIsResponding(false)
+ return
+ }
+
+ setIsResponding(true)
+
+ const completionResponse: CreateCompletionResponse = JSON.parse(e.data)
+ const [{ text }] = completionResponse.choices
+
+ setAnswer((answer) => {
+ return (answer ?? '') + text
+ })
+ })
+
+ eventSource.stream()
+
+ setIsLoading(true)
+ }, [])
function handleResetPrompt() {
setQuery('')
setAnswer(undefined)
- setStatus('')
- setCantHelp(false)
+ setIsResponding(false)
}
return (
<Modal size="xlarge" visible={true} onCancel={onClose} closable={false} hideFooter>
<div
- className={`mx-auto flex flex-col gap-4 rounded-lg p-4 md:pt-6 md:px-6 pb-2 w-full max-w-3xl shadow-2xl overflow-hidden border text-left border-scale-500 bg-scale-100 dark:bg-scale-300 cursor-auto relative min-w-[340px]`}
+ className={`mx-auto max-h-[75vh] flex flex-col gap-4 rounded-lg p-4 md:pt-6 md:px-6 pb-2 w-full max-w-3xl shadow-2xl overflow-hidden border text-left border-scale-500 bg-scale-100 dark:bg-scale-300 cursor-auto relative min-w-[340px]`}
onClick={(e) => e.stopPropagation()}
>
<div className="relative">
@@ -90,7 +107,7 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
onKeyDown={(e) => {
switch (e.key) {
case 'Enter':
- handleConfirm()
+ handleConfirm(query)
return
default:
return
@@ -121,7 +138,10 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
<li>
<button
className="hover:bg-slate-400 hover:dark:bg-slate-400 px-4 py-2 bg-slate-300 dark:bg-slate-200 rounded-lg transition-colors"
- onClick={() => setQuery(question)}
+ onClick={() => {
+ setQuery(question)
+ handleConfirm(question)
+ }}
>
{question}
</button>
@@ -131,16 +151,10 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
</div>
</div>
)}
- {isLoading && (
- <div className="p-6 grid gap-6 mt-4">
- <Loading active>{}</Loading>
- <p className="text-lg text-center">Searching for results</p>
- </div>
- )}
{answer && (
- <div className="px-4 py-4 rounded-lg overflow-y-scroll">
- {answer.includes('Sorry, I don') ? (
- <p className="flex flex-col gap-4 items-center">
+ <div className="px-4 py-4 rounded-lg overflow-y-auto bg-scale-200">
+ {cantHelp ? (
+ <p className="flex flex-col gap-4 items-center p-4">
<div className="grid md:flex items-center gap-2 mt-4 text-center justify-items-center">
<IconAlertCircle />
<p>Sorry, I don&apos;t know how to help with that.</p>
@@ -172,6 +186,12 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
)}
</div>
)}
+ {isLoading && (
+ <div className="p-6 grid gap-6 mt-4">
+ <Loading active>{}</Loading>
+ <p className="text-lg text-center">Searching for results</p>
+ </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">
@@ -181,9 +201,9 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
</a>
</div>
<div className="flex items-center gap-6 py-1">
- {isLoading || cantHelp ? (
+ {status ? (
<span className="bg-scale-400 rounded-lg py-1 px-2 items-center gap-2 hidden md:flex">
- {isLoading && <IconLoader size={14} className="animate-spin" />}
+ {(isLoading || isResponding) && <IconLoader size={14} className="animate-spin" />}
{status}
</span>
) : (
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 1483b705616..a8c42541d9e 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -82,6 +82,7 @@
"remark-gfm": "^3.0.1",
"remark-slug": "^7.0.1",
"shiki": "^0.11.1",
+ "sse.js": "^0.6.1",
"ui": "*",
"unist-builder": "^3.0.1",
"unist-util-filter": "^4.0.1",
@@ -106,4 +107,4 @@
"tsx": "^3.12.2",
"typescript": "^4.5.3"
}
-}
\ No newline at end of file
+}
diff --git a/apps/docs/types/sse.d.ts b/apps/docs/types/sse.d.ts
new file mode 100644
index 00000000000..dbf97ac0836
--- /dev/null
+++ b/apps/docs/types/sse.d.ts
@@ -0,0 +1,12 @@
+declare module 'sse.js' {
+ export type SSEOptions = EventSourceInit & {
+ headers?: Record<string, string>
+ payload?: string
+ method?: string
+ }
+
+ export class SSE extends EventSource {
+ constructor(url: string | URL, sseOptions?: SSEOptions)
+ stream(): void
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index afeada5449f..f5574a4dd8e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -86,6 +86,7 @@
"remark-gfm": "^3.0.1",
"remark-slug": "^7.0.1",
"shiki": "^0.11.1",
+ "sse.js": "^0.6.1",
"ui": "*",
"unist-builder": "^3.0.1",
"unist-util-filter": "^4.0.1",
@@ -34460,6 +34461,11 @@
"node": ">= 0.6"
}
},
+ "node_modules/sse.js": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/sse.js/-/sse.js-0.6.1.tgz",
+ "integrity": "sha512-peXG6GnWqF5hnubhMw0WfB6rqQy7z7LaMBT067vqgQwC3gKz8JGFzexBSV80FqZ9JoUDwo3Xt5nxkrGrgbPrtA=="
+ },
"node_modules/ssr-window": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ssr-window/-/ssr-window-3.0.0.tgz",
@@ -51282,6 +51288,7 @@
"remark-slug": "^7.0.1",
"sass": "^1.55.0",
"shiki": "^0.11.1",
+ "sse.js": "^0.6.1",
"ts-node": "^10.9.1",
"tsconfig": "*",
"tsx": "^3.12.2",
@@ -65343,6 +65350,11 @@
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
"integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="
},
+ "sse.js": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/sse.js/-/sse.js-0.6.1.tgz",
+ "integrity": "sha512-peXG6GnWqF5hnubhMw0WfB6rqQy7z7LaMBT067vqgQwC3gKz8JGFzexBSV80FqZ9JoUDwo3Xt5nxkrGrgbPrtA=="
+ },
"ssr-window": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ssr-window/-/ssr-window-3.0.0.tgz",
diff --git a/supabase/functions/clippy-search/index.ts b/supabase/functions/clippy-search/index.ts
index 3b107d85fd3..47c5a924db4 100644
--- a/supabase/functions/clippy-search/index.ts
+++ b/supabase/functions/clippy-search/index.ts
@@ -2,7 +2,7 @@ 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]'
+import { Configuration, CreateCompletionRequest, OpenAIApi } from 'https://esm.sh/[email protected]'
const openAiKey = Deno.env.get('OPENAI_KEY')
const supabaseUrl = Deno.env.get('SUPABASE_URL')
@@ -166,32 +166,33 @@ Answer as markdown (including related code snippets if available):
console.log(prompt)
- const completionResponse = await openai.createCompletion({
+ 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 (completionResponse.status !== 200) {
+ // TODO: handle response errors
+ if (!response.ok) {
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' },
- }
- )
+ // Proxy the streamed SSE response from OpenAI
+ return new Response(response.body, {
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'text/event-stream',
+ },
+ })
})