parse-client-code.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { generateText, Output } from 'ai'
  2. import { source } from 'common-tags'
  3. import { NextApiRequest, NextApiResponse } from 'next'
  4. import { z } from 'zod'
  5. import { getModel } from '@/lib/ai/model'
  6. import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
  7. import apiWrapper from '@/lib/api/apiWrapper'
  8. const codeSchema = z.object({
  9. sql: z
  10. .string()
  11. .nullable()
  12. .describe(
  13. 'The converted SQL query from the provided client library code. Return null if the code is invalid'
  14. ),
  15. valid: z.boolean().describe('Whether the provided client library code is valid.'),
  16. })
  17. async function handler(req: NextApiRequest, res: NextApiResponse) {
  18. const { method } = req
  19. switch (method) {
  20. case 'POST':
  21. return handlePost(req, res)
  22. default:
  23. res.setHeader('Allow', ['POST'])
  24. res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
  25. }
  26. }
  27. export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
  28. const {
  29. body: { code },
  30. } = req
  31. if (!code) return res.status(400).json({ error: 'Code is required' })
  32. try {
  33. const { modelParams, error: modelError } = await getModel({
  34. provider: 'openai',
  35. modelEntry: DEFAULT_COMPLETION_MODEL,
  36. })
  37. if (modelError) {
  38. return res.status(500).json({ error: modelError.message })
  39. }
  40. const result = await generateText({
  41. ...modelParams,
  42. output: Output.object({ schema: codeSchema }),
  43. prompt: source`
  44. Convert the follow Briven client library code into SQL. The response should only be in JSON with the structure: { sql: string, valid: boolean }
  45. If the client library code does not look valid, return { sql: null, valid: false }. Otherwise return valid as true and sql as the converted SQL query
  46. ${code}
  47. `,
  48. })
  49. return res.json(result.output)
  50. } catch (error) {
  51. if (error instanceof Error) {
  52. console.error(`Code parsing to SQL failed: ${error.message}`)
  53. // Check for context length error
  54. if (error.message.includes('context_length') || error.message.includes('too long')) {
  55. return res.status(400).json({
  56. error:
  57. 'The provided code snippet is too large for Briven Assistant to ingest. Try splitting it into smaller queries.',
  58. })
  59. }
  60. } else {
  61. console.log(`Unknown error: ${error}`)
  62. }
  63. return res.status(500).json({
  64. error: 'There was an unknown error parsing the client library code. Please try again.',
  65. })
  66. }
  67. }
  68. const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
  69. apiWrapper(req, res, handler, { withAuth: true })
  70. export default wrapper