The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(cmdk): sql ai to remember chat history context
Greg Richardson7d29d19e2433
diff --git a/package-lock.json b/package-lock.jsonindex 60f200cd147..cff4e1a295e 100644--- a/package-lock.json+++ b/package-lock.json@@ -9882,6 +9882,12 @@"classnames": "*"}},+ "node_modules/@types/common-tags": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/@types/common-tags/-/common-tags-1.8.1.tgz",+ "integrity": "sha512-20R/mDpKSPWdJs5TOpz3e7zqbeCNuMCPhV7Yndk9KU2Rbij2r5W4RzwDPkzC+2lzUqXYu9rFzTktCBnDjHuNQg==",+ "dev": true+ },"node_modules/@types/d3-array": {"version": "3.0.4","resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.4.tgz",@@ -13979,6 +13985,14 @@"integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==","dev": true},+ "node_modules/common-tags": {+ "version": "1.8.2",+ "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz",+ "integrity": "sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA==",+ "engines": {+ "node": ">=4.0.0"+ }+ },"node_modules/commondir": {"version": "1.0.1","resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",@@ -38924,6 +38938,7 @@"autoprefixer": "^10.4.2","clsx": "^1.2.1","cmdk-supabase": "^0.2.2",+ "common-tags": "^1.8.2","deepmerge": "^4.2.2","formik": "^2.2.9","lodash": "^4.17.20",@@ -38942,6 +38957,7 @@"tailwindcss-radix": "^1.6.0"},"devDependencies": {+ "@types/common-tags": "^1.8.1","@types/react": "^17.0.37","@types/react-dom": "^17.0.11","sql-formatter": "^12.2.0",@@ -46241,6 +46257,12 @@"classnames": "*"}},+ "@types/common-tags": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/@types/common-tags/-/common-tags-1.8.1.tgz",+ "integrity": "sha512-20R/mDpKSPWdJs5TOpz3e7zqbeCNuMCPhV7Yndk9KU2Rbij2r5W4RzwDPkzC+2lzUqXYu9rFzTktCBnDjHuNQg==",+ "dev": true+ },"@types/d3-array": {"version": "3.0.4","resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.4.tgz",@@ -49509,6 +49531,11 @@"integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==","dev": true},+ "common-tags": {+ "version": "1.8.2",+ "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz",+ "integrity": "sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA=="+ },"commondir": {"version": "1.0.1","resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",@@ -67615,11 +67642,13 @@"@supabase/auth-helpers-react": "^0.3.1","@tailwindcss/forms": "^0.4.0","@tailwindcss/typography": "^0.5.0",+ "@types/common-tags": "^1.8.1","@types/react": "^17.0.37","@types/react-dom": "^17.0.11","autoprefixer": "^10.4.2","clsx": "^1.2.1","cmdk-supabase": "^0.2.2",+ "common-tags": "^1.8.2","deepmerge": "^4.2.2","formik": "^2.2.9","lodash": "^4.17.20",@@ -67632,7 +67661,7 @@"react-markdown": "^8.0.3","react-syntax-highlighter": "^15.5.0","remark-gfm": "^3.0.1",- "sql-formatter": "*",+ "sql-formatter": "^12.2.0","sse.js": "^0.6.1","tailwind-merge": "^1.10.0","tailwindcss": "^3.0.15",@@ -69355,7 +69384,7 @@"framer-motion": "^6.5.1","globby": "^12.0.2","gray-matter": "^4.0.2",- "lottie-react": "*",+ "lottie-react": "^2.4.0","markdown-toc": "^1.2.0","marked": "^4.0.12","next": "12.3.2",diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex d0e4f7a2fe2..559c3346a85 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -24,6 +24,7 @@"autoprefixer": "^10.4.2","clsx": "^1.2.1","cmdk-supabase": "^0.2.2",+ "common-tags": "^1.8.2","deepmerge": "^4.2.2","formik": "^2.2.9","lodash": "^4.17.20",@@ -42,6 +43,7 @@"tailwindcss-radix": "^1.6.0"},"devDependencies": {+ "@types/common-tags": "^1.8.1","@types/react": "^17.0.37","@types/react-dom": "^17.0.11","sql-formatter": "^12.2.0",diff --git a/packages/ui/src/components/Command/AiCommand.tsx b/packages/ui/src/components/Command/AiCommand.tsxindex 04587665f50..78314b8858e 100644--- a/packages/ui/src/components/Command/AiCommand.tsx+++ b/packages/ui/src/components/Command/AiCommand.tsx@@ -3,7 +3,15 @@ import type {CreateChatCompletionResponse,CreateChatCompletionResponseChoicesInner,} from 'openai'-import { useCallback, useEffect, useReducer, useRef, useState } from 'react'+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useEffect,+ useReducer,+ useRef,+ useState,+} from 'react'import { SSE } from 'sse.js'@@ -14,7 +22,6 @@ import { CommandGroup, CommandItem } from './Command.utils'import { useCommandMenu } from './CommandMenuProvider'import { cn } from './../../utils/cn'-import { COMMAND_ROUTES } from './Command.constants'const questions = ['How do I get started with Supabase?',@@ -52,18 +59,18 @@ function getEdgeFunctionUrl() {const edgeFunctionUrl = getEdgeFunctionUrl()-enum MessageRole {+export enum MessageRole {User = 'user',Assistant = 'assistant',}-enum MessageStatus {+export enum MessageStatus {Pending = 'pending',InProgress = 'in-progress',Complete = 'complete',}-interface Message {+export interface Message {role: MessageRolecontent: stringstatus: MessageStatus@@ -86,7 +93,11 @@ interface AppendContentAction {content: string}-type MessageAction = NewMessageAction | UpdateMessageAction | AppendContentAction+interface ResetAction {+ type: 'reset'+}++type MessageAction = NewMessageAction | UpdateMessageAction | AppendContentAction | ResetActionfunction messageReducer(state: Message[], messageAction: MessageAction) {let current = [...state]@@ -100,12 +111,20 @@ function messageReducer(state: Message[], messageAction: MessageAction) {}case 'update': {const { index, message } = messageAction- Object.assign(current[index], message)+ if (current[index]) {+ Object.assign(current[index], message)+ }break}case 'append-content': {const { index, content } = messageAction- current[index].content += content+ if (current[index]) {+ current[index].content += content+ }+ break+ }+ case 'reset': {+ current = []break}default: {@@ -116,21 +135,27 @@ function messageReducer(state: Message[], messageAction: MessageAction) {return current}-const AiCommand = () => {+export interface UseAiChatOptions {+ messageTemplate?: (message: string) => string+ setIsLoading?: Dispatch<SetStateAction<boolean>>+}++export function useAiChat({+ messageTemplate = (message) => message,+ setIsLoading,+}: UseAiChatOptions) {+ const eventSourceRef = useRef<SSE>()+const [isResponding, setIsResponding] = useState(false)const [hasError, setHasError] = useState(false)- const eventSourceRef = useRef<SSE>()- const { isLoading, setIsLoading, currentPage, search, setSearch, MarkdownHandler } =- useCommandMenu()const [currentMessageIndex, setCurrentMessageIndex] = useState(1)const [messages, dispatchMessage] = useReducer(messageReducer, [])- const handleConfirm = useCallback(+ const submit = useCallback(async (query: string) => {if (!edgeFunctionUrl) return console.error('No edge function url')- setSearch('')dispatchMessage({type: 'new',message: {@@ -149,30 +174,7 @@ const AiCommand = () => {})setIsResponding(false)setHasError(false)- setIsLoading(true)-- let queryToSend = query-- switch (currentPage) {- case COMMAND_ROUTES.AI:- queryToSend = query- break- case COMMAND_ROUTES.AI_ASK_ANYTHING:- queryToSend = query- break-- case COMMAND_ROUTES.AI_RLS_POLICY:- queryToSend = `Given this table schema:-- Schema STRIPE has tables:- CHARGE with columns [ID, AMOUNT, CREATED, CURRENCY, CUSTOMER_ID]- CUSTOMER with columns [ID, NAME, CREATED, SHIPPING_ADDRESS_STATE]-- \n\nAnswer with only an RLS policy in SQL, no other text: ${query}`- break- default:- break- }+ setIsLoading?.(true)const eventSource = new SSE(`${edgeFunctionUrl}/ai-docs`, {headers: {@@ -184,21 +186,21 @@ const AiCommand = () => {messages: messages.filter(({ status }) => status === MessageStatus.Complete).map(({ role, content }) => ({ role, content }))- .concat({ role: MessageRole.User, content: query }),+ .concat({ role: MessageRole.User, content: messageTemplate(query) }),}),})function handleError<T>(err: T) {- setIsLoading(false)+ setIsLoading?.(false)setIsResponding(false)setHasError(true)console.error(err)}eventSource.addEventListener('error', handleError)- eventSource.addEventListener('message', (e: any) => {+ eventSource.addEventListener('message', (e) => {try {- setIsLoading(false)+ setIsLoading?.(false)if (e.data === '[DONE]') {setIsResponding(false)@@ -230,13 +232,13 @@ const AiCommand = () => {},] = completionResponse.choices as CreateChatCompletionResponseChoicesInnerDelta[]- const text = content ?? ''-- dispatchMessage({- type: 'append-content',- index: currentMessageIndex,- content: text,- })+ if (content) {+ dispatchMessage({+ type: 'append-content',+ index: currentMessageIndex,+ content,+ })+ }} catch (err) {handleError(err)}@@ -246,22 +248,53 @@ const AiCommand = () => {eventSourceRef.current = eventSource- setIsLoading(true)+ setIsLoading?.(true)},[currentMessageIndex, messages])- function handleResetPrompt() {+ function reset() {eventSourceRef.current?.close()eventSourceRef.current = undefined- setSearch('')setIsResponding(false)setHasError(false)+ dispatchMessage({+ type: 'reset',+ })+ }++ return {+ submit,+ reset,+ messages,+ isResponding,+ hasError,}+}++const AiCommand = () => {+ const { isLoading, setIsLoading, search, setSearch, MarkdownHandler } = useCommandMenu()++ const { submit, reset, messages, isResponding, hasError } = useAiChat({+ setIsLoading,+ })++ const handleSubmit = useCallback(+ (message: string) => {+ setSearch('')+ submit(message)+ },+ [submit]+ )++ const handleReset = useCallback(() => {+ setSearch('')+ reset()+ }, [reset])useEffect(() => {if (search) {- handleConfirm(search)+ handleSubmit(search)}}, [])@@ -328,7 +361,7 @@ const AiCommand = () => {type="command"onSelect={() => {if (!search) {- handleConfirm(question)+ handleSubmit(question)}}}forceMount@@ -348,7 +381,7 @@ const AiCommand = () => {Sorry, looks like Clippy is having a hard time!</p><p className="text-sm text-scale-900 text-center">Please try again in a bit.</p>- <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ <Button size="tiny" type="secondary" onClick={handleReset}>Try again?</Button></div>@@ -394,7 +427,7 @@ const AiCommand = () => {if (isLoading || isResponding) {return}- handleConfirm(search)+ handleSubmit(search)returndefault:returndiff --git a/packages/ui/src/components/Command/GenerateSQL.tsx b/packages/ui/src/components/Command/GenerateSQL.tsxindex 13515742bb0..d87821d6f8d 100644--- a/packages/ui/src/components/Command/GenerateSQL.tsx+++ b/packages/ui/src/components/Command/GenerateSQL.tsx@@ -1,11 +1,8 @@-import { SSE } from 'sse.js'+import { useCallback, useEffect, useState } from 'react'import { format } from 'sql-formatter'-import type { CreateCompletionResponse } from 'openai'-import { useCallback, useEffect, useReducer, useRef, useState } from 'react'import {Button,CodeBlock,- IconAlertCircle,IconAlertTriangle,IconCheck,IconClipboard,@@ -13,72 +10,18 @@ import {IconSave,IconUser,Input,+ MessageRole,+ MessageStatus,+ useAiChat,} from 'ui'+import CopyToClipboard from 'react-copy-to-clipboard'import { cn } from './../../utils/cn'+import { SAMPLE_QUERIES } from './Command.constants'import { AiIcon, AiIconChat } from './Command.icons'import { CommandItem } from './Command.utils'import { useCommandMenu } from './CommandMenuProvider'-import CopyToClipboard from 'react-copy-to-clipboard'-import { SAMPLE_QUERIES } from './Command.constants'--function getEdgeFunctionUrl() {- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/$/, '')-- if (!supabaseUrl) return undefined-- // https://github.com/supabase/supabase-js/blob/10d3423506cbd56345f7f6ab2ec2093c8db629d4/src/SupabaseClient.ts#L96- const isPlatform = supabaseUrl.match(/(supabase\.co)|(supabase\.in)/)-- if (isPlatform) {- const [schemeAndProjectId, domain, tld] = supabaseUrl.split('.')- return `${schemeAndProjectId}.functions.${domain}.${tld}`- } else {- return `${supabaseUrl}/functions/v1`- }-}--function promptDataReducer(- state: any[],- action: {- index?: number- answer?: string | undefined- status?: string- query?: string | undefined- type?: 'remove-last-item' | string- }-) {- // set a standard state to use later- let current = [...state]-- if (action.type) {- switch (action.type) {- case 'remove-last-item':- current.pop()- return [...current]- default:- break- }- }-- // check that an index is present- if (action.index === undefined) return [...state]-- if (!current[action.index]) {- current[action.index] = { query: '', answer: '', status: '' }- }-- current[action.index].answer = action.answer-- if (action.query) {- current[action.index].query = action.query- }- if (action.status) {- current[action.index].status = action.status- }-- return [...current]-}+import { stripIndent } from 'common-tags'const SQLOutputActions = ({ answer }: { answer: string }) => {const [showCopied, setShowCopied] = useState(false)@@ -150,104 +93,43 @@ const SQLOutputActions = ({ answer }: { answer: string }) => {}const GenerateSQL = () => {- const [promptIndex, setPromptIndex] = useState(0)- const [answer, setAnswer] = useState<string | undefined>('')- const [isResponding, setIsResponding] = useState(false)- const [hasClippyError, setHasClippyError] = useState(false)const [selectedCategory, setSelectedCategory] = useState<string>(SAMPLE_QUERIES[0].category)- const eventSourceRef = useRef<SSE>()- const [promptData, dispatchPromptData] = useReducer(promptDataReducer, [])const { isLoading, setIsLoading, search, setSearch } = useCommandMenu()- const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."-- const handleConfirm = useCallback(- async (query: string) => {- const edgeFunctionUrl = getEdgeFunctionUrl()-- if (!edgeFunctionUrl) {- return console.error('No edge function url')- }-- setAnswer(undefined)+ const { submit, reset, messages, isResponding, hasError } = useAiChat({+ messageTemplate: (message) =>+ stripIndent`+ Generate a Postgres SQL query based on the following natural language prompt.+ - Only output valid SQL - all explanations must be SQL comments+ - SQL comments should be short+ - Your very last output should be "\`\`\`"+ - For primary keys, always use "integer primary key generated always as identity"++ Natural language prompt:+ ${message}++ Postgres SQL query (markdown SQL only):+ `,+ setIsLoading,+ })++ const handleSubmit = useCallback(+ (message: string) => {setSearch('')- dispatchPromptData({ index: promptIndex, answer: undefined, query })- setIsResponding(false)- setHasClippyError(false)- setIsLoading(true)-- // [Joshen] Eventually we need to pass the table data in here as well- const queryToSend = `-Generate a Postgres SQL query based on the following natural language prompt. For primary keys, always use "integer primary key generated always as identity":-${query}--Postgres SQL query:-`.trim()-- const eventSource = new SSE(`${edgeFunctionUrl}/clippy-search`, {- headers: {- apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',- Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,- 'Content-Type': 'application/json',- },- payload: JSON.stringify({ query: queryToSend, context: promptData }),- })-- function handleError<T>(err: T) {- setIsLoading(false)- setIsResponding(false)- setHasClippyError(true)- console.error(err)- }-- eventSource.addEventListener('error', handleError)- eventSource.addEventListener('message', (e: any) => {- try {- setIsLoading(false)- if (e.data === '[DONE]') {- setIsResponding(false)- setAnswer(undefined)- setPromptIndex((x) => {- return x + 1- })- return- }- setIsResponding(true)-- const completionResponse: CreateCompletionResponse = JSON.parse(e.data)- const [{ text: content }] = completionResponse.choices- const text = content ?? ''-- setAnswer((answer) => {- const currentAnswer = answer ?? ''- dispatchPromptData({ index: promptIndex, answer: currentAnswer + text })- return (answer ?? '') + text- })- } catch (err) {- handleError(err)- }- })-- eventSource.stream()- eventSourceRef.current = eventSource- setIsLoading(true)+ submit(message)},- [promptIndex, promptData]+ [submit])- function handleResetPrompt() {- eventSourceRef.current?.close()- eventSourceRef.current = undefined+ const handleReset = useCallback(() => {setSearch('')- setAnswer(undefined)- setIsResponding(false)- setHasClippyError(false)- }+ reset()+ }, [reset])useEffect(() => {if (search) {- handleConfirm(search)+ handleSubmit(search)}}, [])@@ -265,52 +147,56 @@ Postgres SQL query:return (<div onClick={(e) => e.stopPropagation()}><div className={cn('relative mb-[62px] py-4 max-h-[720px] overflow-auto')}>- {promptData.map((prompt, i) => {- if (!prompt.query) return <></>-- const formattedPromptAnwswer = (prompt?.answer ?? '')- .replace(/`/g, '')- .replace(/sql\n/g, '')- .trim()- const promptAnswer = isResponding- ? formattedPromptAnwswer- : formatAnswer(formattedPromptAnwswer)-- return (- <>- {prompt.query && (+ {messages.map((message) => {+ switch (message.role) {+ case MessageRole.User:+ return (<div className="flex gap-6 mx-4 [overflow-anchor:none] mb-6"><divclassName="w-7 h-7 bg-scale-200 rounded-full border border-scale-400 flex items-center justify-center text-scale-1000 first-letter:ring-scale-200 ring-1 shadow-sm- "+ "><IconUser strokeWidth={1.5} size={16} /></div>- <div className="prose text-scale-1000">{prompt.query}</div>+ <div className="prose text-scale-1000">{message.content}</div></div>- )}-- <div className="px-4 [overflow-anchor:none] mb-6">- {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't know how to help with that.</p>- </div>- <Button size="tiny" type="secondary" onClick={handleResetPrompt}>- Try again?- </Button>- </p>- ) : (+ )+ case MessageRole.Assistant:+ const answer = formatAnswer(+ message.content+ .replace(/```sql/g, '')+ .replace(/```.*/gs, '')+ .replace(/-- End of SQL query\.*/g, '')+ .trim()+ )++ const cantHelp = answer === "Sorry, I don't know how to help with that."++ return (+ <div className="px-4 [overflow-anchor:none] mb-6"><div className="flex gap-6 [overflow-anchor:none] mb-6"><div><AiIconChat /></div><>- {isLoading && promptIndex === i ? (+ {message.status === MessageStatus.Pending ? (<div className="bg-scale-700 h-[21px] w-[13px] mt-1 animate-bounce"></div>+ ) : cantHelp ? (+ <div className="p-6 flex flex-col flex-grow items-center gap-6 mt-4">+ <IconAlertTriangle+ className="text-amber-900"+ strokeWidth={1.5}+ size={21}+ />+ <p className="text-lg text-scale-1200 text-center">+ Sorry, I don't know how to help with that.+ </p>+ <Button size="tiny" type="secondary" onClick={handleReset}>+ Try again?+ </Button>+ </div>) : (<div className="space-y-2 flex-grow max-w-[93%]"><CodeBlock@@ -318,19 +204,18 @@ Postgres SQL query:language="sql"className="relative prose dark:prose-dark bg-scale-300 max-w-none">- {promptAnswer}+ {answer}</CodeBlock>- {!isResponding && <SQLOutputActions answer={prompt.answer} />}+ {!isResponding && <SQLOutputActions answer={answer} />}</div>)}</></div>- )}- </div>- </>- )+ </div>+ )+ }})}- {promptData.length === 0 && !hasClippyError && (+ {messages.length === 0 && !hasError && (<div><div className="px-10"><h3>Example queries</h3>@@ -363,7 +248,7 @@ Postgres SQL query:type="command"onSelect={() => {if (!search) {- handleConfirm(query)+ handleSubmit(query)}}}forceMount@@ -384,14 +269,14 @@ Postgres SQL query:</div>)}- {hasClippyError && (+ {hasError && (<div className="p-6 flex flex-col items-center gap-6 mt-4"><IconAlertTriangle className="text-amber-900" strokeWidth={1.5} size={21} /><p className="text-lg text-scale-1200 text-center">Sorry, looks like Clippy is having a hard time!</p><p className="text-sm text-scale-900 text-center">Please try again in a bit.</p>- <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ <Button size="tiny" type="secondary" onClick={handleReset}>Try again?</Button></div>@@ -439,7 +324,7 @@ Postgres SQL query:if (isLoading || isResponding) {return}- handleConfirm(search)+ handleSubmit(search)returndefault:return