-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbackground.js
260 lines (221 loc) · 8.71 KB
/
background.js
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
let API_KEY = ''; // Generic API key variable
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent';
const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
let selectedModel = 'gemini-1.5-flash-latest'; // Default to Gemini
let apiCallCount = 0;
let pendingTweets = [];
let unrankedTweets = [];
let processingTweets = false;
let currentTabId = null;
let retryTimeout = null;
let processedTweetIds = new Set();
let isPaused = false;
let currentCriteria = [];
async function rankTweets(tweets) {
if (selectedModel.includes('gpt')) {
return rankTweetsWithOpenAI(tweets);
} else {
return rankTweetsWithGemini(tweets);
}
}
async function rankTweetsWithGemini(tweets) {
if (!API_KEY) {
console.log('API key not set.');
return tweets.map(tweet => ({ id: tweet.id, rating: null }));
}
apiCallCount++;
console.log(`Processing ${tweets.length} tweets with Gemini`);
const activeCriteria = currentCriteria.filter(c => c.weight > 0);
const criteriaText = activeCriteria.length > 0
? `You should rank tweets based on the following criteria: ${activeCriteria.map(c => `${c.text}: ${c.weight}`).join(', ')}. Higher weighted criteria should have more impact on the final score. `
: 'You should rank tweets based on how well thought and how well argued out they are. ';
const requestBody = {
contents: [{
parts: [{
text: `You are a professional tweet rater with great philosophical perspectives. ${criteriaText}Rank tweets on a scale of 1-10. Respond with only the numeric ratings, separated by commas.\n\n${tweets.map((tweet, index) => `Tweet ${index + 1}: "${tweet.text}"`).join('\n\n')}`
}]
}]
};
try {
const response = await fetch(`${GEMINI_API_URL}?key=${API_KEY}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody)
});
if (response.status === 429) {
console.warn('API quota reached. Retrying in 5 seconds.');
unrankedTweets.push(...tweets);
scheduleRetry();
return tweets.map(tweet => ({ id: tweet.id, rating: null }));
}
if (!response.ok) {
console.error(`API call failed with status: ${response.status}`);
return tweets.map(tweet => ({ id: tweet.id, rating: -10 }));
}
const data = await response.json();
if (!data.candidates?.[0]?.content?.parts) {
console.error('Unexpected API response structure');
return tweets.map(tweet => ({ id: tweet.id, rating: -1 }));
}
const ratings = data.candidates[0].content.parts[0].text.split(',').map(r => {
const rating = parseInt(r.trim());
return isNaN(rating) ? -100 : rating;
});
return tweets.map((tweet, index) => ({ id: tweet.id.toString(), rating: ratings[index] }));
} catch (error) {
console.error('Error processing tweets:', error.message);
return tweets.map(tweet => ({ id: tweet.id, rating: -4 }));
}
}
async function rankTweetsWithOpenAI(tweets) {
if (!API_KEY) {
console.log('API key not set.');
return tweets.map(tweet => ({ id: tweet.id, rating: null }));
}
apiCallCount++;
console.log(`Processing ${tweets.length} tweets with OpenAI`);
const activeCriteria = currentCriteria.filter(c => c.weight > 0);
const criteriaText = activeCriteria.length > 0
? `You should rank tweets based on the following criteria: ${activeCriteria.map(c => `${c.text}: ${c.weight}`).join(', ')}. Higher weighted criteria should have more impact on the final score. `
: 'You should rank tweets based on how well thought and how well argued out they are. ';
const requestBody = {
model: selectedModel,
messages: [
{
role: "system",
content: "You are a professional tweet rater with great philosophical perspectives."
},
{
role: "user",
content: `${criteriaText}Rank the following tweets on a scale of 1-10. Respond with only the numeric ratings, separated by commas.\n\n${tweets.map((tweet, index) => `Tweet ${index + 1}: "${tweet.text}"`).join('\n\n')}`
}
],
temperature: 0
};
// console.log(`OpenAI API Request #${apiCallCount}:`, JSON.stringify(requestBody, null, 2));
try {
const response = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify(requestBody)
});
if (response.status === 429) {
// console.warn('OpenAI API rate limit reached. Retrying in 5 seconds.');
unrankedTweets.push(...tweets);
scheduleRetry();
return tweets.map(tweet => ({ id: tweet.id, rating: null }));
}
if (!response.ok) {
console.error(`OpenAI API call #${apiCallCount} failed with status: ${response.status}`);
const errorText = await response.text();
console.error('Error response:', errorText);
return tweets.map(tweet => ({ id: tweet.id, rating: -10 }));
}
const data = await response.json();
// console.log(`OpenAI API Response #${apiCallCount}:`, JSON.stringify(data, null, 2));
if (!data.choices || !data.choices[0] || !data.choices[0].message || !data.choices[0].message.content) {
console.error(`OpenAI API call #${apiCallCount} returned unexpected data structure:`);
console.error('Received structure:', JSON.stringify(data, null, 2));
return tweets.map(tweet => ({ id: tweet.id, rating: -1 }));
}
const ratings = data.choices[0].message.content.split(',').map(r => {
const rating = parseInt(r.trim());
return isNaN(rating) ? -100 : rating;
});
// tweets.forEach((tweet, index) => {
// console.log(`Tweet ID: ${tweet.id}, Rating: ${ratings[index]}`);
// });
return tweets.map((tweet, index) => ({
id: tweet.id.toString(),
rating: ratings[index]
}));
} catch (error) {
console.error(`Error in OpenAI API call #${apiCallCount}:`, error);
console.error('Full error object:', JSON.stringify(error, Object.getOwnPropertyNames(error)));
return tweets.map(tweet => ({ id: tweet.id, rating: -4 }));
}
}
// Update message listener to handle model selection
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'updateApiKey') {
console.log('Configuration updated');
API_KEY = request.apiKey;
selectedModel = request.selectedModel;
if (request.criteria) {
currentCriteria = request.criteria;
}
sendResponse({ status: 'Configuration updated' });
return true;
}
if (request.action === 'rankTweets') {
if (!isPaused) {
currentTabId = sender.tab.id;
request.tweets.forEach(tweet => {
pendingTweets.push(tweet);
});
processTweets();
}
return true; // Indicates that the response is sent asynchronously
}
if (request.action === 'togglePause') {
isPaused = request.isPaused;
if (!isPaused) {
processTweets(); // Resume processing if there are pending tweets
}
return true;
}
});
async function processTweets() {
if (isPaused || processingTweets || (pendingTweets.length === 0 && unrankedTweets.length === 0)) return;
if (!API_KEY) {
return;
}
processingTweets = true;
const tweetsToProcess = [...unrankedTweets, ...pendingTweets.splice(0, 10 - unrankedTweets.length)];
unrankedTweets = [];
try {
const ratings = await rankTweets(tweetsToProcess);
if (currentTabId) {
chrome.tabs.sendMessage(currentTabId, { action: 'tweetRatings', ratings });
}
} catch (error) {
console.error('Error ranking tweets:', error);
console.error('Full error object:', JSON.stringify(error, Object.getOwnPropertyNames(error))); // Log full error details
if (currentTabId) {
chrome.tabs.sendMessage(currentTabId, { action: 'tweetRatings', ratings: tweetsToProcess.map(tweet => ({ id: tweet.id, rating: null })) });
}
}
processingTweets = false;
if (pendingTweets.length > 0 || unrankedTweets.length > 0) {
processTweets(); // Process next batch if there are more tweets
}
}
function scheduleRetry() {
if (retryTimeout) {
clearTimeout(retryTimeout);
}
retryTimeout = setTimeout(() => {
retryTimeout = null;
processTweets();
}, 5000);
}
// Initialize the API key from storage when the script loads
chrome.storage.sync.get(['apiKey', 'isPaused', 'rankingCriteria'], (data) => {
if (data.apiKey) {
API_KEY = data.apiKey;
}
if (data.rankingCriteria && Array.isArray(data.rankingCriteria)) {
currentCriteria = data.rankingCriteria;
} else {
currentCriteria = [
{ text: 'thoughtfulness', weight: 0 },
{ text: 'creativity', weight: 0 },
{ text: 'uniqueness', weight: 0 },
{ text: 'humor', weight: 0 }
];
}
isPaused = data.isPaused || false;
});