forked from InverseUI/InverseUI-Recorder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_service.js
More file actions
180 lines (159 loc) · 6.62 KB
/
Copy pathllm_service.js
File metadata and controls
180 lines (159 loc) · 6.62 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
const MODEL_CONFIGS = {
'gpt4': {
endpoint: 'https://api.openai.com/v1/chat/completions',
headers: (apiKey) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
}),
prepareBody: (messages) => ({
model: 'gpt-4-turbo',
messages: messages,
temperature: 0.7,
max_tokens: 4000
}),
parseResponse: (data) => data.choices[0]?.message?.content || '',
},
'gpt3.5': {
endpoint: 'https://api.openai.com/v1/chat/completions',
headers: (apiKey) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
}),
prepareBody: (messages) => ({
model: 'gpt-3.5-turbo',
messages: messages,
temperature: 0.7,
max_tokens: 4000
}),
parseResponse: (data) => data.choices[0]?.message?.content || '',
},
'deepseek': {
endpoint: 'https://api.deepseek.com/v1/chat/completions',
headers: (apiKey) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
}),
prepareBody: (messages) => ({
model: 'deepseek-coder',
messages: messages,
temperature: 0.2,
max_tokens: 4000,
stream: false,
}),
parseResponse: (data) => {
console.log("Parsing Deepseek response:", data);
if (!data) {
throw new Error("Empty response from Deepseek API");
}
if (data.output && typeof data.output === 'string') {
return data.output.trim();
} else if (data.choices && data.choices.length > 0) {
return data.choices[0]?.message?.content ||
data.choices[0]?.text ||
'';
} else {
console.error("Unexpected Deepseek response format:", data);
throw new Error("Cannot parse Deepseek response - unexpected format");
}
},
}
};
export async function generateWithLLM(messages, llmConfig, jsonStr, popupId, errorHTML) {
const modelName = llmConfig.active_model;
const apiKey = llmConfig.models[modelName]?.api_key;
const modelConfig = MODEL_CONFIGS[modelName];
if (!modelConfig) {
console.error(`Unsupported model: ${modelName}`);
showErrorPopup(popupId, errorHTML);
throw new Error(`Unsupported model: ${modelName}`);
}
if (!apiKey) {
console.error(`API key for model ${modelName} is missing.`);
showErrorPopup(popupId, errorHTML);
throw new Error(`API key for model ${modelName} is missing.`);
}
// Log the request details for debugging (without exposing the full API key)
console.log(`Making request to: ${modelConfig.endpoint}`);
console.log(`Model: ${modelName}`);
console.log(`API Key format: ${apiKey.substring(0, 8)}...`);
// Check if messages is properly formatted
if (!Array.isArray(messages)) {
console.error('Messages is not an array:', typeof messages);
showErrorPopup(popupId, errorHTML);
throw new Error('Messages must be an array');
}
console.log('Messages structure:', messages.map(m => ({role: m.role, contentLength: m.content?.length || 0})));
try {
// Prepare the request body with updated model names for OpenAI API
const requestBody = {
...modelConfig.prepareBody(messages),
// OpenAI may have changed their model naming convention
model: modelName === 'gpt4' ? 'gpt-4-turbo' : modelConfig.prepareBody(messages).model
};
console.log('Request body structure:', JSON.stringify(requestBody, (key, value) => {
// Don't log the full content to avoid console clutter
if (key === 'content' && typeof value === 'string' && value.length > 100) {
return value.substring(0, 100) + '...';
}
return value;
}, 2));
// Make the API request
const response = await fetch(modelConfig.endpoint, {
method: 'POST',
headers: modelConfig.headers(apiKey),
body: JSON.stringify(requestBody),
});
// Log response info
console.log(`Response status: ${response.status}`);
if (!response.ok) {
// Get the error details from the response
let errorDetails = '';
try {
const errorJson = await response.json();
errorDetails = JSON.stringify(errorJson);
console.error('API Error details:', errorJson);
} catch (e) {
errorDetails = await response.text();
console.error('API Error text:', errorDetails);
}
console.error(`HTTP error! Status: ${response.status}. Details: ${errorDetails}`);
showErrorPopup(popupId, errorHTML);
// Create data URL from JSON string
const jsonDataUrl = 'data:application/json;base64,' + btoa(unescape(encodeURIComponent(jsonStr)));
chrome.downloads.download({
url: jsonDataUrl,
filename: 'tracking_log.json',
saveAs: true
});
throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorDetails}`);
}
const data = await response.json();
let pythonCode = modelConfig.parseResponse(data);
// Extract code between ```python and ``` markers if present
const codeMatch = pythonCode.match(/```python\n([\s\S]*?)```/);
if (codeMatch) {
pythonCode = codeMatch[1];
}
return pythonCode;
} catch (error) {
console.error('Error generating code:', error);
showErrorPopup(popupId, errorHTML);
throw error;
}
}
// Helper function to show error popup by updating tab instead of window
function showErrorPopup(windowId, errorHTML) {
chrome.tabs.query({ windowId: windowId }, (tabs) => {
if (tabs && tabs.length > 0) {
chrome.tabs.update(tabs[0].id, {
url: 'data:text/html;charset=utf-8,' + encodeURIComponent(errorHTML)
});
} else {
console.error('No tabs found in the specified window');
// Fallback: close the window if we can't update its tab
chrome.windows.remove(windowId).catch(err => {
console.error('Error closing error window:', err);
});
}
});
}