Skip to content

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

feat(sql-editor): edit sql using ai

Greg Richardsond7d79ef19d3c
diff --git a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index 512c0a02f30..fb473156bbf 100644
--- a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -12,6 +12,7 @@ export type MonacoEditorProps = {
id: string
editorRef: MutableRefObject<IStandaloneCodeEditor | null>
isExecuting: boolean
+ autoFocus?: boolean
executeQuery: () => void
onOpenAiWidget?: () => void
onCloseAiWidget?: () => void
@@ -21,6 +22,7 @@ const MonacoEditor = ({
id,
editorRef,
isExecuting,
+ autoFocus = true,
executeQuery,
onOpenAiWidget,
onCloseAiWidget,
@@ -84,9 +86,10 @@ const MonacoEditor = ({
})
})
- // when editor did mount, it will need a delay before focus() works properly
- await timeout(500)
- editor.focus()
+ if (autoFocus) {
+ await timeout(500)
+ editor.focus()
+ }
}
useEffect(() => {
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
index 77ebefd4d13..5696fe910da 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
@@ -1,3 +1,4 @@
+import { stripIndent } from 'common-tags'
import { SqlSnippets, UserContent } from 'types'
import { SQLTemplate } from './SQLEditor.types'
@@ -1201,3 +1202,8 @@ export const NEW_SQL_SNIPPET_SKELETON: UserContent<SqlSnippets.Content> = {
favorite: false,
},
}
+
+export const sqlAiDisclaimerComment = stripIndent`
+ -- Supabase AI is experimental and may produce incorrect answers
+ -- Always verify the output before executing
+`
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 2afa088ce9b..696b240d91e 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -1,19 +1,26 @@
import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSqlEditMutation } from 'data/ai/sql-edit-mutation'
import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import { motion } from 'framer-motion'
-import { useLocalStorage } from 'hooks'
+import { useLocalStorage, useStore } from 'hooks'
import useLatest from 'hooks/misc/useLatest'
import dynamic from 'next/dynamic'
-import { useCallback, useRef, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import Split from 'react-split'
+import { format } from 'sql-formatter'
import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'
-import { AiIcon, IconCornerDownLeft, Input } from 'ui'
+import { AiIcon, Button, IconCheck, IconCornerDownLeft, IconX, Input, cn } from 'ui'
import type { IStandaloneCodeEditor } from './MonacoEditor'
+import { sqlAiDisclaimerComment } from './SQLEditor.constants'
import UtilityPanel from './UtilityPanel/UtilityPanel'
// Load the monaco editor client-side only (does not behave well server-side)
const MonacoEditor = dynamic(() => import('./MonacoEditor'), { ssr: false })
+const DiffEditor = dynamic(
+ () => import('@monaco-editor/react').then(({ DiffEditor }) => DiffEditor),
+ { ssr: false }
+)
const OptionIcon = () => {
return (
@@ -29,10 +36,22 @@ const OptionIcon = () => {
)
}
+type ContentDiff = {
+ original: string
+ modified: string
+}
+
const SQLEditor = () => {
+ const { ui } = useStore()
const { ref, id } = useParams()
const { project } = useProjectContext()
const snap = useSqlEditorStateSnapshot()
+ const { mutateAsync: editSql, isLoading: isEditSqlLoading } = useSqlEditMutation()
+ const [aiInput, setAiInput] = useState('')
+ const [sqlDiff, setSqlDiff] = useState<ContentDiff>()
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ const isDiffOpen = !!sqlDiff
const [savedSplitSize, setSavedSplitSize] = useLocalStorage(
'supabase_sql-editor-split-size',
@@ -68,6 +87,10 @@ const SQLEditor = () => {
const editorRef = useRef<IStandaloneCodeEditor | null>(null)
const executeQuery = useCallback(() => {
+ if (isDiffOpen) {
+ return
+ }
+
// use the latest state
const state = getSqlEditorStateSnapshot()
const snippet = idRef.current && state.snippets[idRef.current]
@@ -84,14 +107,69 @@ const SQLEditor = () => {
sql: overrideSql ?? snippet.snippet.content.sql,
})
}
- }, [isExecuting, project])
+ }, [isExecuting, isDiffOpen, execute, project])
+
+ const acceptAiHandler = useCallback(() => {
+ if (!sqlDiff) {
+ return
+ }
+
+ // TODO: show error if undefined
+ if (id && editorRef.current) {
+ const editorModel = editorRef.current.getModel()
+
+ if (!editorModel) {
+ return
+ }
- const [isAiWidgetOpen, setIsAiWidgetOpen] = useState(false)
+ editorRef.current.executeEdits('apply-ai-edit', [
+ {
+ text: sqlDiff.modified,
+ range: editorModel.getFullModelRange(),
+ },
+ ])
+
+ setAiInput('')
+ setSqlDiff(undefined)
+ setTimeout(() => {
+ inputRef.current?.focus()
+ }, 0)
+ }
+ }, [sqlDiff, id])
+
+ const discardAiHandler = useCallback(() => {
+ setSqlDiff(undefined)
+ setTimeout(() => {
+ inputRef.current?.focus()
+ }, 0)
+ }, [])
+
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (!isDiffOpen) {
+ return
+ }
+
+ switch (e.key) {
+ case 'Enter':
+ acceptAiHandler()
+ return
+ case 'Escape':
+ discardAiHandler()
+ return
+ }
+ }
+
+ window.addEventListener('keydown', handler)
+
+ return () => window.removeEventListener('keydown', handler)
+ }, [isDiffOpen, acceptAiHandler, discardAiHandler])
return (
<div className="flex h-full flex-col">
- {!isAiWidgetOpen && (
+ {!isEditSqlLoading ? (
<motion.div
+ key="ask-ai-input"
layoutId="ask-ai-input"
initial={{
scaleY: 1,
@@ -103,23 +181,156 @@ const SQLEditor = () => {
y: 0,
borderRadius: 0,
}}
- className="w-full flex justify-center z-[1000] mt-0.5 border border-brand-900"
+ className="w-full flex justify-center z-[1000] mt-0.5 bg-brand-400"
>
<Input
autoFocus
size="xlarge"
- icon={<AiIcon className="w-4 h-4 ml-1" />}
- inputClassName="w-full !border-brand-900 border-none py-4 focus:!ring-0"
+ value={aiInput}
+ onChange={(e) => setAiInput(e.currentTarget.value)}
+ disabled={isDiffOpen}
+ inputRef={inputRef}
+ icon={
+ <motion.div
+ key="ask-ai-input-icon"
+ layoutId="ask-ai-input-icon"
+ className="ml-1"
+ initial={{
+ rotate: 0,
+ }}
+ animate={{
+ rotate: 0,
+ }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </motion.div>
+ }
+ inputClassName="w-full !border-brand-900 border-none py-4 focus:!ring-0 placeholder:text-scale-900"
iconContainerClassName="transition text-scale-800 text-brand-900"
placeholder="Ask Supabase AI to modify your query"
className="w-full"
actions={
- <div className="flex items-center space-x-1 mr-6">
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
+ <div className="flex flex-row items-center gap-2 space-x-1 mr-6">
+ {isDiffOpen ? (
+ <>
+ <Button
+ type="primary"
+ size="tiny"
+ icon={<IconCheck />}
+ iconRight={
+ <div className="opacity-30">
+ <IconCornerDownLeft size={12} strokeWidth={1.5} />
+ </div>
+ }
+ onClick={acceptAiHandler}
+ >
+ Accept
+ </Button>
+ <Button
+ type="alternative"
+ size="tiny"
+ icon={<IconX />}
+ iconRight={<span className="opacity-30">ESC</span>}
+ onClick={discardAiHandler}
+ >
+ Discard
+ </Button>
+ </>
+ ) : (
+ <IconCornerDownLeft size={16} strokeWidth={1.5} />
+ )}
</div>
}
+ onKeyPress={async (e) => {
+ if (e.key === 'Enter') {
+ try {
+ const prompt = e.currentTarget.value
+
+ console.log({ prompt })
+
+ if (!prompt) {
+ return
+ }
+
+ const sql = editorRef.current?.getValue()
+
+ if (!sql) {
+ return
+ }
+
+ const { sql: modifiedSql } = await editSql({
+ prompt,
+ sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
+ })
+
+ const formattedSql =
+ sqlAiDisclaimerComment +
+ '\n\n' +
+ format(modifiedSql, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+
+ // TODO: show error
+ if (formattedSql.trim() === sql.trim()) {
+ return
+ }
+
+ setSqlDiff({
+ original: sql,
+ modified: formattedSql,
+ })
+ } catch (error: unknown) {
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ ) {
+ ui.setNotification({
+ category: 'error',
+ message: error.message,
+ })
+ }
+ }
+ }
+ }}
/>
</motion.div>
+ ) : (
+ <motion.div
+ key="ask-ai-loading"
+ layoutId="ask-ai-input"
+ className="w-fit p-5 border border-brand-900 text-brand-900 self-center"
+ initial={{
+ borderRadius: 50,
+ }}
+ animate={{
+ borderRadius: 50,
+ }}
+ transition={{
+ type: 'spring',
+ mass: 0.1,
+ stiffness: 200,
+ damping: 30,
+ }}
+ >
+ <motion.div
+ key="ask-ai-loading-icon"
+ layoutId="ask-ai-input-icon"
+ animate={{
+ rotate: 360,
+ transition: {
+ delay: 0.2,
+ ease: 'linear',
+ duration: 2,
+ repeat: Infinity,
+ },
+ }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </motion.div>
+ </motion.div>
)}
<Split
style={{ height: '100%' }}
@@ -133,7 +344,6 @@ const SQLEditor = () => {
onDragEnd={onDragEnd}
>
<motion.div
- layout="position"
className="dark:border-dark flex-grow overflow-y-auto border-b"
initial={{
opacity: 0,
@@ -150,21 +360,59 @@ const SQLEditor = () => {
{isLoading ? (
<div className="flex h-full w-full items-center justify-center">Loading...</div>
) : (
- <MonacoEditor
- id={id}
- editorRef={editorRef}
- isExecuting={isExecuting}
- executeQuery={executeQuery}
- onOpenAiWidget={() => setIsAiWidgetOpen(true)}
- onCloseAiWidget={() => setIsAiWidgetOpen(false)}
- />
+ <>
+ {isDiffOpen && (
+ <motion.div
+ key="diff-editor"
+ className="w-full h-full"
+ initial={{
+ opacity: 0,
+ filter: 'blur(10px)',
+ }}
+ animate={{
+ opacity: 1,
+ filter: 'blur(0px)',
+ }}
+ >
+ <DiffEditor
+ theme="supabase"
+ language="pgsql"
+ original={sqlDiff.original}
+ modified={sqlDiff.modified}
+ options={{
+ fontSize: 13,
+ }}
+ />
+ </motion.div>
+ )}
+
+ <motion.div
+ key="monaco-editor"
+ className={cn('w-full', 'h-full', isDiffOpen && 'invisible')}
+ >
+ <MonacoEditor
+ id={id}
+ editorRef={editorRef}
+ isExecuting={isExecuting}
+ autoFocus={false}
+ executeQuery={executeQuery}
+ // onOpenAiWidget={() => setIsAiWidgetOpen(true)}
+ // onCloseAiWidget={() => setIsAiWidgetOpen(false)}
+ />
+ </motion.div>
+ </>
)}
</motion.div>
<div className="flex flex-col">
{isLoading ? (
<div className="flex h-full w-full items-center justify-center">Loading...</div>
) : (
- <UtilityPanel id={id} isExecuting={isExecuting} executeQuery={executeQuery} />
+ <UtilityPanel
+ id={id}
+ isExecuting={isExecuting}
+ isDisabled={isDiffOpen}
+ executeQuery={executeQuery}
+ />
)}
</div>
</Split>
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
index e5191a67c69..a2b54e78be8 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
@@ -4,7 +4,10 @@ import { observer } from 'mobx-react-lite'
import { useParams, useTelemetryProps } from 'common'
import { stripIndent } from 'common-tags'
-import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.constants'
+import {
+ SQL_TEMPLATES,
+ sqlAiDisclaimerComment,
+} from 'components/interfaces/SQLEditor/SQLEditor.constants'
import { useSqlGenerateMutation } from 'data/ai/sql-generate-mutation'
import { SqlSnippet } from 'data/content/sql-snippets-query'
import { motion } from 'framer-motion'
@@ -19,11 +22,6 @@ import { AiIcon, IconCornerDownLeft, Input } from 'ui'
import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
import SQLCard from './SQLCard'
-const sqlDisclaimerComment = stripIndent`
- -- Supabase AI is experimental and may produce incorrect answers
- -- Always verify the output before executing
-`
-
const SQLTemplates = observer(() => {
const { ui } = useStore()
const { ref } = useParams()
@@ -128,7 +126,7 @@ const SQLTemplates = observer(() => {
const { title, sql } = await generateSql({ prompt: e.currentTarget.value })
const formattedSql =
- sqlDisclaimerComment +
+ sqlAiDisclaimerComment +
'\n\n' +
format(sql, {
language: 'postgresql',
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index 684046cf877..defe3266ed7 100644
--- a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -8,10 +8,16 @@ import { detectOS } from 'lib/helpers'
export type UtilityActionsProps = {
id: string
isExecuting?: boolean
+ isDisabled?: boolean
executeQuery: () => void
}
-const UtilityActions = ({ id, isExecuting = false, executeQuery }: UtilityActionsProps) => {
+const UtilityActions = ({
+ id,
+ isExecuting = false,
+ isDisabled = false,
+ executeQuery,
+}: UtilityActionsProps) => {
const os = detectOS()
return (
@@ -21,7 +27,7 @@ const UtilityActions = ({ id, isExecuting = false, executeQuery }: UtilityAction
<SizeToggleButton id={id} />
<Button
onClick={() => executeQuery()}
- disabled={isExecuting}
+ disabled={isDisabled}
loading={isExecuting}
type="default"
size="tiny"
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
index 3cd087502f9..a01d84445f2 100644
--- a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
@@ -5,17 +5,23 @@ import UtilityTabResults from './UtilityTabResults'
export type UtilityPanelProps = {
id: string
isExecuting?: boolean
+ isDisabled?: boolean
executeQuery: () => void
}
-const UtilityPanel = ({ id, isExecuting, executeQuery }: UtilityPanelProps) => {
+const UtilityPanel = ({ id, isExecuting, isDisabled, executeQuery }: UtilityPanelProps) => {
return (
<>
<div className="flex justify-between overflow-visible px-6 py-2">
<ResultsDropdown id={id} />
<div className="inline-flex items-center justify-end">
- <UtilityActions id={id} isExecuting={isExecuting} executeQuery={executeQuery} />
+ <UtilityActions
+ id={id}
+ isExecuting={isExecuting}
+ isDisabled={isDisabled}
+ executeQuery={executeQuery}
+ />
</div>
</div>
diff --git a/studio/data/ai/sql-edit-mutation.ts b/studio/data/ai/sql-edit-mutation.ts
new file mode 100644
index 00000000000..47833c40d35
--- /dev/null
+++ b/studio/data/ai/sql-edit-mutation.ts
@@ -0,0 +1,43 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { ResponseFailure } from 'types'
+import { aiKeys } from './keys'
+
+export type SqlEditResponse = {
+ sql: string
+}
+
+export type SqlEditVariables = {
+ prompt: string
+ sql: string
+}
+
+export async function editSql({ prompt, sql }: SqlEditVariables) {
+ const response = (await post<SqlEditResponse>('/api/ai/sql/edit', { prompt, sql })) as
+ | SqlEditResponse
+ | ResponseFailure
+
+ if ('error' in response) {
+ throw response.error
+ }
+
+ return response
+}
+
+type SqlEditData = Awaited<ReturnType<typeof editSql>>
+
+export const useSqlEditMutation = ({
+ onSuccess,
+ ...options
+}: Omit<UseMutationOptions<SqlEditData, unknown, SqlEditVariables>, 'mutationFn'> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<SqlEditData, unknown, SqlEditVariables>((vars) => editSql(vars), {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(aiKeys.sql())
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/studio/data/ai/sql-generate-mutation.ts b/studio/data/ai/sql-generate-mutation.ts
index c763f44b163..62188df44ee 100644
--- a/studio/data/ai/sql-generate-mutation.ts
+++ b/studio/data/ai/sql-generate-mutation.ts
@@ -1,5 +1,6 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { post } from 'lib/common/fetch'
+import { ResponseFailure } from 'types'
import { aiKeys } from './keys'
export type SqlGenerateResponse = {
@@ -12,7 +13,10 @@ export type SqlGenerateVariables = {
}
export async function generateSql({ prompt }: SqlGenerateVariables) {
- const response = await post<SqlGenerateResponse>('/api/ai/sql', { prompt })
+ const response = (await post<SqlGenerateResponse>('/api/ai/sql/generate', { prompt })) as
+ | SqlGenerateResponse
+ | ResponseFailure
+
if ('error' in response) {
throw response.error
}
diff --git a/studio/pages/api/ai/sql/edit.ts b/studio/pages/api/ai/sql/edit.ts
new file mode 100644
index 00000000000..3172dba054e
--- /dev/null
+++ b/studio/pages/api/ai/sql/edit.ts
@@ -0,0 +1,172 @@
+import { SchemaBuilder } from '@serafin/schema-builder'
+import { stripIndent } from 'common-tags'
+import { NextRequest } from 'next/server'
+import type {
+ ChatCompletionRequestMessage,
+ CreateChatCompletionRequest,
+ CreateChatCompletionResponse,
+ ErrorResponse,
+} from 'openai'
+
+export const config = {
+ runtime: 'experimental-edge',
+}
+
+const openAiKey = process.env.OPENAI_KEY
+
+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)
+ - 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')
+ `,
+})
+
+type EditSqlResult = typeof editSqlSchema.T
+
+const completionFunctions = {
+ editSql: {
+ name: 'editSql',
+ description: "Edits a Postgres SQL query based on the user's instructions",
+ parameters: editSqlSchema.schema,
+ },
+}
+
+export default async function handler(req: NextRequest) {
+ const { prompt, sql } = await req.json()
+
+ const model = 'gpt-3.5-turbo-0613'
+ const maxCompletionTokenCount = 2048
+
+ const completionMessages: ChatCompletionRequestMessage[] = [
+ {
+ role: 'user',
+ content: stripIndent`
+ Here is my current SQL:
+ ${sql}
+ `,
+ },
+ // {
+ // role: 'user',
+ // content: stripIndent`
+ // Add to the above SQL using the following instructions:
+ // ${prompt}
+ // `,
+ // },
+ {
+ role: 'user',
+ content: prompt,
+ },
+ ]
+
+ const completionOptions: CreateChatCompletionRequest = {
+ model,
+ messages: completionMessages,
+ max_tokens: maxCompletionTokenCount,
+ temperature: 0,
+ function_call: {
+ name: completionFunctions.editSql.name,
+ },
+ functions: [completionFunctions.editSql],
+ stream: false,
+ }
+
+ console.log({ sql, prompt, completionMessages })
+
+ // await new Promise((resolve) => setTimeout(resolve, 1000))
+
+ // return new Response(
+ // JSON.stringify({
+ // error: 'There was an unknown error editing the SQL snippet. Please try again.',
+ // }),
+ // {
+ // status: 500,
+ // headers: {
+ // 'content-type': 'application/json',
+ // },
+ // }
+ // )
+
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
+ headers: {
+ Authorization: `Bearer ${openAiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ body: JSON.stringify(completionOptions),
+ })
+
+ if (!response.ok) {
+ const errorResponse: ErrorResponse = await response.json()
+ console.error(`AI SQL editing failed: ${errorResponse.error.message}`)
+
+ return new Response(
+ JSON.stringify({
+ error: 'There was an unknown error editing the SQL snippet. Please try again.',
+ }),
+ {
+ status: 500,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ const completionResponse: CreateChatCompletionResponse = await response.json()
+
+ console.log(completionResponse)
+
+ const [firstChoice] = completionResponse.choices
+
+ const sqlResponseString = firstChoice.message?.function_call?.arguments
+
+ if (!sqlResponseString) {
+ console.error(
+ `AI SQL editing failed: OpenAI response succeeded, but response format was incorrect`
+ )
+
+ return new Response(
+ JSON.stringify({
+ error: 'There was an unknown error editing the SQL snippet. Please try again.',
+ }),
+ {
+ status: 500,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ console.log({ sqlResponseString })
+
+ const editSqlResult: EditSqlResult = JSON.parse(sqlResponseString)
+
+ if (!editSqlResult.sql) {
+ console.error(`AI SQL editing failed: Unable to edit SQL for the given prompt`)
+
+ return new Response(
+ JSON.stringify({
+ error: 'Unable to edit SQL. Try adding more details to your prompt.',
+ }),
+ {
+ status: 400,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ return new Response(JSON.stringify(editSqlResult), {
+ headers: {
+ 'content-type': 'application/json',
+ },
+ })
+}
diff --git a/studio/pages/api/ai/sql.ts b/studio/pages/api/ai/sql/generate.ts
similarity index 88%
rename from studio/pages/api/ai/sql.ts
rename to studio/pages/api/ai/sql/generate.ts
index 608071ab171..22d4e5b9cf8 100644
--- a/studio/pages/api/ai/sql.ts
+++ b/studio/pages/api/ai/sql/generate.ts
@@ -17,13 +17,13 @@ const openAiKey = process.env.OPENAI_KEY
const generateSqlSchema = SchemaBuilder.emptySchema()
.addString('sql', {
description: stripIndent`
- The generated SQL.
+ 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
- - Must be valid SQL syntax
+ - Always use double apostrophe in SQL strings (eg. 'Night''s watch')
`,
})
.addString('title', {
@@ -52,10 +52,7 @@ export default async function handler(req: NextRequest) {
const completionMessages: ChatCompletionRequestMessage[] = [
{
role: 'user',
- content: stripIndent`
- Natural language prompt:
- ${prompt}
- `,
+ content: prompt,
},
]
@@ -71,6 +68,20 @@ export default async function handler(req: NextRequest) {
stream: false,
}
+ // await new Promise((resolve) => setTimeout(resolve, 1000))
+
+ // return new Response(
+ // JSON.stringify({
+ // error: 'There was an unknown error generating the SQL snippet. Please try again.',
+ // }),
+ // {
+ // status: 500,
+ // headers: {
+ // 'content-type': 'application/json',
+ // },
+ // }
+ // )
+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
headers: {
Authorization: `Bearer ${openAiKey}`,