ai.ts124 lines, 3.2 KB
| 1 | import OpenAI from "openai"; |
| 2 | import { z } from "zod"; |
| 3 | |
| 4 | let openaiClient: OpenAI | null = null; |
| 5 | |
| 6 | function getOpenAIClient(): OpenAI { |
| 7 | const apiKey = process.env.OPENAI_API_KEY; |
| 8 | if (!apiKey) { |
| 9 | throw new Error("OPENAI_API_KEY is not set"); |
| 10 | } |
| 11 | |
| 12 | if (!openaiClient) { |
| 13 | openaiClient = new OpenAI({ apiKey }); |
| 14 | } |
| 15 | |
| 16 | return openaiClient; |
| 17 | } |
| 18 | |
| 19 | export const ReviewCommentSchema = z.object({ |
| 20 | file: z.string(), |
| 21 | line: z.number(), |
| 22 | severity: z.enum(["critical", "high", "medium", "low"]), |
| 23 | category: z.enum(["bug", "security", "performance", "style", "suggestion"]), |
| 24 | message: z.string(), |
| 25 | suggestion: z.string().optional(), |
| 26 | }); |
| 27 | |
| 28 | export const ReviewResultSchema = z.object({ |
| 29 | summary: z.string(), |
| 30 | riskScore: z.number().min(0).max(100), |
| 31 | comments: z.array(ReviewCommentSchema), |
| 32 | }); |
| 33 | |
| 34 | export type ReviewComment = z.infer<typeof ReviewCommentSchema>; |
| 35 | export type ReviewResult = z.infer<typeof ReviewResultSchema>; |
| 36 | |
| 37 | interface FileChange { |
| 38 | filename: string; |
| 39 | status: string; |
| 40 | additions: number; |
| 41 | deletions: number; |
| 42 | patch?: string; |
| 43 | } |
| 44 | |
| 45 | const SYSTEM_PROMPT = `You are an expert code reviewer. Analyze the provided pull request diff and provide a structured review. |
| 46 | |
| 47 | Your review should: |
| 48 | 1. Identify bugs, security issues, performance problems, and code style issues |
| 49 | 2. Provide a brief summary of the changes |
| 50 | 3. Assign a risk score (0-100) based on the complexity and potential issues |
| 51 | 4. Give specific, actionable feedback with line numbers |
| 52 | |
| 53 | Respond with valid JSON matching this schema: |
| 54 | { |
| 55 | "summary": "Brief summary of changes and overall assessment", |
| 56 | "riskScore": 0-100, |
| 57 | "comments": [ |
| 58 | { |
| 59 | "file": "path/to/file.ts", |
| 60 | "line": 42, |
| 61 | "severity": "critical" | "high" | "medium" | "low", |
| 62 | "category": "bug" | "security" | "performance" | "style" | "suggestion", |
| 63 | "message": "What the issue is", |
| 64 | "suggestion": "How to fix it (optional)" |
| 65 | } |
| 66 | ] |
| 67 | } |
| 68 | |
| 69 | Severity guide: |
| 70 | - critical: Security vulnerabilities, data loss, crashes |
| 71 | - high: Bugs that will cause issues in production |
| 72 | - medium: Should be fixed but won't break things |
| 73 | - low: Style issues, minor improvements |
| 74 | |
| 75 | Be concise but specific. Reference exact line numbers from the diff.`; |
| 76 | |
| 77 | export async function reviewCode( |
| 78 | prTitle: string, |
| 79 | files: FileChange[], |
| 80 | ): Promise<ReviewResult> { |
| 81 | const diffContent = files |
| 82 | .filter((f) => f.patch) |
| 83 | .map( |
| 84 | (f) => `### ${f.filename} (${f.status})\n\`\`\`diff\n${f.patch}\n\`\`\``, |
| 85 | ) |
| 86 | .join("\n\n"); |
| 87 | |
| 88 | if (!diffContent.trim()) { |
| 89 | return { |
| 90 | summary: "No code changes to review (binary files or empty diff).", |
| 91 | riskScore: 0, |
| 92 | comments: [], |
| 93 | }; |
| 94 | } |
| 95 | |
| 96 | const userPrompt = `Review this pull request: |
| 97 | |
| 98 | **Title:** ${prTitle} |
| 99 | |
| 100 | **Changes:** |
| 101 | ${diffContent}`; |
| 102 | |
| 103 | const openai = getOpenAIClient(); |
| 104 | const response = await openai.chat.completions.create({ |
| 105 | model: "gpt-4o-mini", |
| 106 | messages: [ |
| 107 | { role: "system", content: SYSTEM_PROMPT }, |
| 108 | { role: "user", content: userPrompt }, |
| 109 | ], |
| 110 | response_format: { type: "json_object" }, |
| 111 | temperature: 0.3, |
| 112 | max_tokens: 2000, |
| 113 | }); |
| 114 | |
| 115 | const content = response.choices[0]?.message?.content; |
| 116 | if (!content) { |
| 117 | throw new Error("No response from AI"); |
| 118 | } |
| 119 | |
| 120 | const parsed = JSON.parse(content); |
| 121 | const validated = ReviewResultSchema.parse(parsed); |
| 122 | |
| 123 | return validated; |
| 124 | } |