rate.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import { generateText, Output } from 'ai'
  2. import { currentLogger } from 'braintrust'
  3. import { IS_PLATFORM } from 'common'
  4. import { NextApiRequest, NextApiResponse } from 'next'
  5. import { z } from 'zod'
  6. import { rateMessageResponseSchema } from '@/components/ui/AIAssistantPanel/Message.utils'
  7. import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
  8. import { getOrgAIDetails, getProjectAIDetails } from '@/lib/ai/ai-details'
  9. import { IS_TRACING_ENABLED, isTracingAllowed } from '@/lib/ai/braintrust-logger'
  10. import { getModel } from '@/lib/ai/model'
  11. import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
  12. import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer'
  13. import apiWrapper from '@/lib/api/apiWrapper'
  14. export const maxDuration = 30
  15. async function handler(req: NextApiRequest, res: NextApiResponse) {
  16. const { method } = req
  17. switch (method) {
  18. case 'POST':
  19. return handlePost(req, res)
  20. default:
  21. res.setHeader('Allow', ['POST'])
  22. res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
  23. }
  24. }
  25. const requestBodySchema = z.object({
  26. rating: z.enum(['positive', 'negative']),
  27. messages: z.array(z.any()),
  28. messageId: z.string(),
  29. projectRef: z.string(),
  30. orgSlug: z.string().optional(),
  31. reason: z.string().optional(),
  32. spanId: z.string().optional(),
  33. })
  34. export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
  35. const authorization = req.headers.authorization
  36. const accessToken = authorization?.replace('Bearer ', '')
  37. if (IS_PLATFORM && !accessToken) {
  38. return res.status(401).json({ error: 'Authorization token is required' })
  39. }
  40. const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
  41. const { data, error: parseError } = requestBodySchema.safeParse(body)
  42. if (parseError) {
  43. return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
  44. }
  45. const { rating, messages: rawMessages, projectRef, orgSlug, reason, spanId } = data
  46. let aiOptInLevel: AiOptInLevel = 'disabled'
  47. let orgHasHipaaAddon: boolean | undefined
  48. let projectIsSensitive: boolean | undefined
  49. let projectRegion: string | undefined
  50. if (!IS_PLATFORM) {
  51. aiOptInLevel = 'schema'
  52. }
  53. if (IS_PLATFORM && orgSlug && authorization && projectRef) {
  54. try {
  55. const [orgDetails, projectDetails] = await Promise.all([
  56. getOrgAIDetails({ orgSlug, authorization }),
  57. getProjectAIDetails({ projectRef, authorization }),
  58. ])
  59. aiOptInLevel = orgDetails.aiOptInLevel
  60. orgHasHipaaAddon = orgDetails.hasHipaaAddon
  61. projectIsSensitive = projectDetails.isSensitive
  62. projectRegion = projectDetails.region
  63. } catch (error) {
  64. return res.status(400).json({
  65. error: 'There was an error fetching your organization details',
  66. })
  67. }
  68. }
  69. // Only returns last 7 messages
  70. // Filters out tool outputs based on opt-in level using sanitizeMessagePart
  71. const messages = (rawMessages || []).slice(-7).map((msg: any) => {
  72. if (msg && msg.role === 'assistant' && 'results' in msg) {
  73. const cleanedMsg = { ...msg }
  74. delete cleanedMsg.results
  75. return cleanedMsg
  76. }
  77. if (msg && msg.role === 'assistant' && msg.parts) {
  78. const cleanedParts = msg.parts.map((part: any) => {
  79. return sanitizeMessagePart(part, aiOptInLevel)
  80. })
  81. return { ...msg, parts: cleanedParts }
  82. }
  83. return msg
  84. })
  85. try {
  86. const { modelParams, error: modelError } = await getModel({
  87. provider: 'openai',
  88. modelEntry: DEFAULT_COMPLETION_MODEL,
  89. })
  90. if (modelError) {
  91. return res.status(500).json({ error: modelError.message })
  92. }
  93. const { output } = await generateText({
  94. ...modelParams,
  95. output: Output.object({ schema: rateMessageResponseSchema }),
  96. prompt: `
  97. Your job is to look at a Briven Assistant conversation, which the user has given feedback on, and classify it.
  98. The user gave this feedback: ${rating === 'positive' ? 'THUMBS UP (positive)' : 'THUMBS DOWN (negative)'}
  99. ${reason ? `\nUser's reason: ${reason}` : ''}
  100. Raw conversation:
  101. ${JSON.stringify(messages)}
  102. Instructions:
  103. 1. Classify the conversation into ONE of these categories:
  104. - sql_generation: Generating SQL queries, DML statements
  105. - schema_design: Creating tables, columns, relationships
  106. - rls_policies: Row Level Security policies
  107. - edge_functions: Edge Functions or serverless functions
  108. - database_optimization: Performance, indexes, optimization
  109. - debugging: Helping debug errors or issues
  110. - general_help: General questions about Briven features
  111. - other: Anything else
  112. `,
  113. })
  114. // Log feedback to Braintrust if tracing is enabled and span ID is available
  115. if (
  116. IS_TRACING_ENABLED &&
  117. isTracingAllowed({ orgHasHipaaAddon, projectIsSensitive, projectRegion }) &&
  118. spanId
  119. ) {
  120. try {
  121. const logger = currentLogger()
  122. logger?.logFeedback({
  123. id: spanId,
  124. scores: { 'User Rating': rating === 'positive' ? 1 : 0 },
  125. comment: reason,
  126. source: 'external',
  127. })
  128. logger?.updateSpan({
  129. id: spanId,
  130. metadata: { feedbackCategory: output.category },
  131. })
  132. } catch (error) {
  133. console.error('Failed to log feedback to Braintrust:', error)
  134. }
  135. }
  136. return res.json({
  137. category: output.category,
  138. })
  139. } catch (error) {
  140. if (error instanceof Error) {
  141. console.error(`Classifying feedback failed:`, error)
  142. // Check for context length error
  143. if (error.message.includes('context_length') || error.message.includes('too long')) {
  144. return res.status(400).json({
  145. error: 'The conversation is too large to analyze',
  146. })
  147. }
  148. } else {
  149. console.error(`Unknown error: ${error}`)
  150. }
  151. return res.status(500).json({
  152. error: 'There was an unknown error analyzing the feedback.',
  153. })
  154. }
  155. }
  156. const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
  157. apiWrapper(req, res, handler, { withAuth: true })
  158. export default wrapper