The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Merge master resolve conflicts
Joshen Lim756f57ebd009
diff --cc packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsxindex 57755e48406,d87821d6f8d..9cc7ac826eb--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx@@@ -1,125 -1,136 +1,67 @@@- 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 { useCallback, useEffect, useRef, useState } from 'react'import {Button,CodeBlock,IconAlertTriangle,- IconCheck,- IconClipboard,IconCornerDownLeft,- IconSave,IconUser,Input,+ Toggle,+ 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 { stripIndent } from 'common-tags'--const SQLOutputActions = ({ answer }: { answer: string }) => {- const [showCopied, setShowCopied] = useState(false)- const [isSaving, setIsSaving] = useState(false)- const [isSaved, setIsSaved] = useState(false)-- const { project, onSaveGeneratedSQL } = useCommandMenu()-- const applyCallback = () =>- onSaveGeneratedSQL !== undefined- ? new Promise((resolve) => onSaveGeneratedSQL(answer, resolve))- : {}-- const onSelectSaveSnippet = async () => {- setIsSaving(true)- await applyCallback()- setIsSaved(true)- setIsSaving(false)- }-- useEffect(() => {- if (!showCopied) return- const timer = setTimeout(() => setShowCopied(false), 2000)- return () => clearTimeout(timer)- }, [showCopied])-- useEffect(() => {- if (!isSaved) return- const timer = setTimeout(() => setIsSaved(false), 2000)- return () => clearTimeout(timer)- }, [isSaved])-- return (- <div className="flex items-center justify-end space-x-2">- <CopyToClipboard text={answer?.replace(/```.*/g, '').trim()}>- <Button- type="default"- icon={- showCopied ? (- <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />- ) : (- <IconClipboard size="tiny" />- )- }- onClick={() => setShowCopied(true)}- >- {showCopied ? 'Copied' : 'Copy SQL'}- </Button>- </CopyToClipboard>- {project?.ref !== undefined && onSaveGeneratedSQL !== undefined && (- <Button- type="default"- loading={isSaving}- disabled={isSaving}- icon={- isSaved ? (- <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />- ) : (- <IconSave size="tiny" />- )- }- onClick={() => onSelectSaveSnippet()}- >- {isSaved ? 'Snippet saved!' : 'Save into new snippet'}- </Button>- )}- </div>- )-}+import { cn } from '../../../utils/cn'+import { AiIcon, AiIconChat } from '../Command.icons'+import { CommandItem } from '../Command.utils'+import { useCommandMenu } from '../CommandMenuProvider'+import { SAMPLE_QUERIES } from '../Command.constants'+import SQLOutputActions from './SQLOutputActions'- import { getEdgeFunctionUrl, promptDataReducer, generatePrompt } from './GenerateSQL.utils'++import { generatePrompt } from './GenerateSQL.utils'const GenerateSQL = () => {- const [promptIndex, setPromptIndex] = useState(0)- const [_, setAnswer] = useState<string | undefined>('')- const [isResponding, setIsResponding] = useState(false)- const [hasClippyError, setHasClippyError] = useState(false)- const [selectedCategory, setSelectedCategory] = useState<string>(SAMPLE_QUERIES[0].category)++ // [Joshen] Temp hack to ensure that generatePrompt receives updated value++ // of includeSchemaMetadata, needs to be fixed++ const includeSchemaMetadataRef = useRef<any>()+- const { isLoading, setIsLoading, search, setSearch } = useCommandMenu()+ const [includeSchemaMetadata, setIncludeSchemaMetadata] = useState(false)+ const [selectedCategory, setSelectedCategory] = useState<string>(SAMPLE_QUERIES[0].category)- const eventSourceRef = useRef<SSE>()- const [promptData, dispatchPromptData] = useReducer(promptDataReducer, [])- 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"+ const { isLoading, setIsLoading, search, setSearch, isOptedInToAI, metadata, project } =+ useCommandMenu()- Natural language prompt:- ${message}+ const { flags } = metadata || {}+ const allowSendingSchemaMetadata =+ project?.ref !== undefined && flags?.allowCMDKDataOptIn && isOptedInToAI- const handleConfirm = useCallback(- async (query: string) => {- const edgeFunctionUrl = getEdgeFunctionUrl()-- if (!edgeFunctionUrl) {- return console.error('No edge function url')- }-- setAnswer(undefined)- setSearch('')- dispatchPromptData({ index: promptIndex, answer: undefined, query })- setIsResponding(false)- setHasClippyError(false)- setIsLoading(true)-- const queryToSend = generatePrompt(- query,- isOptedInToAI && includeSchemaMetadata ? metadata : undefined- Postgres SQL query (markdown SQL only):- `,++ const { submit, reset, messages, isResponding, hasError } = useAiChat({++ messageTemplate: (message) => {++ return generatePrompt(++ message,++ isOptedInToAI && includeSchemaMetadataRef.current ? metadata : undefined+ )- 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)- }- })++ },+ setIsLoading,+ })- eventSource.stream()- eventSourceRef.current = eventSource- setIsLoading(true)+ const handleSubmit = useCallback(+ (message: string) => {+ setSearch('')+ submit(message)},- [promptIndex, promptData, includeSchemaMetadata]+ [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)-- }++ if (search) handleSubmit(search)++ includeSchemaMetadataRef.current = includeSchemaMetadata}, [])const formatAnswer = (answer: string) => {@@@ -135,30 -146,11 +77,16 @@@return (<div onClick={(e) => e.stopPropagation()}>- <div className={cn('relative mb-[62px] py-4 max-h-[720px] overflow-auto')}>+ <div+ className={cn(+ 'relative py-4 max-h-[720px] overflow-auto',+ allowSendingSchemaMetadata ? 'mb-[83px]' : 'mb-[42px]'+ )}+ >- {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)-- const cantHelp = (prompt?.answer ?? '').includes(- "Sorry, I don't know how to help with that."- )-- 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="@@@ -168,40 -160,62 +96,69 @@@><IconUser strokeWidth={1.5} size={16} /></div>- <div className="prose text-scale-1000">{message.content}</div>+ <div className="flex items-center prose text-scale-1100 text-sm">- {prompt.query}++ {message.content}+ </div></div>- )}+ )+ case MessageRole.Assistant:- const answer = formatAnswer(- message.content- .replace(/```sql/g, '')- .replace(/```.*/gs, '')- .replace(/-- End of SQL query\.*/g, '')- .trim()- )++ const unformattedAnswer = message.content++ .replace(/```sql/g, '')++ .replace(/```.*/gs, '')++ .replace(/-- End of SQL query\.*/g, '')++ .trim()- <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 ? (- <div className="bg-scale-700 h-[21px] w-[13px] mt-1 animate-bounce"></div>- ) : (- <div className="space-y-2 flex-grow max-w-[93%]">- <CodeBlock- hideCopy- language="sql"- className="relative prose dark:prose-dark bg-scale-300 max-w-none"- >- {promptAnswer}- </CodeBlock>++ const answer =++ message.status === MessageStatus.Complete++ ? formatAnswer(unformattedAnswer)++ : unformattedAnswer+ const cantHelp = answer === "Sorry, I don't know how to help with that."- {!isResponding && !cantHelp && <SQLOutputActions answer={prompt.answer} />}- </div>- )}- </>+ return (+ <div className="px-4 [overflow-anchor:none] mb-6">+ <div className="flex gap-6 [overflow-anchor:none] mb-6">+ <div>+ <AiIconChat />+ </div>+ <>+ {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+ hideCopy+ language="sql"+ className="relative prose dark:prose-dark bg-scale-300 max-w-none"+ >+ {answer}+ </CodeBlock>- {!isResponding && <SQLOutputActions answer={answer} />}++ {message.status === MessageStatus.Complete && (++ <SQLOutputActions answer={answer} />++ )}+ </div>+ )}+ </>+ </div></div>- </div>- </>- )+ )+ }})}- {promptData.length === 0 && !hasClippyError && (+++ {messages.length === 0 && !hasError && (<div><div className="px-10"><h3>Example queries</h3>@@@ -268,24 -284,7 +227,30 @@@<div className="[overflow-anchor:auto] h-px w-full"></div></div>++<div className="absolute bottom-0 w-full bg-scale-200 py-3">+ {allowSendingSchemaMetadata && (+ <div className="flex items-center justify-between px-6 py-3">+ <div>+ <p className="text-sm">+ Include table names, column names and their corresponding data types in prompt+ </p>+ <p className="text-sm text-scale-1100">+ This will generate answers that are more relevant to your project's schema+ </p>+ </div>+ <Toggle+ disabled={!isOptedInToAI}+ checked={includeSchemaMetadata}- onChange={() => setIncludeSchemaMetadata((prev) => !prev)}++ onChange={() =>++ setIncludeSchemaMetadata((prev) => {++ includeSchemaMetadataRef.current = !prev++ return !prev++ })++ }+ />+ </div>+ )}<InputclassName="bg-scale-100 rounded mx-3"autoFocus@@@ -319,8 -318,14 +284,8 @@@onKeyDown={(e) => {switch (e.key) {case 'Enter':- if (!search) {- return- }- if (isLoading || isResponding) {- return- }- handleSubmit(search)- return+ if (!search || isLoading || isResponding) return- return handleConfirm(search)++ return handleSubmit(search)default:return}diff --cc packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.tsindex c9338166247,00000000000..8c1164292b2mode 100644,000000..100644--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts@@@ -1,78 -1,0 +1,84 @@@++import { stripIndent } from 'common-tags'+++export 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`+ }+}++export 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]+}+- export const generatePrompt = (query: string, metadata?: any) => {++export const generatePrompt = (prompt: string, metadata?: any) => {+ const { definitions } = metadata || {}- return `++ return stripIndent`+${+ definitions !== undefined+ ? `+Given the following Postgres SQL tables:+${definitions}+`+ : ''+}+- Generate a Postgres SQL query based on the following natural language prompt. For primary keys, always use "integer primary key generated always as identity". All Postgres SQL commands should be written in lowercase letters.++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"+- Prompt:- ${query}++Natural language prompt:++${prompt}+- Postgres SQL query:++Postgres SQL query (markdown SQL only):+`.trim()+}