-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathinvokeDiffReviewLlm.ts
More file actions
66 lines (54 loc) · 2.24 KB
/
invokeDiffReviewLlm.ts
File metadata and controls
66 lines (54 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import OpenAI from "openai";
import { sourcebot_file_diff_review, sourcebot_file_diff_review_schema } from "@/features/agents/review-agent/types";
import { env } from "@sourcebot/shared";
import fs from "fs";
import path from "path";
import { createLogger } from "@sourcebot/shared";
const logger = createLogger('invoke-diff-review-llm');
export const getReviewAgentLogDir = (): string => {
return path.join(env.DATA_CACHE_DIR, 'review-agent');
};
const validateLogPath = (logPath: string): void => {
const resolved = path.resolve(logPath);
const logDir = getReviewAgentLogDir();
if (!resolved.startsWith(logDir + path.sep)) {
throw new Error('reviewAgentLogPath escapes log directory');
}
};
export const invokeDiffReviewLlm = async (reviewAgentLogPath: string | undefined, prompt: string): Promise<sourcebot_file_diff_review> => {
logger.debug("Executing invoke_diff_review_llm");
if (!env.OPENAI_API_KEY) {
logger.error("OPENAI_API_KEY is not set, skipping review agent");
throw new Error("OPENAI_API_KEY is not set, skipping review agent");
}
const openai = new OpenAI({
apiKey: env.OPENAI_API_KEY,
});
if (reviewAgentLogPath) {
validateLogPath(reviewAgentLogPath);
fs.appendFileSync(reviewAgentLogPath, `\n\nPrompt:\n${prompt}`);
}
try {
const completion = await openai.chat.completions.create({
model: "gpt-4.1-mini",
messages: [
{ role: "system", content: prompt }
]
});
const openaiResponse = completion.choices[0].message.content;
if (reviewAgentLogPath) {
validateLogPath(reviewAgentLogPath);
fs.appendFileSync(reviewAgentLogPath, `\n\nResponse:\n${openaiResponse}`);
}
const diffReviewJson = JSON.parse(openaiResponse || '{}');
const diffReview = sourcebot_file_diff_review_schema.safeParse(diffReviewJson);
if (!diffReview.success) {
throw new Error(`Invalid diff review format: ${diffReview.error}`);
}
logger.debug("Completed invoke_diff_review_llm");
return diffReview.data;
} catch (error) {
logger.error('Error calling OpenAI:', error);
throw error;
}
}