mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
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>)
95 lines
3.4 KiB
TypeScript
95 lines
3.4 KiB
TypeScript
import {
|
|
isToolUIPart,
|
|
type DynamicToolUIPart,
|
|
type ModelMessage,
|
|
type ToolUIPart,
|
|
type UIMessage,
|
|
} from 'ai'
|
|
import { source } from 'common-tags'
|
|
|
|
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
|
|
import { isOptInLevelAtLeast } from '@/lib/ai/opt-in-level'
|
|
import { CHAT_PROMPT, GENERAL_PROMPT, LIMITATIONS_PROMPT, SECURITY_PROMPT } from '@/lib/ai/prompts'
|
|
import { NO_DATA_ERROR } from '@/lib/ai/tools/execute-sql-output'
|
|
import { decodeNotebookToolError } from '@/lib/ai/tools/notebook-tool-error'
|
|
import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer'
|
|
import { buildToolsPrompt } from '@/lib/ai/tools/tools-prompt'
|
|
|
|
/** The chat system prompt for the tools the model is given. See `generateAssistantResponse` on caching. */
|
|
export function buildSystemPrompt(toolNames: Iterable<string>): string {
|
|
return source`
|
|
${GENERAL_PROMPT}
|
|
${CHAT_PROMPT}
|
|
${buildToolsPrompt(toolNames)}
|
|
${SECURITY_PROMPT}
|
|
${LIMITATIONS_PROMPT}
|
|
`
|
|
}
|
|
|
|
const INVALID_TOOL_STATES = [
|
|
'input-streaming',
|
|
'input-available',
|
|
'approval-requested',
|
|
'output-error',
|
|
]
|
|
|
|
/**
|
|
* Notebook tool errors are opted into model visibility explicitly (NotebookToolError,
|
|
* encoded in generate-v4.ts's onError). A successful parse against the schema — including
|
|
* its literal `tag` — is proof enough that this was a NotebookToolError; every other
|
|
* output-error stays hidden, same as before. Rewrites errorText back to the plain message
|
|
* so the model sees prose, not JSON.
|
|
*/
|
|
function exposedNotebookErrorPart(
|
|
part: ToolUIPart | DynamicToolUIPart
|
|
): ToolUIPart | DynamicToolUIPart | null {
|
|
if (part.state !== 'output-error') return null
|
|
const decoded = decodeNotebookToolError(part.errorText)
|
|
if (!decoded?.exposeToAssistant) return null
|
|
return { ...part, errorText: decoded.message }
|
|
}
|
|
|
|
/** Trims history to the last 7 messages and strips tool parts the model shouldn't see. */
|
|
export function prepareMessagesForModel(rawMessages: UIMessage[], aiOptInLevel: AiOptInLevel) {
|
|
return (rawMessages || []).slice(-7).map((msg) => {
|
|
if (msg && msg.role === 'assistant' && 'results' in msg) {
|
|
const cleanedMsg = { ...msg }
|
|
delete cleanedMsg.results
|
|
return cleanedMsg
|
|
}
|
|
if (msg && msg.role === 'assistant' && msg.parts) {
|
|
const cleanedParts = msg.parts.flatMap((part) => {
|
|
if (!isToolUIPart(part)) return [part]
|
|
if (!INVALID_TOOL_STATES.includes(part.state))
|
|
return [sanitizeMessagePart(part, aiOptInLevel)]
|
|
const exposed = exposedNotebookErrorPart(part)
|
|
return exposed ? [sanitizeMessagePart(exposed, aiOptInLevel)] : []
|
|
})
|
|
return { ...msg, parts: cleanedParts }
|
|
}
|
|
return msg
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Database errors can echo row values. Sanitize same-request steps here.
|
|
* `prepareMessagesForModel` drops errors from later turns.
|
|
*/
|
|
export function hideToolErrorsFromModel(messages: ModelMessage[], aiOptInLevel: AiOptInLevel) {
|
|
if (isOptInLevelAtLeast(aiOptInLevel, 'schema_and_log_and_data')) return messages
|
|
|
|
return messages.map((message) => {
|
|
if (message.role !== 'tool') return message
|
|
return {
|
|
...message,
|
|
content: message.content.map((part) =>
|
|
part.type === 'tool-result' &&
|
|
part.toolName === 'execute_sql' &&
|
|
(part.output.type === 'error-text' || part.output.type === 'error-json')
|
|
? { ...part, output: { type: 'error-text' as const, value: NO_DATA_ERROR } }
|
|
: part
|
|
),
|
|
}
|
|
})
|
|
}
|