Spaces:
Paused

assistant / ui /web /src /lib /api.js
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
17.9 kB
// Thin HTTP + WebSocket client for the LocalAiLab FastAPI backend.
export function getSessionToken() {
if (typeof window !== "undefined" && window.__SESSION_TOKEN__) {
return window.__SESSION_TOKEN__;
}
return "";
}
function authHeaders(extra = {}) {
const token = getSessionToken();
const headers = { ...extra };
if (token) {
headers["X-Session-Token"] = token;
}
return headers;
}
export async function getJSON(path) {
const r = await fetch(path, { headers: authHeaders({ Accept: "application/json" }) });
if (!r.ok) throw new Error(`HTTP ${r.status} β€” ${path}`);
return r.json();
}
export async function postForm(path, formData) {
const r = await fetch(path, { method: "POST", headers: authHeaders(), body: formData });
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.json();
}
export async function postJSON(path, payload) {
const r = await fetch(path, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify(payload),
});
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
const ct = r.headers.get("content-type") || "";
return ct.includes("json") ? r.json() : r.text();
}
export function fetchMeta() {
return getJSON("/api/meta");
}
export function fetchI18n(lang) {
return getJSON(`/api/i18n?lang=${encodeURIComponent(lang)}`);
}
export function saveSettings(payload) {
return postJSON("/api/settings", payload);
}
export function saveReport(payload) {
return postJSON("/api/reports", payload);
}
export function resetAgent(payload) {
return postJSON("/api/agent/reset", payload);
}
/**
* POST a raw image File to /api/upload; returns { ok, path } β€” the temp
* path is sent through the chat WS and deleted server-side after the run.
*/
export async function uploadImage(file) {
const r = await fetch("/api/upload", { method: "POST", headers: authHeaders(), body: file });
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.json();
}
/** mmproj (vision projector) choices for the current VLM + provider. */
export function fetchMmproj(vlm, provider) {
return getJSON(
`/api/mmproj?vlm=${encodeURIComponent(vlm)}&provider=${encodeURIComponent(provider)}`
);
}
/** The 'already downloaded?' notice for a provider/model pair β€” the header
* model-status chip reads this (web port of the Gradio model-status card). */
export function fetchModelNotice(provider, model, type = "llm", lang = "kh") {
return getJSON(
`/api/model-notice?provider=${encodeURIComponent(provider)}&model=${encodeURIComponent(model)}&type=${encodeURIComponent(type)}&lang=${encodeURIComponent(lang)}`
);
}
/** Check if a model is cached, needs download, its download size, and resolved id. */
export function fetchModelCheck(provider, model, type = "llm", lang = "kh") {
return getJSON(
`/api/model-check?provider=${encodeURIComponent(provider)}&model=${encodeURIComponent(model)}&type=${encodeURIComponent(type)}&lang=${encodeURIComponent(lang)}`
);
}
// ── Model pre-download ────────────────────────────────────────────────
/** Trigger a background download of a HuggingFace model (repo id). */
export function startModelDownload(modelId, modelLabel = "") {
return postJSON("/api/model-download", { model_id: modelId, model_label: modelLabel });
}
/** Poll model download progress. */
export function modelDownloadStatus() {
return getJSON("/api/model-download");
}
/** Signal an in-flight model download to abort. */
export function cancelModelDownload() {
return postJSON("/api/model-download-cancel", {});
}
/** Available disk space on the user_data drive. */
export function fetchDiskSpace() {
return getJSON("/api/disk-space");
}
/** Delete a downloaded model from disk. */
export function deleteModel(modelId) {
return postJSON("/api/model-delete", { model_id: modelId });
}
// ── STT ────────────────────────────────────────────────────────────────
export function sttTranscribe(file, { sttLabel = "", language = "auto" } = {}) {
const fd = new FormData();
fd.append("audio", file);
fd.append("stt_label", sttLabel);
fd.append("language", language);
return postForm("/api/stt/transcribe", fd);
}
/** Upload audio for WebSocket-based STT β€” returns {path} for /ws/stt/transcribe. */
export function sttUpload(file) {
const fd = new FormData();
fd.append("audio", file);
return postForm("/api/stt/upload", fd);
}
export const sttAnalyse = (payload) => postJSON("/api/stt/analyse", payload);
export const sttSaveTxt = (payload) => postJSON("/api/stt/save-txt", payload);
export const sttLoad = (modelLabel, lang = "kh") => postJSON("/api/stt/load", { model_label: modelLabel, lang });
export const sttUnload = () => postJSON("/api/stt/unload", {});
/** Save the current audio File into user_data/outputs/ (the STT tab's
* "πŸ’Ύ Save Audio" button). The client always sends WAV, the format every
* STT backend reads. Returns { ok, path }.
*/
export async function sttSaveAudio(file, filename = "") {
const fd = new FormData();
fd.append("audio", file);
fd.append("filename", filename);
return postForm("/api/stt/save-audio", fd);
}
/** Open user_data/outputs/ in the OS file explorer. */
export const sttOpenOutputs = () => postJSON("/api/stt/open-outputs", {});
/** Reduce background noise in the audio and return the cleaned WAV as a
* Blob (the endpoint answers audio/wav, not JSON β€” the STT tab swaps the
* result in as the current audio). JSON error bodies still throw with their
* message. */
export async function sttDenoise(file, strength = "aggressive") {
const fd = new FormData();
fd.append("audio", file);
fd.append("strength", strength);
const r = await fetch("/api/stt/denoise", { method: "POST", headers: authHeaders(), body: fd });
const ct = r.headers.get("content-type") || "";
if (!r.ok || !ct.includes("audio/")) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.blob();
}
// ── Data Analysis ──────────────────────────────────────────────────────
export function analyzeData({
files,
question = "",
modelLabel = "",
useMemory = true,
maxSteps = "",
executionTimeout = "",
lang = "kh",
} = {}) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
fd.append("question", question);
fd.append("model_label", modelLabel);
fd.append("use_memory", useMemory ? "true" : "false");
fd.append("lang", lang);
if (maxSteps) fd.append("max_steps", maxSteps);
if (executionTimeout) fd.append("execution_timeout", executionTimeout);
return postForm("/api/data/analyze", fd);
}
/** Upload data files (CSV/XLSX) to temp storage for the Data Analysis chat
* tab β€” the WS payload then carries the returned paths (like Vision's
* image upload). Returns { paths }. */
export async function dataUpload(files) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
return postForm("/api/data/upload", fd);
}
export const resetData = () => postJSON("/api/data/reset", {});
/** Chart image URL for a saved PNG basename. The backend guards every
* /api/* route with the session token (X-Session-Token header on fetch
* calls; `?token=` query param for WebSockets). An <img src> tag cannot
* send headers, so the token travels as a query param here β€” otherwise
* every chart 401s and renders as a broken image. */
export const dataChartUrl = (name) => {
const base = `/api/data/chart/${encodeURIComponent(name)}`;
const token = getSessionToken();
return token ? `${base}?token=${encodeURIComponent(token)}` : base;
};
/** The Data Analysis charts folder: its full path (display) + open it in
* the OS file explorer (mirrors the STT outputs folder). */
export const dataOutputDir = () => getJSON("/api/data/output-dir");
export const dataOpenOutputs = () => postJSON("/api/data/open-outputs", {});
// ── Knowledge Base ─────────────────────────────────────────────────────
// Indexing streams live progress as Server-Sent Events (text/event-stream):
// each `log` event carries one terminal status line ([RAG] embedding load,
// [transformers] model warnings …) and a final `done` event carries the
// result message. `onLog(line)` is called for every streamed line so the KB
// tab can render + copy the same text the console showed.
export async function kbIndex({ files, theme = [], subtheme = [], visualRetriever = "", lang = "kh", embedProvider = "", embedModel = "", onLog } = {}) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
// theme/subtheme are arrays (the multi-select tag dropdowns) β€” send each
// value as a repeated form field so the backend sees every selected tag.
for (const v of [].concat(theme || [])) if (v) fd.append("theme", v);
for (const v of [].concat(subtheme || [])) if (v) fd.append("subtheme", v);
fd.append("visualRetriever", visualRetriever);
fd.append("lang", lang);
if (embedProvider) fd.append("embed_provider", embedProvider);
if (embedModel) fd.append("embed_model", embedModel);
const res = await fetch("/api/kb/index", { method: "POST", headers: authHeaders(), body: fd });
if (!res.ok || !res.body) {
throw new Error(`kb/index failed: ${res.status}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
let finalMsg = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf("\n\n")) !== -1) {
const chunk = buf.slice(0, idx);
buf = buf.slice(idx + 2);
const dataLine = chunk.split("\n").find((l) => l.startsWith("data: "));
if (!dataLine) continue;
let data;
try {
data = JSON.parse(dataLine.slice(6));
} catch {
continue;
}
if (data.type === "log") {
if (onLog) onLog(data.line);
} else if (data.type === "done") {
finalMsg = data.message || "";
}
}
}
if (!finalMsg && onLog) onLog("βœ” Indexing finished.");
return { ok: true, message: finalMsg };
}
export const kbDocs = (refresh = false) => getJSON(`/api/kb/docs?refresh=${refresh ? 1 : 0}`);
export const kbThemes = (theme = "") => getJSON(`/api/kb/themes?theme=${encodeURIComponent(theme)}`);
export const kbDelete = (selected, rows, lang = "kh") => postJSON("/api/kb/delete", { selected, rows, lang });
export const kbClear = (lang = "kh") => postJSON("/api/kb/clear", { lang });
export const kbVisualDocs = () => getJSON("/api/kb/visual-docs");
export const kbVisualDelete = (selected, rows, lang = "kh") => postJSON("/api/kb/visual-delete", { selected, rows, lang });
export const kbVisualClear = (lang = "kh") => postJSON("/api/kb/visual-clear", { lang });
// ── Settings ───────────────────────────────────────────────────────────
export const fetchSettings = (lang = "kh") => getJSON(`/api/settings?lang=${encodeURIComponent(lang)}`);
export const saveSetting = (key, value, tab) => postJSON("/api/settings/save", { key, value, tab });
export const freeVram = (lang = "kh") => postJSON("/api/settings/free-vram", { lang });
export const restartApp = (lang = "kh") => postJSON("/api/restart", { lang });
export const fetchMemory = () => getJSON("/api/settings/memory");
export const clearReports = (days) => postJSON("/api/settings/clear-reports", { days });
export const openReports = (tab = "", path = "") => postJSON("/api/settings/open-reports", { tab, path });
export const refreshReports = () => postJSON("/api/settings/refresh-reports", {});
export const deleteReport = (rel) => postJSON("/api/settings/delete-report", { rel });
export const startDownload = (component) => postJSON("/api/settings/download", { component });
export const downloadStatus = () => getJSON("/api/settings/download");
/** llama-cpp-python detection report ({ detected, options }) β€” fetched when
* the Settings install button is clicked so the popup can show the user
* every build available on this PC instead of silently installing CPU. */
export const llmCppInfo = () => getJSON("/api/settings/llm-cpp-info");
/** Install a user-chosen llama-cpp-python build (auto / cpu / cuda /
* vulkan). Reuses the shared download job β€” same poll/status/stream. */
export const llmCppInstall = (choice) => postJSON("/api/settings/llm-cpp-install", { choice });
/** llama-server download plan ({ detected, options }) β€” fetched when the
* Settings download button is clicked so the popup can show the user every
* build available on this PC (CPU / CUDA 12.4 / CUDA 13.3) instead of
* silently auto-picking one. */
export const llamaServerInfo = () => getJSON("/api/settings/llama-server-info");
/** Download a user-chosen llama-server build (auto / cpu / cuda12 /
* cuda13). Reuses the shared download job β€” same poll/status/stream. */
export const llamaServerInstall = (choice) => postJSON("/api/settings/llama-server-install", { choice });
/** whisper-server download plan ({ detected, options }) β€” fetched when the
* Settings download button is clicked so the popup can show the user every
* build available on this PC (CPU / cuBLAS 11.8 / cuBLAS 12.4) instead of
* silently downloading the CPU build. */
export const whisperServerInfo = () => getJSON("/api/settings/whisper-server-info");
/** Download a user-chosen whisper-server build (auto / cpu / cuda11 /
* cuda12). Reuses the shared download job β€” same poll/status/stream. */
export const whisperServerInstall = (choice) => postJSON("/api/settings/whisper-server-install", { choice });
/** PyTorch install plan ({ detected, options }) β€” fetched when the Settings
* "Detect & Install GPU PyTorch" button is clicked so the popup can show
* the user every build available on this PC (CPU / CUDA / Intel XPU /
* AMD ROCm) instead of silently installing the recommended path. */
export const pytorchInfo = () => getJSON("/api/settings/pytorch-info");
/** Install a user-chosen PyTorch build (auto / cpu / cuda / xpu / rocm).
* Reuses the shared download job β€” same poll/status/stream. */
export const pytorchInstall = (choice) => postJSON("/api/settings/pytorch-install", { choice });
// ── About & Feedback ──────────────────────────────────────────────────
export const fetchAbout = (lang = "kh") => getJSON(`/api/about?lang=${encodeURIComponent(lang)}`);
export const fetchDiagnostics = (lang = "kh") => getJSON(`/api/feedback/diagnostics?lang=${encodeURIComponent(lang)}`);
export const submitFeedback = (payload) => postJSON("/api/feedback", payload);
/**
* Open a backend WebSocket. onMessage receives every server event object.
* `path` defaults to the chat socket (/ws/chat) β€” pass e.g. "/ws/stt/analyse"
* for the STT report-analysis stream, which speaks the same event protocol
* (live / update / final / error). Returns { send(payload), close() } β€”
* send() queues until the socket opens.
*/
export function openChatSocket(onMessage, path = "/ws/chat") {
const proto = location.protocol === "https:" ? "wss" : "ws";
const token = getSessionToken();
const tokenQuery = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`${proto}://${location.host}${path}${tokenQuery}`);
const queue = [];
let closedNormally = false;
ws.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === "final" || data.type === "error") {
closedNormally = true;
}
onMessage(data);
} catch {
/* ignore */
}
};
ws.onerror = () => {
if (!closedNormally) {
onMessage({ type: "error", message: "WebSocket connection error" });
}
};
ws.onclose = (e) => {
if (!closedNormally && !e.wasClean) {
onMessage({ type: "error", message: "Server connection lost" });
}
};
ws.onopen = () => {
while (queue.length) ws.send(queue.shift());
};
return {
send(payload) {
const raw = JSON.stringify(payload);
if (ws.readyState === WebSocket.OPEN) ws.send(raw);
else queue.push(raw);
},
close() {
closedNormally = true;
try {
ws.close();
} catch {
/* already closed */
}
},
};
}