mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 09:25:06 +03:00
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Chore / dependency upgrade. ## What is the current behavior? Studio is on AI SDK 6 (`ai` ^6.0.174, `@ai-sdk/react` ^3). Tool approvals still use the v6 `needsApproval` flag on individual tools. ## What is the new behavior? Upgrades Studio to AI SDK 7 (`ai` 7.0.59) and the matching `@ai-sdk/*` packages. Aligns call sites with v7 names (`instructions`, `isStepCount`, `onEnd`, `ToolExecutionOptions`). This is the bottom of stack #49171. Later layers add a shared Confirm card and AssistantQueryCell. ## Additional context - Stack: #49167 → #49168 → #49169 → #49170 - `needsApproval` on tools is left as-is in this PR so the upgrade can land independently. A follow-up can move those gates to `streamText({ toolApproval })` and `experimental_toolApprovalSecret`. - Independent of the notebook preview stack ([#49112](https://github.com/supabase/supabase/pull/49112), [#49159](https://github.com/supabase/supabase/pull/49159)), which should merge first before we wrap notebook proposals in Confirm. ## Test plan - [ ] `pnpm --filter studio test` for `lib/ai/tools/*` and assistant generate path - [ ] Assistant chat still streams and tool-approval SQL / Edge Function still pause for confirm - [ ] Evals still run with mock tools (`needsApproval: false` overrides) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Updated AI-powered chat, onboarding, SQL, code completion, and recipe generation workflows for more reliable responses. * Streaming responses now better preserve reasoning and source information where available. * Improved tool privacy notices while preserving dynamically generated tool descriptions. * Refined AI response handling, including step limits and structured policy results. * **Bug Fixes** * Improved compatibility across AI-powered tool interactions and execution scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
282 lines
8.2 KiB
TypeScript
282 lines
8.2 KiB
TypeScript
import pgMeta from '@supabase/pg-meta'
|
|
import type { JwtPayload } from '@supabase/supabase-js'
|
|
import { pipeUIMessageStreamToResponse, safeValidateUIMessages, toUIMessageStream } from 'ai'
|
|
import { IS_PLATFORM } from 'common'
|
|
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
import z from 'zod'
|
|
|
|
import { executeSql } from '@/data/sql/execute-sql-mutation'
|
|
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
|
|
import { getAIDetails } from '@/lib/ai/ai-details'
|
|
import { NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'
|
|
import {
|
|
assistantMessageMetadataSchema,
|
|
messagesIncludeLogsSnippets,
|
|
} from '@/lib/ai/assistant-message-metadata'
|
|
import { isTracingAllowed } from '@/lib/ai/braintrust-logger'
|
|
import { generateAssistantResponse } from '@/lib/ai/generate-assistant-response'
|
|
import { isExplorerEnabled } from '@/lib/ai/is-explorer-enabled'
|
|
import { getModel } from '@/lib/ai/model'
|
|
import {
|
|
DEFAULT_ASSISTANT_ADVANCE_MODEL_ID,
|
|
DEFAULT_ASSISTANT_BASE_MODEL_ID,
|
|
getAssistantModelEntry,
|
|
isAssistantBaseModelId,
|
|
isKnownAssistantModelId,
|
|
type AssistantModelId,
|
|
} from '@/lib/ai/model.utils'
|
|
import { getTools } from '@/lib/ai/tools'
|
|
import { apiWrapper } from '@/lib/api/apiWrapper'
|
|
import { executeQuery } from '@/lib/api/self-hosted/query'
|
|
import { getURL } from '@/lib/helpers'
|
|
import { trustedUserEmail } from '@/lib/server/configcat'
|
|
|
|
export const maxDuration = 120
|
|
|
|
export const config = {
|
|
api: {
|
|
bodyParser: {
|
|
sizeLimit: '5mb',
|
|
},
|
|
},
|
|
}
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse, claims?: JwtPayload) {
|
|
const { method } = req
|
|
|
|
switch (method) {
|
|
case 'POST':
|
|
return handlePost(req, res, claims)
|
|
default:
|
|
res.setHeader('Allow', ['POST'])
|
|
res.status(405).json({
|
|
data: null,
|
|
error: { message: `Method ${method} Not Allowed` },
|
|
})
|
|
}
|
|
}
|
|
|
|
const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
|
|
apiWrapper(req, res, handler, { withAuth: true })
|
|
|
|
export default wrapper
|
|
|
|
const requestBodySchema = z.object({
|
|
messages: z.array(z.any()),
|
|
projectRef: z.string(),
|
|
connectionString: z.string(),
|
|
schema: z.string().optional(),
|
|
table: z.string().optional(),
|
|
chatId: z.string().optional(),
|
|
chatName: z.string().optional(),
|
|
supportMode: z.boolean().optional(),
|
|
orgSlug: z.string().optional(),
|
|
model: z.string().optional(),
|
|
})
|
|
|
|
async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: JwtPayload) {
|
|
const authorization = req.headers.authorization
|
|
const accessToken = authorization?.replace('Bearer ', '')
|
|
|
|
if (IS_PLATFORM && !accessToken) {
|
|
return res.status(401).json({ error: 'Authorization token is required' })
|
|
}
|
|
|
|
const userId = claims?.sub
|
|
|
|
const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
|
const { data, error: parseError } = requestBodySchema.safeParse(body)
|
|
|
|
if (parseError) {
|
|
return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
|
|
}
|
|
|
|
const {
|
|
messages: rawMessages,
|
|
projectRef,
|
|
connectionString,
|
|
orgSlug,
|
|
chatId,
|
|
chatName,
|
|
model: rawRequestedModel,
|
|
supportMode,
|
|
} = data
|
|
|
|
const requestedModel: AssistantModelId | undefined =
|
|
rawRequestedModel && isKnownAssistantModelId(rawRequestedModel) ? rawRequestedModel : undefined
|
|
|
|
const messagesValidation = await safeValidateUIMessages({
|
|
messages: rawMessages,
|
|
metadataSchema: assistantMessageMetadataSchema,
|
|
})
|
|
if (!messagesValidation.success) {
|
|
return res.status(400).json({
|
|
error: 'Invalid request body',
|
|
message: messagesValidation.error.message,
|
|
})
|
|
}
|
|
const messages = messagesValidation.data
|
|
|
|
const includesLogsSnippets = messagesIncludeLogsSnippets(messages)
|
|
|
|
let aiOptInLevel: AiOptInLevel = 'disabled'
|
|
let hasAccessToAdvanceModel = false
|
|
let orgHasHipaaAddon: boolean | undefined
|
|
let projectIsSensitive: boolean | null | undefined
|
|
let projectRegion: string | undefined
|
|
let orgId: number | undefined
|
|
let planId: string | undefined
|
|
|
|
if (!IS_PLATFORM) {
|
|
aiOptInLevel = 'schema'
|
|
hasAccessToAdvanceModel = true
|
|
}
|
|
|
|
if (IS_PLATFORM && orgSlug && authorization && projectRef) {
|
|
try {
|
|
const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })
|
|
|
|
aiOptInLevel = aiDetails.aiOptInLevel
|
|
hasAccessToAdvanceModel = aiDetails.hasAccessToAdvanceModel
|
|
orgHasHipaaAddon = aiDetails.hasHipaaAddon
|
|
orgId = aiDetails.orgId
|
|
planId = aiDetails.planId
|
|
projectIsSensitive = aiDetails.isSensitive
|
|
projectRegion = aiDetails.region
|
|
} catch (error) {
|
|
return res.status(400).json({
|
|
error: 'There was an error fetching your organization details',
|
|
})
|
|
}
|
|
}
|
|
|
|
const explorerEnabled = await isExplorerEnabled(trustedUserEmail(claims?.email))
|
|
|
|
const envThrottled = process.env.IS_THROTTLED !== 'false'
|
|
|
|
let effectiveModel: AssistantModelId = requestedModel ?? DEFAULT_ASSISTANT_ADVANCE_MODEL_ID
|
|
if (!hasAccessToAdvanceModel || (envThrottled && !isAssistantBaseModelId(effectiveModel))) {
|
|
effectiveModel = DEFAULT_ASSISTANT_BASE_MODEL_ID
|
|
}
|
|
|
|
const {
|
|
modelParams,
|
|
error: modelError,
|
|
systemProviderOptions,
|
|
} = await getModel({
|
|
provider: 'openai',
|
|
modelEntry: getAssistantModelEntry(effectiveModel),
|
|
})
|
|
|
|
if (modelError) {
|
|
return res.status(500).json({ error: modelError.message })
|
|
}
|
|
|
|
try {
|
|
const abortController = new AbortController()
|
|
req.on('close', () => abortController.abort())
|
|
req.on('aborted', () => abortController.abort())
|
|
// Fires when the response finishes streaming or the connection drops, which
|
|
// is what tears down the remote MCP connection opened in getTools.
|
|
res.on('close', () => abortController.abort())
|
|
|
|
const tools = await getTools({
|
|
projectRef,
|
|
connectionString,
|
|
authorization,
|
|
aiOptInLevel,
|
|
accessToken,
|
|
baseUrl: getURL(),
|
|
supportMode,
|
|
isExplorerEnabled: explorerEnabled,
|
|
signal: abortController.signal,
|
|
})
|
|
|
|
// Get a list of all schemas to add to context
|
|
const getSchemas = async (): Promise<string> => {
|
|
const pgMetaSchemasList = pgMeta.schemas.list()
|
|
type Schemas = z.infer<(typeof pgMetaSchemasList)['zod']>
|
|
|
|
const { result: schemas } = await executeSql<Schemas>(
|
|
{
|
|
projectRef,
|
|
connectionString,
|
|
sql: pgMetaSchemasList.sql,
|
|
},
|
|
undefined,
|
|
{
|
|
'Content-Type': 'application/json',
|
|
...(authorization && { Authorization: authorization }),
|
|
},
|
|
IS_PLATFORM ? undefined : executeQuery
|
|
)
|
|
|
|
return schemas?.length > 0
|
|
? `The available database schema names are: ${JSON.stringify(schemas)}`
|
|
: NO_SCHEMA_ACCESS_MESSAGE
|
|
}
|
|
|
|
const result = await generateAssistantResponse({
|
|
messages,
|
|
...modelParams,
|
|
tools,
|
|
aiOptInLevel,
|
|
getSchemas: aiOptInLevel !== 'disabled' ? getSchemas : undefined,
|
|
projectRef,
|
|
chatId,
|
|
chatName,
|
|
allowTracing: isTracingAllowed({
|
|
orgHasHipaaAddon,
|
|
projectIsSensitive,
|
|
projectRegion,
|
|
}),
|
|
supportMode,
|
|
userId,
|
|
orgId,
|
|
planId,
|
|
includesLogsSnippets,
|
|
isExplorerEnabled: explorerEnabled,
|
|
requestedModel,
|
|
systemProviderOptions,
|
|
abortSignal: abortController.signal,
|
|
onSpanCreated: (spanId) => {
|
|
res.setHeader('x-braintrust-span-id', spanId)
|
|
},
|
|
})
|
|
|
|
const stream = toUIMessageStream({
|
|
stream: result.stream,
|
|
sendReasoning: true,
|
|
onError: (error) => {
|
|
console.error('Assistant stream error:', error)
|
|
|
|
if (error == null) {
|
|
return 'unknown error'
|
|
}
|
|
|
|
if (typeof error === 'string') {
|
|
return error
|
|
}
|
|
|
|
if (error instanceof Error) {
|
|
return error.message
|
|
}
|
|
|
|
return JSON.stringify(error)
|
|
},
|
|
})
|
|
|
|
pipeUIMessageStreamToResponse({
|
|
response: res,
|
|
stream,
|
|
headers: { 'Content-Encoding': 'none' },
|
|
})
|
|
} catch (error) {
|
|
console.error('Error in handlePost:', error)
|
|
if (error instanceof Error) {
|
|
return res.status(500).json({ message: error.message })
|
|
}
|
|
return res.status(500).json({ message: 'An unexpected error occurred.' })
|
|
}
|
|
}
|