Skip to content

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

fix(sql-editor): switch ai routes to node runtime

Greg Richardson08654e349f2a
diff --git a/studio/pages/api/ai/sql/debug.ts b/studio/pages/api/ai/sql/debug.ts
index 1c34f5a5c08..8338faf228b 100644
--- a/studio/pages/api/ai/sql/debug.ts
+++ b/studio/pages/api/ai/sql/debug.ts
@@ -1,6 +1,7 @@
import { SchemaBuilder } from '@serafin/schema-builder'
import { stripIndent } from 'common-tags'
-import { NextRequest } from 'next/server'
+import apiWrapper from 'lib/api/apiWrapper'
+import { NextApiRequest, NextApiResponse } from 'next'
import type {
ChatCompletionRequestMessage,
CreateChatCompletionRequest,
@@ -8,10 +9,6 @@ import type {
ErrorResponse,
} from 'openai'
-export const config = {
- runtime: 'experimental-edge',
-}
-
const openAiKey = process.env.OPENAI_KEY
const debugSqlSchema = SchemaBuilder.emptySchema()
@@ -35,8 +32,28 @@ const completionFunctions = {
},
}
-export default async function handler(req: NextRequest) {
- const { errorMessage, sql } = await req.json()
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return res.status(500).json({
+ error: 'No OPENAI_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: { errorMessage, sql },
+ } = req
const model = 'gpt-3.5-turbo-0613'
const maxCompletionTokenCount = 2048
@@ -86,17 +103,9 @@ export default async function handler(req: NextRequest) {
console.log({ errorResponse })
console.error(`AI SQL debugging failed: ${errorResponse.error.message}`)
- return new Response(
- JSON.stringify({
- error: 'There was an unknown error debugging the SQL snippet. Please try again.',
- }),
- {
- status: 500,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error debugging the SQL snippet. Please try again.',
+ })
}
const completionResponse: CreateChatCompletionResponse = await response.json()
@@ -112,17 +121,9 @@ export default async function handler(req: NextRequest) {
`AI SQL debugging failed: OpenAI response succeeded, but response format was incorrect`
)
- return new Response(
- JSON.stringify({
- error: 'There was an unknown error debugging the SQL snippet. Please try again.',
- }),
- {
- status: 500,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error debugging the SQL snippet. Please try again.',
+ })
}
console.log({ sqlResponseString })
@@ -132,22 +133,14 @@ export default async function handler(req: NextRequest) {
if (!debugSqlResult.sql) {
console.error(`AI SQL debugging failed: Unable to debug SQL for the given error message`)
- return new Response(
- JSON.stringify({
- error: 'Unable to debug SQL',
- }),
- {
- status: 400,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ return res.status(400).json({
+ error: 'Unable to debug SQL',
+ })
}
- return new Response(JSON.stringify(debugSqlResult), {
- headers: {
- 'content-type': 'application/json',
- },
- })
+ return res.json(debugSqlResult)
}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default wrapper
diff --git a/studio/pages/api/ai/sql/edit.ts b/studio/pages/api/ai/sql/edit.ts
index e0299f72526..111e28c675a 100644
--- a/studio/pages/api/ai/sql/edit.ts
+++ b/studio/pages/api/ai/sql/edit.ts
@@ -1,6 +1,7 @@
import { SchemaBuilder } from '@serafin/schema-builder'
import { stripIndent } from 'common-tags'
-import { NextRequest } from 'next/server'
+import apiWrapper from 'lib/api/apiWrapper'
+import { NextApiRequest, NextApiResponse } from 'next'
import type {
ChatCompletionRequestMessage,
CreateChatCompletionRequest,
@@ -8,10 +9,6 @@ import type {
ErrorResponse,
} from 'openai'
-export const config = {
- runtime: 'experimental-edge',
-}
-
const openAiKey = process.env.OPENAI_KEY
const editSqlSchema = SchemaBuilder.emptySchema().addString('sql', {
@@ -37,8 +34,28 @@ const completionFunctions = {
},
}
-export default async function handler(req: NextRequest) {
- const { prompt, sql } = await req.json()
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return res.status(500).json({
+ error: 'No OPENAI_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 },
+ } = req
const model = 'gpt-3.5-turbo-0613'
const maxCompletionTokenCount = 2048
@@ -51,13 +68,6 @@ export default async function handler(req: NextRequest) {
${sql}
`,
},
- // {
- // role: 'user',
- // content: stripIndent`
- // Add to the above SQL using the following instructions:
- // ${prompt}
- // `,
- // },
{
role: 'user',
content: prompt,
@@ -78,20 +88,6 @@ export default async function handler(req: NextRequest) {
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}`,
@@ -105,17 +101,9 @@ export default async function handler(req: NextRequest) {
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',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error editing the SQL snippet. Please try again.',
+ })
}
const completionResponse: CreateChatCompletionResponse = await response.json()
@@ -131,17 +119,9 @@ export default async function handler(req: NextRequest) {
`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',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error editing the SQL snippet. Please try again.',
+ })
}
console.log({ sqlResponseString })
@@ -151,22 +131,14 @@ export default async function handler(req: NextRequest) {
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 res.status(400).json({
+ error: 'Unable to edit SQL. Try adding more details to your prompt.',
+ })
}
- return new Response(JSON.stringify(editSqlResult), {
- headers: {
- 'content-type': 'application/json',
- },
- })
+ return res.json(editSqlResult)
}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default wrapper
diff --git a/studio/pages/api/ai/sql/generate.ts b/studio/pages/api/ai/sql/generate.ts
index 22d4e5b9cf8..3318e5e23ee 100644
--- a/studio/pages/api/ai/sql/generate.ts
+++ b/studio/pages/api/ai/sql/generate.ts
@@ -1,6 +1,7 @@
import { SchemaBuilder } from '@serafin/schema-builder'
import { stripIndent } from 'common-tags'
-import { NextRequest } from 'next/server'
+import apiWrapper from 'lib/api/apiWrapper'
+import { NextApiRequest, NextApiResponse } from 'next'
import type {
ChatCompletionRequestMessage,
CreateChatCompletionRequest,
@@ -8,10 +9,6 @@ import type {
ErrorResponse,
} from 'openai'
-export const config = {
- runtime: 'experimental-edge',
-}
-
const openAiKey = process.env.OPENAI_KEY
const generateSqlSchema = SchemaBuilder.emptySchema()
@@ -43,8 +40,28 @@ const completionFunctions = {
},
}
-export default async function handler(req: NextRequest) {
- const { prompt } = await req.json()
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return res.status(500).json({
+ error: 'No OPENAI_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 },
+ } = req
const model = 'gpt-3.5-turbo-0613'
const maxCompletionTokenCount = 1024
@@ -68,20 +85,6 @@ 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}`,
@@ -95,17 +98,9 @@ export default async function handler(req: NextRequest) {
const errorResponse: ErrorResponse = await response.json()
console.error(`AI SQL generation failed: ${errorResponse.error.message}`)
- 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',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error generating the SQL snippet. Please try again.',
+ })
}
const completionResponse: CreateChatCompletionResponse = await response.json()
@@ -121,17 +116,9 @@ export default async function handler(req: NextRequest) {
`AI SQL generation failed: OpenAI response succeeded, but response format was incorrect`
)
- 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',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error generating the SQL snippet. Please try again.',
+ })
}
const generateSqlResult: GenerateSqlResult = JSON.parse(sqlResponseString)
@@ -139,22 +126,16 @@ export default async function handler(req: NextRequest) {
if (!generateSqlResult.sql) {
console.error(`AI SQL generation failed: Unable to generate SQL for the given prompt`)
- return new Response(
- JSON.stringify({
- error: 'Unable to generate SQL. Try adding more details to your prompt.',
- }),
- {
- status: 400,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ res.status(400).json({
+ error: 'Unable to generate SQL. Try adding more details to your prompt.',
+ })
+
+ return
}
- return new Response(JSON.stringify(generateSqlResult), {
- headers: {
- 'content-type': 'application/json',
- },
- })
+ return res.json(generateSqlResult)
}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default wrapper
diff --git a/studio/pages/api/ai/sql/title.ts b/studio/pages/api/ai/sql/title.ts
index 25b4241f7b3..c419d7063b7 100644
--- a/studio/pages/api/ai/sql/title.ts
+++ b/studio/pages/api/ai/sql/title.ts
@@ -1,6 +1,7 @@
import { SchemaBuilder } from '@serafin/schema-builder'
import { stripIndent } from 'common-tags'
-import { NextRequest } from 'next/server'
+import apiWrapper from 'lib/api/apiWrapper'
+import { NextApiRequest, NextApiResponse } from 'next'
import type {
ChatCompletionRequestMessage,
CreateChatCompletionRequest,
@@ -8,10 +9,6 @@ import type {
ErrorResponse,
} from 'openai'
-export const config = {
- runtime: 'experimental-edge',
-}
-
const openAiKey = process.env.OPENAI_KEY
const generateTitleSchema = SchemaBuilder.emptySchema()
@@ -38,8 +35,28 @@ const completionFunctions = {
},
}
-export default async function handler(req: NextRequest) {
- const { sql } = await req.json()
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return res.status(500).json({
+ error: 'No OPENAI_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: { sql },
+ } = req
const model = 'gpt-3.5-turbo-0613'
const maxCompletionTokenCount = 1024
@@ -76,17 +93,9 @@ export default async function handler(req: NextRequest) {
const errorResponse: ErrorResponse = await response.json()
console.error(`AI title generation failed: ${errorResponse.error.message}`)
- return new Response(
- JSON.stringify({
- error: 'There was an unknown error generating the snippet title. Please try again.',
- }),
- {
- status: 500,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error generating the snippet title. Please try again.',
+ })
}
const completionResponse: CreateChatCompletionResponse = await response.json()
@@ -102,17 +111,9 @@ export default async function handler(req: NextRequest) {
`AI title generation failed: OpenAI response succeeded, but response format was incorrect`
)
- return new Response(
- JSON.stringify({
- error: 'There was an unknown error generating the snippet title. Please try again.',
- }),
- {
- status: 500,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ return res.status(500).json({
+ error: 'There was an unknown error generating the snippet title. Please try again.',
+ })
}
const generateTitleResult: GenerateTitleResult = JSON.parse(titleResponseString)
@@ -120,22 +121,14 @@ export default async function handler(req: NextRequest) {
if (!generateTitleResult.title) {
console.error(`AI title generation failed: Unable to generate title for the given SQL`)
- return new Response(
- JSON.stringify({
- error: 'Unable to generate title',
- }),
- {
- status: 400,
- headers: {
- 'content-type': 'application/json',
- },
- }
- )
+ res.status(400).json({
+ error: 'Unable to generate title',
+ })
}
- return new Response(JSON.stringify(generateTitleResult), {
- headers: {
- 'content-type': 'application/json',
- },
- })
+ return res.json(generateTitleResult)
}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default wrapper