From 7388b2718edbd15d8f4c7392ab3c501bc5839fa6 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 09:55:53 +0000 Subject: [PATCH] feat(llm): run a GGUF chat model locally with llama.cpp Settings > Local model lists GGUF chat models with the memory and disk each needs; the ones this machine can run can be picked. Lens downloads the model from Hugging Face (pinned revision, SHA-256 checked, resumed), fetches llama.cpp's server for the platform unless llama-server is installed, runs it with its own API key under a lease, and makes it the LLM provider, putting the previous provider back when turned off. Any GGUF on Hugging Face works as hf:owner/repo/file.gguf. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_014Fki157VgxFETzSSpwFwYe --- DEVLOG.md | 5 +- docs/local-models.md | 51 ++ fastapi_backend/app/api/v1/routes/admin.py | 23 +- fastapi_backend/app/cli.py | 3 +- fastapi_backend/app/core/runtime.py | 18 +- fastapi_backend/app/domain/local_llm.py | 609 ++++++++++++++++++ fastapi_backend/app/domain/settings.py | 38 ++ fastapi_backend/app/domain/store.py | 13 + fastapi_backend/app/schemas/admin.py | 44 ++ .../tests/domain/test_local_llm.py | 209 ++++++ mkdocs.yml | 1 + .../__tests__/settings-local-model.test.tsx | 102 +++ nextjs-frontend/app/openapi-client/index.ts | 13 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 34 + .../app/openapi-client/types.gen.ts | 212 ++++++ .../components/settings/bodies.tsx | 119 ++++ nextjs-frontend/components/settings/model.ts | 57 ++ .../components/settings/settings-shell.tsx | 2 + nextjs-frontend/openapi.json | 328 ++++++++++ 19 files changed, 1876 insertions(+), 5 deletions(-) create mode 100644 docs/local-models.md create mode 100644 fastapi_backend/app/domain/local_llm.py create mode 100644 fastapi_backend/tests/domain/test_local_llm.py create mode 100644 nextjs-frontend/__tests__/settings-local-model.test.tsx diff --git a/DEVLOG.md b/DEVLOG.md index 879939b01..5047922f3 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -30,11 +30,12 @@ Todo: language, events and sentiment; provider speaker labels in speaker separation - [x] Voice chat: own speech-to-text engine; ElevenLabs and Deepgram text to speech - [x] Settings → Speech providers in the web app; new engines in Transcription and Speaker separation -- [ ] Local LLM: GGUF catalog filtered by this machine, download from Hugging Face, llama.cpp server as the provider +- [x] Local LLM: GGUF catalog filtered by this machine, download from Hugging Face, llama.cpp server as the provider Refine later: per-minute prices for provider calls in the ledger; AssemblyAI and Deepgram summaries, chapters and entities as optional imports next to Lens's own analysis; several endpoints per service; speaker labels kept across -chunks of long OpenAI-compatible transcriptions. +chunks of long OpenAI-compatible transcriptions; CUDA and Vulkan builds of llama.cpp; local embedding models. + ## 2026-10-04 · Topics: a controlled vocabulary apart from entities Goal (Adeel): entities and topics are mixed (a topic is an entity of type TERM, which is also the fallback type for diff --git a/docs/local-models.md b/docs/local-models.md new file mode 100644 index 000000000..b10a2b542 --- /dev/null +++ b/docs/local-models.md @@ -0,0 +1,51 @@ +# Local models + +Lens can run a chat model itself, so summaries, templates and the assistant work with no model server and nothing +leaving the machine. It uses [llama.cpp](https://github.com/ggml-org/llama.cpp)'s server and GGUF files from +Hugging Face. + +Status: built. Planned: GPU builds of llama.cpp (CUDA, Vulkan) fetched by Lens, local embedding models. + +## Use it + +**Settings → Local model**: + +1. Pick a model. The list shows each model's download size and the memory it needs (the weights, the context, and room + for Lens). Models this machine can't run, or has no disk for, are greyed out. Small ones (Qwen2.5 0.5B, Llama 3.2 + 1B, Qwen2.5 1.5B) run on a Raspberry Pi; 7B and 8B models want 16 GB or a GPU. +2. Turn on **Run a model here** and save. + +Lens then, in the background: + +- fetches llama.cpp's server, unless `llama-server` is already on PATH (Homebrew: `brew install llama.cpp`) or + `local_llm.server` names it in archive.yaml. The release build for Linux x64, Linux arm64 and macOS (Metal on Apple + Silicon) goes into `data_dir/bin/llama.cpp`; +- downloads the model into `data_dir/models/gguf`, resuming an interrupted download. Listed models are pinned to a + revision and checked against their SHA-256; +- starts the server with its own random API key (not on the command line), and once it answers makes it the LLM + provider. The provider that was set before is kept and put back when you turn the local model off. + +The page shows each step (fetching llama.cpp, downloading with a percentage, starting, running) and the server's last +lines when something goes wrong. Downloaded models can be deleted there to free the disk. + +Any other GGUF chat model on Hugging Face works too: set the model to `hf://.gguf`. Gated models +need `HF_TOKEN` in the environment. + +## Settings + +| Setting | Default | | +| --- | --- | --- | +| `local_llm.enabled` | off | | +| `local_llm.model` | none | a listed id, or `hf:owner/repo/file.gguf` | +| `local_llm.use_as_provider` | on | off: it runs, and you point things at it yourself | +| `local_llm.context` | 4096 | tokens; more needs more memory | +| `local_llm.threads` | auto | | +| `local_llm.gpu_layers` | 999 | as many as fit on a GPU; 0 for CPU only | +| `local_llm.port` | 8091 | | +| `local_llm.host` | automatic | the address workers reach it at (in Docker, the container's address) | +| `local_llm.server` | none | llama-server's path; archive.yaml only | + +One Lens process runs the server at a time (it holds a lease, like the Cloudflare tunnel). In Docker, workers in +other containers reach it at the container's address on the compose network. + +Code: `fastapi_backend/app/domain/local_llm.py`. diff --git a/fastapi_backend/app/api/v1/routes/admin.py b/fastapi_backend/app/api/v1/routes/admin.py index 0994a5cb8..6f373786d 100644 --- a/fastapi_backend/app/api/v1/routes/admin.py +++ b/fastapi_backend/app/api/v1/routes/admin.py @@ -13,7 +13,7 @@ from app import email from app.api.deps import AdminReader, AdminWriter, Cfg, Db, domain_errors from app.core.middleware import host_name -from app.domain import auth, bridge, jobs, llm, semantic, settings, sources, speech, store, telemetry, tunnel +from app.domain import auth, bridge, jobs, llm, local_llm, semantic, settings, sources, speech, store, telemetry, tunnel from app.schemas.admin import ( AuditEntry, BridgeStatus, @@ -22,7 +22,9 @@ Health, IndexQueued, LlmTestResult, + LocalLlmStatus, MailTestResult, + Removed, SemanticStatus, SpeechTestResult, Started, @@ -95,6 +97,25 @@ def bridge_status(user: AdminReader, cfg: Cfg, db: Db) -> BridgeStatus: return BridgeStatus(**bridge.status(db, cfg)) +@router.get("/settings/local-llm/status") +def local_llm_status(user: AdminReader, cfg: Cfg, db: Db) -> LocalLlmStatus: + """The chat model Lens runs itself: the models this machine can run, which are downloaded, and how the server is + doing (fetching llama.cpp, downloading, starting, running).""" + return LocalLlmStatus.model_validate(local_llm.status(db, cfg)) + + +@router.delete("/settings/local-llm/models") +def remove_local_model(user: AdminWriter, cfg: Cfg, db: Db, model: str = Query(..., max_length=400)) -> Removed: + """Delete a downloaded model's file to free the disk (not the one running).""" + try: + removed = local_llm.remove(cfg, model) + except local_llm.LocalModelError as e: + raise HTTPException(409, str(e)) from None + if removed: + auth.audit(db, user.as_audit(), "local_llm.remove", None, {"model": model}) + return Removed(removed=removed) + + @router.get("/settings/tunnel/status") def tunnel_status(user: AdminReader, cfg: Cfg, db: Db) -> TunnelStatus: """How the Cloudflare tunnel (Settings › Remote access) is doing: its address, whether it's connected, and diff --git a/fastapi_backend/app/cli.py b/fastapi_backend/app/cli.py index 49d9ce3ab..c8c77d917 100644 --- a/fastapi_backend/app/cli.py +++ b/fastapi_backend/app/cli.py @@ -210,7 +210,7 @@ def platform_main(argv, config): import threading import time - from .domain import auth, bridge, jobs, notify, passkeys, routines, sensors, settings, sources, telemetry, tunnel + from .domain import auth, bridge, jobs, local_llm, notify, passkeys, routines, sensors, settings, sources, telemetry, tunnel ap = argparse.ArgumentParser(prog="lens") sub = ap.add_subparsers(dest="cmd", required=True) @@ -302,6 +302,7 @@ def password(): sensors.start(db, C, stop, log=print, name=wk.name) # and the sensor hub, while sensors are on bridge.start(db, C, stop, lambda: cfg, name=wk.name, log_fn=print) # and the chat-room bridge, while it's on tunnel.start(db, C, stop, name=wk.name, log=print) # and the Cloudflare tunnel, while it's on + local_llm.start(db, C, stop, name=wk.name, log=print) # and the local chat model, while it's on _stop_on_term() try: wk.loop(stop) diff --git a/fastapi_backend/app/core/runtime.py b/fastapi_backend/app/core/runtime.py index 4587dcc21..db60ac73c 100644 --- a/fastapi_backend/app/core/runtime.py +++ b/fastapi_backend/app/core/runtime.py @@ -10,7 +10,22 @@ from typing import Any from app.config import settings as env -from app.domain import auth, bridge, components, content_types, jobs, notify, routines, sensors, settings, setup, store, templates, tunnel +from app.domain import ( + auth, + bridge, + components, + content_types, + jobs, + local_llm, + notify, + routines, + sensors, + settings, + setup, + store, + templates, + tunnel, +) log = logging.getLogger("lens") @@ -62,6 +77,7 @@ def start_background(self) -> None: sensors.start(self.db, self.current, self.stop, log=log.info, name=f"api-{os.getpid()}") bridge.start(self.db, self.current, self.stop, lambda: self.base, name=f"api-{os.getpid()}", log_fn=log.warning) tunnel.start(self.db, self.current, self.stop, name=f"api-{os.getpid()}", log=log.info) + local_llm.start(self.db, self.current, self.stop, name=f"api-{os.getpid()}", log=log.info) def close(self) -> None: self.stop.set() diff --git a/fastapi_backend/app/domain/local_llm.py b/fastapi_backend/app/domain/local_llm.py new file mode 100644 index 000000000..7d236612b --- /dev/null +++ b/fastapi_backend/app/domain/local_llm.py @@ -0,0 +1,609 @@ +"""A chat model run by Lens itself: a GGUF file from Hugging Face, served by llama.cpp (Settings › LLM provider › +Run a model here; docs/local-models.md). + +The catalog lists chat models in GGUF with what each needs; the ones this machine can run (memory, disk) are offered. +Picking one downloads it into data_dir/models/gguf (pinned to a revision and checked against its SHA-256), fetches +llama.cpp's server when it isn't installed (`llama-server` on PATH, local_llm.server, or llama.cpp's GitHub release +for this platform into data_dir/bin/llama.cpp), and runs it with its own API key. Once it answers, it becomes the LLM +provider (local_llm.use_as_provider); turning it off puts the provider that was there before back. + +Any other GGUF on Hugging Face works too: local_llm.model "hf://.gguf". + +One process runs the server at a time, holding a lease on the `app_service:local_llm` row like the tunnel does, and +keeps its state there (downloading, starting, running, its address, the last lines it printed). +""" + +from __future__ import annotations + +import datetime as dt +import hashlib +import json +import os +import pathlib +import platform +import re +import secrets +import shutil +import socket +import subprocess +import tarfile +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +import zipfile + +from . import machine, settings, store + +R = store.R +ROW = R("app_service", "local_llm") +LEASE_SECONDS = 30 +TICK_SECONDS = 5 +RETRY = (5, 30, 120, 600) +LOG_LINES = 40 +HF = "https://huggingface.co" +RELEASES_API = "https://api.github.com/repos/ggml-org/llama.cpp/releases/latest" +GB = 1024**3 +HF_REF = re.compile(r"^hf:([\w.-]+/[\w.-]+)/([\w./-]+\.gguf)$") +# llama.cpp's release builds, by (system, machine): the CPU (and, on a Mac, Metal) one +ASSETS = { + ("linux", "x86_64"): re.compile(r"-bin-ubuntu-x64\.(zip|tar\.gz)$"), + ("linux", "arm64"): re.compile(r"-bin-ubuntu-arm64\.(zip|tar\.gz)$"), + ("darwin", "arm64"): re.compile(r"-bin-macos-arm64\.(zip|tar\.gz)$"), + ("darwin", "x86_64"): re.compile(r"-bin-macos-x64\.(zip|tar\.gz)$"), +} + + +def _m(id_, label, repo, rev, file, size, sha, license_, about, tools=True): + return {"id": id_, "label": label, "repo": repo, "revision": rev, "file": file, "size": size, "sha256": sha, + "license": license_, "about": about, "tools": tools} # fmt: skip + + +# Chat models in GGUF (Q4_K_M unless said), smallest first, pinned to the revision whose file was checked. +CATALOG = [ + _m("qwen2.5-0.5b", "Qwen2.5 0.5B Instruct", "Qwen/Qwen2.5-0.5B-Instruct-GGUF", "9217f5db79a29953eb74d5343926648285ec7e67", + "qwen2.5-0.5b-instruct-q4_k_m.gguf", 491400032, "74a4da8c9fdbcd15bd1f6d01d621410d31c6fc00986f5eb687824e7b93d7a9db", + "apache-2.0", "Tiny and quick; fine for routine choices on a Raspberry Pi, weak at long answers."), + _m("gemma-3-1b", "Gemma 3 1B", "ggml-org/gemma-3-1b-it-GGUF", "f9c28bcd85737ffc5aef028638d3341d49869c27", + "gemma-3-1b-it-Q4_K_M.gguf", 806058240, "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135", + "gemma", "Small, many languages.", tools=False), + _m("llama-3.2-1b", "Llama 3.2 1B Instruct", "bartowski/Llama-3.2-1B-Instruct-GGUF", "067b946cf014b7c697f3654f621d577a3e3afd1c", + "Llama-3.2-1B-Instruct-Q4_K_M.gguf", 807694464, "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83", + "llama3.2", "Small, good at following instructions."), + _m("smollm2-1.7b", "SmolLM2 1.7B Instruct", "HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF", "2d4a76a30b4af41ecd395c35725ac11688d4cfe4", + "smollm2-1.7b-instruct-q4_k_m.gguf", 1055609536, "decd2598bc2c8ed08c19adc3c8fdd461ee19ed5708679d1c54ef54a5a30d4f33", + "apache-2.0", "Small and open; English."), + _m("qwen2.5-1.5b", "Qwen2.5 1.5B Instruct", "Qwen/Qwen2.5-1.5B-Instruct-GGUF", "91cad51170dc346986eccefdc2dd33a9da36ead9", + "qwen2.5-1.5b-instruct-q4_k_m.gguf", 1117320736, "6a1a2eb6d15622bf3c96857206351ba97e1af16c30d7a74ee38970e434e9407e", + "apache-2.0", "A good small all-rounder with tool calls; fits 4 GB machines."), + _m("qwen3-1.7b", "Qwen3 1.7B (Q8_0)", "Qwen/Qwen3-1.7B-GGUF", "90862c4b9d2787eaed51d12237eafdfe7c5f6077", + "Qwen3-1.7B-Q8_0.gguf", 1834426016, "061b54daade076b5d3362dac252678d17da8c68f07560be70818cace6590cb1a", + "apache-2.0", "Thinks before it answers; tool calls."), + _m("llama-3.2-3b", "Llama 3.2 3B Instruct", "bartowski/Llama-3.2-3B-Instruct-GGUF", "5ab33fa94d1d04e903623ae72c95d1696f09f9e8", + "Llama-3.2-3B-Instruct-Q4_K_M.gguf", 2019377696, "6c1a2b41161032677be168d354123594c0e6e67d2b9227c84f296ad037c728ff", + "llama3.2", "Solid summaries on 8 GB machines."), + _m("qwen2.5-3b", "Qwen2.5 3B Instruct", "Qwen/Qwen2.5-3B-Instruct-GGUF", "7dabda4d13d513e3e842b20f0d435c732f172cbe", + "qwen2.5-3b-instruct-q4_k_m.gguf", 2104932768, "626b4a6678b86442240e33df819e00132d3ba7dddfe1cdc4fbb18e0a9615c62d", + "qwen-research", "Good summaries and tool calls on 8 GB machines; research licence."), + _m("gemma-3-4b", "Gemma 3 4B", "ggml-org/gemma-3-4b-it-GGUF", "d0976223747697cb51e056d85c532013931fe52e", + "gemma-3-4b-it-Q4_K_M.gguf", 2489757856, "882e8d2db44dc554fb0ea5077cb7e4bc49e7342a1f0da57901c0802ea21a0863", + "gemma", "Strong for its size, many languages.", tools=False), + _m("phi-4-mini", "Phi-4 mini Instruct", "bartowski/microsoft_Phi-4-mini-instruct-GGUF", "7ff82c2aaa4dde30121698a973765f39be5288c0", + "microsoft_Phi-4-mini-instruct-Q4_K_M.gguf", 2491874688, "01999f17c39cc3074afae5e9c539bc82d45f2dd7faa3917c66cbef76fce8c0c2", + "mit", "Good at reasoning and English text."), + _m("qwen3-4b", "Qwen3 4B", "Qwen/Qwen3-4B-GGUF", "bc640142c66e1fdd12af0bd68f40445458f3869b", + "Qwen3-4B-Q4_K_M.gguf", 2497280256, "7485fe6f11af29433bc51cab58009521f205840f5b4ae3a32fa7f92e8534fdf5", + "apache-2.0", "The best small model for the assistant's tools."), + _m("qwen2.5-7b", "Qwen2.5 7B Instruct", "bartowski/Qwen2.5-7B-Instruct-GGUF", "8911e8a47f92bac19d6f5c64a2e2095bd2f7d031", + "Qwen2.5-7B-Instruct-Q4_K_M.gguf", 4683074240, "65b8fcd92af6b4fefa935c625d1ac27ea29dcb6ee14589c55a8f115ceaaa1423", + "apache-2.0", "Good everywhere; wants 16 GB or a GPU."), + _m("llama-3.1-8b", "Llama 3.1 8B Instruct", "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF", "bf5b95e96dac0462e2a09145ec66cae9a3f12067", + "Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf", 4920739232, "7b064f5842bf9532c91456deda288a1b672397a54fa729aa665952863033557c", + "llama3.1", "Good everywhere; wants 16 GB or a GPU."), + _m("qwen3-8b", "Qwen3 8B", "Qwen/Qwen3-8B-GGUF", "7c41481f57cb95916b40956ab2f0b139b296d974", + "Qwen3-8B-Q4_K_M.gguf", 5027783488, "d98cdcbd03e17ce47681435b5150e34c1417f50b5c0019dd560e4882c5745785", + "apache-2.0", "Strong reasoning and tools; wants 16 GB or a GPU."), + _m("gemma-3-12b", "Gemma 3 12B", "ggml-org/gemma-3-12b-it-GGUF", "ec0cbabd8dbff316f659876a50202295c3c4a314", + "gemma-3-12b-it-Q4_K_M.gguf", 7300574976, "7bb69bff3f48a7b642355d64a90e481182a7794707b3133890646b1efa778ff5", + "gemma", "Large; 16 GB at least.", tools=False), + _m("mistral-nemo-12b", "Mistral Nemo 12B Instruct", "bartowski/Mistral-Nemo-Instruct-2407-GGUF", "a2dd64a0a76ea1bdb2bb6ab6fa5496b003c7c908", + "Mistral-Nemo-Instruct-2407-Q4_K_M.gguf", 7477208192, "7c1a10d202d8788dbe5628dc962254d10654c853cae6aaeca0618f05490d4a46", + "apache-2.0", "Large, long context; 16 GB at least."), + _m("qwen3-14b", "Qwen3 14B", "Qwen/Qwen3-14B-GGUF", "530227a7d994db8eca5ab5ced2fb692b614357fd", + "Qwen3-14B-Q4_K_M.gguf", 9001752960, "500a8806e85ee9c83f3ae08420295592451379b4f8cf2d0f41c15dffeb6b81f0", + "apache-2.0", "Large; 24 GB or a GPU with 12 GB."), +] # fmt: skip +BY_ID = {m["id"]: m for m in CATALOG} + + +class LocalModelError(RuntimeError): + """The model or llama.cpp can't be had here; the message says what to do instead.""" + + +# ---------- settings and the catalog ---------- +def conf(cfg): + return {**store.DEFAULTS["local_llm"], **(cfg.get("local_llm") or {})} + + +def resolve(ref): + """A catalog entry for a catalog id or an "hf://.gguf" reference.""" + if ref in BY_ID: + return BY_ID[ref] + m = HF_REF.match(ref or "") + if not m: + raise LocalModelError(f"unknown model {ref!r}: pick one from the list, or give hf://.gguf") + repo, file = m.groups() + name = pathlib.PurePosixPath(file).name + return {"id": ref, "label": name.removesuffix(".gguf"), "repo": repo, "revision": "main", "file": file, "size": None, + "sha256": None, "license": None, "about": "From Hugging Face", "tools": True} # fmt: skip + + +def memory_needed(size, context=4096): + """GB of memory a model of this many bytes needs to run with this context: the weights, the context cache, and + room for Lens itself.""" + return round(size / GB * 1.15 + context / 4096 * 0.5 + 1.0, 1) + + +def models_dir(cfg): + return pathlib.Path(cfg["data_dir"]) / "models" / "gguf" + + +def model_path(cfg, m): + return models_dir(cfg) / m["repo"].replace("/", "__") / pathlib.PurePosixPath(m["file"]).name + + +def catalog(cfg): + """The catalog, with what this machine makes of each: downloaded, fits (memory), room (disk).""" + mach = machine.probe(cfg["data_dir"]) + mem, disk, ctx = mach.get("memory_gb"), mach.get("disk_free_gb"), conf(cfg)["context"] + vram = max([g.get("memory_gb") or 0 for g in mach.get("gpus") or []] or [0]) + out = [] + for m in CATALOG: + need = memory_needed(m["size"], ctx) + here = model_path(cfg, m).is_file() + out.append( + { + **{k: m[k] for k in ("id", "label", "repo", "file", "license", "about", "tools")}, + "size_gb": round(m["size"] / GB, 2), + "memory_gb": need, + "downloaded": here, + "fits": mem is None or need <= mem or (vram and m["size"] / GB * 1.15 <= vram), + "room": here or disk is None or m["size"] / GB + 0.5 <= disk, + } + ) + return out, mach + + +def downloaded(cfg): + """GGUF files in data_dir/models/gguf: [{path, size_gb}].""" + root = models_dir(cfg) + return ( + [{"path": str(p.relative_to(root)), "size_gb": round(p.stat().st_size / GB, 2)} for p in sorted(root.glob("*/*.gguf"))] + if root.is_dir() + else [] + ) + + +def remove(cfg, ref): + """Delete a downloaded model's file. Not the one running.""" + m = resolve(ref) + if conf(cfg)["enabled"] and conf(cfg)["model"] == ref: + raise LocalModelError("that model is running; pick another or turn the local model off first") + p = model_path(cfg, m) + if not p.is_file(): + return False + p.unlink() + for part in p.parent.glob("*.part"): + part.unlink() + if not any(p.parent.iterdir()): + p.parent.rmdir() + return True + + +# ---------- downloading ---------- +def _open(url, headers=None, timeout=60): + req = urllib.request.Request(url, headers={"User-Agent": "lens", **(headers or {})}) + token = os.environ.get("HF_TOKEN") + if token and urllib.parse.urlsplit(url).hostname == "huggingface.co": + req.add_header("Authorization", f"Bearer {token}") + return urllib.request.urlopen(req, timeout=timeout) + + +def download(cfg, m, progress=None, stop=None): + """The model's file into data_dir/models/gguf, resuming a part already there; checked against its SHA-256 when the + catalog knows it. Returns the path.""" + dest = model_path(cfg, m) + if dest.is_file(): + return dest + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_suffix(".gguf.part") + have = tmp.stat().st_size if tmp.exists() else 0 + url = f"{HF}/{m['repo']}/resolve/{m['revision']}/{urllib.parse.quote(m['file'])}" + free = shutil.disk_usage(dest.parent).free + if m["size"] and m["size"] - have > free: + raise LocalModelError(f"not enough disk for {m['label']}: needs {m['size'] / GB:.1f} GB, {free / GB:.1f} GB free") + try: + r = _open(url, {"Range": f"bytes={have}-"} if have else None) + except urllib.error.HTTPError as e: + if e.code == 416: # the part is already whole + r = None + else: + raise LocalModelError( + f"Hugging Face said {e.code} for {m['repo']}/{m['file']}" + + (" (a gated model: set HF_TOKEN)" if e.code in (401, 403) else "") + ) from None + except (urllib.error.URLError, TimeoutError, OSError) as e: + raise LocalModelError(f"can't reach Hugging Face: {getattr(e, 'reason', e)}") from None + if r is not None: + with r: + if have and r.status != 206: + have = 0 # the server sent the whole file + total = have + int(r.headers.get("Content-Length") or 0) or m["size"] + last = 0.0 + with open(tmp, "ab" if have else "wb") as f: + done = have + while chunk := r.read(1 << 20): + if stop is not None and stop(): + raise LocalModelError("stopped") + f.write(chunk) + done += len(chunk) + if progress and time.monotonic() - last > 1: + progress(done, total) + last = time.monotonic() + if progress: + progress(done, total) + if m["sha256"]: + h = hashlib.sha256() + with open(tmp, "rb") as f: + while chunk := f.read(1 << 22): + h.update(chunk) + if h.hexdigest() != m["sha256"]: + tmp.unlink() + raise LocalModelError(f"the download of {m['label']} didn't match its checksum; it will be fetched again") + tmp.replace(dest) + return dest + + +# ---------- llama.cpp ---------- +def _platform(): + system = platform.system().lower() + arch = {"x86_64": "x86_64", "amd64": "x86_64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower(), platform.machine()) + return system, arch + + +def server_binary(cfg): + """llama.cpp's server: local_llm.server, llama-server on PATH, or the copy Lens fetched; None when there's none.""" + own = conf(cfg).get("server") + if own: + return own if os.access(own, os.X_OK) else None + found = shutil.which("llama-server") + if found: + return found + root = pathlib.Path(cfg["data_dir"]) / "bin" / "llama.cpp" + hit = next((p for p in sorted(root.rglob("llama-server")) if p.is_file()), None) if root.is_dir() else None + return str(hit) if hit else None + + +def fetch_server(cfg, say=None): + """llama.cpp's latest release build for this platform into data_dir/bin/llama.cpp. Returns llama-server's path.""" + want = ASSETS.get(_platform()) + if not want: + raise LocalModelError( + f"no llama.cpp build to fetch for {' '.join(_platform())}: install llama.cpp (llama-server on PATH) or set local_llm.server" + ) + try: + with _open(RELEASES_API, {"Accept": "application/vnd.github+json"}, timeout=30) as r: + rel = json.load(r) + except (urllib.error.URLError, TimeoutError, OSError, ValueError) as e: + raise LocalModelError(f"can't reach llama.cpp's releases on GitHub: {getattr(e, 'reason', e)}") from None + asset = next((a for a in rel.get("assets") or [] if want.search(a.get("name", ""))), None) + if not asset: + raise LocalModelError(f"llama.cpp {rel.get('tag_name')} has no build for {' '.join(_platform())}; install llama-server yourself") + root = pathlib.Path(cfg["data_dir"]) / "bin" / "llama.cpp" + tmp = root.parent / asset["name"] + root.parent.mkdir(parents=True, exist_ok=True) + if say: + say(f"downloading llama.cpp {rel.get('tag_name')} ({asset['name']})") + try: + with _open(asset["browser_download_url"], timeout=120) as r, open(tmp, "wb") as f: + shutil.copyfileobj(r, f, 1 << 20) + except (urllib.error.URLError, TimeoutError, OSError) as e: + tmp.unlink(missing_ok=True) + raise LocalModelError(f"couldn't download llama.cpp: {getattr(e, 'reason', e)}") from None + if root.exists(): + shutil.rmtree(root) + root.mkdir() + try: + if asset["name"].endswith(".zip"): + with zipfile.ZipFile(tmp) as z: + for info in z.infolist(): + target = (root / info.filename).resolve() + if root.resolve() not in target.parents and target != root.resolve(): + continue # nothing outside the folder + z.extract(info, root) + mode = info.external_attr >> 16 + if mode: + os.chmod(target, mode & 0o777 or 0o644) + else: + with tarfile.open(tmp) as t: + t.extractall(root, filter="data") + finally: + tmp.unlink(missing_ok=True) + exe = next((p for p in sorted(root.rglob("llama-server")) if p.is_file()), None) + if not exe: + raise LocalModelError("the llama.cpp download has no llama-server in it") + exe.chmod(0o755) + return str(exe) + + +def address(cfg): + """(host to bind, host others reach it at). In a container, other containers (workers) reach it at its address.""" + own = conf(cfg).get("host") + if machine.probe().get("container"): + try: + ip = socket.gethostbyname(socket.gethostname()) + except OSError: + ip = "127.0.0.1" + return "0.0.0.0", own or ip # noqa: S104 - other containers call it; it has its own API key + return "127.0.0.1", own or "127.0.0.1" + + +# ---------- state ---------- +def _now(): + return dt.datetime.now(dt.timezone.utc) + + +def _ts(t=None): + return (t or _now()).isoformat() + + +def state(db): + row = db.one("SELECT * FROM $r", r=ROW) or {} + row.pop("id", None) + if isinstance(row.get("log"), str): + row["log"] = json.loads(row["log"]) + return row + + +def status(db, cfg): + s, c = state(db), conf(cfg) + live = bool(s.get("at") and s["at"] >= _ts(_now() - dt.timedelta(seconds=LEASE_SECONDS))) + models, mach = catalog(cfg) + return { + "enabled": c["enabled"], + "model": c["model"], + "phase": (s.get("phase") or "off") if live and c["enabled"] else "off", + "progress": s.get("progress") if live else None, + "url": s.get("url") if live and s.get("phase") == "running" else None, + "error": s.get("error") if c["enabled"] else None, + "log": s.get("log") or [], + "process": s.get("owner") if live else None, + "server": server_binary(cfg), + "catalog": models, + "files": downloaded(cfg), + "machine": {k: mach.get(k) for k in ("os", "arch", "cpus", "memory_gb", "disk_free_gb", "apple_silicon", "cuda")}, + } + + +class Runner: + """Holds the lease and runs llama-server with the picked model while local_llm.enabled is on.""" + + def __init__(self, db, cfg_fn, name, log=None): + self.db, self.cfg_fn, self.name, self.log = db, cfg_fn, name, log or (lambda *a: None) + self.proc: subprocess.Popen | None = None + self.sig = None + self.lines: list[str] = [] + self.phase, self.error, self.progress, self.url = "off", None, None, None + self.fails, self.next_try = 0, 0.0 + self.worker: threading.Thread | None = None + self.lock = threading.Lock() + self.halt = False + + # the lease and the row + def _lease(self): + now = _now() + return bool( + self.db.rows( + "UPSERT $r MERGE {owner: $me, at: $t} WHERE owner = NONE OR owner = $me OR at < $stale RETURN AFTER", + r=ROW, + me=self.name, + t=_ts(now), + stale=_ts(now - dt.timedelta(seconds=LEASE_SECONDS)), + ) + ) + + def _save(self, **extra): + with self.lock: + d = {"phase": self.phase, "error": self.error, "progress": self.progress, "url": self.url, + "log": json.dumps(self.lines[-LOG_LINES:]), **extra} # fmt: skip + self.db.q("UPDATE $r MERGE $d WHERE owner = $me", r=ROW, d=d, me=self.name) + + def _say(self, line): + with self.lock: + self.lines = (self.lines + [str(line)[:300]])[-LOG_LINES:] + + def _key(self, cfg): + """The server's API key, made once and kept sealed.""" + s = state(self.db) + if s.get("key"): + try: + return settings.unseal(cfg, s["key"], "local_llm.key") + except Exception: # noqa: BLE001 - the secret key changed: make a new one + pass + key = "lens-" + secrets.token_urlsafe(24) + self.db.q("UPDATE $r SET key = $k WHERE owner = $me", r=ROW, k=settings.seal(cfg, key, "local_llm.key"), me=self.name) + return key + + # the LLM provider + def _point_provider(self, cfg, url, model_name, key): + """Make this server the LLM provider, keeping what was there to put back later.""" + if not conf(cfg)["use_as_provider"]: + return + llm = cfg.get("llm") or {} + if llm.get("base_url") == url and llm.get("model") == model_name and llm.get("api_key") == key: + return + s = state(self.db) + if "previous" not in s and llm.get("base_url") != url: + prev = {"base_url": llm.get("base_url"), "model": llm.get("model")} + if llm.get("api_key"): + prev["api_key"] = settings.seal(cfg, llm["api_key"], "local_llm.previous") + self.db.q("UPDATE $r SET previous = $p WHERE owner = $me", r=ROW, p=prev, me=self.name) + settings.save(self.db, cfg, "llm", {"base_url": url, "model": model_name, "api_key": key}, "local model") + self.log("local model: the LLM provider is now %s at %s", model_name, url) + + def _restore_provider(self, cfg): + s = state(self.db) + prev = s.get("previous") + if prev is None: + return + llm = cfg.get("llm") or {} + if s.get("url") and llm.get("base_url") == s.get("url"): # still ours: put back what was there + key = None + if prev.get("api_key"): + try: + key = settings.unseal(cfg, prev["api_key"], "local_llm.previous") + except Exception: # noqa: BLE001 + key = None + settings.save( + self.db, cfg, "llm", {"base_url": prev.get("base_url"), "model": prev.get("model"), "api_key": key or ""}, "local model" + ) + self.db.q("UPDATE $r SET previous = NONE WHERE owner = $me", r=ROW, me=self.name) + + # the process + def stop_process(self): + p, self.proc = self.proc, None + if p and p.poll() is None: + p.terminate() + try: + p.wait(10) + except subprocess.TimeoutExpired: + p.kill() + + def _read(self, proc): + for raw in proc.stdout: + line = raw.rstrip() + if line: + self._say(line) + code = proc.wait() + if self.proc is proc: + self.error = f"llama-server stopped (exit {code}); {self.lines[-1] if self.lines else 'no output'}" + self.phase = "error" + self.fails += 1 + self.next_try = time.monotonic() + RETRY[min(self.fails - 1, len(RETRY) - 1)] + self.proc = None + self._save() + + def _prepare(self, cfg, m, sig): + """Fetch what's missing and start the server (in a thread: downloads take a while).""" + try: + exe = server_binary(cfg) + if not exe: + self.phase = "fetching-server" + self._save() + exe = fetch_server(cfg, say=self._say) + path = model_path(cfg, m) + if not path.is_file(): + self.phase = "downloading" + self._say(f"downloading {m['repo']}/{m['file']}") + self._save() + + def progress(done, total): + self.progress = {"done": done, "total": total} + self._save() + + download(cfg, m, progress, stop=lambda: self.halt or self.sig != sig) + self.progress = None + if self.halt or self.sig != sig: + return + c = conf(cfg) + bind, host = address(cfg) + key = self._key(cfg) + cmd = [exe, "-m", str(path), "--host", bind, "--port", str(c["port"]), "-c", str(c["context"]), "--alias", m["id"], + "--jinja", "-ngl", str(c["gpu_layers"])] # fmt: skip + if c.get("threads"): + cmd += ["-t", str(c["threads"])] + env = dict(os.environ) + env["LLAMA_ARG_API_KEY"] = key # llama-server's --api-key, not on the command line where `ps` shows it + lib = str(pathlib.Path(exe).parent) + env["LD_LIBRARY_PATH"] = lib + (os.pathsep + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "") + self.phase = "starting" + self._save() + self.proc = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1) + threading.Thread(target=self._read, args=(self.proc,), daemon=True, name="llama-server-log").start() + url = f"http://{host}:{c['port']}/v1" + deadline = time.monotonic() + 600 + while time.monotonic() < deadline and self.proc and self.proc.poll() is None and not self.halt: + try: + with _open(f"http://127.0.0.1:{c['port']}/health", timeout=5) as r: + if r.status == 200: + break + except (urllib.error.URLError, OSError): + pass + time.sleep(1) + if not (self.proc and self.proc.poll() is None): + return + self.url, self.phase, self.error, self.fails = url, "running", None, 0 + self._save() + self._point_provider(self.cfg_fn(), url, m["id"], key) + except (LocalModelError, OSError) as e: + self.error, self.phase = str(e), "error" + self.fails += 1 + self.next_try = time.monotonic() + RETRY[min(self.fails - 1, len(RETRY) - 1)] + self._save() + + def tick(self): + cfg = self.cfg_fn() + c = conf(cfg) + if not c["enabled"] or not c["model"]: + if self.proc or self.phase != "off": + if self._lease(): + self._restore_provider(cfg) + self.stop_process() + self.sig, self.phase, self.url, self.error, self.progress = None, "off", None, None, None + self._save() + return + if not self._lease(): + if self.proc: + self.stop_process() + return + sig = json.dumps([c["model"], c["port"], c["context"], c["threads"], c["gpu_layers"], c["server"], c["host"]]) + if sig != self.sig: + self.stop_process() + self.sig, self.fails, self.next_try, self.url, self.error, self.lines = sig, 0, 0.0, None, None, [] + busy = self.worker is not None and self.worker.is_alive() + if busy or (self.proc and self.proc.poll() is None): + self._save() + return + if time.monotonic() < self.next_try: + self._save() + return + try: + m = resolve(c["model"]) + except LocalModelError as e: + self.error, self.phase = str(e), "error" + self._save() + return + self.worker = threading.Thread(target=self._prepare, args=(cfg, m, sig), daemon=True, name="local-llm") + self.worker.start() + + def loop(self, stop): + while not stop.is_set(): + try: + self.tick() + except Exception as e: # noqa: BLE001 - keep the runner alive; the error shows in Settings + self.error = f"{type(e).__name__}: {e}" + try: + self._save() + except Exception: # noqa: BLE001 + pass + stop.wait(TICK_SECONDS) + self.halt = True + self.stop_process() + self.db.q("UPDATE $r SET owner = NONE, phase = 'off' WHERE owner = $me", r=ROW, me=self.name) + + +def start(db, cfg_fn, stop, name, log=None): + r = Runner(db, cfg_fn, name, log) + threading.Thread(target=r.loop, args=(stop,), daemon=True, name="local-llm-runner").start() + return r diff --git a/fastapi_backend/app/domain/settings.py b/fastapi_backend/app/domain/settings.py index e5462da6f..39010351b 100644 --- a/fastapi_backend/app/domain/settings.py +++ b/fastapi_backend/app/domain/settings.py @@ -39,6 +39,8 @@ "components": None, "voice": None, "speech": None, + # llama-server's path is a startup setting only (the web app can't choose what the server runs) + "local_llm": ("enabled", "model", "use_as_provider", "context", "threads", "gpu_layers", "port", "host"), "mail": None, "bridge": None, "notifications": None, @@ -382,6 +384,8 @@ def _check(section, key, value, default): return value.strip() if section == "speech": return _speech_setting(key, value) + if section == "local_llm": + return _local_llm_setting(key, value) if section == "decisions" and key != "engine": return _decision_setting(key, value) if (section, key) == ("documents", "attachment_resources"): @@ -429,6 +433,40 @@ def _check(section, key, value, default): return value +LOCAL_LLM_RANGES = {"context": (512, 262144), "threads": (1, 512), "gpu_layers": (0, 999), "port": (1024, 65535)} + + +def _local_llm_setting(key, value): + from . import local_llm + + if key in ("enabled", "use_as_provider"): + if not isinstance(value, bool): + raise ValueError(f"local_llm.{key} is true or false") + return value + if key == "model": + if value in (None, ""): + return None + if not isinstance(value, str): + raise ValueError("local_llm.model is a model from the list, or hf://.gguf") + try: + local_llm.resolve(value.strip()) + except local_llm.LocalModelError as e: + raise ValueError(f"local_llm.model: {e}") from None + return value.strip() + if key == "host": + if value in (None, ""): + return None + if not (isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9.:\[\]-]{1,253}", value.strip())): + raise ValueError("local_llm.host is a host name or address other processes reach this server at") + return value.strip() + if key == "threads" and value is None: + return None + lo, hi = LOCAL_LLM_RANGES[key] + if not (isinstance(value, int) and not isinstance(value, bool) and lo <= value <= hi): + raise ValueError(f"local_llm.{key} is a whole number from {lo} to {hi}") + return value + + def _speech_setting(key, value): if key.endswith("_base_url"): if not (isinstance(value, str) and VIEWER_URL.match(value.strip())): diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index ccd4bae76..904f8bcf8 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -261,6 +261,19 @@ def labels(): "tts_voice": None, "tts_api_key": None, }, + # a chat model Lens runs itself with llama.cpp (domain/local_llm.py): model is a catalog id or + # "hf://.gguf"; server is llama-server's path (a startup setting; else PATH, else fetched) + "local_llm": { + "enabled": False, + "model": None, + "use_as_provider": True, + "context": 4096, + "threads": None, + "gpu_layers": 999, + "port": 8091, + "host": None, + "server": None, + }, # speech providers (domain/speech.py): transcription, speakers and text to speech by a service instead of this # server, picked in transcribe.engine, diarize.engine and voice. A base URL can be a proxy or a compatible server. "speech": { diff --git a/fastapi_backend/app/schemas/admin.py b/fastapi_backend/app/schemas/admin.py index fc5e5f157..1eb9f80f1 100644 --- a/fastapi_backend/app/schemas/admin.py +++ b/fastapi_backend/app/schemas/admin.py @@ -43,6 +43,50 @@ class TunnelStatus(ResponseModel): process: str | None = Field(None, description="the server process running cloudflared") +class LocalModel(ResponseModel): + id: str + label: str + repo: str + file: str + license: str | None = None + about: str + tools: bool = Field(description="good at the assistant's tool calls") + size_gb: float + memory_gb: float = Field(description="memory it needs to run, with room for Lens") + downloaded: bool + fits: bool = Field(description="this machine has the memory (or GPU memory) for it") + room: bool = Field(description="there's disk for it, or it's downloaded") + + +class LocalModelFile(ResponseModel): + path: str + size_gb: float + + +class LocalLlmProgress(ResponseModel): + done: int + total: int | None = None + + +class LocalLlmStatus(ResponseModel): + enabled: bool + model: str | None = None + phase: Literal["off", "fetching-server", "downloading", "starting", "running", "error"] + progress: LocalLlmProgress | None = None + url: str | None = Field(None, description="the OpenAI-compatible address it answers at, while running") + error: str | None = None + log: list[str] = Field(default_factory=list, description="llama-server's last lines") + process: str | None = Field(None, description="the server process running it") + server: str | None = Field(None, description="llama-server's path, when it's here") + catalog: list[LocalModel] + files: list[LocalModelFile] + machine: dict[str, Any] + + +class Removed(ResponseModel): + removed: bool + + class BridgeTestResult(ResponseModel): ok: bool error: str | None = None diff --git a/fastapi_backend/tests/domain/test_local_llm.py b/fastapi_backend/tests/domain/test_local_llm.py new file mode 100644 index 000000000..3c7c2c8db --- /dev/null +++ b/fastapi_backend/tests/domain/test_local_llm.py @@ -0,0 +1,209 @@ +"""A chat model Lens runs itself: the catalog against this machine, downloads from Hugging Face (resumed, checked), +llama.cpp's server fetched and run, and the LLM provider pointed at it and put back.""" + +from __future__ import annotations + +import hashlib +import http.server +import io +import json +import os +import socket +import sys +import threading +import zipfile + +import pytest + +from app.domain import local_llm, machine, settings, store + +R = store.R +BLOB = b"GGUF" + os.urandom(4000) +FAKE_SERVER = """#!{python} +import http.server, json, os, sys +args = sys.argv[1:] +port = int(args[args.index("--port") + 1]) +key = os.environ.get("LLAMA_ARG_API_KEY") +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + def do_GET(self): + ok = self.path == "/health" or self.headers.get("Authorization") == f"Bearer {{key}}" + body = json.dumps({{"status": "ok", "args": args, "keyed": bool(key)}}).encode() + self.send_response(200 if ok else 401) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) +print("llama server listening", flush=True) +http.server.HTTPServer(("127.0.0.1", port), H).serve_forever() +""" + + +class Hub(http.server.BaseHTTPRequestHandler): + """Hugging Face's resolve URLs and GitHub's release API, as far as Lens uses them.""" + + ranges = [] + + def log_message(self, *a): + pass + + def do_GET(self): + if self.path == "/releases/latest": + host = f"http://127.0.0.1:{self.server.server_address[1]}" + body = json.dumps({"tag_name": "b9999", "assets": [{"name": "llama-b9999-bin-win-cpu-x64.zip", "browser_download_url": "x"}, + {"name": "llama-b9999-bin-ubuntu-x64.zip", "browser_download_url": f"{host}/llama.zip"}]}).encode() # fmt: skip + return self._send(body) + if self.path == "/llama.zip": + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + info = zipfile.ZipInfo("build/bin/llama-server") + info.external_attr = 0o755 << 16 + z.writestr(info, "#!/bin/sh\necho hi\n") + z.writestr("build/bin/libllama.so", b"lib") + z.writestr("../evil", b"no") + return self._send(buf.getvalue()) + if "/resolve/" in self.path: + rng = self.headers.get("Range") + Hub.ranges.append(rng) + start = int(rng.split("=")[1].rstrip("-")) if rng else 0 + self.send_response(206 if rng else 200) + self.send_header("Content-Length", str(len(BLOB) - start)) + self.end_headers() + self.wfile.write(BLOB[start:]) + return None + self.send_error(404) + + def _send(self, body): + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +@pytest.fixture +def hub(monkeypatch): + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Hub) + threading.Thread(target=srv.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + monkeypatch.setattr(local_llm, "HF", base) + monkeypatch.setattr(local_llm, "RELEASES_API", base + "/releases/latest") + Hub.ranges.clear() + yield base + srv.shutdown() + + +def tiny(sha=None): + return {"id": "tiny", "label": "Tiny", "repo": "acme/tiny-GGUF", "revision": "abc", "file": "tiny-q4.gguf", "size": len(BLOB), + "sha256": sha or hashlib.sha256(BLOB).hexdigest(), "license": "mit", "about": "test", "tools": True} # fmt: skip + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def test_the_catalog_says_what_this_machine_can_run(cfg, monkeypatch): + real = machine.probe + monkeypatch.setattr(machine, "probe", lambda data_dir=None: {**real(data_dir), "memory_gb": 4.0, "gpus": [], "disk_free_gb": 3.0}) + models, mach = local_llm.catalog(cfg) + by = {m["id"]: m for m in models} + assert by["qwen2.5-0.5b"]["fits"] and by["qwen2.5-1.5b"]["fits"] + assert not by["qwen2.5-7b"]["fits"] and not by["qwen3-14b"]["fits"] + assert by["qwen2.5-1.5b"]["room"] and not by["qwen2.5-7b"]["room"] + assert not any(m["downloaded"] for m in models) + assert all(m["sha256"] and len(m["revision"]) == 40 for m in local_llm.CATALOG) # pinned and checked + assert local_llm.memory_needed(1024**3) == 2.6 + + +def test_settings_take_a_listed_model_or_any_gguf_on_hugging_face(db, cfg): + settings.save(db, cfg, "local_llm", {"model": "qwen3-4b", "enabled": True, "context": 8192}, "t") + settings.save(db, cfg, "local_llm", {"model": "hf:acme/My-Model-GGUF/my-model-Q4_K_M.gguf"}, "t") + m = local_llm.resolve("hf:acme/My-Model-GGUF/my-model-Q4_K_M.gguf") + assert (m["repo"], m["file"], m["sha256"]) == ("acme/My-Model-GGUF", "my-model-Q4_K_M.gguf", None) + for bad in ({"model": "gpt-9"}, {"model": "hf:acme/x/notes.txt"}, {"context": 10}, {"port": 80}, {"host": "a b"}): + with pytest.raises(ValueError): + settings.save(db, cfg, "local_llm", bad, "t") + with pytest.raises(ValueError): + settings.save(db, cfg, "local_llm", {"server": "/bin/sh"}, "t") # what the server runs is set at startup only + eff = settings.effective(db, cfg) + assert eff["local_llm"]["enabled"] and eff["local_llm"]["context"] == 8192 + assert not cfg["local_llm"]["enabled"] # off by default + + +def test_downloads_resume_and_are_checked(cfg, hub): + m = tiny() + part = local_llm.model_path(cfg, m).with_suffix(".gguf.part") + part.parent.mkdir(parents=True) + part.write_bytes(BLOB[:1000]) + seen = [] + path = local_llm.download(cfg, m, progress=lambda d, t: seen.append((d, t))) + assert path.read_bytes() == BLOB and not part.exists() + assert Hub.ranges == ["bytes=1000-"] and seen[-1] == (len(BLOB), len(BLOB)) + assert local_llm.downloaded(cfg) == [{"path": "acme__tiny-GGUF/tiny-q4.gguf", "size_gb": 0.0}] + bad = {**tiny("0" * 64), "file": "other.gguf"} + with pytest.raises(local_llm.LocalModelError, match="checksum"): + local_llm.download(cfg, bad) + assert not local_llm.model_path(cfg, bad).exists() + + +def test_llama_cpp_is_fetched_for_this_platform(cfg, hub, monkeypatch): + monkeypatch.setattr(local_llm.shutil, "which", lambda name: None) + assert local_llm.server_binary(cfg) is None + monkeypatch.setattr(local_llm, "_platform", lambda: ("linux", "x86_64")) + exe = local_llm.fetch_server(cfg) + assert exe.endswith("build/bin/llama-server") and os.access(exe, os.X_OK) + assert local_llm.server_binary(cfg) == exe + assert not (local_llm.pathlib.Path(cfg["data_dir"]) / "bin" / "evil").exists() + monkeypatch.setattr(local_llm, "_platform", lambda: ("windows", "x86_64")) + with pytest.raises(local_llm.LocalModelError, match="install llama.cpp"): + local_llm.fetch_server(cfg) + + +def test_the_server_runs_becomes_the_provider_and_puts_the_old_one_back(db, cfg, folder, hub, monkeypatch): + exe = folder / "llama-server" + exe.write_text(FAKE_SERVER.format(python=sys.executable)) + exe.chmod(0o755) + monkeypatch.setitem(local_llm.BY_ID, "tiny", tiny()) + monkeypatch.setattr(local_llm.machine, "probe", lambda data_dir=None: {"container": False}) + cfg["local_llm"]["server"] = str(exe) + port = free_port() + settings.save(db, cfg, "llm", {"base_url": "https://api.example/v1", "model": "big", "api_key": "sk-old"}, "t") + settings.save(db, cfg, "local_llm", {"enabled": True, "model": "tiny", "port": port}, "t") + s = settings.Settings(db, cfg) + run = local_llm.Runner(db, s.current, "test") + try: + run.tick() + run.worker.join(30) + assert run.phase == "running", (run.error, run.lines) + url = f"http://127.0.0.1:{port}/v1" + llm = s.current()["llm"] + assert (llm["base_url"], llm["model"]) == (url, "tiny") and llm["api_key"].startswith("lens-") + st = local_llm.status(db, s.current()) + assert st["phase"] == "running" and st["url"] == url and st["process"] == "test" + assert "--alias" in run.proc.args and str(local_llm.model_path(cfg, tiny())) in run.proc.args + assert llm["api_key"] not in " ".join(run.proc.args) # the key isn't on the command line + with pytest.raises(local_llm.LocalModelError, match="running"): + local_llm.remove(s.current(), "tiny") + settings.save(db, cfg, "local_llm", {"enabled": False}, "t") + run.tick() + llm = s.current()["llm"] + assert (llm["base_url"], llm["model"], llm["api_key"]) == ("https://api.example/v1", "big", "sk-old") + assert run.proc is None and local_llm.status(db, s.current())["phase"] == "off" + assert local_llm.remove(s.current(), "tiny") is True + finally: + run.halt = True + run.stop_process() + + +def test_status_and_removal_over_the_api(client, db, cfg, monkeypatch): + from tests.helpers import login, make_user + + make_user(db, "ad@x.io", "admin password 1", admin=True) + h = login(client, "ad@x.io", "admin password 1") + r = client.get("/api/v1/settings/local-llm/status", headers=h) + assert r.status_code == 200, r.text + j = r.json() + assert j["phase"] == "off" and len(j["catalog"]) == len(local_llm.CATALOG) and j["files"] == [] + assert client.delete("/api/v1/settings/local-llm/models?model=qwen3-4b", headers=h).json() == {"removed": False} + assert client.delete("/api/v1/settings/local-llm/models?model=nope", headers=h).status_code == 409 diff --git a/mkdocs.yml b/mkdocs.yml index b06b86a25..c285fd990 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -71,6 +71,7 @@ nav: - Components: components.md - Video: video.md - Speech providers: speech-providers.md + - Local models: local-models.md - Chat and batch runs: assistant.md - Notifications: notifications.md - Chat rooms: chat-rooms.md diff --git a/nextjs-frontend/__tests__/settings-local-model.test.tsx b/nextjs-frontend/__tests__/settings-local-model.test.tsx new file mode 100644 index 000000000..94ad8beef --- /dev/null +++ b/nextjs-frontend/__tests__/settings-local-model.test.tsx @@ -0,0 +1,102 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Admin } from "@/app/openapi-client"; +import { SettingsSection } from "@/components/settings/section"; +import type { SettingsView } from "@/components/settings/model"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Admin: { updateSettings: jest.fn(), localLlmStatus: jest.fn(), removeLocalModel: jest.fn() }, + Metadata: {}, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push: jest.fn() }) })); +jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ namespaces: [] }) })); +jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const VIEW = { + local_llm: { + values: { + enabled: false, + model: null, + use_as_provider: true, + context: 4096, + threads: null, + gpu_layers: 999, + port: 8091, + host: null, + }, + }, +} as unknown as SettingsView; +const model = (id: string, label: string, fits: boolean, downloaded = false) => ({ + id, + label, + repo: `acme/${id}`, + file: `${id}.gguf`, + license: "apache-2.0", + about: "test", + tools: true, + size_gb: fits ? 1.0 : 9.0, + memory_gb: fits ? 2.2 : 12.0, + downloaded, + fits, + room: true, +}); +const STATUS = { + enabled: false, + model: null, + phase: "off", + progress: null, + url: null, + error: null, + log: [], + process: null, + server: null, + catalog: [model("small", "Small 1B", true, true), model("big", "Big 14B", false)], + files: [{ path: "acme__small/small.gguf", size_gb: 1.0 }], + machine: { memory_gb: 4, disk_free_gb: 20, cpus: 4 }, +}; + +function show() { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + return render( + + + undefined} /> + + , + ); +} + +describe("local model", () => { + beforeEach(() => { + (Admin.updateSettings as jest.Mock).mockReset().mockImplementation(() => ok({ ok: true })); + (Admin.localLlmStatus as jest.Mock).mockReset().mockImplementation(() => ok(STATUS)); + (Admin.removeLocalModel as jest.Mock).mockReset().mockImplementation(() => ok({ removed: true })); + }); + + it("offers the models that fit, and saves the pick", async () => { + show(); + const small = await screen.findByRole("button", { name: /Small 1B/ }); + expect(screen.getByRole("button", { name: /Big 14B/ })).toBeDisabled(); + expect(screen.getByText(/4.0 GB memory, 20 GB free disk, 4 CPUs/)).toBeInTheDocument(); + fireEvent.click(small); + expect(small).toHaveAttribute("aria-pressed", "true"); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(Admin.updateSettings).toHaveBeenCalledTimes(1)); + expect((Admin.updateSettings as jest.Mock).mock.calls[0][0]).toMatchObject({ + path: { section: "local_llm" }, + body: { model: "small" }, + }); + }); + + it("deletes a downloaded model", async () => { + show(); + fireEvent.click(await screen.findByRole("button", { name: "Delete" })); + await waitFor(() => expect(Admin.removeLocalModel).toHaveBeenCalledTimes(1)); + expect((Admin.removeLocalModel as jest.Mock).mock.calls[0][0]).toMatchObject({ query: { model: "small" } }); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 346530fd5..4512d5225 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1430,6 +1430,13 @@ export type { ListWorkflowsResponses, LlmEstimate, LlmTestResult, + LocalLlmProgress, + LocalLlmStatus, + LocalLlmStatusData, + LocalLlmStatusResponse, + LocalLlmStatusResponses, + LocalModel, + LocalModelFile, LocalModelServer, LockVaultData, LockVaultError, @@ -1755,6 +1762,12 @@ export type { ReindexSearchData, ReindexSearchResponse, ReindexSearchResponses, + Removed, + RemoveLocalModelData, + RemoveLocalModelError, + RemoveLocalModelErrors, + RemoveLocalModelResponse, + RemoveLocalModelResponses, RemoveLoginProviderData, RemoveLoginProviderError, RemoveLoginProviderErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 6e4b4b3df..0eaa80a2d 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -740,6 +740,8 @@ import type { ListWorkersResponses, ListWorkflowsData, ListWorkflowsResponses, + LocalLlmStatusData, + LocalLlmStatusResponses, LockVaultData, LockVaultErrors, LockVaultResponses, @@ -859,6 +861,9 @@ import type { RegisterResponses, ReindexSearchData, ReindexSearchResponses, + RemoveLocalModelData, + RemoveLocalModelErrors, + RemoveLocalModelResponses, RemoveLoginProviderData, RemoveLoginProviderErrors, RemoveLoginProviderResponses, @@ -2180,6 +2185,35 @@ export class Admin { }); } + /** + * Local Llm Status + * + * The chat model Lens runs itself: the models this machine can run, which are downloaded, and how the server is + * doing (fetching llama.cpp, downloading, starting, running). + */ + public static localLlmStatus( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/settings/local-llm/status", + ...options, + }); + } + + /** + * Remove Local Model + * + * Delete a downloaded model's file to free the disk (not the one running). + */ + public static removeLocalModel( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/settings/local-llm/models", + ...options, + }); + } + /** * Tunnel Status * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 96eefc177..074c237b9 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -5660,6 +5660,161 @@ export type LlmTestResult = { [key: string]: unknown; }; +/** + * LocalLlmProgress + */ +export type LocalLlmProgress = { + /** + * Done + */ + done: number; + /** + * Total + */ + total?: number | null; + [key: string]: unknown; +}; + +/** + * LocalLlmStatus + */ +export type LocalLlmStatus = { + /** + * Enabled + */ + enabled: boolean; + /** + * Model + */ + model?: string | null; + /** + * Phase + */ + phase: "off" | "fetching-server" | "downloading" | "starting" | "running" | "error"; + progress?: LocalLlmProgress | null; + /** + * Url + * + * the OpenAI-compatible address it answers at, while running + */ + url?: string | null; + /** + * Error + */ + error?: string | null; + /** + * Log + * + * llama-server's last lines + */ + log?: Array; + /** + * Process + * + * the server process running it + */ + process?: string | null; + /** + * Server + * + * llama-server's path, when it's here + */ + server?: string | null; + /** + * Catalog + */ + catalog: Array; + /** + * Files + */ + files: Array; + /** + * Machine + */ + machine: { + [key: string]: unknown; + }; + [key: string]: unknown; +}; + +/** + * LocalModel + */ +export type LocalModel = { + /** + * Id + */ + id: string; + /** + * Label + */ + label: string; + /** + * Repo + */ + repo: string; + /** + * File + */ + file: string; + /** + * License + */ + license?: string | null; + /** + * About + */ + about: string; + /** + * Tools + * + * good at the assistant's tool calls + */ + tools: boolean; + /** + * Size Gb + */ + size_gb: number; + /** + * Memory Gb + * + * memory it needs to run, with room for Lens + */ + memory_gb: number; + /** + * Downloaded + */ + downloaded: boolean; + /** + * Fits + * + * this machine has the memory (or GPU memory) for it + */ + fits: boolean; + /** + * Room + * + * there's disk for it, or it's downloaded + */ + room: boolean; + [key: string]: unknown; +}; + +/** + * LocalModelFile + */ +export type LocalModelFile = { + /** + * Path + */ + path: string; + /** + * Size Gb + */ + size_gb: number; + [key: string]: unknown; +}; + /** * LocalModelServer */ @@ -9870,6 +10025,17 @@ export type RefreshRequest = { refresh_token: string; }; +/** + * Removed + */ +export type Removed = { + /** + * Removed + */ + removed: boolean; + [key: string]: unknown; +}; + /** * Rendition * @@ -16164,6 +16330,52 @@ export type BridgeStatusResponses = { export type BridgeStatusResponse = BridgeStatusResponses[keyof BridgeStatusResponses]; +export type LocalLlmStatusData = { + body?: never; + path?: never; + query?: never; + url: "/api/v1/settings/local-llm/status"; +}; + +export type LocalLlmStatusResponses = { + /** + * Successful Response + */ + 200: LocalLlmStatus; +}; + +export type LocalLlmStatusResponse = LocalLlmStatusResponses[keyof LocalLlmStatusResponses]; + +export type RemoveLocalModelData = { + body?: never; + path?: never; + query: { + /** + * Model + */ + model: string; + }; + url: "/api/v1/settings/local-llm/models"; +}; + +export type RemoveLocalModelErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RemoveLocalModelError = RemoveLocalModelErrors[keyof RemoveLocalModelErrors]; + +export type RemoveLocalModelResponses = { + /** + * Successful Response + */ + 200: Removed; +}; + +export type RemoveLocalModelResponse = RemoveLocalModelResponses[keyof RemoveLocalModelResponses]; + export type TunnelStatusData = { body?: never; path?: never; diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx index 99546d6df..13b9e8769 100644 --- a/nextjs-frontend/components/settings/bodies.tsx +++ b/nextjs-frontend/components/settings/bodies.tsx @@ -210,6 +210,8 @@ export function SectionBody({ ctx }: { ctx: BodyCtx }) { ); case "llm": return ; + case "local-model": + return ; case "ai": return ; case "search": @@ -1520,3 +1522,120 @@ function SpeechTest({ provider, dirty }: { provider: string; dirty: boolean }) { ); } + +const PHASE: Record = { + off: "Off", + "fetching-server": "Fetching llama.cpp", + downloading: "Downloading the model", + starting: "Starting", + running: "Running", + error: "Not running", +}; + +function gb(n: number) { + return `${n < 10 ? n.toFixed(1) : Math.round(n)} GB`; +} + +function LocalModelBody({ ctx }: { ctx: BodyCtx }) { + const client = useApiClient(); + const qc = useQueryClient(); + const status = useQuery({ + queryKey: ["local-llm-status"], + queryFn: () => data(Admin.localLlmStatus({ client })), + refetchInterval: (q) => { + const p = q.state.data?.phase; + return p && p !== "off" && p !== "running" ? 2_000 : 15_000; + }, + }); + const remove = useMutation({ + mutationFn: (model: string) => data(Admin.removeLocalModel({ client, query: { model } })), + onSuccess: () => void qc.invalidateQueries({ queryKey: ["local-llm-status"] }), + }); + const pick = ctx.state("local_llm.model"); + const picked = String(ctx.form["local_llm.model"] ?? ""); + const s = status.data; + const mach = (s?.machine ?? {}) as { memory_gb?: number | null; disk_free_gb?: number | null; cpus?: number }; + const pct = s?.progress?.total ? Math.round((s.progress.done / s.progress.total) * 100) : null; + return ( + <> + {s && s.enabled && ( + + {s.phase === "running" ? `Answering at ${s.url}` : (s.error ?? s.log?.at(-1) ?? "Getting it ready")} + + )} + +

