The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Make the conversational AI in the SQL editor default (#23142)
Ivan Vasilov6f5cabdc62a2
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxindex b70197b5551..d047d8cdb10 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx@@ -22,7 +22,6 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}[LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]: false,[LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT]: false,[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]: false,- [LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT]: false,})useEffect(() => {@@ -36,8 +35,6 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT) === 'true',[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]:localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS) === 'true',- [LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT]:- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT) === 'true',})}}, [])@@ -72,8 +69,3 @@ export const useIsColumnLevelPrivilegesEnabled = () => {const { flags } = useFeaturePreviewContext()return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]}--export const useIsSQLEditorAiAssistantEnabled = () => {- const { flags } = useFeaturePreviewContext()- return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT]-}diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxindex bd930be6d16..7ec434e29f0 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx@@ -5,7 +5,6 @@ import { useRouter } from 'next/router'import { useEffect, useState } from 'react'import { Button, IconExternalLink, IconEye, IconEyeOff, Modal, ScrollArea, cn } from 'ui'-import { useFlag } from 'hooks'import { LOCAL_STORAGE_KEYS } from 'lib/constants'import Telemetry from 'lib/telemetry'import { useAppStateSnapshot } from 'state/app-state'@@ -13,11 +12,8 @@ import APISidePanelPreview from './APISidePanelPreview'import CLSPreview from './CLSPreview'import { useFeaturePreviewContext } from './FeaturePreviewContext'import RLSAIAssistantPreview from './RLSAIAssistantPreview'-import { SQLEditorAIAssistantPreview } from './SQLEditorAIAssistantPreview'const FeaturePreviewModal = () => {- const isAIConversational = useFlag('sqlEditorConversationalAi')-// [Ivan] We should probably move this to a separate file, together with LOCAL_STORAGE_KEYS. We should make adding new feature previews as simple as possible.const FEATURE_PREVIEWS: { key: string; name: string; content: any; discussionsUrl?: string }[] = [{@@ -38,17 +34,6 @@ const FeaturePreviewModal = () => {content: <CLSPreview />,discussionsUrl: 'https://github.com/orgs/supabase/discussions/20295',},- // the user should only be able to see the panel for the AI assistant if the feature flag is true- ...(isAIConversational- ? [- {- key: LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT,- name: 'SQL Editor Conversational Assistant ',- content: <SQLEditorAIAssistantPreview />,- discussionsUrl: 'https://github.com/orgs/supabase/discussions/21967',- },- ]- : []),]const router = useRouter()diff --git a/apps/studio/components/interfaces/App/FeaturePreview/SQLEditorAIAssistantPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/SQLEditorAIAssistantPreview.tsxdeleted file mode 100644index f73b69bd09f..00000000000--- a/apps/studio/components/interfaces/App/FeaturePreview/SQLEditorAIAssistantPreview.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { useParams } from 'common'-import { Markdown } from 'components/interfaces/Markdown'-import { BASE_PATH } from 'lib/constants'-import Image from 'next/image'--export const SQLEditorAIAssistantPreview = () => {- const { ref } = useParams()-- return (- <div className="space-y-2">- <div className="mb-4 flex flex-col gap-y-2">- <Markdown- className="text-foreground-light max-w-full"- content="When using the [SQL Editor](http://supabase.com/project/_/sql) you'll have access to a new and improved conversational AI Assistant which you can use to help you write your queries."- />- <Markdown- className="text-foreground-light max-w-full"- content={`Let our AI Assistant handle the SQL while you focus on building your app.`}- />- </div>- <Image- src={`${BASE_PATH}/img/previews/rls-ai-assistant-preview.png`}- width={1860}- height={970}- alt="api-docs-side-panel-preview"- className="rounded border"- />- <div className="space-y-2 !mt-4">- <p className="text-sm">Enabling this preview will:</p>- <ul className="list-disc pl-6 text-sm text-foreground-light space-y-1">- <li>- <Markdown- className="text-foreground-light"- content={`Replace the existing single-input UI with a side panel where you can have a full, contextual conversation.`}- />- </li>- <li>- <Markdown- className="text-foreground-light"- content={`The Assistant will iteratively generate SQL from your natural language prompts.`}- />- </li>- </ul>- </div>- </div>- )-}diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsxindex 2d80336ec67..95a62459b7c 100644--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx@@ -33,9 +33,9 @@ interface AiAssistantPanelProps {selectedMessage?: stringloading: booleanonSubmit: (s: string) => void+ onClearHistory: () => voidonDiff: ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => voidonClose: () => void- onChange: (value: boolean) => void}export const AiAssistantPanel = ({@@ -44,8 +44,8 @@ export const AiAssistantPanel = ({loading,onSubmit,onDiff,+ onClearHistory,onClose,- onChange,}: AiAssistantPanelProps) => {const router = useRouter()const { profile } = useProfile()@@ -67,7 +67,6 @@ export const AiAssistantPanel = ({resolver: zodResolver(FormSchema),defaultValues: { chat: '' },})- const formChatValue = form.getValues().chatconst pendingReply = loading && last(messages)?.role === 'user'// try to scroll on each rerender to the bottom@@ -86,10 +85,6 @@ export const AiAssistantPanel = ({}}, [loading])- useEffect(() => {- onChange(formChatValue.length === 0)- }, [formChatValue])-return (<div className="flex flex-col h-full min-w-[400px] w-[400px] border-l border-control"><div@@ -112,21 +107,26 @@ export const AiAssistantPanel = ({</Button>}>- <Button- type="default"- className="w-min"- icon={- <div- className={cn(- 'w-2 h-2 rounded-full',- includeSchemaMetadata ? 'bg-brand' : 'border border-stronger'- )}- />- }- onClick={() => snap.setShowAiSettingsModal(true)}- >- {includeSchemaMetadata ? 'Include' : 'Exclude'} database metadata in queries- </Button>+ <div className="flex flex-row justify-between">+ <Button+ type="default"+ className="w-min"+ icon={+ <div+ className={cn(+ 'w-2 h-2 rounded-full',+ includeSchemaMetadata ? 'bg-brand' : 'border border-stronger'+ )}+ />+ }+ onClick={() => snap.setShowAiSettingsModal(true)}+ >+ {includeSchemaMetadata ? 'Include' : 'Exclude'} database metadata in queries+ </Button>+ <Button type="warning" onClick={() => onClearHistory()}>+ Clear history+ </Button>+ </div></Message>{messages.map((m) => (@@ -145,18 +145,6 @@ export const AiAssistantPanel = ({{pendingReply && <Message key="thinking" role="assistant" content="Thinking..." />}<div ref={bottomRef} className="h-1" />- {/* <div className="grid grid-cols-12 gap-2 p-2">- {ASSISTANT_TEMPLATES.map((template) => (- <CardButton- hideChevron- key={template.name}- title={template.name}- description={template.description}- className="!p-3 col-span-12 h-auto [&>div>div]:!mt-0 [&>div>h5]:text-sm"- onClick={() => onSubmit(template.prompt)}- />- ))}- </div> */}</div><Form_Shadcn_ {...form}>diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex eaea903d658..2be93efde6d 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -1,15 +1,13 @@import type { Monaco } from '@monaco-editor/react'import { useChat } from 'ai/react'-import { AnimatePresence, motion } from 'framer-motion'+import { motion } from 'framer-motion'import dynamic from 'next/dynamic'import { useRouter } from 'next/router'-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import toast from 'react-hot-toast'-import { format } from 'sql-formatter'import { useParams, useTelemetryProps } from 'common'-import { useSqlEditMutation } from 'data/ai/sql-edit-mutation'-import { useSqlGenerateMutation } from 'data/ai/sql-generate-mutation'+import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'import { useSqlTitleGenerateMutation } from 'data/ai/sql-title-mutation'import type { SqlSnippet } from 'data/content/sql-snippets-query'import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'@@ -18,22 +16,19 @@ import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'import { useFormatQueryMutation } from 'data/sql/format-sql-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { isError } from 'data/utils/error-check'-import { useFlag, useLocalStorageQuery, useSelectedOrganization, useSelectedProject } from 'hooks'+import { useLocalStorageQuery, useSelectedOrganization, useSelectedProject } from 'hooks'import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { wrapWithRoleImpersonation } from 'lib/role-impersonation'import Telemetry from 'lib/telemetry'+import { format } from 'sql-formatter'import { useAppStateSnapshot } from 'state/app-state'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { isRoleImpersonationEnabled, useGetImpersonatedRole } from 'state/role-impersonation-state'import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'import {AiIconAnimation,- IconCornerDownLeft,- IconSettings,- IconX,- Input_Shadcn_,Loading,ResizableHandle,ResizablePanel,@@ -41,7 +36,6 @@ import {cn,} from 'ui'import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'-import { useIsSQLEditorAiAssistantEnabled } from '../App/FeaturePreview/FeaturePreviewContext'import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'import { AiAssistantPanel } from './AiAssistantPanel'@@ -52,7 +46,6 @@ import {DiffType,IStandaloneCodeEditor,IStandaloneDiffEditor,- SQLEditorContextValues,} from './SQLEditor.types'import {checkDestructiveQuery,@@ -70,18 +63,6 @@ const DiffEditor = dynamic({ ssr: false })-const SQLEditorContext = createContext<SQLEditorContextValues | undefined>(undefined)--export function useSqlEditor() {- const values = useContext(SQLEditorContext)-- if (!values) {- throw new Error('No SQL editor context. Are you using useSqlEditor() outside of SQLEditor?')- }-- return values-}-const SQLEditor = () => {const { ref, id: urlId } = useParams()const router = useRouter()@@ -100,23 +81,15 @@ const SQLEditor = () => {const snap = useSqlEditorStateSnapshot()const databaseSelectorState = useDatabaseSelectorStateSnapshot()- const aiAssistantFlag = useFlag('sqlEditorConversationalAi')- const aiAssistantFeaturePreview = useIsSQLEditorAiAssistantEnabled()- const isAiAssistantOn = aiAssistantFlag && aiAssistantFeaturePreview-const { mutate: formatQuery } = useFormatQueryMutation()- const { mutateAsync: generateSql, isLoading: isGenerateSqlLoading } = useSqlGenerateMutation()- const { mutateAsync: editSql, isLoading: isEditSqlLoading } = useSqlEditMutation()- const { mutateAsync: titleSql } = useSqlTitleGenerateMutation()const { mutateAsync: generateSqlTitle } = useSqlTitleGenerateMutation()+ const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()- const [aiInput, setAiInput] = useState('')const [selectedMessage, setSelectedMessage] = useState<string>()const [debugSolution, setDebugSolution] = useState<string>()const [sourceSqlDiff, setSourceSqlDiff] = useState<ContentDiff>()const [pendingTitle, setPendingTitle] = useState<string>()const [hasSelection, setHasSelection] = useState<boolean>(false)- const inputRef = useRef<HTMLInputElement>(null)const showReadReplicasUI = project?.is_read_replicas_enabled@@ -135,21 +108,15 @@ const SQLEditor = () => {const selectedProject = useSelectedProject()const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? falseconst [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)+ const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema+const [isAcceptDiffLoading, setIsAcceptDiffLoading] = useState(false)const [, setAiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)- const [, setIsSchemaSuggestionDismissed] = useLocalStorageQuery(- 'supabase_sql-editor-ai-schema-suggestion-dismissed',- false- )-- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchemaconst [selectedDiffType, setSelectedDiffType] = useState<DiffType | undefined>(undefined)const [isFirstRender, setIsFirstRender] = useState(true)const [lineHighlights, setLineHighlights] = useState<string[]>([])- const isAiLoading = isGenerateSqlLoading || isEditSqlLoading-// Used for cleaner framer motion transitionsuseEffect(() => {setIsFirstRender(false)@@ -178,11 +145,14 @@ const SQLEditor = () => {const monacoRef = useRef<Monaco | null>(null)const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)+ // Use chat id because useChat doesn't have a reset function to clear all messages+ const [chatId, setChatId] = useState(uuidv4())const {messages: chatMessages,append,isLoading: isLoadingChat,} = useChat({+ id: chatId,api: `${BASE_PATH}/api/ai/sql/generate-v2`,body: {existingSql: editorRef.current?.getValue(),@@ -245,8 +215,6 @@ const SQLEditor = () => {},})- const snippet = id ? snap.snippets[id] : null-const isLoading = urlId === 'new' ? false : !(id && ref && snap.loaded[ref])/**@@ -394,36 +362,68 @@ const SQLEditor = () => {[profile?.id, project?.id, ref, router, snap])- const updateEditorWithCheckForDiff = ({- id,- diffType,- sql,- }: {- id: string- diffType: DiffType- sql: string- }) => {- const editorModel = editorRef.current?.getModel()- if (!editorModel) return-- setAiQueryCount((count) => count + 1)-- const existingValue = editorRef.current?.getValue() ?? ''- if (existingValue.length === 0) {- editorRef.current?.executeEdits('apply-ai-message', [- {- text: `${sqlAiDisclaimerComment}\n\n${sql}`,- range: editorModel.getFullModelRange(),- },- ])- } else {- setSelectedMessage(id)- const currentSql = editorRef.current?.getValue()- const diff = { original: currentSql || '', modified: sql }- setSourceSqlDiff(diff)- setSelectedDiffType(diffType)+ const updateEditorWithCheckForDiff = useCallback(+ ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => {+ const editorModel = editorRef.current?.getModel()+ if (!editorModel) return++ setAiQueryCount((count) => count + 1)++ const existingValue = editorRef.current?.getValue() ?? ''+ if (existingValue.length === 0) {+ // if the editor is empty, just copy over the code+ editorRef.current?.executeEdits('apply-ai-message', [+ {+ text: `${sqlAiDisclaimerComment}\n\n${sql}`,+ range: editorModel.getFullModelRange(),+ },+ ])+ } else {+ setSelectedMessage(id)+ const currentSql = editorRef.current?.getValue()+ const diff = { original: currentSql || '', modified: sql }+ setSourceSqlDiff(diff)+ setSelectedDiffType(diffType)+ }+ },+ [setAiQueryCount]+ )++ const onDebug = useCallback(async () => {+ try {+ const snippet = snap.snippets[id]+ const result = snap.results[id]?.[0]++ const { solution, sql } = await debugSql({+ sql: snippet.snippet.content.sql.replace(sqlAiDisclaimerComment, '').trim(),+ errorMessage: result.error.message,+ entityDefinitions,+ })++ const formattedSql =+ sqlAiDisclaimerComment ++ '\n\n' ++ format(sql, {+ language: 'postgresql',+ keywordCase: 'lower',+ })+ setDebugSolution(solution)+ setSourceSqlDiff({+ original: snippet.snippet.content.sql,+ modified: formattedSql,+ })+ setSelectedDiffType(DiffType.Modification)+ } catch (error: unknown) {+ // [Joshen] There's a tendency for the SQL debug to chuck a lengthy error message+ // that's not relevant for the user - so we prettify it here by avoiding to return the+ // entire error body from the assistant+ if (isError(error)) {+ toast.error(+ `Sorry, the assistant failed to debug your query! Please try again with a different one.`+ )+ }}- }+ }, [debugSql, entityDefinitions, id, snap.results, snap.snippets])const acceptAiHandler = useCallback(async () => {try {@@ -448,7 +448,7 @@ const SQLEditor = () => {const sql = diffModel.modified.getValue()if (selectedDiffType === DiffType.NewSnippet) {- const { title } = await titleSql({ sql })+ const { title } = await generateSqlTitle({ sql })await handleNewQuery(sql, title)} else {editorRef.current.executeEdits('apply-ai-edit', [@@ -473,7 +473,6 @@ const SQLEditor = () => {router)- setAiInput('')setSelectedMessage(undefined)setSelectedDiffType(DiffType.Modification)setDebugSolution(undefined)@@ -486,7 +485,7 @@ const SQLEditor = () => {sourceSqlDiff,selectedDiffType,handleNewQuery,- titleSql,+ generateSqlTitle,debugSolution,telemetryProps,router,@@ -596,17 +595,7 @@ const SQLEditor = () => {}, [selectedDiffType, sourceSqlDiff])return (- <SQLEditorContext.Provider- value={{- aiInput,- setAiInput,- sqlDiff: sourceSqlDiff,- setSqlDiff: setSourceSqlDiff,- debugSolution,- setDebugSolution,- setSelectedDiffType,- }}- >+ <><ConfirmModalvisible={isConfirmModalOpen}title="Destructive operation"@@ -629,221 +618,38 @@ const SQLEditor = () => {direction="vertical"autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_SPLIT_SIZE}>- {isAiOpen && !hasHipaaAddon && (+ {(isAiOpen || isDiffOpen) && !hasHipaaAddon && (<AISchemaSuggestionPopoveronClickSettings={() => {appSnap.setShowAiSettingsModal(true)}}>- <>- {!isAiAssistantOn ? (- <motion.div- key="ask-ai-input-container"- layoutId="ask-ai-input-container"- variants={{ visible: { borderRadius: 0, x: 0 }, hidden: { x: 100 } }}- initial={isFirstRender ? 'visible' : 'hidden'}- animate="visible"- className="w-full flex justify-center z-10 h-[60px] bg-brand-200 border-b border-brand-400 px-5"- >- <div- className={cn(- 'w-full !border-brand-900 border-none !shadow-none',- 'flex items-center gap-3'- )}- >- <motion.div layoutId="ask-ai-input-icon" transition={{ duration: 0.1 }}>- <AiIconAnimation loading={isAiLoading} />- </motion.div>-- <AnimatePresence initial={false} mode="wait">- {debugSolution && (- <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-brand-600">- {debugSolution}- </div>- )}- {!isAiLoading && !debugSolution && (- <motion.div- key="ask-ai-input"- className="w-full h-full relative flex items-center"- variants={{- visible: { opacity: 1, y: 0 },- hidden: { opacity: 0, y: -25 },- }}- initial="hidden"- animate="visible"- exit="hidden"- transition={{ duration: 0.1 }}- >- <Input_Shadcn_- value={aiInput}- onChange={(e) => setAiInput(e.currentTarget.value)}- disabled={isDiffOpen}- ref={inputRef}- className={cn(- '!p-0 bg-transparent border-transparent text-sm text-brand-600 placeholder:text-brand-500 focus:!ring-0',- 'focus-visible:ring-0 focus-visible:ring-offset-0',- 'appearance-none outline-none'- )}- placeholder={- !debugSolution- ? !snippet?.snippet.content.sql.trim()- ? 'Ask Supabase AI to build a query'- : 'Ask Supabase AI to modify your query'- : ''- }- onKeyDown={(e) => {- if (e.key === 'Escape' && !aiInput) {- setIsAiOpen(false)- }- }}- onKeyPress={async (e) => {- if (e.key === 'Enter') {- try {- const prompt = e.currentTarget.value-- if (!prompt) {- return- }-- const currentSql = editorRef.current?.getValue()-- let sql: string | undefined- let title: string | undefined-- if (!currentSql) {- ;({ sql, title } = await generateSql({- prompt,- entityDefinitions,- }))- } else {- ;({ sql } = await editSql({- prompt,- sql: currentSql.replace(sqlAiDisclaimerComment, '').trim(),- entityDefinitions,- }))- }-- setAiQueryCount((count) => count + 1)-- const formattedSql = format(sql, {- language: 'postgresql',- keywordCase: 'lower',- })-- // If this was an edit and AI returned the same SQL as before- if (currentSql && formattedSql.trim() === currentSql.trim()) {- toast.error(- 'Unable to edit SQL. Try adding more details to your prompt.'- )- return- }-- setSourceSqlDiff({- original: currentSql ?? '',- modified: formattedSql,- })- setSelectedDiffType(DiffType.Modification)-- if (title) setPendingTitle(title)- } catch (error: unknown) {- if (isError(error)) toast.error(error.message)- }- }- }}- />- </motion.div>- )}- {isAiLoading && (- <motion.div- key="ask-ai-loading"- className="p-0 flex flex-row gap-2 items-center w-full"- variants={{- visible: { opacity: 1, y: 0 },- hidden: { opacity: 0, y: 25 },- }}- transition={{ duration: 0.2 }}- initial="hidden"- animate="visible"- exit="hidden"- >- <motion.span- className="text-sm text-brand-600 px-3"- animate={{- opacity: ['0.5', '0.75', '0.5'],- transition: { ease: 'linear', duration: 0.33, repeat: Infinity },- }}- >- Thinking...- </motion.span>- </motion.div>- )}- </AnimatePresence>- <div className="flex flex-row items-center gap-3 mr-1">- {isDiffOpen ? (- <DiffActionBar- loading={isAcceptDiffLoading}- selectedDiffType={selectedDiffType || DiffType.Modification}- onChangeDiffType={(diffType) => setSelectedDiffType(diffType)}- onAccept={acceptAiHandler}- onCancel={discardAiHandler}- />- ) : (- <>- <div- className={cn(- 'transition text-brand-600',- !aiInput ? 'opacity-0' : 'opacity-100'- )}- >- <IconCornerDownLeft size={16} strokeWidth={1.5} />- </div>- <button- onClick={() => {- setIsSchemaSuggestionDismissed(true)- appSnap.setShowAiSettingsModal(true)- }}- className="text-brand-600 hover:text-brand-600 transition"- >- <IconSettings className="cursor-pointer" />- </button>- <button- className="transition text-brand-500 hover:text-brand-600"- onClick={() => setIsAiOpen(false)}- >- <IconX size={21} />- </button>- </>- )}- </div>+ {isDiffOpen ? (+ <motion.div+ key="ask-ai-input-container"+ layoutId="ask-ai-input-container"+ variants={{ visible: { borderRadius: 0, x: 0 }, hidden: { x: 100 } }}+ initial={isFirstRender ? 'visible' : 'hidden'}+ animate="visible"+ className={cn(+ 'flex flex-row items-center gap-3 justify-end px-2 py-2 w-full z-10',+ 'bg-brand-200 border-b border-brand-400 !shadow-none'+ )}+ >+ {debugSolution && (+ <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-brand-600">+ {debugSolution}</div>- </motion.div>- ) : isDiffOpen ? (- <motion.div- key="ask-ai-input-container"- layoutId="ask-ai-input-container"- variants={{ visible: { borderRadius: 0, x: 0 }, hidden: { x: 100 } }}- initial={isFirstRender ? 'visible' : 'hidden'}- animate="visible"- className={cn(- 'flex flex-row items-center gap-3 justify-end px-2 py-2 w-full z-10',- 'bg-brand-200 border-b border-brand-400 !shadow-none'- )}- >- {debugSolution && (- <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-brand-600">- {debugSolution}- </div>- )}- <DiffActionBar- loading={isAcceptDiffLoading}- selectedDiffType={selectedDiffType || DiffType.Modification}- onChangeDiffType={(diffType) => setSelectedDiffType(diffType)}- onAccept={acceptAiHandler}- onCancel={discardAiHandler}- />- </motion.div>- ) : null}- </>+ )}+ <DiffActionBar+ loading={isAcceptDiffLoading}+ selectedDiffType={selectedDiffType || DiffType.Modification}+ onChangeDiffType={(diffType) => setSelectedDiffType(diffType)}+ onAccept={acceptAiHandler}+ onCancel={discardAiHandler}+ />+ </motion.div>+ ) : null}</AISchemaSuggestionPopover>)}<ResizablePanel collapsible collapsedSize={10} minSize={20}>@@ -886,60 +692,6 @@ const SQLEditor = () => {modified={defaultSqlDiff.modified}onMount={(editor) => {diffEditorRef.current = editor-- // This logic deducts whether the diff should be addition or replacement on initial diffing.- // With the AI assistant is not necessary because it has separate buttons for addition and- // replacement. Using this logic with the AI assistant would probably annoy the users.- if (isAiAssistantOn) {- return- }- let isFirstLoad = true-- editor.onDidUpdateDiff(() => {- if (!isFirstLoad) {- return- }-- const model = editor.getModel()- const lineChanges = editor.getLineChanges()-- if (!model || !lineChanges || lineChanges.length === 0) {- return- }-- const original = model.original.getValue()- const formattedOriginal = format(- original.replace(sqlAiDisclaimerComment, '').trim(),- {- language: 'postgresql',- keywordCase: 'lower',- }- )-- const modified = model.modified.getValue()-- const lineStart = original.includes(sqlAiDisclaimerComment)- ? (sqlAiDisclaimerComment + '\n\n').split('\n').length- : 0- const lineEnd = model.original.getLineCount()- const totalLines = lineEnd - lineStart-- // If any change overwrites >50% of the original code,- // and the the modified code doesn't contain the original code,- // predict that this is an addition instead of a modification- const isAddition =- lineChanges.some(- (lineChange) =>- lineChange.originalEndLineNumber -- lineChange.originalStartLineNumber >- totalLines * 0.5- ) && !modified.includes(formattedOriginal)-- if (isAddition) {- setSelectedDiffType(DiffType.Addition)- }- isFirstLoad = false- })}}options={{ fontSize: 13 }}/>@@ -981,14 +733,16 @@ const SQLEditor = () => {id={id}isExecuting={isExecuting}isDisabled={isDiffOpen}+ isDebugging={isDebugSqlLoading}hasSelection={hasSelection}prettifyQuery={prettifyQuery}executeQuery={executeQuery}+ onDebug={onDebug}/>)}</ResizablePanel></ResizablePanelGroup>- {isAiOpen && isAiAssistantOn && (+ {isAiOpen && (<AiAssistantPanelmessages={messages}selectedMessage={selectedMessage}@@ -1000,13 +754,13 @@ const SQLEditor = () => {createdAt: new Date(),})}+ onClearHistory={() => setChatId(uuidv4())}onDiff={updateEditorWithCheckForDiff}- onChange={() => {}}onClose={() => setIsAiOpen(false)}/>)}</div>- </SQLEditorContext.Provider>+ </>)}diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsindex 3a9d362e977..d76787eb063 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts@@ -1,11 +1,11 @@+import { removeCommentsFromSql } from 'lib/helpers'+import type { SqlSnippets, UserContent } from 'types'import {NEW_SQL_SNIPPET_SKELETON,destructiveSqlRegex,sqlAiDisclaimerComment,} from './SQLEditor.constants'-import type { SqlSnippets, UserContent } from 'types'import { ContentDiff, DiffType } from './SQLEditor.types'-import { removeCommentsFromSql } from 'lib/helpers'export const createSqlSnippetSkeleton = ({id,@@ -80,9 +80,11 @@ ${isNpx ? 'npx ' : ''}supabase snippets download ${id} > \\`export const compareAsModification = (sqlDiff: ContentDiff) => {+ const formattedModified = sqlDiff.modified.replace(sqlAiDisclaimerComment, '').trim()+return {original: sqlDiff.original,- modified: `${sqlAiDisclaimerComment}\n\n${sqlDiff.modified}`,+ modified: `${sqlAiDisclaimerComment}\n\n${formattedModified}`,}}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsxindex 2e2920f08d9..5137718984a 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx@@ -14,10 +14,12 @@ import UtilityTabResults from './UtilityTabResults'export type UtilityPanelProps = {id: stringisExecuting?: boolean+ isDebugging?: booleanisDisabled?: booleanhasSelection: booleanprettifyQuery: () => voidexecuteQuery: () => void+ onDebug: () => void}const DEFAULT_CHART_CONFIG = {@@ -30,10 +32,12 @@ const DEFAULT_CHART_CONFIG = {const UtilityPanel = ({id,isExecuting,+ isDebugging,isDisabled,hasSelection,prettifyQuery,executeQuery,+ onDebug,}: UtilityPanelProps) => {const snap = useSqlEditorStateSnapshot()const { ref } = useParams()@@ -134,7 +138,13 @@ const UtilityPanel = ({</div></TabsList_Shadcn_><TabsContent_Shadcn_ className="mt-0 h-full" value="results">- <UtilityTabResults id={id} isExecuting={isExecuting} />+ <UtilityTabResults+ id={id}+ isExecuting={isExecuting}+ isDisabled={isDisabled}+ onDebug={onDebug}+ isDebugging={isDebugging}+ /></TabsContent_Shadcn_><TabsContent_Shadcn_ className="mt-0 h-full" value="chart"><ChartConfig results={result} config={chartConfig} onConfigChange={onConfigChange} />diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsxindex 60925f083bd..8d9226b2704 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx@@ -1,51 +1,33 @@import { useParams } from 'common'-import toast from 'react-hot-toast'-import { format } from 'sql-formatter'import { AiIconAnimation, Button } from 'ui'import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'-import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'-import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import { isError } from 'data/utils/error-check'-import { useLocalStorageQuery, useSelectedOrganization, useSelectedProject } from 'hooks'-import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'+import { useSelectedOrganization } from 'hooks'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { useSqlEditorStateSnapshot } from 'state/sql-editor'-import { useSqlEditor } from '../SQLEditor'-import { sqlAiDisclaimerComment } from '../SQLEditor.constants'-import { DiffType } from '../SQLEditor.types'import Results from './Results'export type UtilityTabResultsProps = {id: stringisExecuting?: boolean+ isDisabled?: boolean+ onDebug: () => void+ isDebugging?: boolean}-const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {+const UtilityTabResults = ({+ id,+ isExecuting,+ isDisabled,+ isDebugging,+ onDebug,+}: UtilityTabResultsProps) => {const { ref } = useParams()const snap = useSqlEditorStateSnapshot()const state = useDatabaseSelectorStateSnapshot()- const selectedProject = useSelectedProject()const organization = useSelectedOrganization()- const { sqlDiff, setDebugSolution, setAiInput, setSqlDiff, setSelectedDiffType } = useSqlEditor()- const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()-- const isOptedInToAI = organization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false- const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema-- const { data } = useEntityDefinitionsQuery(- {- projectRef: selectedProject?.ref,- connectionString: selectedProject?.connectionString,- },- { enabled: includeSchemaMetadata }- )-- const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined-const snippet = snap.snippets[id]const result = snap.results[id]?.[0]const isUtilityPanelCollapsed = (snippet?.splitSizes?.[1] ?? 0) === 0@@ -140,41 +122,9 @@ const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {)}{!hasHipaaAddon && (<Button- icon={<AiIconAnimation className="scale-75 w-3 h-3" loading={isDebugSqlLoading} />}- disabled={!!sqlDiff || isDebugSqlLoading}- onClick={async () => {- try {- const { solution, sql } = await debugSql({- sql: snippet.snippet.content.sql.replace(sqlAiDisclaimerComment, '').trim(),- errorMessage: result.error.message,- entityDefinitions,- })-- const formattedSql =- sqlAiDisclaimerComment +- '\n\n' +- format(sql, {- language: 'postgresql',- keywordCase: 'lower',- })- setAiInput('')- setDebugSolution(solution)- setSqlDiff({- original: snippet.snippet.content.sql,- modified: formattedSql,- })- setSelectedDiffType(DiffType.Modification)- } catch (error: unknown) {- // [Joshen] There's a tendency for the SQL debug to chuck a lengthy error message- // that's not relevant for the user - so we prettify it here by avoiding to return the- // entire error body from the assistant- if (isError(error)) {- toast.error(- `Sorry, the assistant failed to debug your query! Please try again with a different one.`- )- }- }- }}+ icon={<AiIconAnimation className="scale-75 w-3 h-3" loading={isDebugging} />}+ disabled={!!isDisabled || isDebugging}+ onClick={onDebug}>Debug with Supabase AI</Button>diff --git a/apps/studio/data/ai/sql-edit-mutation.ts b/apps/studio/data/ai/sql-edit-mutation.tsdeleted file mode 100644index 0127f17d1bf..00000000000--- a/apps/studio/data/ai/sql-edit-mutation.ts+++ /dev/null@@ -1,52 +0,0 @@-import { useMutation, UseMutationOptions } from '@tanstack/react-query'-import toast from 'react-hot-toast'--import { isResponseOk, post } from 'lib/common/fetch'-import { BASE_PATH } from 'lib/constants'-import type { ResponseError } from 'types'--export type SqlEditResponse = {- sql: string-}--export type SqlEditVariables = {- prompt: string- sql: string- entityDefinitions?: string[]-}--export async function editSql({ prompt, sql, entityDefinitions }: SqlEditVariables) {- const response = await post<SqlEditResponse>(BASE_PATH + '/api/ai/sql/edit', {- prompt,- sql,- entityDefinitions,- })-- if (!isResponseOk(response)) {- throw response.error- }-- return response-}--type SqlEditData = Awaited<ReturnType<typeof editSql>>--export const useSqlEditMutation = ({- onSuccess,- onError,- ...options-}: Omit<UseMutationOptions<SqlEditData, ResponseError, SqlEditVariables>, 'mutationFn'> = {}) => {- return useMutation<SqlEditData, ResponseError, SqlEditVariables>((vars) => editSql(vars), {- async onSuccess(data, variables, context) {- await onSuccess?.(data, variables, context)- },- async onError(data, variables, context) {- if (onError === undefined) {- toast.error(`Failed to edit SQL: ${data.message}`)- } else {- onError(data, variables, context)- }- },- ...options,- })-}diff --git a/apps/studio/data/ai/sql-generate-mutation.ts b/apps/studio/data/ai/sql-generate-mutation.tsdeleted file mode 100644index e26b54a0776..00000000000--- a/apps/studio/data/ai/sql-generate-mutation.ts+++ /dev/null@@ -1,57 +0,0 @@-import { useMutation, UseMutationOptions } from '@tanstack/react-query'-import toast from 'react-hot-toast'--import { isResponseOk, post } from 'lib/common/fetch'-import { BASE_PATH } from 'lib/constants'-import type { ResponseError } from 'types'--export type SqlGenerateResponse = {- title: string- sql: string-}--export type SqlGenerateVariables = {- prompt: string- entityDefinitions?: string[]-}--export async function generateSql({ prompt, entityDefinitions }: SqlGenerateVariables) {- const response = await post<SqlGenerateResponse>(BASE_PATH + '/api/ai/sql/generate', {- prompt,- entityDefinitions,- })-- if (!isResponseOk(response)) {- throw response.error- }-- return response-}--type SqlGenerateData = Awaited<ReturnType<typeof generateSql>>--export const useSqlGenerateMutation = ({- onSuccess,- onError,- ...options-}: Omit<- UseMutationOptions<SqlGenerateData, ResponseError, SqlGenerateVariables>,- 'mutationFn'-> = {}) => {- return useMutation<SqlGenerateData, ResponseError, SqlGenerateVariables>(- (vars) => generateSql(vars),- {- async onSuccess(data, variables, context) {- await onSuccess?.(data, variables, context)- },- async onError(data, variables, context) {- if (onError === undefined) {- toast.error(`Failed to generate SQL: ${data.message}`)- } else {- onError(data, variables, context)- }- },- ...options,- }- )-}diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.tsindex 0e55cf6dc87..9eb40e54dd5 100644--- a/apps/studio/lib/constants/index.ts+++ b/apps/studio/lib/constants/index.ts@@ -34,7 +34,6 @@ export const LOCAL_STORAGE_KEYS = {UI_PREVIEW_API_SIDE_PANEL: 'supabase-ui-api-side-panel',UI_PREVIEW_RLS_AI_ASSISTANT: 'supabase-ui-rls-ai-assistant',UI_PREVIEW_CLS: 'supabase-ui-cls',- UI_PREVIEW_SQL_EDITOR_AI_ASSISTANT: 'supabase-ui-sql-editor-ai-assistant',DASHBOARD_HISTORY: (ref: string) => `dashboard-history-${ref}`,diff --git a/apps/studio/pages/api/ai/sql/edit.ts b/apps/studio/pages/api/ai/sql/edit.tsdeleted file mode 100644index 71714a73994..00000000000--- a/apps/studio/pages/api/ai/sql/edit.ts+++ /dev/null@@ -1,80 +0,0 @@-import { ContextLengthError, EmptySqlError, editSql } from 'ai-commands'-import apiWrapper from 'lib/api/apiWrapper'-import { NextApiRequest, NextApiResponse } from 'next'-import { OpenAI } from 'openai'--const openAiKey = process.env.OPENAI_API_KEY-const openai = new OpenAI({ apiKey: openAiKey })--async function handler(req: NextApiRequest, res: NextApiResponse) {- if (!openAiKey) {- return res.status(500).json({- error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',- })- }-- const { method } = req-- switch (method) {- case 'POST':- return handlePost(req, res)- default:- res.setHeader('Allow', ['POST'])- res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })- }-}--export async function handlePost(req: NextApiRequest, res: NextApiResponse) {- const {- body: { prompt, sql, entityDefinitions },- } = req-- try {- const result = await editSql(openai, prompt, sql, entityDefinitions)- return res.json(result)- } catch (error) {- if (error instanceof Error) {- console.error(`AI SQL editing failed: ${error.message}`)-- const hasEntityDefinitions = entityDefinitions !== undefined && entityDefinitions.length > 0-- if (error instanceof ContextLengthError) {- // If there are more entity definitions than the SQL provided, attribute the- // error to the database metadata- if (hasEntityDefinitions) {- const definitionsLength = entityDefinitions.reduce(- (sum: number, def: string) => sum + def.length,- 0- )- if (definitionsLength > sql.length) {- return res.status(400).json({- error:- 'Your database metadata is too large for Supabase AI to ingest. Try disabling database metadata in AI settings.',- })- }- }- // Otherwise attribute the error to the SQL being too large- return res.status(400).json({- error:- 'Your SQL query is too large for Supabase AI to ingest. Try splitting it into smaller queries.',- })- }-- if (error instanceof EmptySqlError) {- res.status(400).json({- error: 'Unable to edit SQL. Try adding more details to your prompt.',- })- }- } else {- console.log(`Unknown error: ${error}`)- }-- return res.status(500).json({- error: 'There was an unknown error editing the SQL snippet. Please try again.',- })- }-}--const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)--export default wrapperdiff --git a/apps/studio/pages/api/ai/sql/generate.ts b/apps/studio/pages/api/ai/sql/generate.tsdeleted file mode 100644index cd72e8e5d5e..00000000000--- a/apps/studio/pages/api/ai/sql/generate.ts+++ /dev/null@@ -1,65 +0,0 @@-import { ContextLengthError, EmptySqlError, generateSql } from 'ai-commands'-import apiWrapper from 'lib/api/apiWrapper'-import { NextApiRequest, NextApiResponse } from 'next'-import { OpenAI } from 'openai'--const openAiKey = process.env.OPENAI_API_KEY-const openai = new OpenAI({ apiKey: openAiKey })--async function handler(req: NextApiRequest, res: NextApiResponse) {- if (!openAiKey) {- return res.status(500).json({- error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',- })- }-- const { method } = req-- switch (method) {- case 'POST':- return handlePost(req, res)- default:- res.setHeader('Allow', ['POST'])- res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })- }-}--export async function handlePost(req: NextApiRequest, res: NextApiResponse) {- const {- body: { prompt, entityDefinitions },- } = req-- try {- const result = await generateSql(openai, prompt, entityDefinitions)- return res.json(result)- } catch (error) {- if (error instanceof Error) {- console.error(`AI SQL generation failed: ${error.message}`)-- const hasEntityDefinitions = entityDefinitions !== undefined && entityDefinitions.length > 0-- if (error instanceof ContextLengthError && hasEntityDefinitions) {- return res.status(400).json({- error:- 'Your database metadata is too large for Supabase AI to ingest. Try disabling database metadata in AI settings.',- })- }-- if (error instanceof EmptySqlError) {- res.status(400).json({- error: 'Unable to generate SQL. Try adding more details to your prompt.',- })- }- } else {- console.log(`Unknown error: ${error}`)- }-- return res.status(500).json({- error: 'There was an unknown error generating the SQL snippet. Please try again.',- })- }-}--const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)--export default wrapperdiff --git a/packages/ai-commands/src/__snapshots__/sql.test.ts.snap b/packages/ai-commands/src/__snapshots__/sql.test.ts.snapindex ed775186dac..6fc082f6c93 100644--- a/packages/ai-commands/src/__snapshots__/sql.test.ts.snap+++ b/packages/ai-commands/src/__snapshots__/sql.test.ts.snap@@ -21,23 +21,6 @@ fromemployees;"`;-exports[`edit add length constraint 1`] = `-"create table employees (- id bigint primary key generated always as identity,- name text check (length(name) >= 4),- email text-);"-`;--exports[`generate single table with specified columns 1`] = `-"create table employees (- id bigint primary key generated always as identity,- name text,- email text,- position text-);"-`;-exports[`rls chat select policy using table definition 1`] = `{"checkExpression": undefined,diff --git a/packages/ai-commands/src/sql.test.ts b/packages/ai-commands/src/sql.test.tsindex a6f612229aa..24c5ab2f7ed 100644--- a/packages/ai-commands/src/sql.test.ts+++ b/packages/ai-commands/src/sql.test.ts@@ -2,42 +2,12 @@ import { describe, expect, test } from '@jest/globals'import { codeBlock } from 'common-tags'import OpenAI from 'openai'import { collectStream, extractMarkdownSql, formatSql, getPolicyInfo } from '../test/util'-import { debugSql, editSql, generateSql, titleSql } from './sql'+import { debugSql, titleSql } from './sql'import { chatRlsPolicy } from './sql.edge'const openAiKey = process.env.OPENAI_API_KEYconst openai = new OpenAI({ apiKey: openAiKey })-describe('generate', () => {- test('single table with specified columns', async () => {- const { sql, title } = await generateSql(- openai,- 'create a table to track employees with name, email, and position'- )-- expect(formatSql(sql)).toMatchSnapshot()- await expect(title).toMatchCriteria('relates to employees')- })-})--describe('edit', () => {- test('add length constraint', async () => {- const { sql } = await editSql(- openai,- 'force name to be at least 4 characters',- codeBlock`- create table employees (- id bigint primary key generated always as identity,- name text,- email text- );- `- )-- expect(formatSql(sql)).toMatchSnapshot()- })-})-describe('debug', () => {test('fix order of operations', async () => {const { sql } = await debugSql(diff --git a/packages/ai-commands/src/sql.ts b/packages/ai-commands/src/sql.tsindex bd39f633c9a..3b58bdb0e5b 100644--- a/packages/ai-commands/src/sql.ts+++ b/packages/ai-commands/src/sql.ts@@ -4,43 +4,6 @@ import { jsonrepair } from 'jsonrepair'import OpenAI from 'openai'import { ContextLengthError, EmptyResponseError, EmptySqlError } from './errors'-// Declare JSON schema for each function that the LLM can call-const generateSqlSchema = SchemaBuilder.emptySchema()- .addString('sql', {- description: stripIndent`- The generated SQL (must be valid SQL).- - For primary keys, always use "id bigint primary key generated always as identity" (not serial)- - Prefer creating foreign key references in the create statement- - Prefer 'text' over 'varchar'- - Prefer 'timestamp with time zone' over 'date'- - Use vector(384) data type for any embedding/vector related query- - Always use double apostrophe in SQL strings (eg. 'Night''s watch')- - Always use semicolons- `,- })- .addString('title', {- description: stripIndent`- The title of the SQL.- - Omit words like 'SQL', 'Postgres', or 'Query'- `,- })--const editSqlSchema = SchemaBuilder.emptySchema().addString('sql', {- description: stripIndent`- The modified SQL (must be valid SQL).- - Assume the query hasn't been executed yet- - For primary keys, always use "id bigint primary key generated always as identity" (not serial)- - When creating tables, always add foreign key references inline- - Prefer 'text' over 'varchar'- - Prefer 'timestamp with time zone' over 'date'- - Use vector(384) data type for any embedding/vector related query- - Always use double apostrophe in SQL strings (eg. 'Night''s watch')- - Use real examples when possible- - Add constraints if requested- - Always use semicolons- `,-})-const debugSqlSchema = SchemaBuilder.emptySchema().addString('solution', {description: 'A short suggested solution for the error (as concise as possible).',@@ -64,23 +27,11 @@ const generateTitleSchema = SchemaBuilder.emptySchema()})// Reference auto-generated types for each JSON schema-export type GenerateSqlResult = typeof generateSqlSchema.T-export type EditSqlResult = typeof editSqlSchema.Texport type DebugSqlResult = typeof debugSqlSchema.Texport type GenerateTitleResult = typeof generateTitleSchema.T// Combine the completion functionsconst completionFunctions = {- generateSql: {- name: 'generateSql',- description: 'Generates Postgres SQL based on a natural language prompt',- parameters: generateSqlSchema.schema as Record<string, unknown>,- },- editSql: {- name: 'editSql',- description: "Edits a Postgres SQL query based on the user's instructions",- parameters: editSqlSchema.schema as Record<string, unknown>,- },debugSql: {name: 'debugSql',description: stripIndent`@@ -109,164 +60,6 @@ const completionFunctions = {},} satisfies Record<string, OpenAI.Chat.Completions.ChatCompletionCreateParams.Function>-/**- * Generates a SQL snippet based on the provided prompt.- *- * @returns The generated SQL along with a title for it.- */-export async function generateSql(openai: OpenAI, prompt: string, entityDefinitions?: string[]) {- const hasEntityDefinitions = entityDefinitions !== undefined && entityDefinitions.length > 0-- const completionMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []-- if (hasEntityDefinitions) {- completionMessages.push({- role: 'user',- content: codeBlock`- Here is my database schema for reference:- ${entityDefinitions.join('\n\n')}- `,- })- }-- completionMessages.push({- role: 'user',- content: prompt,- })-- try {- const completionResponse = await openai.chat.completions.create({- model: 'gpt-3.5-turbo-0125',- messages: completionMessages,- max_tokens: 1024,- temperature: 0,- tool_choice: {- type: 'function',- function: {- name: completionFunctions.generateSql.name,- },- },- tools: [- {- type: 'function',- function: completionFunctions.generateSql,- },- ],- stream: false,- })-- const [firstChoice] = completionResponse.choices- const [firstTool] = firstChoice.message?.tool_calls ?? []-- const sqlResponseString = firstTool?.function.arguments-- if (!sqlResponseString) {- throw new EmptyResponseError()- }-- const repairedJsonString = jsonrepair(sqlResponseString)-- const result: GenerateSqlResult = JSON.parse(repairedJsonString)-- if (!result.sql) {- throw new EmptySqlError()- }-- return result- } catch (error) {- if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {- throw new ContextLengthError()- }- throw error- }-}--/**- * Modifies a SQL snippet based on the provided prompt.- *- * @returns The modified SQL.- */-export async function editSql(- openai: OpenAI,- prompt: string,- sql: string,- entityDefinitions?: string[]-) {- const hasEntityDefinitions = entityDefinitions !== undefined && entityDefinitions.length > 0-- const completionMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []-- if (hasEntityDefinitions) {- completionMessages.push({- role: 'user',- content: codeBlock`- Here is my database schema for reference:- ${entityDefinitions.join('\n\n')}- `,- })- }-- completionMessages.push(- {- role: 'user',- content: stripIndent`- Here is my current SQL:- ${sql}- `,- },- {- role: 'user',- content: prompt,- }- )-- try {- const completionResponse = await openai.chat.completions.create({- model: 'gpt-3.5-turbo-0125',- messages: completionMessages,- max_tokens: 2048,- temperature: 0,- tool_choice: {- type: 'function',- function: {- name: completionFunctions.editSql.name,- },- },- tools: [- {- type: 'function',- function: completionFunctions.editSql,- },- ],- stream: false,- })-- const [firstChoice] = completionResponse.choices- const [firstTool] = firstChoice.message?.tool_calls ?? []-- const sqlResponseString = firstTool?.function.arguments-- if (!sqlResponseString) {- throw new EmptyResponseError()- }-- const repairedJsonString = jsonrepair(sqlResponseString)-- const result: EditSqlResult = JSON.parse(repairedJsonString)-- if (!result.sql) {- throw new EmptySqlError()- }-- return result- } catch (error) {- if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {- throw new ContextLengthError()- }- throw error- }-}-/*** Debugs SQL errors.*