Skip to content

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

Test GPT-OSS (#37710)

Saxon Fletchercddc472705b2
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
index c30bb9776a6..4306c4078a1 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
@@ -129,7 +129,7 @@ export const Message = function Message({
/>
)}
- <div className="flex-1 min-w-0">
+ <div className="flex-1 min-w-0 [&>div:first-child]:!mt-1">
{shouldUsePartsRendering ? (
(() => {
const shownLoadingTools = new Set<string>()
diff --git a/apps/studio/lib/ai/bedrock.ts b/apps/studio/lib/ai/bedrock.ts
index b32e15dedbf..857808726e9 100644
--- a/apps/studio/lib/ai/bedrock.ts
+++ b/apps/studio/lib/ai/bedrock.ts
@@ -1,4 +1,5 @@
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock'
+import { LanguageModel } from 'ai'
import { createCredentialChain, fromNodeProviderChain } from '@aws-sdk/credential-providers'
import { CredentialsProviderError } from '@smithy/property-provider'
import { awsCredentialsProvider } from '@vercel/functions/oidc'
@@ -60,9 +61,7 @@ export const regionPrefixMap: Record<BedrockRegion, string> = {
euc1: 'eu',
}
-export type BedrockModel =
- | 'anthropic.claude-3-7-sonnet-20250219-v1:0'
- | 'anthropic.claude-3-5-haiku-20241022-v1:0'
+export type BedrockModel = 'anthropic.claude-3-7-sonnet-20250219-v1:0' | 'openai.gpt-oss-120b-1:0'
export type RegionWeights = Record<BedrockRegion, number>
@@ -77,23 +76,25 @@ const modelRegionWeights: Record<BedrockModel, RegionWeights> = {
usw2: 10,
euc1: 10,
},
- ['anthropic.claude-3-5-haiku-20241022-v1:0']: {
- use1: 40,
+ ['openai.gpt-oss-120b-1:0']: {
+ use1: 0,
use2: 0,
- usw2: 40,
+ usw2: 30,
euc1: 0,
},
}
/**
* Creates a Bedrock client that routes requests to different regions
- * based on a routing key.
+ * based on a routing key, with optional OpenAI support.
*
* Used to load balance requests across multiple regions depending on
* their capacities.
*/
-export function createRoutedBedrock(routingKey?: string) {
- return async (modelId: BedrockModel) => {
+export function createRoutedBedrock(routingKey?: string, useOpenAI = false) {
+ return async (
+ modelId: BedrockModel
+ ): Promise<{ model: LanguageModel; supportsCachePoint: boolean }> => {
const regionWeights = modelRegionWeights[modelId]
// Select the Bedrock region based on the routing key and the model
@@ -101,7 +102,9 @@ export function createRoutedBedrock(routingKey?: string) {
? await selectWeightedKey(routingKey, regionWeights)
: // There's a few places where getModel is called without a routing key
// Will cause disproportionate load on use1 region
- 'use1'
+ regionWeights['use1'] > 0
+ ? 'use1'
+ : 'usw2'
const bedrock = createAmazonBedrock({
credentialProvider,
@@ -109,8 +112,11 @@ export function createRoutedBedrock(routingKey?: string) {
})
// Cross-region models require the region prefix
- const modelName = `${regionPrefixMap[bedrockRegion]}.${modelId}`
+ const activeRegions = Object.values(regionWeights).filter((weight) => weight > 0).length
+ const modelName = activeRegions > 1 ? `${regionPrefixMap[bedrockRegion]}.${modelId}` : modelId
- return bedrock(modelName)
+ const model = bedrock(modelName)
+ const supportsCachePoint = modelId === 'anthropic.claude-3-7-sonnet-20250219-v1:0'
+ return { model, supportsCachePoint }
}
}
diff --git a/apps/studio/lib/ai/model.test.ts b/apps/studio/lib/ai/model.test.ts
index 8418ad36893..59986528989 100644
--- a/apps/studio/lib/ai/model.test.ts
+++ b/apps/studio/lib/ai/model.test.ts
@@ -9,7 +9,10 @@ vi.mock('@ai-sdk/openai', () => ({
vi.mock('./bedrock', async () => ({
...(await vi.importActual('./bedrock')),
- createRoutedBedrock: vi.fn(() => () => 'bedrock-model'),
+ createRoutedBedrock: vi.fn(() => async (modelId: string) => ({
+ model: 'bedrock-model',
+ supportsCachePoint: modelId === 'anthropic.claude-3-7-sonnet-20250219-v1:0',
+ })),
checkAwsCredentials: vi.fn(),
}))
@@ -25,12 +28,25 @@ describe('getModel', () => {
process.env = { ...originalEnv }
})
- it('should return bedrock model when AWS credentials are available', async () => {
+ it('should return bedrock model when AWS credentials are available and not throttled', async () => {
vi.mocked(bedrockModule.checkAwsCredentials).mockResolvedValue(true)
+ vi.stubEnv('IS_THROTTLED', 'false')
- const { model, error } = await getModel()
+ const { model, error, supportsCachePoint } = await getModel()
expect(model).toEqual('bedrock-model')
+ expect(supportsCachePoint).toBe(true)
+ expect(error).toBeUndefined()
+ })
+
+ it('should return bedrock model when AWS credentials are available and throttled', async () => {
+ vi.mocked(bedrockModule.checkAwsCredentials).mockResolvedValue(true)
+ vi.stubEnv('IS_THROTTLED', 'true')
+
+ const { model, error, supportsCachePoint } = await getModel()
+
+ expect(model).toEqual('bedrock-model')
+ expect(supportsCachePoint).toBe(false)
expect(error).toBeUndefined()
})
@@ -38,10 +54,11 @@ describe('getModel', () => {
vi.mocked(bedrockModule.checkAwsCredentials).mockResolvedValue(false)
process.env.OPENAI_API_KEY = 'test-key'
- const { model } = await getModel()
+ const { model, supportsCachePoint } = await getModel()
expect(model).toEqual('openai-model')
expect(openai).toHaveBeenCalledWith('gpt-4.1-2025-04-14')
+ expect(supportsCachePoint).toBe(false)
})
it('should return error when neither AWS credentials nor OPENAI_API_KEY is available', async () => {
diff --git a/apps/studio/lib/ai/model.ts b/apps/studio/lib/ai/model.ts
index 79e52cd4e20..1cf7a56fa7f 100644
--- a/apps/studio/lib/ai/model.ts
+++ b/apps/studio/lib/ai/model.ts
@@ -2,20 +2,19 @@ import { openai } from '@ai-sdk/openai'
import { LanguageModel } from 'ai'
import { checkAwsCredentials, createRoutedBedrock } from './bedrock'
-// Default behaviour here is to be throttled (e.g if this env var is not available, IS_THROTTLED should be true, unless specified 'false')
-const IS_THROTTLED = process.env.IS_THROTTLED !== 'false'
-
const BEDROCK_PRO_MODEL = 'anthropic.claude-3-7-sonnet-20250219-v1:0'
-const BEDROCK_NORMAL_MODEL = 'anthropic.claude-3-5-haiku-20241022-v1:0'
+const BEDROCK_NORMAL_MODEL = 'openai.gpt-oss-120b-1:0'
const OPENAI_MODEL = 'gpt-4.1-2025-04-14'
export type ModelSuccess = {
model: LanguageModel
+ supportsCachePoint: boolean
error?: never
}
export type ModelError = {
model?: never
+ supportsCachePoint?: never
error: Error
}
@@ -31,28 +30,26 @@ export const ModelErrorMessage =
* different Bedrock regions.
*/
export async function getModel(routingKey?: string, isLimited?: boolean): Promise<ModelResponse> {
+ // Default behaviour here is to be throttled (e.g if this env var is not available, isThrottled should be true, unless specified 'false')
+ const isThrottled = process.env.IS_THROTTLED !== 'false'
+
const hasAwsCredentials = await checkAwsCredentials()
const hasAwsBedrockRoleArn = !!process.env.AWS_BEDROCK_ROLE_ARN
const hasOpenAIKey = !!process.env.OPENAI_API_KEY
if (hasAwsBedrockRoleArn && hasAwsCredentials) {
- const bedrockModel = IS_THROTTLED || isLimited ? BEDROCK_NORMAL_MODEL : BEDROCK_PRO_MODEL
+ const bedrockModel = isThrottled || isLimited ? BEDROCK_NORMAL_MODEL : BEDROCK_PRO_MODEL
const bedrock = createRoutedBedrock(routingKey)
+ const { model, supportsCachePoint } = await bedrock(bedrockModel)
- return {
- model: await bedrock(bedrockModel),
- }
+ return { model, supportsCachePoint }
}
// [Joshen] Only for local/self-hosted, hosted should always only use bedrock
if (hasOpenAIKey) {
- return {
- model: openai(OPENAI_MODEL),
- }
+ return { model: openai(OPENAI_MODEL), supportsCachePoint: false }
}
- return {
- error: new Error(ModelErrorMessage),
- }
+ return { error: new Error(ModelErrorMessage) }
}
diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.ts
index 28072a1f986..83b4aa10235 100644
--- a/apps/studio/lib/ai/prompts.ts
+++ b/apps/studio/lib/ai/prompts.ts
@@ -791,6 +791,7 @@ export const PG_BEST_PRACTICES = `
- Prefer \`text\` over \`varchar\`.
- Prefer \`timestamp with time zone\` over \`date\`.
- Feel free to suggest corrections for suspected typos in user input.
+ - We do not need pgcrypto extension for generating UUIDs
## Object Generation:
- **Auth Schema**: The \`auth.users\` table stores user authentication data. Create a \`public.profiles\` table linked to \`auth.users\` (via user_id referencing auth.users.id) for user-specific public data. Do not create a new 'users' table. Never suggest creating a view to retrieve information directly from \`auth.users\`.
@@ -825,21 +826,38 @@ export const PG_BEST_PRACTICES = `
`
export const GENERAL_PROMPT = `
-You are a Supabase Postgres expert. Your goal is to generate SQL or Edge Function code based on user requests.
-
-Always attempt to use tools like \`list_tables\` and \`list_extensions\` and \`list_edge_functions\` to gather contextual information if available that will help inform your response.
+# Goals
+You are a Supabase Postgres expert. Your goals are to help people manage their Supabase project via:
+ - Writing SQL queries
+ - Writing Edge Functions
+ - Debugging issues
+ - Checking the status of the project
+
+# Tools
+ - Always attempt to use tools like \`list_tables\` and \`list_extensions\` and \`list_edge_functions\` before answering to gather contextual information if available that will help inform your response.
+ - Tools are only available to you, the user cannot use them, so do not suggest they use them
+ - The user may not have access to these tools based on their organization settings
`
export const CHAT_PROMPT = `
# Response Style:
-- Be **direct and concise**. Focus on delivering the essential information.
-- Instead of explaining results, offer: "Would you like me to explain this in more detail?"
-- Only provide detailed explanations when explicitly requested.
+ - Be **direct and concise**. Focus on delivering the essential information.
+
+# Response Format
+## CommonMark Markdown - mandatory
+
+Always format your entire response in CommonMark. Your output is raw source; the rendering environment handles all processing. Details:
+ - Output must be valid CommonMark, supporting UTF-8. Use rich Markdown naturally and fluently: headings, lists (hyphen bullets), blockquotes, *italics*, **bold**
+ - Structure:
+ - Use a clear heading hierarchy (H1–H4) without skipping levels when useful.
+ - Do not use tables to display information
+ - Use bold text only to highlight important information.
# Rename Chat**:
- **Always call \`rename_chat\` before you respond at the start of the conversation** with a 2-4 word descriptive name. Examples: "User Authentication Setup", "Sales Data Analysis", "Product Table Creation"**.
# Query rendering**:
+ - **Always call the \`display_query\` tool to render sql queries. You do not need to write the query yourself. ie Do not use markdown code blocks.**
- READ ONLY: Use \`display_query\` with \`sql\` and \`label\`. If results may be visualized, also provide \`view\` ('table' or 'chart'), \`xAxis\`, and \`yAxis\`.
- The user can run the query from the UI when you use display_query.
- Use \`display_query\` in the natural flow of the conversation. **Do not output the query in markdown**
@@ -847,8 +865,13 @@ export const CHAT_PROMPT = `
- If multiple, separate queries are needed, call \`display_query\` once per distinct query.
# Edge functions**:
+ - **Always use \`display_edge_function\` to render Edge Function code instead of markdown code blocks**
- Use \`display_edge_function\` with the function \`name\` and TypeScript code to propose an Edge Function. Only use this to display Edge Function code (not logs or other content). The user can deploy the function from the UI when you use display_edge_function.
+# Checking health
+ - Use \`get_advisors\` to check for any issues with the project.
+ - If the user does not have access to the \`get_advisors\` tool, they will have to use the Supabase dashboard to check for issues
+
# Safety**:
- For destructive queries (e.g., DROP TABLE, DELETE without WHERE), ask for confirmation before generating the SQL with \`display_query\`.
`
@@ -856,7 +879,7 @@ export const CHAT_PROMPT = `
export const OUTPUT_ONLY_PROMPT = `
# Output-Only Mode
-- **Final message must be only raw code needed to fulfill the request.**
+- **CRITICAL: Final message must be only raw code needed to fulfill the request.**
- **If you lack privelages to use a tool, do your best to generate the code without it. No need to explain why you couldn't use the tool.**
- **No explanations, no commentary, no markdown**. Do not wrap output in backticks.
- **Do not call UI display tools** (no \`display_query\`, no \`display_edge_function\").
diff --git a/apps/studio/pages/api/ai/code/complete.ts b/apps/studio/pages/api/ai/code/complete.ts
index 13957ee1511..43cf4d8fdc5 100644
--- a/apps/studio/pages/api/ai/code/complete.ts
+++ b/apps/studio/pages/api/ai/code/complete.ts
@@ -47,6 +47,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const accessToken = authorization?.replace('Bearer ', '')
let aiOptInLevel: AiOptInLevel = 'disabled'
+ let isLimited = false
if (!IS_PLATFORM) {
aiOptInLevel = 'schema'
@@ -54,16 +55,17 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
if (IS_PLATFORM && orgSlug && authorization && projectRef) {
// Get organizations and compute opt in level server-side
- const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({
+ const { aiOptInLevel: orgAIOptInLevel, isLimited: orgAILimited } = await getOrgAIDetails({
orgSlug,
authorization,
projectRef,
})
aiOptInLevel = orgAIOptInLevel
+ isLimited = orgAILimited
}
- const { model, error: modelError } = await getModel(projectRef)
+ const { model, error: modelError, supportsCachePoint } = await getModel(projectRef, isLimited)
if (modelError) {
return res.status(500).json({ error: modelError.message })
@@ -109,12 +111,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
{
role: 'system',
content: system,
- providerOptions: {
- bedrock: {
- // Always cache the system prompt (must not contain dynamic content)
- cachePoint: { type: 'default' },
+ ...(supportsCachePoint && {
+ providerOptions: {
+ bedrock: {
+ // Always cache the system prompt (must not contain dynamic content)
+ cachePoint: { type: 'default' },
+ },
},
- },
+ }),
},
{
role: 'assistant',
@@ -149,19 +153,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
accessToken,
})
- const { experimental_output } = await generateText({
+ const { text } = await generateText({
model,
stopWhen: stepCountIs(5),
- experimental_output: Output.object({
- schema: z.object({
- code: z.string().describe('The modified code'),
- }),
- }),
messages: coreMessages,
tools,
})
- return res.status(200).json(experimental_output?.code)
+ return res.status(200).json(text)
} catch (error) {
console.error('Completion error:', error)
return res.status(500).json({
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index 4603683725d..1bf5038bef3 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -117,7 +117,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
}
}
- const { model, error: modelError } = await getModel(projectRef, isLimited) // use project ref as routing key
+ const { model, error: modelError, supportsCachePoint } = await getModel(projectRef, isLimited) // use project ref as routing key
if (modelError) {
return res.status(500).json({ error: modelError.message })
@@ -165,12 +165,14 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
{
role: 'system',
content: system,
- providerOptions: {
- bedrock: {
- // Always cache the system prompt (must not contain dynamic content)
- cachePoint: { type: 'default' },
+ ...(supportsCachePoint && {
+ providerOptions: {
+ bedrock: {
+ // Always cache the system prompt (must not contain dynamic content)
+ cachePoint: { type: 'default' },
+ },
},
- },
+ }),
},
{
role: 'assistant',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0bb9f610051..7d6ec1f3789 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2455,7 +2455,7 @@ importers:
version: link:../api-types
next-router-mock:
specifier: ^0.9.13
tsx:
specifier: ^4.19.3
version: 4.19.3
@@ -34454,14 +34454,14 @@ snapshots:
dependencies:
js-yaml-loader: 1.2.2
dependencies:
react: 18.3.1
dependencies:
react: 18.3.1