+ This machine: {mach.memory_gb != null ? `${gb(mach.memory_gb)} memory` : "memory unknown"} + {mach.disk_free_gb != null ? `, ${gb(mach.disk_free_gb)} free disk` : ""} + {mach.cpus ? `, ${mach.cpus} CPUs` : ""}. Models that don’t fit are greyed out; small ones run on a Raspberry + Pi. +

+ {!s && } + {s && ( +
    + {s.catalog.map((m) => ( +
  • + +
  • + ))} +
+ )} + + +
+ + + + + +
+ {s && s.files.length > 0 && ( +
+ Downloaded + {s.files.map((f) => { + const m = s.catalog.find((x) => f.path.endsWith(`/${x.file}`)); + const ref = m ? m.id : `hf:${f.path.replace("__", "/")}`; + return ( +
+ {f.path} + {gb(f.size_gb)} + +
+ ); + })} + {remove.isError && {remove.error.message}} +
+ )} + + ); +} diff --git a/nextjs-frontend/components/settings/model.ts b/nextjs-frontend/components/settings/model.ts index 815afbadd..e3ad5cb5a 100644 --- a/nextjs-frontend/components/settings/model.ts +++ b/nextjs-frontend/components/settings/model.ts @@ -57,6 +57,7 @@ export type SectionId = | "voice-ids" | "analysis" | "llm" + | "local-model" | "ai" | "search" | "reports" @@ -134,6 +135,13 @@ export const SECTIONS: SectionSpec[] = [ backend: ["llm"], description: "The OpenAI-compatible model used for summaries, templates and chat.", }, + { + id: "local-model", + label: "Local model", + backend: ["local_llm"], + description: + "Run a chat model on this machine with llama.cpp: pick one that fits, and Lens downloads it from Hugging Face and serves it as the LLM provider.", + }, { id: "ai", label: "AI assistant", @@ -928,6 +936,55 @@ export const FIELDS: FieldSpec[] = [ placeholder: "the LLM provider’s", }, { section: "voice", key: "tts_api_key", label: "Speech server API key", kind: "secret" }, + // Local model + { section: "local_llm", key: "enabled", label: "Run a model here", kind: "switch" }, + { + section: "local_llm", + key: "model", + label: "Model", + kind: "text", + mono: true, + nullable: true, + placeholder: "pick one below", + hint: "One from the list, or any GGUF on Hugging Face as hf:owner/repo/file.gguf", + }, + { + section: "local_llm", + key: "use_as_provider", + label: "Make it the LLM provider", + kind: "switch", + hint: "Off: it runs, and you point the LLM provider (or anything else) at it yourself", + }, + { section: "local_llm", key: "context", label: "Context", kind: "int", min: 512, max: 262144, unit: "tokens" }, + { + section: "local_llm", + key: "threads", + label: "CPU threads", + kind: "int", + min: 1, + max: 512, + nullable: true, + placeholder: "auto", + }, + { + section: "local_llm", + key: "gpu_layers", + label: "Layers on the GPU", + kind: "int", + min: 0, + max: 999, + hint: "999: as many as fit; 0: CPU only", + }, + { section: "local_llm", key: "port", label: "Port", kind: "int", min: 1024, max: 65535 }, + { + section: "local_llm", + key: "host", + label: "Address others reach it at", + kind: "text", + mono: true, + nullable: true, + placeholder: "automatic", + }, // Speech providers ...SPEECH_PROVIDERS.flatMap((p): FieldSpec[] => [ { diff --git a/nextjs-frontend/components/settings/settings-shell.tsx b/nextjs-frontend/components/settings/settings-shell.tsx index 0f400779e..efbe986fe 100644 --- a/nextjs-frontend/components/settings/settings-shell.tsx +++ b/nextjs-frontend/components/settings/settings-shell.tsx @@ -14,6 +14,7 @@ import { ChartNoAxesColumn, Clapperboard, Cpu, + HardDrive, FileType, Fingerprint, Globe, @@ -62,6 +63,7 @@ const ICON: Record = { "voice-ids": Fingerprint, analysis: ScanText, llm: Sparkles, + "local-model": HardDrive, ai: Bot, search: Search, reports: ChartNoAxesColumn, diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index e08cd45b4..b0db45639 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -2285,6 +2285,72 @@ } } }, + "/api/v1/settings/local-llm/status": { + "get": { + "tags": [ + "admin" + ], + "summary": "Local Llm Status", + "description": "The chat model Lens runs itself: the models this machine can run, which are downloaded, and how the server is\ndoing (fetching llama.cpp, downloading, starting, running).", + "operationId": "local_llm_status", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LocalLlmStatus" + } + } + } + } + } + } + }, + "/api/v1/settings/local-llm/models": { + "delete": { + "tags": [ + "admin" + ], + "summary": "Remove Local Model", + "description": "Delete a downloaded model's file to free the disk (not the one running).", + "operationId": "remove_local_model", + "parameters": [ + { + "name": "model", + "in": "query", + "required": true, + "schema": { + "type": "string", + "maxLength": 400, + "title": "Model" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Removed" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/settings/tunnel/status": { "get": { "tags": [ @@ -30363,6 +30429,254 @@ ], "title": "LlmTestResult" }, + "LocalLlmProgress": { + "properties": { + "done": { + "type": "integer", + "title": "Done" + }, + "total": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Total" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "done" + ], + "title": "LocalLlmProgress" + }, + "LocalLlmStatus": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled" + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Model" + }, + "phase": { + "type": "string", + "enum": [ + "off", + "fetching-server", + "downloading", + "starting", + "running", + "error" + ], + "title": "Phase" + }, + "progress": { + "anyOf": [ + { + "$ref": "#/components/schemas/LocalLlmProgress" + }, + { + "type": "null" + } + ] + }, + "url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Url", + "description": "the OpenAI-compatible address it answers at, while running" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" + }, + "log": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Log", + "description": "llama-server's last lines" + }, + "process": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Process", + "description": "the server process running it" + }, + "server": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Server", + "description": "llama-server's path, when it's here" + }, + "catalog": { + "items": { + "$ref": "#/components/schemas/LocalModel" + }, + "type": "array", + "title": "Catalog" + }, + "files": { + "items": { + "$ref": "#/components/schemas/LocalModelFile" + }, + "type": "array", + "title": "Files" + }, + "machine": { + "additionalProperties": true, + "type": "object", + "title": "Machine" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "enabled", + "phase", + "catalog", + "files", + "machine" + ], + "title": "LocalLlmStatus" + }, + "LocalModel": { + "properties": { + "id": { + "type": "string", + "title": "Id" + }, + "label": { + "type": "string", + "title": "Label" + }, + "repo": { + "type": "string", + "title": "Repo" + }, + "file": { + "type": "string", + "title": "File" + }, + "license": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "License" + }, + "about": { + "type": "string", + "title": "About" + }, + "tools": { + "type": "boolean", + "title": "Tools", + "description": "good at the assistant's tool calls" + }, + "size_gb": { + "type": "number", + "title": "Size Gb" + }, + "memory_gb": { + "type": "number", + "title": "Memory Gb", + "description": "memory it needs to run, with room for Lens" + }, + "downloaded": { + "type": "boolean", + "title": "Downloaded" + }, + "fits": { + "type": "boolean", + "title": "Fits", + "description": "this machine has the memory (or GPU memory) for it" + }, + "room": { + "type": "boolean", + "title": "Room", + "description": "there's disk for it, or it's downloaded" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "label", + "repo", + "file", + "about", + "tools", + "size_gb", + "memory_gb", + "downloaded", + "fits", + "room" + ], + "title": "LocalModel" + }, + "LocalModelFile": { + "properties": { + "path": { + "type": "string", + "title": "Path" + }, + "size_gb": { + "type": "number", + "title": "Size Gb" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "path", + "size_gb" + ], + "title": "LocalModelFile" + }, "LocalModelServer": { "properties": { "kind": { @@ -37609,6 +37923,20 @@ ], "title": "RefreshRequest" }, + "Removed": { + "properties": { + "removed": { + "type": "boolean", + "title": "Removed" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "removed" + ], + "title": "Removed" + }, "Rendition": { "properties": { "from": {