-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseUniversalAI.js
More file actions
683 lines (592 loc) · 19.4 KB
/
useUniversalAI.js
File metadata and controls
683 lines (592 loc) · 19.4 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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import { useState, useCallback, useRef, useEffect } from "react";
// ---------------------------------------------------------------------------
// Cloud Provider Registry
// ---------------------------------------------------------------------------
export const CLOUD_PROVIDERS = {
anthropic: {
id: "anthropic",
name: "Anthropic (Claude)",
baseUrl: "https://api.anthropic.com",
chatPath: "/v1/messages",
modelsPath: null, // no public /models endpoint for browser use
browserDirect: false,
authStyle: "x-api-key",
extraHeaders: { "anthropic-version": "2023-06-01" },
keyPrefix: "sk-ant-",
pricing: "Claude Sonnet ~$3/$15 pro 1M Tokens, Haiku ~$0.80/$4, Opus ~$15/$75",
defaultModels: [
{ id: "claude-sonnet-4-20250514", name: "Claude Sonnet 4" },
{ id: "claude-haiku-4-20250414", name: "Claude Haiku 4" },
{ id: "claude-opus-4-20250514", name: "Claude Opus 4" },
],
},
openai: {
id: "openai",
name: "OpenAI (GPT)",
baseUrl: "https://api.openai.com",
chatPath: "/v1/chat/completions",
modelsPath: "/v1/models",
browserDirect: true,
authStyle: "bearer",
extraHeaders: {},
keyPrefix: "sk-",
pricing: "GPT-4o ~$2.50/$10, GPT-4o-mini ~$0.15/$0.60, o4-mini ~$1.10/$4.40",
defaultModels: [
{ id: "gpt-4o", name: "GPT-4o" },
{ id: "gpt-4o-mini", name: "GPT-4o Mini" },
{ id: "o4-mini", name: "o4-mini" },
{ id: "o3", name: "o3" },
],
},
gemini: {
id: "gemini",
name: "Google Gemini",
baseUrl: "https://generativelanguage.googleapis.com",
chatPath: "/v1beta/chat/completions",
modelsPath: "/v1beta/models",
browserDirect: true,
authStyle: "bearer",
extraHeaders: {},
keyPrefix: "AI",
pricing: "Gemini 2.5 Flash kostenlos bis Limit, Pro ~$1.25/$10 pro 1M Tokens",
defaultModels: [
{ id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },
{ id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },
{ id: "gemini-2.0-flash", name: "Gemini 2.0 Flash" },
],
},
mistral: {
id: "mistral",
name: "Mistral AI",
baseUrl: "https://api.mistral.ai",
chatPath: "/v1/chat/completions",
modelsPath: "/v1/models",
browserDirect: true,
authStyle: "bearer",
extraHeaders: {},
keyPrefix: "",
pricing: "Mistral Large ~$2/$6, Small ~$0.10/$0.30, Codestral ~$0.30/$0.90",
defaultModels: [
{ id: "mistral-large-latest", name: "Mistral Large" },
{ id: "mistral-small-latest", name: "Mistral Small" },
{ id: "codestral-latest", name: "Codestral" },
],
},
openrouter: {
id: "openrouter",
name: "OpenRouter",
baseUrl: "https://openrouter.ai/api",
chatPath: "/v1/chat/completions",
modelsPath: "/v1/models",
browserDirect: true,
authStyle: "bearer",
extraHeaders: {
"HTTP-Referer": typeof window !== "undefined" ? window.location.origin : "",
"X-Title": "Mythos Content Factory",
},
keyPrefix: "sk-or-",
pricing: "Pay-per-use, Preise variieren je nach Modell. Viele kostenlose Modelle verfuegbar.",
defaultModels: [
{ id: "anthropic/claude-sonnet-4", name: "Claude Sonnet 4 (via OR)" },
{ id: "openai/gpt-4o", name: "GPT-4o (via OR)" },
{ id: "google/gemini-2.5-flash", name: "Gemini 2.5 Flash (via OR)" },
{ id: "deepseek/deepseek-r1", name: "DeepSeek R1 (via OR)" },
],
},
groq: {
id: "groq",
name: "Groq (Ultra-Fast)",
baseUrl: "https://api.groq.com/openai",
chatPath: "/v1/chat/completions",
modelsPath: "/v1/models",
browserDirect: true,
authStyle: "bearer",
extraHeaders: {},
keyPrefix: "gsk_",
pricing: "Sehr guenstig: Llama 3.3 70B ~$0.59/$0.79, 8B ~$0.05/$0.08 pro 1M Tokens",
defaultModels: [
{ id: "llama-3.3-70b-versatile", name: "Llama 3.3 70B" },
{ id: "llama-3.1-8b-instant", name: "Llama 3.1 8B Instant" },
{ id: "mixtral-8x7b-32768", name: "Mixtral 8x7B" },
],
},
};
// ---------------------------------------------------------------------------
// LocalStorage helpers
// ---------------------------------------------------------------------------
const KEYS_STORAGE = "universal_ai_keys";
const CONFIG_STORAGE = "universal_ai_config";
const FREEMIUM_STORAGE = "universal_ai_freemium";
const PROXY_STORAGE = "universal_ai_proxy";
function loadKeys() {
try {
return JSON.parse(localStorage.getItem(KEYS_STORAGE) || "{}");
} catch {
return {};
}
}
function saveKeys(keys) {
localStorage.setItem(KEYS_STORAGE, JSON.stringify(keys));
}
function loadConfig() {
try {
return JSON.parse(localStorage.getItem(CONFIG_STORAGE) || "{}");
} catch {
return {};
}
}
function saveConfig(cfg) {
localStorage.setItem(CONFIG_STORAGE, JSON.stringify(cfg));
}
function loadFreemium() {
try {
const data = JSON.parse(localStorage.getItem(FREEMIUM_STORAGE) || "{}");
const today = new Date().toISOString().slice(0, 10);
if (data.date !== today) return { date: today, used: 0 };
return data;
} catch {
return { date: new Date().toISOString().slice(0, 10), used: 0 };
}
}
function saveFreemium(data) {
localStorage.setItem(FREEMIUM_STORAGE, JSON.stringify(data));
}
function maskKey(key) {
if (!key) return "";
if (key.length <= 8) return "****";
return key.slice(0, 4) + "****" + key.slice(-4);
}
// ---------------------------------------------------------------------------
// Request helpers
// ---------------------------------------------------------------------------
function buildHeaders(provider, apiKey, proxyUrl) {
const cfg = CLOUD_PROVIDERS[provider];
if (!cfg) return {};
const headers = { "Content-Type": "application/json", ...cfg.extraHeaders };
if (cfg.authStyle === "x-api-key") {
// Anthropic -- when going through a proxy we send as Bearer instead
if (proxyUrl) {
headers["Authorization"] = `Bearer ${apiKey}`;
} else {
headers["x-api-key"] = apiKey;
}
} else {
headers["Authorization"] = `Bearer ${apiKey}`;
}
return headers;
}
function buildBody(provider, model, prompt, systemPrompt, history) {
const cfg = CLOUD_PROVIDERS[provider];
if (!cfg) return {};
// Anthropic uses a different body shape
if (provider === "anthropic") {
const messages = [...(history || [])];
messages.push({ role: "user", content: prompt });
const body = { model, messages, max_tokens: 4096 };
if (systemPrompt) body.system = systemPrompt;
return body;
}
// OpenAI-compatible providers
const messages = [];
if (systemPrompt) messages.push({ role: "system", content: systemPrompt });
if (history) messages.push(...history);
messages.push({ role: "user", content: prompt });
return { model, messages, max_tokens: 4096 };
}
function buildStreamBody(provider, model, prompt, systemPrompt, history) {
const body = buildBody(provider, model, prompt, systemPrompt, history);
body.stream = true;
return body;
}
function resolveUrl(provider, proxyUrl) {
const cfg = CLOUD_PROVIDERS[provider];
if (!cfg) return "";
if (provider === "anthropic" && proxyUrl) {
// proxy should relay to Anthropic; we hit proxy + chatPath
return proxyUrl + cfg.chatPath;
}
return cfg.baseUrl + cfg.chatPath;
}
// ---------------------------------------------------------------------------
// SSE stream parser
// ---------------------------------------------------------------------------
function parseSSEChunk(provider, line) {
if (!line.startsWith("data: ")) return null;
const raw = line.slice(6).trim();
if (raw === "[DONE]") return { done: true, text: "" };
try {
const json = JSON.parse(raw);
if (provider === "anthropic") {
// Anthropic stream events: content_block_delta
if (json.type === "content_block_delta" && json.delta) {
return { done: false, text: json.delta.text || "" };
}
if (json.type === "message_stop") {
return { done: true, text: "" };
}
return null; // other event types (message_start, content_block_start, etc.)
}
// OpenAI-compatible
const choice = json.choices && json.choices[0];
if (!choice) return null;
if (choice.finish_reason) return { done: true, text: choice.delta?.content || "" };
return { done: false, text: choice.delta?.content || "" };
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// Extract non-streaming response text
// ---------------------------------------------------------------------------
function extractResponseText(provider, json) {
if (provider === "anthropic") {
if (json.content && json.content.length > 0) {
return json.content.map((b) => b.text || "").join("");
}
return "";
}
// OpenAI-compatible
if (json.choices && json.choices[0]) {
return json.choices[0].message?.content || "";
}
return "";
}
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
const FREEMIUM_LIMIT = 5;
export function useUniversalAI() {
const [keys, setKeysState] = useState(loadKeys);
const [config, setConfigState] = useState(() => {
const c = loadConfig();
return {
provider: c.provider || "openai",
model: c.model || "gpt-4o",
};
});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [cloudModels, setCloudModels] = useState([]);
const [freemium, setFreemiumState] = useState(loadFreemium);
const [proxyUrl, setProxyUrlState] = useState(
() => localStorage.getItem(PROXY_STORAGE) || ""
);
const abortRef = useRef(null);
// derived
const activeProvider = config.provider;
const activeModel = config.model;
const activeKey = keys[activeProvider] || "";
const isConnected = !!activeKey;
// --- key management ---
const setApiKey = useCallback((provider, key) => {
setKeysState((prev) => {
const next = { ...prev, [provider]: key };
saveKeys(next);
return next;
});
}, []);
const removeApiKey = useCallback((provider) => {
setKeysState((prev) => {
const next = { ...prev };
delete next[provider];
saveKeys(next);
return next;
});
}, []);
const getApiKey = useCallback(
(provider) => keys[provider || activeProvider] || "",
[keys, activeProvider]
);
const getMaskedKey = useCallback(
(provider) => maskKey(keys[provider || activeProvider] || ""),
[keys, activeProvider]
);
// --- provider / model switching ---
const setProvider = useCallback(
(id) => {
if (!CLOUD_PROVIDERS[id]) return;
const defaultModel = CLOUD_PROVIDERS[id].defaultModels[0]?.id || "";
setConfigState((prev) => {
const next = { ...prev, provider: id, model: defaultModel };
saveConfig(next);
return next;
});
setCloudModels([]);
setError(null);
},
[]
);
const setModel = useCallback(
(modelId) => {
setConfigState((prev) => {
const next = { ...prev, model: modelId };
saveConfig(next);
return next;
});
},
[]
);
// --- proxy url ---
const setProxyUrl = useCallback((url) => {
const cleaned = (url || "").replace(/\/+$/, "");
setProxyUrlState(cleaned);
localStorage.setItem(PROXY_STORAGE, cleaned);
}, []);
// --- freemium guard ---
const consumeFreemium = useCallback(() => {
const current = loadFreemium();
if (current.used >= FREEMIUM_LIMIT) {
return false;
}
const next = { ...current, used: current.used + 1 };
saveFreemium(next);
setFreemiumState(next);
return true;
}, []);
// refresh freemium count on mount / day change
useEffect(() => {
setFreemiumState(loadFreemium());
}, []);
// --- detect models ---
const detectModels = useCallback(
async (providerId) => {
const pid = providerId || activeProvider;
const cfg = CLOUD_PROVIDERS[pid];
if (!cfg || !cfg.modelsPath) {
setCloudModels(cfg ? cfg.defaultModels : []);
return cfg ? cfg.defaultModels : [];
}
const key = keys[pid];
if (!key) {
setError("Kein API-Key fuer " + cfg.name + " hinterlegt.");
return [];
}
try {
const url =
pid === "anthropic" && proxyUrl
? proxyUrl + cfg.modelsPath
: cfg.baseUrl + cfg.modelsPath;
const res = await fetch(url, {
headers: buildHeaders(pid, key, proxyUrl),
});
if (!res.ok) {
throw new Error("Modelle konnten nicht geladen werden (HTTP " + res.status + ")");
}
const json = await res.json();
const list = (json.data || json.models || []).map((m) => ({
id: m.id,
name: m.name || m.id,
}));
if (list.length > 0) {
setCloudModels(list);
return list;
}
setCloudModels(cfg.defaultModels);
return cfg.defaultModels;
} catch (err) {
setError("Fehler beim Laden der Modelle: " + err.message);
setCloudModels(cfg.defaultModels);
return cfg.defaultModels;
}
},
[activeProvider, keys, proxyUrl]
);
// --- ask (non-streaming) ---
const ask = useCallback(
async (prompt, systemPrompt, options = {}) => {
const pid = options.provider || activeProvider;
const mid = options.model || activeModel;
const key = keys[pid];
const cfg = CLOUD_PROVIDERS[pid];
if (!cfg) {
throw new Error("Unbekannter Provider: " + pid);
}
// freemium check
if (!key) {
if (!consumeFreemium()) {
throw new Error(
"Tageslimit erreicht (" +
FREEMIUM_LIMIT +
" kostenlose Anfragen/Tag). Bitte eigenen API-Key hinterlegen."
);
}
}
// CORS check for Anthropic without proxy
if (pid === "anthropic" && !proxyUrl && !key) {
throw new Error(
"Anthropic blockiert direkte Browser-Anfragen (CORS). Bitte Proxy-URL setzen oder anderen Provider waehlen."
);
}
if (pid === "anthropic" && !proxyUrl && key) {
throw new Error(
"Anthropic blockiert direkte Browser-Anfragen (CORS). Bitte Proxy-URL unter Einstellungen setzen."
);
}
setIsLoading(true);
setError(null);
const maxRetries = options.retries ?? 2;
let lastError = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const url = resolveUrl(pid, proxyUrl);
const body = buildBody(pid, mid, prompt, systemPrompt, options.history);
const headers = buildHeaders(pid, key, proxyUrl);
const controller = new AbortController();
abortRef.current = controller;
const res = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(body),
signal: controller.signal,
});
if (!res.ok) {
const errBody = await res.text().catch(() => "");
if (res.status === 429 && attempt < maxRetries) {
// rate limit -- back off and retry
await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
continue;
}
throw new Error(
"API-Fehler " + res.status + ": " + (errBody.slice(0, 200) || res.statusText)
);
}
const json = await res.json();
const text = extractResponseText(pid, json);
setIsLoading(false);
return text;
} catch (err) {
lastError = err;
if (err.name === "AbortError") {
setIsLoading(false);
throw new Error("Anfrage abgebrochen.");
}
if (attempt >= maxRetries) break;
}
}
setIsLoading(false);
const msg = lastError?.message || "Unbekannter Fehler";
setError(msg);
throw new Error(msg);
},
[activeProvider, activeModel, keys, proxyUrl, consumeFreemium]
);
// --- askStream ---
const askStream = useCallback(
async (prompt, systemPrompt, history, onChunk) => {
const pid = activeProvider;
const mid = activeModel;
const key = keys[pid];
const cfg = CLOUD_PROVIDERS[pid];
if (!cfg) {
throw new Error("Unbekannter Provider: " + pid);
}
if (!key) {
if (!consumeFreemium()) {
throw new Error(
"Tageslimit erreicht (" +
FREEMIUM_LIMIT +
" kostenlose Anfragen/Tag). Bitte eigenen API-Key hinterlegen."
);
}
}
if (pid === "anthropic" && !proxyUrl) {
throw new Error(
"Anthropic blockiert direkte Browser-Anfragen (CORS). Bitte Proxy-URL setzen."
);
}
setIsLoading(true);
setError(null);
try {
const url = resolveUrl(pid, proxyUrl);
const body = buildStreamBody(pid, mid, prompt, systemPrompt, history);
const headers = buildHeaders(pid, key, proxyUrl);
const controller = new AbortController();
abortRef.current = controller;
const res = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(body),
signal: controller.signal,
});
if (!res.ok) {
const errBody = await res.text().catch(() => "");
throw new Error(
"Stream-Fehler " + res.status + ": " + (errBody.slice(0, 200) || res.statusText)
);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullText = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith(":")) continue;
// Anthropic sends "event: " lines before "data: " lines
if (trimmed.startsWith("event:")) continue;
const parsed = parseSSEChunk(pid, trimmed);
if (!parsed) continue;
if (parsed.text) {
fullText += parsed.text;
if (onChunk) onChunk(parsed.text, fullText);
}
if (parsed.done) break;
}
}
setIsLoading(false);
return fullText;
} catch (err) {
setIsLoading(false);
if (err.name === "AbortError") {
throw new Error("Stream abgebrochen.");
}
const msg = err.message || "Stream-Fehler";
setError(msg);
throw new Error(msg);
}
},
[activeProvider, activeModel, keys, proxyUrl, consumeFreemium]
);
// --- abort ---
const abortStream = useCallback(() => {
if (abortRef.current) {
abortRef.current.abort();
abortRef.current = null;
}
setIsLoading(false);
}, []);
// ---------------------------------------------------------------------------
// Return
// ---------------------------------------------------------------------------
return {
// state
provider: activeProvider,
model: activeModel,
apiKey: maskKey(activeKey),
isConnected,
isLoading,
error,
freemiumUsed: freemium.used,
freemiumLimit: FREEMIUM_LIMIT,
// actions
ask,
askStream,
abortStream,
setProvider,
setModel,
setApiKey,
removeApiKey,
getApiKey,
getMaskedKey,
detectModels,
setProxyUrl,
// data
providers: CLOUD_PROVIDERS,
cloudModels,
};
}