| 1 | // Proveedor genérico para APIs externas (configuración avanzada): |
| 2 | // - kind 'openai' → /chat/completions (OpenAI, Ollama, llama-server…) |
| 3 | // - kind 'anthropic' → /v1/messages (Claude) |
| 4 | // Las llamadas salen DIRECTAS del navegador del usuario al proveedor; la clave |
| 5 | // no pasa por ningún servidor nuestro. Streaming SSE en ambos dialectos. |
| 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 = () => {}, signal = null) { |
| 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 | // packHistoryAsync: el empaquetado puede tener que codificar embeddings, así |
| 30 | // que se resuelve ANTES de armar el cuerpo. Con el lado semántico apagado |
| 31 | // devuelve exactamente lo mismo que la versión síncrona de siempre. |
| 32 | const packed = await packHistoryAsync(history, 3000); |
| 33 | const body = { |
| 34 | model: cfg.model, |
| 35 | messages: [{ role: 'system', content: system }, ...packed], |
| 36 | stream: true, |
| 37 | max_tokens: cfg.maxTokens || 1024, |
| 38 | }; |
| 39 | if (cfg.temperature != null) body.temperature = cfg.temperature; |
| 40 | if (cfg.top_p != null) body.top_p = cfg.top_p; |
| 41 | if (cfg.thinking != null) body.chat_template_kwargs = { enable_thinking: cfg.thinking }; |
| 42 | |
| 43 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/chat/completions', { |
| 44 | signal, |
| 45 | method: 'POST', headers, body: JSON.stringify(body), |
| 46 | }); |
| 47 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 48 | |
| 49 | let out = ''; |
| 50 | await readSSE(res.body, payload => { |
| 51 | if (payload === '[DONE]') return; |
| 52 | const d = JSON.parse(payload).choices?.[0]?.delta || {}; |
| 53 | if (d.reasoning_content) onToken(d.reasoning_content); |
| 54 | if (d.content) { out += d.content; onToken(d.content); } |
| 55 | }); |
| 56 | return out.trim(); |
| 57 | } |
| 58 | |
| 59 | // ---- Anthropic Messages ---- |
| 60 | async function anthropicChat(history, system, onToken) { |
| 61 | const packed = await packHistoryAsync(history, 3000); |
| 62 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/v1/messages', { |
| 63 | method: 'POST', |
| 64 | headers: { |
| 65 | 'Content-Type': 'application/json', |
| 66 | 'x-api-key': cfg.apiKey, |
| 67 | 'anthropic-version': '2023-06-01', |
| 68 | 'anthropic-dangerous-direct-browser-access': 'true', |
| 69 | }, |
| 70 | body: JSON.stringify({ |
| 71 | model: cfg.model, |
| 72 | max_tokens: cfg.maxTokens || 1024, |
| 73 | system, |
| 74 | stream: true, |
| 75 | messages: forAnthropic(packed), |
| 76 | }), |
| 77 | }); |
| 78 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 79 | |
| 80 | let out = ''; |
| 81 | await readSSE(res.body, payload => { |
| 82 | const evt = JSON.parse(payload); |
| 83 | if (evt.type === 'content_block_delta' && evt.delta?.text) { |
| 84 | out += evt.delta.text; onToken(evt.delta.text); |
| 85 | } |
| 86 | }); |
| 87 | return out.trim(); |
| 88 | } |
| 89 | |
| 90 | // Anthropic exige roles alternos empezando por user; fusiona consecutivos. |
| 91 | function forAnthropic(msgs) { |
| 92 | const merged = []; |
| 93 | for (const m of msgs) { |
| 94 | const role = m.role === 'assistant' ? 'assistant' : 'user'; |
| 95 | const last = merged[merged.length - 1]; |
| 96 | if (last && last.role === role) last.content += '\n' + m.content; |
| 97 | else merged.push({ role, content: m.content }); |
| 98 | } |
| 99 | if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: '(continúa)' }); |
| 100 | return merged; |
| 101 | } |
| 102 | |
| 103 | // Lector SSE común: invoca fn con el texto tras cada 'data:'. |
| 104 | async function readSSE(stream, fn) { |
| 105 | const reader = stream.getReader(); |
| 106 | const dec = new TextDecoder(); |
| 107 | let buf = ''; |
| 108 | for (;;) { |
| 109 | const { done, value } = await reader.read(); |
| 110 | if (done) break; |
| 111 | buf += dec.decode(value, { stream: true }); |
| 112 | let nl; |
| 113 | while ((nl = buf.indexOf('\n')) >= 0) { |
| 114 | const line = buf.slice(0, nl).trim(); |
| 115 | buf = buf.slice(nl + 1); |
| 116 | if (!line.startsWith('data:')) continue; |
| 117 | const payload = line.slice(5).trim(); |
| 118 | if (!payload) continue; |
| 119 | try { fn(payload); } catch { /* chunk parcial */ } |
| 120 | } |
| 121 | } |
| 122 | } |