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): sql ai api

Greg Richardson871eac8ec17c
diff --git a/package-lock.json b/package-lock.json
index f0146dee490..94f69e91d9c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -43433,6 +43433,7 @@
"monaco-editor": "0.33.0",
"next": "^12.3.2",
"next-transpile-modules": "^9.0.0",
+ "openai": "^3.3.0",
"openapi-types": "^12.0.2",
"p-queue": "^6.6.2",
"papaparse": "^5.3.1",
@@ -43807,6 +43808,14 @@
"url": "https://github.com/sponsors/epoberezkin"
}
},
+ "studio/node_modules/axios": {
+ "version": "0.26.1",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz",
+ "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==",
+ "dependencies": {
+ "follow-redirects": "^1.14.8"
+ }
+ },
"studio/node_modules/clsx": {
"version": "1.2.1",
"license": "MIT",
@@ -43924,6 +43933,19 @@
"ramda": "0.29.0"
}
},
+ "studio/node_modules/form-data": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
+ "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"studio/node_modules/fs-extra": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz",
@@ -43978,6 +44000,15 @@
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="
},
+ "studio/node_modules/openai": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/openai/-/openai-3.3.0.tgz",
+ "integrity": "sha512-uqxI/Au+aPRnsaQRe8CojU0eCR7I0mBiKjD3sNMzY6DaC1ZVrc85u98mtJW6voDug8fgGN+DIZmTDxTthxb7dQ==",
+ "dependencies": {
+ "axios": "^0.26.0",
+ "form-data": "^4.0.0"
+ }
+ },
"studio/node_modules/proxy-compare": {
"version": "2.3.0",
"license": "MIT"
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
index a17307cfde5..9454fa6e158 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
@@ -4,6 +4,7 @@ import { observer } from 'mobx-react-lite'
import { useParams, useTelemetryProps } from 'common'
import { SQL_TEMPLATES } 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'
import { useCheckPermissions, useStore } from 'hooks'
@@ -22,6 +23,7 @@ const SQLTemplates = observer(() => {
const router = useRouter()
const { profile } = useProfile()
const [sql, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
+ const { mutateAsync: generateSql, isLoading: isSqlGenerateLoading } = useSqlGenerateMutation()
const telemetryProps = useTelemetryProps()
const snap = useSqlEditorStateSnapshot()
@@ -78,6 +80,13 @@ const SQLTemplates = observer(() => {
iconContainerClassName="transition text-scale-800 text-brand-900"
placeholder="Ask Supabase AI to build a query"
className="w-full max-w-2xl"
+ onKeyPress={async (e) => {
+ if (e.key === 'Enter') {
+ const { sql, title } = await generateSql({ prompt: e.currentTarget.value })
+
+ await handleNewQuery(sql, title)
+ }
+ }}
actions={
<div className="flex items-center space-x-1 mr-6">
<IconCornerDownLeft size={16} strokeWidth={1.5} />
@@ -85,6 +94,7 @@ const SQLTemplates = observer(() => {
}
/>
</motion.div>
+ {isSqlGenerateLoading && <motion.div className="mt-4">Loading...</motion.div>}
</div>
<div>
<div className="mb-4">
diff --git a/studio/data/ai/keys.ts b/studio/data/ai/keys.ts
new file mode 100644
index 00000000000..21baabc0d0a
--- /dev/null
+++ b/studio/data/ai/keys.ts
@@ -0,0 +1,3 @@
+export const aiKeys = {
+ sql: () => ['sql'] as const,
+}
diff --git a/studio/data/ai/sql-generate-mutation.ts b/studio/data/ai/sql-generate-mutation.ts
new file mode 100644
index 00000000000..af25bd2f7f3
--- /dev/null
+++ b/studio/data/ai/sql-generate-mutation.ts
@@ -0,0 +1,39 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { aiKeys } from './keys'
+
+export type SqlGenerateResponse = {
+ sql: string
+ title: string
+}
+
+export type SqlGenerateVariables = {
+ prompt: string
+}
+
+export async function generateSql({ prompt }: SqlGenerateVariables) {
+ const response = await post<SqlGenerateResponse>('/api/ai/sql', { prompt })
+ if ('error' in response) {
+ throw response.error
+ }
+
+ return response
+}
+
+type SqlGenerateData = Awaited<ReturnType<typeof generateSql>>
+
+export const useSqlGenerateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<UseMutationOptions<SqlGenerateData, unknown, SqlGenerateVariables>, 'mutationFn'> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<SqlGenerateData, unknown, SqlGenerateVariables>((vars) => generateSql(vars), {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(aiKeys.sql())
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/studio/package.json b/studio/package.json
index f8ce2b18691..563c588ec35 100644
--- a/studio/package.json
+++ b/studio/package.json
@@ -66,6 +66,7 @@
"monaco-editor": "0.33.0",
"next": "^12.3.2",
"next-transpile-modules": "^9.0.0",
+ "openai": "^3.3.0",
"openapi-types": "^12.0.2",
"p-queue": "^6.6.2",
"papaparse": "^5.3.1",
diff --git a/studio/pages/api/ai/sql.ts b/studio/pages/api/ai/sql.ts
new file mode 100644
index 00000000000..b39b2384236
--- /dev/null
+++ b/studio/pages/api/ai/sql.ts
@@ -0,0 +1,92 @@
+import { stripIndent } from 'common-tags'
+import { NextRequest } from 'next/server'
+import type {
+ ChatCompletionRequestMessage,
+ CreateChatCompletionRequest,
+ CreateChatCompletionResponse,
+} from 'openai'
+
+export const config = {
+ runtime: 'experimental-edge',
+}
+
+const openAiKey = process.env.OPENAI_KEY
+
+export default async function handler(req: NextRequest) {
+ const { prompt } = await req.json()
+
+ const model = 'gpt-3.5-turbo-0613'
+ const maxCompletionTokenCount = 1024
+
+ const completionMessages: ChatCompletionRequestMessage[] = [
+ {
+ role: 'user',
+ content: stripIndent`
+ Natural language prompt:
+ ${prompt}
+ `,
+ },
+ ]
+
+ const completionOptions: CreateChatCompletionRequest = {
+ model,
+ messages: completionMessages,
+ max_tokens: maxCompletionTokenCount,
+ temperature: 0,
+ function_call: {
+ name: 'generateSql',
+ },
+ functions: [
+ {
+ name: 'generateSql',
+ description: 'Generates Postgres SQL based on a natural language prompt',
+ parameters: {
+ type: 'object',
+ properties: {
+ sql: {
+ type: 'string',
+ description: stripIndent`
+ The generated SQL.
+ - For primary keys, prefer "id" and always use "bigint primary key generated always as identity"
+ `,
+ },
+ title: {
+ type: 'string',
+ description: stripIndent`
+ The title of the SQL.
+ - Omit words like 'SQL', 'Postgres', or 'query'
+ `,
+ },
+ },
+ required: ['sql', 'title'],
+ },
+ },
+ ],
+ stream: false,
+ }
+
+ 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),
+ })
+
+ const result: CreateChatCompletionResponse = await response.json()
+
+ console.log(result)
+
+ const [firstChoice] = result.choices
+
+ const sqlResponseString = firstChoice.message?.function_call?.arguments
+
+ const sqlResponse = sqlResponseString ? JSON.parse(sqlResponseString) : undefined
+
+ return new Response(JSON.stringify(sqlResponse), {
+ headers: {
+ 'content-type': 'application/json',
+ },
+ })
+}