-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
65 lines (52 loc) · 1.52 KB
/
Copy pathbackground.js
File metadata and controls
65 lines (52 loc) · 1.52 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
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({
openaiKey: "put your own"
});
console.log("API key stored");
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "ANALYZE_CODE") {
analyzeCodeWithLLM(message.payload)
.then(result => sendResponse({ result }))
.catch(error => {
console.error("LLM Error:", error);
sendResponse({ error: error.message });
});
return true;
}
});
// send to llm
async function analyzeCodeWithLLM(code) {
const { openaiKey } = await chrome.storage.local.get("openaiKey");
if (!openaiKey) {
throw new Error("OpenAI API key not found.");
}
const prompt = `
You are a senior algorithm expert.
Analyze the following code and provide:
1. Time Complexity (Big-O)
2. Space Complexity (Big-O)
3. Short explanation (2-4 sentences)
Code: ${code}
`;
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${openaiKey}`
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are an expert in algorithms." },
{ role: "user", content: prompt }
],
temperature: 0
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error?.message || "OpenAI API error");
}
return data.choices[0].message.content;
}