-
Notifications
You must be signed in to change notification settings - Fork 27
438 lines (379 loc) · 16.8 KB
/
auto-llm-issue-review.yml
File metadata and controls
438 lines (379 loc) · 16.8 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
name: "LLM Issue Review (Model Label Trigger)"
on:
issues:
types: [labeled]
workflow_dispatch:
inputs:
issue_number:
description: "Issue number"
required: true
type: number
llm_provider:
description: "LLM provider (optional: openai, gemini, anthropic)"
required: false
default: ""
type: string
llm_model:
description: "Model name (provider-specific, e.g. gpt-5.4, gpt-5.4-pro, gpt-5.3-codex)"
required: false
default: ""
type: string
trigger_label:
description: "Label to emulate (optional)"
required: false
default: ""
type: string
permissions:
contents: read
issues: write
concurrency:
group: llm-issue-review-${{ github.repository }}-${{ github.event.issue.number || github.event.inputs.issue_number }}
cancel-in-progress: true
jobs:
review:
runs-on: [self-hosted, linux, x64, big]
steps:
- name: Run LLM issue review and comment
uses: actions/github-script@v7.1.0
env:
ISSUE_NUMBER: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.issue_number || github.event.issue.number }}
TRIGGER_LABEL: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.trigger_label || github.event.label.name }}
LLM_PROVIDER: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.llm_provider || '' }}
LLM_MODEL: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.llm_model || '' }}
OPENAI_BASE_URL: ${{ vars.OPENAI_BASE_URL || 'https://api.openai.com/v1' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const issueNumber = Number(process.env.ISSUE_NUMBER || "0");
if (!issueNumber) {
core.setFailed("ISSUE_NUMBER is required (set inputs.issue_number for workflow_dispatch).");
return;
}
const triggerLabel = (process.env.TRIGGER_LABEL || "").trim();
if (!triggerLabel) {
core.info("No trigger label found; skipping.");
return;
}
function parseProviderModelFromLabel(label) {
const raw = String(label || "").trim();
if (!raw) return null;
// Explicit formats:
// - llm:<provider>:<model>
// - <provider>:<model> (provider in {openai, gemini, anthropic})
let m = raw.match(/^llm:([^:]+):(.+)$/i);
if (m) return { provider: m[1].toLowerCase(), model: m[2].trim(), raw };
m = raw.match(/^(openai|gemini|anthropic):(.+)$/i);
if (m) return { provider: m[1].toLowerCase(), model: m[2].trim(), raw };
// Short formats based on common model prefixes
if (/^gpt-/i.test(raw) || /^o\d/i.test(raw) || /^o1/i.test(raw)) {
return { provider: "openai", model: raw, raw };
}
if (/^gemini/i.test(raw)) {
const model = raw.toLowerCase() === "gemini3" ? "gemini-3" : raw;
return { provider: "gemini", model, raw };
}
if (/^claude-/i.test(raw)) {
return { provider: "anthropic", model: raw, raw };
}
return null;
}
const labelParsed = parseProviderModelFromLabel(triggerLabel);
if (!labelParsed) {
core.info(`Label '${triggerLabel}' does not look like a model label; skipping.`);
return;
}
const provider = (process.env.LLM_PROVIDER || labelParsed.provider || "").trim().toLowerCase();
const model = (process.env.LLM_MODEL || labelParsed.model || "").trim();
if (!provider || !model) {
core.setFailed(`Unable to determine provider/model from label '${triggerLabel}'.`);
return;
}
const marker = `<!-- llm-issue-review:${triggerLabel} -->`;
// Skip if already commented for this label
const { data: comments } = await github.rest.issues.listComments({
owner,
repo,
issue_number: issueNumber,
per_page: 100,
});
if (comments.some(c => typeof c.body === "string" && c.body.includes(marker))) {
core.info("A review comment for this label already exists; skipping.");
return;
}
const issueResp = await github.rest.issues.get({
owner,
repo,
issue_number: issueNumber,
});
const issue = issueResp.data;
async function tryGetRepoFile(path) {
try {
const res = await github.rest.repos.getContent({
owner,
repo,
path,
});
if (!res?.data || Array.isArray(res.data) || res.data.type !== "file") return null;
const b64 = res.data.content || "";
const buf = Buffer.from(b64, "base64");
const text = buf.toString("utf8");
return text;
} catch (e) {
return null;
}
}
function extractLikelyPaths(text) {
const body = String(text || "");
const found = new Set();
// Backticked paths
for (const m of body.matchAll(/`([^`]+)`/g)) {
const p = (m[1] || "").trim();
if (p.includes("/") && !p.startsWith("http")) found.add(p);
}
// Loose paths (very heuristic)
for (const m of body.matchAll(/(^|\s)([\w./-]+\.[\w]+)(\s|$)/g)) {
const p = (m[2] || "").trim();
if (p.includes("/") && !p.startsWith("http")) found.add(p);
}
return Array.from(found).slice(0, 5);
}
const referencedPaths = extractLikelyPaths(issue.body || "");
const fileSnippets = [];
for (const p of referencedPaths) {
const content = await tryGetRepoFile(p);
if (!content) continue;
const snippet = content.length > 6000 ? content.slice(0, 6000) + "\n...(truncated)..." : content;
fileSnippets.push({ path: p, snippet });
}
const automationTxt = await tryGetRepoFile("AUTOMATION.txt");
const systemPrompt = [
"You are an expert software engineer.",
"You are reviewing a GitHub issue and optionally some referenced code.",
"Be specific, actionable, and concise.",
"Prioritize correctness, security, maintainability, and tests.",
"If information is missing, ask short clarifying questions.",
].join(" ");
const promptParts = [];
promptParts.push(`Repository: ${owner}/${repo}`);
promptParts.push(`Issue #${issueNumber}: ${issue.title || ""}`);
promptParts.push(`Trigger label: ${triggerLabel}`);
promptParts.push("");
promptParts.push("Issue body:");
promptParts.push(issue.body || "(no body)");
if (automationTxt) {
promptParts.push("");
promptParts.push("AUTOMATION.txt (guidance):");
promptParts.push(automationTxt.length > 4000 ? automationTxt.slice(0, 4000) + "\n...(truncated)..." : automationTxt);
}
if (fileSnippets.length) {
promptParts.push("");
promptParts.push("Referenced file snippets:");
for (const f of fileSnippets) {
promptParts.push(`---\nFile: ${f.path}\n\n${f.snippet}`);
}
}
promptParts.push("");
promptParts.push("Output format:");
promptParts.push("- Short summary");
promptParts.push("- Issues and risks (High/Medium/Low)");
promptParts.push("- Proposed plan (next steps)");
promptParts.push("- Suggested tests");
const userPrompt = promptParts.join("\n");
function getOpenAIReasoningEffort(model) {
const normalized = String(model || "").trim().toLowerCase();
if (!normalized) return null;
if (normalized === "gpt-5.4" || normalized === "gpt-5.4-pro" || normalized === "gpt-5.3-codex") {
return "xhigh";
}
if (normalized === "gpt-5-pro") {
return "high";
}
if (/^gpt-5(?:[.-]|$)/.test(normalized)) {
return "high";
}
return null;
}
function extractResponsesText(data) {
if (typeof data?.output_text === "string" && data.output_text.trim()) {
return data.output_text.trim();
}
const parts = [];
for (const item of data?.output || []) {
if (item?.type !== "message") continue;
for (const content of item.content || []) {
if ((content?.type === "output_text" || content?.type === "text") && typeof content.text === "string") {
parts.push(content.text);
}
}
}
return parts.join("\n").trim();
}
async function callOpenAI({ apiKey, baseUrl, model, messages }) {
if (!apiKey) throw new Error("OPENAI_API_KEY is not set.");
const normalizedModel = String(model || "").trim().toLowerCase();
const reasoningEffort = getOpenAIReasoningEffort(normalizedModel);
if (normalizedModel === "gpt-5.3-codex") {
const url = `${baseUrl.replace(/\/$/, "")}/responses`;
const payload = {
model,
input: messages.map(message => ({
role: message.role,
content: message.content,
})),
max_output_tokens: 2048,
};
if (reasoningEffort) {
payload.reasoning = { effort: reasoningEffort };
}
const resp = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`OpenAI Responses API error (${resp.status}): ${text}`);
}
const data = await resp.json();
const content = extractResponsesText(data);
if (!content) throw new Error("OpenAI Responses API returned no content.");
return { content, reasoningEffort };
}
const url = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
const payload = { model, messages };
const isGpt5ish = /gpt-?5/i.test(model) || /^o\d/i.test(model) || /^o1/i.test(model);
if (isGpt5ish) {
payload.max_completion_tokens = 2048;
if (reasoningEffort) {
payload.reasoning_effort = reasoningEffort;
}
} else {
payload.max_tokens = 2048;
payload.temperature = 0.2;
}
const resp = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`OpenAI API error (${resp.status}): ${text}`);
}
const data = await resp.json();
const content = data?.choices?.[0]?.message?.content;
if (!content) throw new Error("OpenAI API returned no content.");
return { content, reasoningEffort };
}
async function callGemini({ apiKey, model, prompt }) {
if (!apiKey) throw new Error("GEMINI_API_KEY is not set.");
const geminiModel = model || "gemini-1.5-pro";
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(geminiModel)}:generateContent?key=${encodeURIComponent(apiKey)}`;
const payload = {
contents: [{ role: "user", parts: [{ text: prompt }] }],
generationConfig: { temperature: 0.2, maxOutputTokens: 2048 },
};
const resp = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Gemini API error (${resp.status}): ${text}`);
}
const data = await resp.json();
const parts = data?.candidates?.[0]?.content?.parts || [];
const text = parts.map(p => p.text || "").join("").trim();
if (!text) throw new Error("Gemini API returned no content.");
return text;
}
async function callAnthropic({ apiKey, model, system, prompt }) {
if (!apiKey) throw new Error("ANTHROPIC_API_KEY is not set.");
const anthropicModel = model || "claude-3-5-sonnet-latest";
const url = "https://api.anthropic.com/v1/messages";
const payload = {
model: anthropicModel,
max_tokens: 2048,
temperature: 0.2,
system,
messages: [{ role: "user", content: prompt }],
};
const resp = await fetch(url, {
method: "POST",
headers: {
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Anthropic API error (${resp.status}): ${text}`);
}
const data = await resp.json();
const text = (data?.content || []).map(p => p.text || "").join("").trim();
if (!text) throw new Error("Anthropic API returned no content.");
return text;
}
let reviewText = "";
let reasoningEffort = "";
try {
if (provider === "openai") {
const openAIResult = await callOpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseUrl: process.env.OPENAI_BASE_URL,
model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt },
],
});
reviewText = openAIResult.content;
reasoningEffort = openAIResult.reasoningEffort || "";
} else if (provider === "gemini") {
reviewText = await callGemini({
apiKey: process.env.GEMINI_API_KEY,
model,
prompt: `${systemPrompt}\n\n${userPrompt}`,
});
} else if (provider === "anthropic") {
reviewText = await callAnthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model,
system: systemPrompt,
prompt: userPrompt,
});
} else {
throw new Error(`Unsupported provider: ${provider}`);
}
} catch (e) {
core.setFailed(e.message || String(e));
return;
}
const commentBody = [
marker,
`Provider: ${provider}`,
`Model: ${model}`,
...(reasoningEffort ? [`Reasoning effort: ${reasoningEffort}`] : []),
"",
reviewText,
].join("\n");
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: commentBody,
});