Files
supabase/apps/studio/pages/api/ai/sql/suggest.ts
Greg Richardson a6f1313490 AI SQL: Update model + add test suite (#19644)
* refactor: ai sql logic to common package

* feat: ai sql tests

* feat: test rls policy ai chat assistant

* refactor: jest env loading

* feat(ai): improve sql title and description quality

* fix: ai message role type

* Move the new files to a separate package.

* Remove a forgotten console.log.

* Migrate the tests to use snapshots and commit the snapshots.

* Separate the functions which require edge runtime to be exported via /edge subpath.

* Bust the turbo cache when one of the deps has been rebuilt.

* chore: fix package main/type references

* fix: package lock out of sync

* fix: ai sql debugging to fix typos

---------

Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2023-12-18 11:23:59 -07:00

67 lines
1.7 KiB
TypeScript

import { StreamingTextResponse } from 'ai'
import { chatRlsPolicy } from 'ai-commands/edge'
import { NextRequest } from 'next/server'
import OpenAI from 'openai'
export const runtime = 'edge'
const openAiKey = process.env.OPENAI_KEY
export default async function handler(req: NextRequest) {
if (!openAiKey) {
return new Response(
JSON.stringify({
error: 'No OPENAI_KEY set. Create this environment variable to use AI features.',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
const { method } = req
switch (method) {
case 'POST':
return handlePost(req)
default:
return new Response(
JSON.stringify({ data: null, error: { message: `Method ${method} Not Allowed` } }),
{
status: 405,
headers: { 'Content-Type': 'application/json', Allow: 'POST' },
}
)
}
}
async function handlePost(request: NextRequest) {
const openai = new OpenAI({ apiKey: openAiKey })
const body = await (request.json() as Promise<{
messages: { content: string; role: 'user' | 'assistant' }[]
entityDefinitions: string[]
policyDefinition: string
}>)
const { messages, entityDefinitions, policyDefinition } = body
try {
const stream = await chatRlsPolicy(openai, messages, entityDefinitions, policyDefinition)
return new StreamingTextResponse(stream)
} catch (error) {
console.error(error)
return new Response(
JSON.stringify({
error: 'There was an error processing your request',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
}