difflytic
Version:
AI-powered code review for GitLab/GitHub MRs using OpenAI and more.
53 lines (52 loc) • 2.54 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAI = void 0;
const BaseAI_1 = require("./BaseAI");
const Config_1 = __importDefault(require("../utils/Config"));
class OpenAI extends BaseAI_1.BaseAI {
constructor() {
super();
this.apiUrl = Config_1.default.get('OPENAI_API_URL', 'https://api.openai.com/v1/chat/completions');
this.apiKey = Config_1.default.get('OPENAI_API_KEY');
if (!this.apiKey) {
throw new Error('OPENAI_API_KEY is required in environment variables');
}
}
async analyzeCode(code, mode = 'file') {
let prompt = '';
if (mode === 'function') {
prompt = `You are a code reviewer. Review the following code changes at the function level. Focus only on code implementation. For each suggestion or improvement, provide a code example or replacement using code blocks. Avoid unnecessary explanations or complexity.\n\n${code}`;
}
else if (mode === 'block') {
prompt = `You are a code reviewer. Review the following code changes at the block level. Focus only on code implementation. For each suggestion or improvement, provide a code example or replacement using code blocks. Avoid unnecessary explanations or complexity.\n\n${code}`;
}
else {
prompt = `You are a code reviewer. Review the following code changes. Focus only on code implementation. For each suggestion or improvement, provide a code example or replacement using code blocks. Avoid unnecessary explanations or complexity.\n\n${code}`;
}
const body = {
model: 'gpt-4.1-nano',
messages: [
{ role: 'system', content: 'You are an expert code reviewer.' },
{ role: 'user', content: prompt }
],
max_tokens: 512
};
const res = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
});
if (!res.ok) {
throw new Error(`OpenAI API error: ${res.status} ${res.statusText}`);
}
const data = await res.json();
return data.choices?.[0]?.message?.content || '';
}
}
exports.OpenAI = OpenAI;