-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
180 lines (159 loc) · 6.23 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
// background.js
const ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';
const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
chrome.runtime.onInstalled.addListener(() => {
console.log('Extension installed');
chrome.storage.local.get(['anthropicApiKey', 'openaiApiKey'], (result) => {
if (!result.anthropicApiKey && !result.openaiApiKey) {
console.log('API keys not found, opening options page');
chrome.tabs.create({ url: 'options.html' });
} else {
console.log('API key(s) found');
}
});
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Received message:', message);
if (message.action === 'summarize') {
console.log('Summarizing content');
summarizeContent(message.content)
.then(summary => {
console.log('Summary generated successfully');
sendResponse({ summary });
})
.catch(error => {
console.error('Error generating summary:', error);
sendResponse({ error: error.message });
});
return true; // Indicates that the response is sent asynchronously
}
});
async function summarizeContent(content) {
console.log('Fetching API keys from storage');
const { anthropicApiKey, openaiApiKey } = await chrome.storage.local.get(['anthropicApiKey', 'openaiApiKey']);
console.log('API Keys retrieved:',
anthropicApiKey ? 'Anthropic: Yes' : 'Anthropic: No',
openaiApiKey ? 'OpenAI: Yes' : 'OpenAI: No'
);
if (!anthropicApiKey && !openaiApiKey) {
console.error('No API keys set');
throw new Error('No API keys set. Please set either Anthropic or OpenAI API key in the extension options.');
}
if (anthropicApiKey) {
return summarizeWithAnthropic(content, anthropicApiKey);
} else {
return summarizeWithOpenAI(content, openaiApiKey);
}
}
async function summarizeWithAnthropic(content, apiKey) {
console.log('Sending request to Anthropic API');
try {
const response = await fetch(ANTHROPIC_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: 'claude-3-sonnet-20240229',
messages: [
{
role: 'user',
content: `Summarize the following web page content in bullet points:\n\n${content}`
}
],
max_tokens: 1000,
}),
});
console.log('API response status:', response.status, response.statusText);
if (!response.ok) {
const errorBody = await response.text();
console.error('Error body:', errorBody);
throw new Error(`Failed to get summary from Anthropic API: ${response.status} ${response.statusText}\nError details: ${errorBody}`);
}
console.log('API request successful');
const result = await response.json();
console.log('API response:', JSON.stringify(result, null, 2));
if (result.content && Array.isArray(result.content) && result.content.length > 0 && result.content[0].text) {
return result.content[0].text;
} else {
console.error('Unexpected API response structure:', JSON.stringify(result, null, 2));
throw new Error('Unexpected Anthropic API response structure');
}
} catch (error) {
console.error('Error in Anthropic API request:', error);
throw error;
}
}
function truncateContent(content, maxTokens = 3000) {
// Rough estimate: 1 token ~= 4 characters
const maxChars = maxTokens * 4;
console.log(`Original content length: ${content.length} characters`);
if (content.length > maxChars) {
console.log(`Content too long, truncating to ${maxChars} characters`);
// Take the first third and the last third of the content
const thirdLength = Math.floor(maxChars / 3);
const firstPart = content.slice(0, thirdLength);
const lastPart = content.slice(-thirdLength);
return firstPart + "\n...[content truncated]...\n" + lastPart;
}
console.log(`Content within limit, not truncating`);
return content;
}
function simpleSummarize(content, maxSentences = 20) {
const sentences = content.match(/[^\.!\?]+[\.!\?]+/g) || [];
if (sentences.length > maxSentences) {
console.log(`Summarizing content to ${maxSentences} sentences`);
return sentences.slice(0, maxSentences).join(' ');
}
return content;
}
async function summarizeWithOpenAI(content, apiKey) {
console.log('Preparing content for OpenAI API');
let processedContent = simpleSummarize(content);
processedContent = truncateContent(processedContent);
console.log(`Processed content length: ${processedContent.length} characters`);
try {
console.log('Sending request to OpenAI API');
const response = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant that summarizes web page content in bullet points. Focus on the main points and key information.'
},
{
role: 'user',
content: `Summarize the following web page content in bullet points:\n\n${processedContent}`
}
],
max_tokens: 1000,
}),
});
console.log('API response status:', response.status, response.statusText);
if (!response.ok) {
const errorBody = await response.text();
console.error('Error body:', errorBody);
throw new Error(`Failed to get summary from OpenAI API: ${response.status} ${response.statusText}\nError details: ${errorBody}`);
}
console.log('API request successful');
const result = await response.json();
console.log('API response:', JSON.stringify(result, null, 2));
if (result.choices && result.choices.length > 0 && result.choices[0].message && result.choices[0].message.content) {
return result.choices[0].message.content;
} else {
console.error('Unexpected API response structure:', JSON.stringify(result, null, 2));
throw new Error('Unexpected OpenAI API response structure');
}
} catch (error) {
console.error('Error in OpenAI API request:', error);
throw error;
}
}