| 1 | // Generic provider for external APIs (advanced configuration): |
| 2 | // - kind 'openai' → /chat/completions (OpenAI, Ollama, llama-server…) |
| 3 | // - kind 'anthropic' → /v1/messages (Claude) |
| 4 | // Calls go DIRECTLY from the user's browser to the provider; the key never |
| 5 | // passes through any server of ours. SSE streaming in both dialects. |
| 6 | import { packHistoryAsync } from '../context.js'; |
| 7 | |
| 8 | let cfg = null; |
| 9 | export let name = 'API'; |
| 10 | |
| 11 | export function configure(c) { cfg = c; name = c.label; } |
| 12 | |
| 13 | export async function load() { |
| 14 | if (!cfg) throw new Error('proveedor sin configurar'); |
| 15 | if (cfg.kind !== 'anthropic' && !cfg.apiKey && !cfg.baseURL.includes('localhost') && cfg.baseURL !== '/v1') |
| 16 | throw new Error('falta la clave de API (config avanzada)'); |
| 17 | } |
| 18 | |
| 19 | export async function chat(history, system, onToken = () => {}) { |
| 20 | return cfg.kind === 'anthropic' |
| 21 | ? anthropicChat(history, system, onToken) |
| 22 | : openaiChat(history, system, onToken); |
| 23 | } |
| 24 | |
| 25 | // ---- OpenAI-compatible ---- |
| 26 | async function openaiChat(history, system, onToken) { |
| 27 | const headers = { 'Content-Type': 'application/json' }; |
| 28 | if (cfg.apiKey) headers.Authorization = 'Bearer ' + cfg.apiKey; |
| 29 | const body = { |
| 30 | model: cfg.model, |
| 31 | messages: [{ role: 'system', content: system }, ...await packHistoryAsync(history, 3000)], |
| 32 | stream: true, |
| 33 | max_tokens: cfg.maxTokens || 1024, |
| 34 | }; |
| 35 | if (cfg.temperature != null) body.temperature = cfg.temperature; |
| 36 | if (cfg.top_p != null) body.top_p = cfg.top_p; |
| 37 | if (cfg.thinking != null) body.chat_template_kwargs = { enable_thinking: cfg.thinking }; |
| 38 | |
| 39 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/chat/completions', { |
| 40 | method: 'POST', headers, body: JSON.stringify(body), |
| 41 | }); |
| 42 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 43 | |
| 44 | let out = ''; |
| 45 | await readSSE(res.body, payload => { |
| 46 | if (payload === '[DONE]') return; |
| 47 | const d = JSON.parse(payload).choices?.[0]?.delta || {}; |
| 48 | if (d.reasoning_content) onToken(d.reasoning_content); |
| 49 | if (d.content) { out += d.content; onToken(d.content); } |
| 50 | }); |
| 51 | return out.trim(); |
| 52 | } |
| 53 | |
| 54 | // ---- Anthropic Messages ---- |
| 55 | async function anthropicChat(history, system, onToken) { |
| 56 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/v1/messages', { |
| 57 | method: 'POST', |
| 58 | headers: { |
| 59 | 'Content-Type': 'application/json', |
| 60 | 'x-api-key': cfg.apiKey, |
| 61 | 'anthropic-version': '2023-06-01', |
| 62 | 'anthropic-dangerous-direct-browser-access': 'true', |
| 63 | }, |
| 64 | body: JSON.stringify({ |
| 65 | model: cfg.model, |
| 66 | max_tokens: cfg.maxTokens || 1024, |
| 67 | system, |
| 68 | stream: true, |
| 69 | messages: forAnthropic(await packHistoryAsync(history, 3000)), |
| 70 | }), |
| 71 | }); |
| 72 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 73 | |
| 74 | let out = ''; |
| 75 | await readSSE(res.body, payload => { |
| 76 | const evt = JSON.parse(payload); |
| 77 | if (evt.type === 'content_block_delta' && evt.delta?.text) { |
| 78 | out += evt.delta.text; onToken(evt.delta.text); |
| 79 | } |
| 80 | }); |
| 81 | return out.trim(); |
| 82 | } |
| 83 | |
| 84 | // Anthropic requires alternating roles starting with user; merge consecutive ones. |
| 85 | function forAnthropic(msgs) { |
| 86 | const merged = []; |
| 87 | for (const m of msgs) { |
| 88 | const role = m.role === 'assistant' ? 'assistant' : 'user'; |
| 89 | const last = merged[merged.length - 1]; |
| 90 | if (last && last.role === role) last.content += '\n' + m.content; |
| 91 | else merged.push({ role, content: m.content }); |
| 92 | } |
| 93 | if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: '(continúa)' }); |
| 94 | return merged; |
| 95 | } |
| 96 | |
| 97 | // Shared SSE reader: calls fn with the text after each 'data:'. |
| 98 | async function readSSE(stream, fn) { |
| 99 | const reader = stream.getReader(); |
| 100 | const dec = new TextDecoder(); |
| 101 | let buf = ''; |
| 102 | for (;;) { |
| 103 | const { done, value } = await reader.read(); |
| 104 | if (done) break; |
| 105 | buf += dec.decode(value, { stream: true }); |
| 106 | let nl; |
| 107 | while ((nl = buf.indexOf('\n')) >= 0) { |
| 108 | const line = buf.slice(0, nl).trim(); |
| 109 | buf = buf.slice(nl + 1); |
| 110 | if (!line.startsWith('data:')) continue; |
| 111 | const payload = line.slice(5).trim(); |
| 112 | if (!payload) continue; |
| 113 | try { fn(payload); } catch { /* partial chunk */ } |
| 114 | } |
| 115 | } |
| 116 | } |