| 1 | // Modelo vía ONNX Runtime Web (transformers.js, WebGPU con fallback a wasm). |
| 2 | // Patrón copiado de la demo verificada en agentic-install |
| 3 | // (lab/bitacora/posts/08-jspace-live.html): dtype 'q4' obligatorio — q4f16 |
| 4 | // genera basura vía WebGPU incluso con shader-f16. |
| 5 | import { MODEL, ONNX_MODELS, setOnnxModel } from '../model-config.js'; |
| 6 | import { packHistoryAsync } from '../context.js'; |
| 7 | |
| 8 | export let name = MODEL.label; |
| 9 | |
| 10 | // Elegir qué ONNX cargar. Si cambia respecto al ya cargado, se descarta la |
| 11 | // sesión para que load() cree la nueva (un modelo distinto = otra sesión). |
| 12 | let generator = null, TextStreamer = null, cargadoKey = null; |
| 13 | export function configure(key) { |
| 14 | const antes = MODEL.key; |
| 15 | setOnnxModel(key); |
| 16 | name = MODEL.label; |
| 17 | if (MODEL.key !== cargadoKey && generator) { try { generator?.dispose?.(); } catch {} generator = null; } |
| 18 | return MODEL.key !== antes; |
| 19 | } |
| 20 | export function models() { return Object.values(ONNX_MODELS); } |
| 21 | |
| 22 | export async function load(onProgress = () => {}) { |
| 23 | if (generator) return; // un solo modelo: nunca recargar/duplicar la sesión |
| 24 | const tf = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@4'); |
| 25 | TextStreamer = tf.TextStreamer; |
| 26 | if (MODEL.selfHosted) { |
| 27 | tf.env.allowRemoteModels = false; |
| 28 | tf.env.localModelPath = MODEL.basePath; |
| 29 | } |
| 30 | // navigator.gpu puede EXISTIR como API sin que haya un adaptador real |
| 31 | // (ciertos Linux/drivers, entornos sandboxed, navegadores headless…) — usar |
| 32 | // solo la presencia del objeto como señal hace que pipeline() intente |
| 33 | // WebGPU, falle con "Failed to get GPU adapter" DESPUÉS de descargar el |
| 34 | // modelo entero, y en preloadModel() eso encadena a probar Gemma (varios |
| 35 | // GB) para nada. Comprobar el adaptador de verdad antes de elegir. |
| 36 | let device = 'wasm'; |
| 37 | if (navigator.gpu) { |
| 38 | try { device = (await navigator.gpu.requestAdapter()) ? 'webgpu' : 'wasm'; } |
| 39 | catch { device = 'wasm'; } |
| 40 | } |
| 41 | generator = await tf.pipeline('text-generation', MODEL.id, { |
| 42 | device, |
| 43 | dtype: MODEL.dtype, |
| 44 | progress_callback: onProgress, |
| 45 | }); |
| 46 | cargadoKey = MODEL.key; |
| 47 | } |
| 48 | |
| 49 | // Liberar el modelo (vigilante de RAM): suelta los buffers wasm/WebGPU. |
| 50 | export async function unload() { |
| 51 | try { await generator?.dispose?.(); } catch { /* mejor esfuerzo */ } |
| 52 | generator = null; cargadoKey = null; |
| 53 | } |
| 54 | |
| 55 | export async function chat(history, system, onToken = () => {}) { |
| 56 | if (!generator) throw new Error('Modelo no cargado'); |
| 57 | // ACE-lite: eviction por relevancia. Presupuesto amplio (LFM2.5 aguanta |
| 58 | // contexto largo); el tope POR MENSAJE (context.js) evita que un README |
| 59 | // gigante dispare «Too many tokens requested». |
| 60 | const messages = [{ role: 'system', content: system }, ...(await packHistoryAsync(history, 5000))]; |
| 61 | const streamer = new TextStreamer(generator.tokenizer, { |
| 62 | skip_prompt: true, |
| 63 | skip_special_tokens: true, |
| 64 | callback_function: onToken, |
| 65 | }); |
| 66 | const out = await generator(messages, { |
| 67 | max_new_tokens: 1024, |
| 68 | do_sample: false, // determinista: los tool calls JSON lo agradecen |
| 69 | repetition_penalty: 1.1, |
| 70 | return_full_text: false, |
| 71 | streamer, |
| 72 | }); |
| 73 | const gen = out[0].generated_text; |
| 74 | let txt = (typeof gen === 'string' ? gen : gen.at(-1).content); |
| 75 | // Modelos de razonamiento (Qwen3): fuera el <think>. Si quedó abierto por el |
| 76 | // tope de tokens, nos quedamos con lo de después de la última apertura. |
| 77 | if (txt.includes('<think>')) { |
| 78 | txt = txt.replace(/<think>[\s\S]*?<\/think>/g, ''); |
| 79 | const i = txt.lastIndexOf('<think>'); |
| 80 | if (i !== -1) txt = txt.slice(i + 7); |
| 81 | txt = txt.replace(/<\/?think>/g, ''); |
| 82 | } |
| 83 | return txt.trim(); |
| 84 | } |