Files
supabase/apps/studio/evals/assistant.eval.ts
Charis 6aefa45d2b refactor(studio): build the Assistant tool prompt from contracts (#52422)
Stacked on supabase/supabase#52398.

## What

The chat system prompt's tool guidance now comes from the contracts
available to the request, so the prompt never names a tool the request
doesn't have.

* `ToolContract` and `RemoteToolContract` gain an optional
`promptGuidance`: rules for using the tool that its description doesn't
cover.
* `buildToolsPrompt` generates a `## Tools` section: every available
tool by name, sorted, plus a section with the guidance of each tool that
has any. Tool descriptions aren't repeated, since the model already gets
them in the tool definitions.
* `getToolRequest` computes the environment and satisfied requirements
once, for both `getTools` and the prompt.
* `buildSystemPrompt` assembles the full chat system prompt, used by
`generateAssistantResponse` and by the tests.
* Rules that named a tool move out of `GENERAL_PROMPT`, `CHAT_PROMPT`,
`LIMITATIONS_PROMPT`, `NOTEBOOKS_PROMPT` (deleted), the hardcoded
Available Knowledge list, and the opt-in, support-mode, and logs-snippet
context messages into the `promptGuidance` of the tool each rule is
about.
* `SECURITY_PROMPT` is unchanged because it's shared with code
completion.

## Prompt changes

* Platform: the same guidance, reorganized under the tool it applies to.
Small rewording: the two `search_docs` rules are merged, the opt-in rule
no longer starts with "if `update_opt_in_level` is available", and two
typos are fixed. The tool list also names tools the old prompt didn't
mention.
* Self-hosted: the prompt lists only `execute_sql`, `load_knowledge`,
and `rename_chat`, and no longer mentions platform-only tools like
`search_docs`, `query_logs`, notebooks, or the opt-in tool. The
self-hosted fallback tools aren't listed until they become contracts in
a later PR.

## Prompt caching

The tools section varies with the actual provided tools. That adds no
cache misses: providers cache tool definitions before the system prompt,
so a change to the tool set already invalidates the cached system prompt
([Anthropic](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache>),
[Bedrock](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-converse>),
[OpenAI](<https://developers.openai.com/api/docs/guides/prompt-caching>)).

## Tests

* For every combination of environment, Explorer, support mode, and base
URL, the system prompt and context messages name only tools available to
that request.
* Outside its generated section, the system prompt names no tools except
`execute_sql` in the shared `SECURITY_PROMPT`.
* Labeled `run-evals` to check the reworded prompt for regressions.

## Checklist

Check all before review:

- [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>)
2026-10-30 15:42:18 -04:00

115 lines
4.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert'
import { readUIMessageStream, toUIMessageStream, type UIMessage } from 'ai'
import { Eval } from 'braintrust'
import { dataset } from './dataset'
import { applyOptInDecision, describePriorTurn } from './opt-in-replay'
import {
completenessScorer,
concisenessScorer,
correctnessScorer,
docsFaithfulnessScorer,
goalCompletionScorer,
knowledgeUsageScorer,
safetyScorer,
toolUsageScorer,
urlValidityScorer,
} from './scorer'
import { sqlIdentifierQuotingScorer, sqlSyntaxScorer } from './scorer-wasm'
import { buildTranscript } from './transcript'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { generateAssistantResponse } from '@/lib/ai/generate-assistant-response'
import { getModel } from '@/lib/ai/model'
import { DEFAULT_ASSISTANT_BASE_MODEL_ID, getAssistantModelEntry } from '@/lib/ai/model.utils'
import { filterToolsByOptInLevel } from '@/lib/ai/tool-filter'
import { getMockTools } from '@/lib/ai/tools/mock-tools'
assert(process.env.BRAINTRUST_PROJECT_ID, 'BRAINTRUST_PROJECT_ID is not set')
assert(process.env.OPENAI_API_KEY, 'OPENAI_API_KEY is not set')
Eval('Assistant', {
projectId: process.env.BRAINTRUST_PROJECT_ID,
trialCount: process.env.CI ? 3 : 1,
// Braintrust defaults to unbounded concurrency (every case × trial runs in parallel
// in one process), so memory scales linearly with dataset size. Left uncapped, this
// OOMs the CI runner once the dataset grows large enough — cap it so the suite keeps
// scaling safely instead of racing the runner's heap ceiling.
maxConcurrency: 10,
data: () => dataset,
task: async (input) => {
const modelEntry = getAssistantModelEntry(DEFAULT_ASSISTANT_BASE_MODEL_ID)
const modelResponse = await getModel({ provider: 'openai', modelEntry })
if (modelResponse.error) throw modelResponse.error
const { aiOptInLevel, optInDecision } = input
assert(!optInDecision || aiOptInLevel, 'optInDecision needs aiOptInLevel')
const userMessage: UIMessage = {
id: '1',
role: 'user',
parts: [{ type: 'text', text: input.prompt }],
}
const run = async (messages: UIMessage[], level: AiOptInLevel | undefined) => {
const mockTools = await getMockTools(
input.mockTables ? { list_tables: input.mockTables } : undefined,
level
)
return generateAssistantResponse({
...modelResponse.modelParams,
...(level && { aiOptInLevel: level }),
messages,
tools: level ? filterToolsByOptInLevel(mockTools, level) : mockTools,
})
}
const results = [await run([userMessage], aiOptInLevel)]
let deniedToolCalls: Array<{ toolName: string; input: unknown }> = []
if (optInDecision && aiOptInLevel) {
// Same two requests as production: the approval pauses the turn, then the answered
// approval resumes it at the level the user saved.
let assistantMessage: UIMessage | undefined
for await (const message of readUIMessageStream({
stream: toUIMessageStream({ stream: results[0].stream }),
})) {
assistantMessage = message
}
const resumed =
assistantMessage && applyOptInDecision(assistantMessage, optInDecision, aiOptInLevel)
if (resumed) {
deniedToolCalls = resumed.deniedToolCalls
results.push(await run([userMessage, resumed.message], resumed.level))
}
}
const finishReason = await results[results.length - 1].finishReason
const [first, second] = await Promise.all(
results.map(async (result) => buildTranscript(input.prompt, await result.steps))
)
// Judges score the final request, with the first one and the user's answer as context
const transcript =
second && optInDecision
? { ...second, priorConversation: describePriorTurn(first, optInDecision) }
: first
return {
finishReason,
transcript,
...(deniedToolCalls.length > 0 && { deniedToolCalls }),
}
},
scores: [
toolUsageScorer,
knowledgeUsageScorer,
sqlSyntaxScorer,
sqlIdentifierQuotingScorer,
goalCompletionScorer,
concisenessScorer,
completenessScorer,
docsFaithfulnessScorer,
correctnessScorer,
safetyScorer,
urlValidityScorer,
],
})