import { createContext, useCallback, useContext, useMemo, useState, html } from "./runtime.js"; import { useCloud } from "./cloud.js"; // Chat runs against the user's own OpenAI-compatible endpoint, or against a // hosted model included in a plan. The Paragraph models are 2.5–61 GB // checkpoints: they are downloaded for the Mac/iOS app or any GGUF runner, not // executed inside a browser tab. const EngineContext = createContext(null); function readEndpoint(key) { try { return localStorage.getItem(key) || ""; } catch { return ""; } } export function EngineProvider({ children }) { const cloud = useCloud(); // The developer's hosted models (paid for with the plan's budget), chosen here. const [hostedId, setHostedId] = useState(() => readEndpoint("explication.hosted.model")); const setHostedModel = useCallback((id) => { try { localStorage.setItem("explication.hosted.model", id || ""); } catch { // ignore } setHostedId(id || ""); }, []); const hosted = useMemo( () => cloud.models.find((m) => m.id === hostedId && m.enabled !== false) || null, [cloud.models, hostedId] ); const hostedReady = !!hosted && !!hosted.endpoint_url && cloud.canHost(hosted); const [endpoint, setEndpointState] = useState(() => ({ baseUrl: readEndpoint("explication.endpoint.baseUrl").trim(), model: readEndpoint("explication.endpoint.model").trim(), key: readEndpoint("explication.endpoint.key").trim() })); const setEndpoint = useCallback((next) => { const clean = { baseUrl: (next.baseUrl || "").trim(), model: (next.model || "").trim(), key: (next.key || "").trim() }; try { localStorage.setItem("explication.endpoint.baseUrl", clean.baseUrl); localStorage.setItem("explication.endpoint.model", clean.model); localStorage.setItem("explication.endpoint.key", clean.key); } catch { // ignore quota errors } setEndpointState(clean); }, []); const hasEndpoint = !!endpoint.baseUrl && !!endpoint.model; /** * Streams a reply. Returns the full text. */ const chat = useCallback( async (messages, onToken) => { if (hasEndpoint) { const base = endpoint.baseUrl.replace(/\/+$/, ""); const res = await fetch(`${base}/chat/completions`, { method: "POST", headers: { "Content-Type": "application/json", ...(endpoint.key ? { Authorization: `Bearer ${endpoint.key}` } : {}) }, body: JSON.stringify({ model: endpoint.model, messages, stream: true, temperature: 0.4 }) }); if (!res.ok) throw new Error(`The endpoint returned ${res.status}. Check the URL, model and key in Settings.`); if (!res.body) { const data = await res.json(); const text = data?.choices?.[0]?.message?.content || ""; if (onToken) onToken(text); return text; } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let full = ""; while (true) { const { value, done } = 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.startsWith("data:")) continue; const payload = trimmed.slice(5).trim(); if (payload === "[DONE]") continue; try { const json = JSON.parse(payload); const delta = json?.choices?.[0]?.delta?.content || ""; if (delta) { full += delta; onToken && onToken(full); } } catch { // A partial SSE line; wait for the next chunk. } } } return full; } if (hostedReady) { return cloud.hostedChat(hosted, messages, onToken); } throw new Error( "No model is connected. Add an OpenAI-compatible endpoint in Settings, or download a Paragraph model and run it on your own machine." ); }, [hasEndpoint, endpoint, hostedReady, hosted, cloud] ); const value = useMemo( () => ({ endpoint, hasEndpoint, hosted, hostedId, hostedReady, setHostedModel, canGenerate: hasEndpoint || hostedReady, chat, setEndpoint }), [endpoint, hasEndpoint, hosted, hostedId, hostedReady, setHostedModel, chat, setEndpoint] ); return html`<${EngineContext.Provider} value=${value}>${children}`; } export function useEngine() { const value = useContext(EngineContext); if (!value) throw new Error("useEngine must be used inside EngineProvider"); return value; }