Files
supabase/apps/studio/lib/ai/generate-assistant-response.ts
Matt Rossman ddabeac30c feat(studio): enable EU Assistant tracing (#53332)
Enables Braintrust tracing and feedback for Assistant chats on EU-region
projects. This was the final holdout that makes it so that tracing is
applied consistently across all projects.

Adds `projectRegion` metadata to root traces so the project’s region is
recorded with each chat (consistent with the existing
[isHighComplianceProject
metadata](https://github.com/supabase/supabase/blob/917dcb388939b8c54ea13c1e31b3c7285fb2ca65/apps/studio/lib/ai/generate-assistant-response.ts#L188)).

Verified in staging with a [successful Assistant trace recording
`projectRegion:
eu-central-1`](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=1b4a05d7a6c1414e62f532094aa39dc1&sid=4fdc76b08a4c5a43).

<img width="2656" height="1560" alt="CleanShot 2026-11-12 at 1 12 30
PM@2x"
src="https://github.com/user-attachments/assets/4e81033a-c754-46db-845d-586d1d71e035"
/>

Closes AI-1197
2026-11-13 11:02:46 -05:00

201 lines
6.1 KiB
TypeScript

import * as ai from 'ai'
import {
convertToModelMessages,
isStepCount,
type LanguageModel,
type ModelMessage,
type SystemModelMessage,
type TimeoutConfiguration,
type ToolSet,
type UIMessage,
} from 'ai'
import { startSpan, traced, withCurrent, wrapAISDK, type Span } from 'braintrust'
import type { AssistantEvalInput } from '@/evals/scorer'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { buildAssistantContextMessages, NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'
import { IS_TRACING_ENABLED } from '@/lib/ai/braintrust-logger'
import {
buildSystemPrompt,
hideToolErrorsFromModel,
prepareMessagesForModel,
} from '@/lib/ai/generate-assistant-response.utils'
import type { contract as renameChatContract } from '@/lib/ai/tools/rename-chat'
import type { ToolContractInput } from '@/lib/ai/tools/types'
const { streamText: tracedStreamText } = wrapAISDK(ai)
export async function generateAssistantResponse({
messages: rawMessages,
model,
tools,
aiOptInLevel = 'schema',
getSchemas,
projectRef,
projectRegion,
chatId,
chatName,
allowTracing,
supportMode,
userId,
orgId,
orgSlug,
planId,
isHighComplianceProject,
includesLogsSnippets,
systemProviderOptions,
providerOptions,
requestedModel,
effectiveModel,
abortSignal,
timeout,
onSpanCreated,
}: {
messages: UIMessage[]
model: LanguageModel
tools: ToolSet
aiOptInLevel?: AiOptInLevel
getSchemas?: () => Promise<string>
projectRef?: string
projectRegion?: string
chatId?: string
chatName?: string
allowTracing?: boolean
supportMode?: boolean
userId?: string
orgId?: number
orgSlug?: string
planId?: string
isHighComplianceProject?: boolean
/** Whether any user message in the conversation attached a logs (ClickHouse) query. */
includesLogsSnippets?: boolean
requestedModel?: string
/** The model actually used after entitlement/throttle fallback. */
effectiveModel?: string
systemProviderOptions?: Record<string, any>
providerOptions?: Record<string, any>
abortSignal?: AbortSignal
timeout?: TimeoutConfiguration<ToolSet>
onSpanCreated?: (spanId: string) => void
}) {
const shouldTrace = allowTracing ?? IS_TRACING_ENABLED
const run = async (span?: Span) => {
const messages = prepareMessagesForModel(rawMessages, aiOptInLevel)
const schemasString =
aiOptInLevel !== 'disabled' && getSchemas
? shouldTrace
? await traced(async () => getSchemas(), { name: 'getSchemas', type: 'function' })
: await getSchemas()
: NO_SCHEMA_ACCESS_MESSAGE
// Important: do not use per-request dynamic content in the system prompt or Bedrock will
// not cache it. The tools section varies with the tool set. That costs no extra cache
// misses: providers cache tools before the system prompt, so a change to the tool set
// already invalidates the cached system prompt.
const system = buildSystemPrompt(Object.keys(tools))
const systemMessage: SystemModelMessage = {
role: 'system',
content: system,
...(systemProviderOptions && { providerOptions: systemProviderOptions }),
}
const coreMessages: ModelMessage[] = [
...buildAssistantContextMessages({
projectRef,
chatName,
schemasString,
supportMode,
includesLogsSnippets,
aiOptInLevel,
}),
...(await convertToModelMessages(messages)),
]
const streamTextFn = shouldTrace ? tracedStreamText : ai.streamText
// onEnd still fires after an abort once a step has finished, so end the span only once.
let isSpanEnded = false
const endSpan = (metadata: Record<string, unknown>) => {
if (!span || isSpanEnded) return
isSpanEnded = true
span.log({ metadata })
span.end()
}
return streamTextFn({
model,
instructions: systemMessage,
stopWhen: isStepCount(20),
messages: coreMessages,
prepareStep: ({ messages }) => ({
messages: hideToolErrorsFromModel(messages, aiOptInLevel),
}),
...(providerOptions && { providerOptions }),
tools,
...(abortSignal && { abortSignal }),
...(timeout && { timeout }),
...(span && {
onEnd: ({ steps, finishReason }) => {
const metadata: Record<string, unknown> = {
isFinalStep: finishReason === 'stop',
}
for (const step of steps) {
for (const toolCall of step.toolCalls) {
if (toolCall.toolName === 'rename_chat') {
const { newName } = toolCall.input as ToolContractInput<typeof renameChatContract>
metadata.chatName = newName
}
}
}
endSpan(metadata)
},
// The call aborts on either the request signal or `timeout`, so an unaborted
// request signal means the deadline stopped it.
onAbort: () => {
endSpan({ isAborted: true, isTimedOut: !abortSignal?.aborted })
},
}),
} satisfies Parameters<typeof ai.streamText>[0])
}
if (shouldTrace) {
// startSpan instead of traced() so we control when the span closes via onEnd.
// Scorers read from child spans (LLM + tool) in the trace rather than a root span output field.
const span = startSpan({ name: 'generateAssistantResponse', type: 'function' })
onSpanCreated?.(span.id)
const lastUserMessage = rawMessages.findLast((m) => m.role === 'user')
const lastUserText = lastUserMessage?.parts
?.filter((p): p is { type: 'text'; text: string } => p.type === 'text')
.map((p) => p.text)
.join('\n')
span.log({
input: { prompt: lastUserText ?? '' } satisfies AssistantEvalInput,
metadata: {
projectRef,
projectRegion,
chatId,
chatName,
aiOptInLevel,
userId,
orgId,
orgSlug,
planId,
isHighComplianceProject,
requestedModel,
effectiveModel,
gitBranch: process.env.VERCEL_GIT_COMMIT_REF,
environment: process.env.NEXT_PUBLIC_ENVIRONMENT,
},
})
return withCurrent(span, () => run(span))
}
return run()
}