-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproviders.js
More file actions
232 lines (209 loc) · 7.14 KB
/
Copy pathproviders.js
File metadata and controls
232 lines (209 loc) · 7.14 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
/* Lens — providers.js
Auto-detects AI provider from API key prefix.
Supports: Groq, OpenAI, Anthropic, Google Gemini, Mistral, Cohere, Together AI
Shared by both content.js and popup.js via importScripts / inline copy.
*/
const PROVIDERS = {
groq: {
name: 'Groq',
prefix: 'gsk_',
endpoint: 'https://api.groq.com/openai/v1/chat/completions',
model: 'llama-3.3-70b-versatile',
format: 'openai',
free: true,
headers: (key) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${key}`
}),
},
openai: {
name: 'OpenAI',
prefix: 'sk-',
// sk-proj- is also OpenAI
endpoint: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-4o-mini',
format: 'openai',
free: false,
headers: (key) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${key}`
}),
},
anthropic: {
name: 'Anthropic',
prefix: 'sk-ant-',
endpoint: 'https://api.anthropic.com/v1/messages',
model: 'claude-haiku-4-5-20251001',
format: 'anthropic',
free: false,
headers: (key) => ({
'Content-Type': 'application/json',
'x-api-key': key,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
}),
},
gemini: {
name: 'Google Gemini',
prefix: 'AIza',
// Gemini uses URL-based key, not header
endpoint: (key) => `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${key}`,
model: 'gemini-1.5-flash',
format: 'gemini',
free: true,
headers: () => ({ 'Content-Type': 'application/json' }),
},
mistral: {
name: 'Mistral',
// No fixed prefix — detected by elimination after others
prefix: null,
endpoint: 'https://api.mistral.ai/v1/chat/completions',
model: 'mistral-small-latest',
format: 'openai',
free: false,
headers: (key) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${key}`
}),
},
together: {
name: 'Together AI',
prefix: null,
endpoint: 'https://api.together.xyz/v1/chat/completions',
model: 'meta-llama/Llama-3-70b-chat-hf',
format: 'openai',
free: false,
headers: (key) => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${key}`
}),
},
};
/* Detect provider from key */
function detectProvider(key) {
if (!key) return null;
const k = key.trim();
if (k.startsWith('gsk_')) return 'groq';
if (k.startsWith('sk-ant-')) return 'anthropic';
if (k.startsWith('AIza')) return 'gemini';
if (k.startsWith('sk-proj-') || (k.startsWith('sk-') && !k.startsWith('sk-ant-'))) return 'openai';
// Together AI keys are long hex strings
if (/^[a-f0-9]{64}$/i.test(k)) return 'together';
// Mistral keys are typically 32-char alphanumeric
if (/^[A-Za-z0-9]{32}$/.test(k)) return 'mistral';
return null;
}
/* Build and send a chat request, return response text */
async function callProvider(key, messages, jsonMode = true) {
const providerKey = detectProvider(key);
if (!providerKey) throw new Error('UNKNOWN_PROVIDER');
const p = PROVIDERS[providerKey];
// ── OpenAI-compatible format (Groq, OpenAI, Mistral, Together) ──
if (p.format === 'openai') {
const body = {
model: p.model,
temperature: 0.1,
max_tokens: 1400,
messages,
};
if (jsonMode && providerKey !== 'together') {
body.response_format = { type: 'json_object' };
}
const res = await fetch(p.endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify(body),
});
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_' + res.status);
const data = await res.json();
return data.choices?.[0]?.message?.content || '';
}
// ── Anthropic format ──
if (p.format === 'anthropic') {
// Anthropic uses system + user separately
const system = messages.find(m => m.role === 'system')?.content || '';
const userMsgs = messages.filter(m => m.role !== 'system');
const res = await fetch(p.endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify({
model: p.model,
max_tokens: 1400,
system: system || 'Return only valid JSON.',
messages: userMsgs,
}),
});
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_' + res.status);
const data = await res.json();
return data.content?.[0]?.text || '';
}
// ── Google Gemini format ──
if (p.format === 'gemini') {
const combined = messages.map(m => m.content).join('\n\n');
const endpoint = typeof p.endpoint === 'function' ? p.endpoint(key) : p.endpoint;
const res = await fetch(endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify({
contents: [{ parts: [{ text: combined }] }],
generationConfig: { temperature: 0.1, maxOutputTokens: 1400 },
}),
});
if (res.status === 400) throw new Error('INVALID_KEY');
if (res.status === 429) throw new Error('RATE_LIMIT');
if (!res.ok) throw new Error('API_' + res.status);
const data = await res.json();
return data.candidates?.[0]?.content?.parts?.[0]?.text || '';
}
throw new Error('UNSUPPORTED_FORMAT');
}
/* Parse JSON safely from any provider response */
function parseProviderJSON(text) {
const clean = text.replace(/```json|```/g, '').trim();
return JSON.parse(clean);
}
/* Test key with a minimal call */
async function testProviderKey(key) {
const providerKey = detectProvider(key);
if (!providerKey) throw new Error('UNKNOWN_PROVIDER');
const p = PROVIDERS[providerKey];
if (p.format === 'openai') {
const res = await fetch(p.endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify({ model: p.model, max_tokens: 5, messages: [{ role: 'user', content: 'Hi' }] }),
});
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) return true; // rate limited = key valid
if (!res.ok) throw new Error('API_' + res.status);
return true;
}
if (p.format === 'anthropic') {
const res = await fetch(p.endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify({ model: p.model, max_tokens: 5, messages: [{ role: 'user', content: 'Hi' }] }),
});
if (res.status === 401) throw new Error('INVALID_KEY');
if (res.status === 429) return true;
if (!res.ok) throw new Error('API_' + res.status);
return true;
}
if (p.format === 'gemini') {
const endpoint = typeof p.endpoint === 'function' ? p.endpoint(key) : p.endpoint;
const res = await fetch(endpoint, {
method: 'POST',
headers: p.headers(key),
body: JSON.stringify({ contents: [{ parts: [{ text: 'Hi' }] }], generationConfig: { maxOutputTokens: 5 } }),
});
if (res.status === 400) throw new Error('INVALID_KEY');
if (res.status === 429) return true;
if (!res.ok) throw new Error('API_' + res.status);
return true;
}
return true;
}