| 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 | // `signal` corta la petición de verdad: fetch la aborta y la conexión se cierra, |
| 20 | // así que el proveedor deja de generar (y de cobrar) en cuanto se pulsa parar. |
| 21 | // Antes chat() la recibía pero no la pasaba: openaiChat usaba un `signal` que no |
| 22 | // existía en su ámbito y CADA llamada a un proveedor OpenAI-compatible |
| 23 | // reventaba con «signal is not defined». |
| 24 | // |
| 25 | // El 4º argumento es la señal sola o `{ signal, onPrefill }` (ver senalDe). Sin |
| 26 | // normalizarlo, el objeto de opciones llegaba a fetch como si fuera la señal y |
| 27 | // CADA llamada reventaba con un TypeError. |
| 28 | export async function chat(history, system, onToken = () => {}, opciones = null) { |
| 29 | const signal = senalDe(opciones); |
| 30 | return cfg.kind === 'anthropic' |
| 31 | ? anthropicChat(history, system, onToken, signal) |
| 32 | : openaiChat(history, system, onToken, signal); |
| 33 | } |
| 34 | |
| 35 | // El 4º argumento de chat() llega de dos formas y las dos valen, igual que en |
| 36 | // chat() del motor propio: la señal de parar sola, o un objeto de opciones que |
| 37 | // la lleva dentro (`{ signal, onPrefill }`, el que manda el agente cuando pinta |
| 38 | // la espera del motor). Lo que este proveedor no usa, como onPrefill, se ignora. |
| 39 | // La señal se reconoce por la forma y no por la clase, como en el motor: una de |
| 40 | // otro reino (un iframe, un worker) no es `instanceof` de la de esta página. |
| 41 | function senalDe(x) { |
| 42 | if (!x || typeof x !== 'object') return null; |
| 43 | if (typeof x.aborted === 'boolean') return x; |
| 44 | return x.signal && typeof x.signal.aborted === 'boolean' ? x.signal : null; |
| 45 | } |
| 46 | |
| 47 | // Parado a media respuesta: AbortError, como el de fetch, con lo generado hasta |
| 48 | // ese punto en `partial` por si alguien lo quiere. |
| 49 | function abortado(partial) { |
| 50 | const e = new DOMException('Parado', 'AbortError'); |
| 51 | try { e.partial = partial; } catch { /* sin expandos: da igual */ } |
| 52 | return e; |
| 53 | } |
| 54 | |
| 55 | // ---- OpenAI-compatible ---- |
| 56 | async function openaiChat(history, system, onToken, signal) { |
| 57 | const headers = { 'Content-Type': 'application/json' }; |
| 58 | if (cfg.apiKey) headers.Authorization = 'Bearer ' + cfg.apiKey; |
| 59 | // packHistoryAsync: el empaquetado puede tener que codificar embeddings, así |
| 60 | // que se resuelve ANTES de armar el cuerpo. Con el lado semántico apagado |
| 61 | // devuelve exactamente lo mismo que la versión síncrona de siempre. |
| 62 | const packed = await packHistoryAsync(history, 3000); |
| 63 | const body = { |
| 64 | model: cfg.model, |
| 65 | messages: [{ role: 'system', content: system }, ...packed], |
| 66 | stream: true, |
| 67 | max_tokens: cfg.maxTokens || 1024, |
| 68 | }; |
| 69 | if (cfg.temperature != null) body.temperature = cfg.temperature; |
| 70 | if (cfg.top_p != null) body.top_p = cfg.top_p; |
| 71 | if (cfg.thinking != null) body.chat_template_kwargs = { enable_thinking: cfg.thinking }; |
| 72 | |
| 73 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/chat/completions', { |
| 74 | signal, |
| 75 | method: 'POST', headers, body: JSON.stringify(body), |
| 76 | }); |
| 77 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 78 | |
| 79 | let out = ''; |
| 80 | try { |
| 81 | await readSSE(res.body, payload => { |
| 82 | if (payload === '[DONE]') return; |
| 83 | const d = JSON.parse(payload).choices?.[0]?.delta || {}; |
| 84 | if (d.reasoning_content) onToken(d.reasoning_content); |
| 85 | if (d.content) { out += d.content; onToken(d.content); } |
| 86 | }, signal); |
| 87 | } catch (e) { |
| 88 | if (signal?.aborted) throw abortado(out.trim()); |
| 89 | throw e; |
| 90 | } |
| 91 | return out.trim(); |
| 92 | } |
| 93 | |
| 94 | // ---- Anthropic Messages ---- |
| 95 | async function anthropicChat(history, system, onToken, signal) { |
| 96 | const packed = await packHistoryAsync(history, 3000); |
| 97 | const res = await fetch(cfg.baseURL.replace(/\/$/, '') + '/v1/messages', { |
| 98 | signal, |
| 99 | method: 'POST', |
| 100 | headers: { |
| 101 | 'Content-Type': 'application/json', |
| 102 | 'x-api-key': cfg.apiKey, |
| 103 | 'anthropic-version': '2023-06-01', |
| 104 | 'anthropic-dangerous-direct-browser-access': 'true', |
| 105 | }, |
| 106 | body: JSON.stringify({ |
| 107 | model: cfg.model, |
| 108 | max_tokens: cfg.maxTokens || 1024, |
| 109 | system, |
| 110 | stream: true, |
| 111 | messages: forAnthropic(packed), |
| 112 | }), |
| 113 | }); |
| 114 | if (!res.ok || !res.body) throw new Error('HTTP ' + res.status + ' ' + (await res.text().catch(() => '')).slice(0, 120)); |
| 115 | |
| 116 | let out = ''; |
| 117 | try { |
| 118 | await readSSE(res.body, payload => { |
| 119 | const evt = JSON.parse(payload); |
| 120 | if (evt.type === 'content_block_delta' && evt.delta?.text) { |
| 121 | out += evt.delta.text; onToken(evt.delta.text); |
| 122 | } |
| 123 | }, signal); |
| 124 | } catch (e) { |
| 125 | if (signal?.aborted) throw abortado(out.trim()); |
| 126 | throw e; |
| 127 | } |
| 128 | return out.trim(); |
| 129 | } |
| 130 | |
| 131 | // Anthropic exige roles alternos empezando por user; fusiona consecutivos. |
| 132 | function forAnthropic(msgs) { |
| 133 | const merged = []; |
| 134 | for (const m of msgs) { |
| 135 | const role = m.role === 'assistant' ? 'assistant' : 'user'; |
| 136 | const last = merged[merged.length - 1]; |
| 137 | if (last && last.role === role) last.content += '\n' + m.content; |
| 138 | else merged.push({ role, content: m.content }); |
| 139 | } |
| 140 | if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: '(continúa)' }); |
| 141 | return merged; |
| 142 | } |
| 143 | |
| 144 | // Lector SSE común: invoca fn con el texto tras cada 'data:'. Con la señal |
| 145 | // abortada no entrega ni un evento más, aunque ya estén en el búfer: un mismo |
| 146 | // trozo de red puede traer varios, y sin esto saldrían tokens después de |
| 147 | // pulsar parar. |
| 148 | async function readSSE(stream, fn, signal = null) { |
| 149 | const reader = stream.getReader(); |
| 150 | const dec = new TextDecoder(); |
| 151 | let buf = ''; |
| 152 | const corta = () => { |
| 153 | if (!signal?.aborted) return; |
| 154 | reader.cancel().catch(() => {}); |
| 155 | throw new DOMException('Parado', 'AbortError'); |
| 156 | }; |
| 157 | for (;;) { |
| 158 | corta(); |
| 159 | const { done, value } = await reader.read(); |
| 160 | if (done) break; |
| 161 | buf += dec.decode(value, { stream: true }); |
| 162 | let nl; |
| 163 | while ((nl = buf.indexOf('\n')) >= 0) { |
| 164 | corta(); |
| 165 | const line = buf.slice(0, nl).trim(); |
| 166 | buf = buf.slice(nl + 1); |
| 167 | if (!line.startsWith('data:')) continue; |
| 168 | const payload = line.slice(5).trim(); |
| 169 | if (!payload) continue; |
| 170 | try { fn(payload); } catch { /* chunk parcial */ } |
| 171 | } |
| 172 | } |
| 173 | } |