mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
## Problem Studio's AI API routes under `routes/api/ai/**` still run legacy Next Pages Router handlers through `compat/next/api.ts`. Part 2 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the active AI routes to native TanStack Start (`Request` → `Response`) handlers and drops 3 unused AI endpoints. ## Solution **Changed:** - Migrated 8 active AI routes (`ai/code/complete`, `ai/feedback/{classify,rate}`, and `ai/sql/{check-api-key,cron-v2,filter-v1,generate-v4,title-v2}`) to `createApiHandlers` and `parseJsonBody` - Replaced Node `pipeUIMessageStreamToResponse` in `ai/sql/generate-v4.ts` with native `createUIMessageStreamResponse`, preserving the `x-braintrust-span-id` header - Replaced `req.on`/`res.on` in `ai/sql/generate-v4.ts` with `AbortSignal.any([request.signal, done.signal])` and a `TransformStream` whose `flush`/`cancel` tear down the MCP connection opened in `getTools` on stream completion, cancellation, or setup error - Removed the custom malformed-JSON handling in `ai/code/complete.ts` in favor of the wrapper's `400` - Updated `lib/api/generate-v4.test.ts` to assert against the real native SSE `Response` stream instead of mocking `pipeUIMessageStreamToResponse`, with a shared `mockOpenStream()` helper, a stream-cancellation abort test, and a Braintrust tracing test asserting `x-braintrust-span-id` matches the exported root span - Updated `lib/ai/README.md` to drop references to removed endpoints **Removed:** - Removed 3 unused AI routes (`routes/api/ai/onboarding/design.ts`, `routes/api/ai/sql/parse-client-code.ts`, and `routes/api/ai/sql/policy.ts`), dropped them from `lib/hosted-api-allowlist.ts`, and regenerated `routeTree.gen.ts` - Removed the now-unused `withoutApprovalTools` helper from `lib/ai/tool-filter.ts` and its test from `lib/ai/tool-filter.test.ts` **Behavior changes vs master:** - `ai/code/complete` returns the wrapper's `400` JSON `{ error: { message: 'Invalid JSON' } }` for malformed bodies - Unused `ai/onboarding/design`, `ai/sql/parse-client-code`, and `ai/sql/policy` endpoints have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/generate-v4.test.ts lib/api/rate.test.ts lib/ai/tool-filter.test.ts`. 2. Send a prompt in the AI Assistant panel, verify streaming output, and cancel mid-stream. 3. Trigger SQL title, cron, and filter generation as well as AI code completion. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
109 lines
3.7 KiB
TypeScript
109 lines
3.7 KiB
TypeScript
import { createFileRoute } from '@tanstack/react-router'
|
|
import { generateText, Output } from 'ai'
|
|
import { z } from 'zod'
|
|
|
|
import { getModel } from '@/lib/ai/model'
|
|
import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
|
|
import { parseJsonBody } from '@/lib/api/apiHelpers'
|
|
import { createApiHandlers, type ApiHandlerContext } from '@/lib/api/apiWrapper'
|
|
|
|
async function handlePost({ request }: ApiHandlerContext) {
|
|
const { prompt } = await parseJsonBody<{ prompt?: string }>(request)
|
|
|
|
if (!prompt) {
|
|
return Response.json({ error: 'Prompt is required' }, { status: 400 })
|
|
}
|
|
|
|
try {
|
|
const { modelParams, error: modelError } = await getModel({
|
|
provider: 'openai',
|
|
modelEntry: DEFAULT_COMPLETION_MODEL,
|
|
})
|
|
|
|
if (modelError) {
|
|
return Response.json({ error: modelError.message }, { status: 500 })
|
|
}
|
|
|
|
const { output } = await generateText({
|
|
...modelParams,
|
|
output: Output.object({
|
|
schema: z.object({
|
|
feedback_category: z.enum(['support', 'feedback', 'unknown']),
|
|
}),
|
|
}),
|
|
temperature: 0,
|
|
prompt: `
|
|
Classify the following feedback as ONE of: support, feedback, unknown.
|
|
- support: bug reports, help requests, or issues
|
|
- feedback: feature requests or suggestions
|
|
- unknown: unclear or unrelated
|
|
|
|
If you can't determine support or feedback, always output "unknown".
|
|
|
|
Only output a JSON object in this format: { "feedback_category": "support|feedback|unknown" }
|
|
|
|
Examples:
|
|
Feedback: "Whenever I try to invite a team member, the invite email doesn't get sent."
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "I have reached the storage limit for my project and my plan. I cannot understand how I can expand the storage space in my project."
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "Please delete the project x in my account"
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "My billing page is broken"
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "I accidentally deleted my database—can it be recovered?"
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "My login tokens are expiring too quickly, even though I didn't change any settings."
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "Can you add more integrations?"
|
|
Response: { "feedback_category": "feedback" }
|
|
|
|
Feedback: "I'm getting charged for a project I thought I deleted. Can you help me stop billing?"
|
|
Response: { "feedback_category": "support" }
|
|
|
|
Feedback: "Could you support OAuth login for more providers like Apple or LinkedIn?"
|
|
Response: { "feedback_category": "feedback" }
|
|
|
|
Feedback: "It's unclear in the docs how to set up row-level security with multiple roles."
|
|
Response: { "feedback_category": "feedback" }
|
|
|
|
Feedback: "I am trying to pause my Pro project"
|
|
Response: { "feedback_category": "feedback" }
|
|
|
|
Feedback: "${prompt}"
|
|
Response:
|
|
`,
|
|
})
|
|
|
|
return Response.json({ feedback_category: output.feedback_category })
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
console.error(`Classifying this feedback failed`)
|
|
|
|
// Check for context length error
|
|
if (error.message.includes('context_length') || error.message.includes('too long')) {
|
|
return Response.json({ error: 'This prompt is too large to ingest' }, { status: 400 })
|
|
}
|
|
} else {
|
|
console.error(`Unknown error: ${error}`)
|
|
}
|
|
|
|
return Response.json(
|
|
{ error: 'There was an unknown error generating the feedback category.' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
export const Route = createFileRoute('/api/ai/feedback/classify')({
|
|
server: {
|
|
handlers: createApiHandlers({ POST: handlePost }, { withAuth: true }),
|
|
},
|
|
})
|