"""llmhost command-line interface.""" import argparse import json import os import shutil import socket import subprocess import sys import threading import time import urllib.request from . import hfcache, hw, opencode, paths, plan, service from .backends import vllm as vllm_backend # stdlib-only module; safe to import anywhere VERSION = "0.1.0" def say(msg=""): print(msg, flush=True) class Spinner: """Shows that a slow step is running: a spinner with elapsed seconds on a terminal, a plain line otherwise. Ends with a check mark and how long it took.""" FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" def __init__(self, msg): self.msg = msg self.tty = sys.stdout.isatty() self._stop = threading.Event() def _spin(self): i = 0 while not self._stop.wait(0.1): sys.stdout.write(f"\r{self.FRAMES[i % len(self.FRAMES)]} {self.msg}… {time.time() - self.t0:.0f}s ") sys.stdout.flush() i += 1 def __enter__(self): self.t0 = time.time() if self.tty: sys.stdout.write(f"\n{self.FRAMES[0]} {self.msg}…") sys.stdout.flush() self._thread = threading.Thread(target=self._spin, daemon=True) self._thread.start() else: say(f"\n{self.msg}…") return self def __exit__(self, *exc): if self.tty: self._stop.set() self._thread.join() mark = "✗" if exc[0] else "✓" sys.stdout.write(f"\r\033[K{mark} {self.msg} ({time.time() - self.t0:.0f}s)\n") sys.stdout.flush() return False def backend_module(name): if name == "vllm": from .backends import vllm return vllm from .backends import mlx return mlx def hardware_name(info): g = info["gpus"] if not g: return "no GPU" if info["kind"] == "apple": return f"{g[0]['name']}, {info['ram_gib']:.0f} GB unified memory" names = {x["name"] for x in g} return f"{len(g)}× {names.pop()}" if len(g) > 1 and len(names) == 1 else ", ".join(x["name"] for x in g) def print_plan(info, p): say(f"Hardware: {hardware_name(info)}") if p.get("backend"): tp = f" across {p['tp']} GPUs" if p.get("tp", 1) > 1 else "" say(f"Backend: {'vLLM' if p['backend'] == 'vllm' else 'MLX'} · {p['budget_gib']} GiB usable{tp} · preference: {p['prefer']}") for n in info.get("notes", []): say(f"Note: {n}") if p["models"]: say("\nModels that fit:") for m in p["models"]: dl = "downloaded" if hfcache.is_downloaded(m["repo"]) else f"{m['weights_gib']} GiB to download" say(f" {m['name']:18} {m['format']:9} ~{m['est_context'] // 1024}k ctx {m['repo']} ({dl})") if p["excluded"]: say("\nToo big for this hardware:") for e in p["excluded"]: say(f" {e['name']:18} {e['reason']}") def cmd_detect(a): say(json.dumps(hw.detect(), indent=2)) def cmd_plan(a): info = hw.simulate(a.simulate) if a.simulate else hw.detect() p = plan.plan(info, paths.load_catalog(), a.prefer) if a.json: say(json.dumps(p, indent=2)) return print_plan(info, p) if not p["models"]: say("\nNothing fits. " + (p.get("reason") or "")) def cmd_setup(a): info = hw.detect() cat = paths.load_catalog() old = paths.load_config() prefer = a.prefer or old.get("prefer", "balanced") p = plan.plan(info, cat, prefer) print_plan(info, p) if not p["models"]: raise SystemExit("\nNothing can run on this machine: " + (p.get("reason") or "no model fits")) names = [m["name"] for m in p["models"]] active = a.default or old.get("active") if active not in names: if a.default: raise SystemExit(f"--default {a.default} doesn't fit this hardware (fits: {', '.join(names)})") active = names[0] first = next(m for m in p["models"] if m["name"] == active) need = 0 if hfcache.is_downloaded(first["repo"]) else first["weights_gib"] + 5 if info["disk_free_gib"] < need: raise SystemExit(f"\nNot enough disk: {active} needs ~{need:.0f} GiB free in {paths.hf_hub_dir()}, " f"{info['disk_free_gib']:.0f} GiB available.") say(f"\nDefault model: {active}") if not a.yes and sys.stdin.isatty(): if input("Continue with setup? [Y/n] ").strip().lower() not in ("", "y", "yes"): raise SystemExit("aborted") # Our own services would hold the ports on a re-run; stop them so anything still # listening belongs to another program. (--no-start leaves a running setup alone.) # MLX needs two ports: the proxy, and mlx_lm.server on the next one. api_span = 2 if p["backend"] == "mlx" else 1 if not a.no_start: with Spinner("Stopping llm-host's running services"): for name in service.NAMES: service.stop(name) # Stopping returns before the old processes have let go of their ports (launchd # especially), so wait for our own ports to close before checking what's free. if old.get("api_port"): ours = list(range(old["api_port"], old["api_port"] + api_span)) + [old.get("web_port", 8080)] wait_ports_free(ours, timeout=30) # Ports saved by an earlier setup are pinned: clients are configured with them, so a # busy saved port is an error, never a reason to move. Only a first install auto-picks. api_port = choose_port("API", a.api_port, old.get("api_port", 8000), api_span, a.no_start, avoid=set(), pinned="api_port" in old) web_port = choose_port("dashboard", a.web_port, old.get("web_port", 8080), 1, a.no_start, avoid=set(range(api_port, api_port + api_span)), pinned="web_port" in old) say(f"\n== Installing {p['backend']} (this can take several minutes) ==") backend_info = {} if a.skip_backend else backend_module(p["backend"]).install(info, say) cfg = { "version": 1, "kind": info["kind"], "backend": p["backend"], "hardware_name": hardware_name(info), "budget_gib": p["budget_gib"], "tp": p["tp"], "prefer": prefer, "api_port": api_port, "web_port": web_port, "max_jobs": vllm_backend.max_jobs(info["ram_gib"], info["cpus"]), "models": p["models"], "excluded": p["excluded"], "active": active, p["backend"]: {**old.get(p["backend"], {}), **backend_info}, } paths.save_config(cfg) key = paths.api_key(create=True) say("\n== Installing services ==") for name in service.NAMES: service.install(name) if not paths.IS_MAC and not service.enable_linger(): say("Note: couldn't enable lingering, so the server stops when you log out. Fix: sudo loginctl enable-linger $USER") if not a.no_start: service.restart("web") service.restart("model") host = default_host() say(f""" Done. API: http://{host}:{cfg['api_port']}/v1 (OpenAI-compatible) Dashboard: http://{host}:{cfg['web_port']} API key: {paths.KEY_FILE} (show it with: llmhost key) Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch with: llmhost logs -f"}""") if not a.no_opencode: setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode) say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.") if os.environ.get("LLMHOST_PATH_NOTE"): say("\n" + os.environ["LLMHOST_PATH_NOTE"]) def setup_opencode(cfg, ask, install_ok=False, later="llmhost opencode-setup"): """Offer to install opencode, then point it at this server via localhost.""" if not opencode.find(): if not install_ok: if not ask: say(f"\nopencode isn't installed. To install it and connect it to llm-host: {later}") return if input("\nopencode isn't installed. Install it and connect it to llm-host? [Y/n] ").strip().lower() not in ("", "y", "yes"): say("Skipped. Later: llmhost opencode-setup") return say("\n== Installing opencode ==") if not opencode.install(say): say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup") return say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")") status, path = opencode.configure(cfg) if status == "has-comments": say(f"\n{path} has comments, which an automatic edit would delete, so it was left as is.\n" f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg)}") return msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status] say(f"\nopencode: {msg} the `{opencode.PROVIDER}` provider in {path} (http://localhost:{cfg['api_port']}/v1).") if status == "added": say(f"Start it with: opencode (pick a model with /models; this server answers as {opencode.PROVIDER}/{cfg['active']})") def cmd_opencode_setup(a): setup_opencode(_service_check(), ask=sys.stdin.isatty(), install_ok=a.yes, later="llmhost opencode-setup --yes") def port_free(port): # Check both: another program may hold only 127.0.0.1:port, and macOS can still let # 0.0.0.0:port bind while it does. for addr in ("0.0.0.0", "127.0.0.1"): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((addr, port)) except OSError: return False finally: s.close() return True def port_owner(port): """Best-effort name of the program listening on a port.""" try: out = subprocess.run(["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN"], capture_output=True, text=True, timeout=5).stdout.splitlines() if len(out) > 1: f = out[1].split() return f"{f[0]} (pid {f[1]})" except (OSError, subprocess.TimeoutExpired): pass return "another program" def wait_ports_free(ports, timeout): deadline = time.time() + timeout while time.time() < deadline and not all(port_free(p) for p in ports): time.sleep(0.5) def choose_port(label, explicit, current, span, no_start, avoid, pinned=False): """Use the requested or saved port. Only an unpinned default moves to a free port.""" def busy_in(p): return next((q for q in range(p, p + span) if q in avoid or not port_free(q)), None) def owner(q): return "llm-host's API" if q in avoid else port_owner(q) flag = "--api-port" if label == "API" else "--web-port" want = explicit or current busy = busy_in(want) if busy is None: return want if no_start: say(f"Note: {label} port {busy} is in use by {owner(busy)}; it must be free before you start llm-host.") return want if explicit or pinned: why = "" if explicit else f" (llm-host is configured to use it; pass {flag} to change it)" raise SystemExit(f"{label} port {busy} is in use by {owner(busy)}{why}.") for p in range(want + span, want + 100): if busy_in(p) is None: say(f"Note: {label} port {busy} is in use by {owner(busy)}; using port {p} instead.") return p raise SystemExit(f"No free port near {want} for the {label}; pass {flag}.") def default_host(): h = socket.gethostname() return h if "." in h else h + ".local" def _service_check(): cfg = paths.load_config() if not cfg: raise SystemExit("Not set up yet; run `llmhost setup`.") return cfg def cmd_status(a): cfg = _service_check() host = default_host() for name in service.NAMES: st, up = service.state(name) upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else "" say(f"{name:6} {st}{upt}") try: req = urllib.request.Request(f"http://127.0.0.1:{cfg['api_port']}/v1/models", headers={"Authorization": f"Bearer {paths.api_key()}"}) served = [m["id"] for m in json.load(urllib.request.urlopen(req, timeout=3))["data"]] say(f"serving {', '.join(served)}") except Exception: say(f"active model {cfg['active']} is not answering yet") say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}") def cmd_models(a): cfg = _service_check() for m in cfg["models"]: mark = "*" if m["name"] == cfg["active"] else " " dl = "downloaded" if hfcache.is_downloaded(m["repo"]) else f"{m['weights_gib']} GiB to download" say(f"{mark} {m['name']:18} {m['format']:9} ~{m['est_context'] // 1024}k ctx {m['repo']} ({dl})") for e in cfg.get("excluded", []): say(f" {e['name']:18} (doesn't fit: {e['reason']})") def cmd_switch(a): cfg = _service_check() names = [m["name"] for m in cfg["models"]] if a.model not in names: raise SystemExit(f"{a.model} isn't available here. Choose from: {', '.join(names)}") cfg["active"] = a.model paths.save_config(cfg) service.restart("model") say(f"Switched to {a.model}. Watch it load with: llmhost logs -f") def cmd_ctl(a): _service_check() if a.cmd == "start": service.start("web") # after `setup --no-start` neither service is running getattr(service, a.cmd)("model") say(f"model server: {a.cmd} requested") def cmd_logs(a): _service_check() if a.follow: os.execvp(service.log_command("model")[0], service.log_command("model")) for line in service.logs("web" if a.web else "model", a.n): say(line) def cmd_key(a): say(paths.api_key()) def cmd_download(a): cfg = _service_check() m = next((x for x in cfg["models"] if x["name"] == a.model), None) if not m: raise SystemExit(f"{a.model} isn't available here; see `llmhost models`") venv = paths.DATA / ("venv-vllm" if cfg["backend"] == "vllm" else "venv-mlx") hf = venv / "bin/hf" os.execv(str(hf), [str(hf), "download", m["repo"]]) def cmd_opencode(a): cfg = _service_check() host = a.host or default_host() prov = a.provider or f"llmhost-{host.split('.')[0]}" keyfile = f"~/.config/opencode/{prov}.key" snippet = { "$schema": "https://opencode.ai/config.json", "provider": {prov: opencode.provider_block(cfg, host, keyfile, host.split(".")[0])}, "model": f"{prov}/{cfg['active']}", } if a.json: say(json.dumps(snippet, indent=2)) return say(f"""(On this machine itself, `llmhost opencode-setup` does all of this automatically.) On another machine running opencode: 1. Save the API key: mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} (or paste the output of `llmhost key` into {keyfile}) 2. Merge this into ~/.config/opencode/opencode.json: """) say(json.dumps(snippet, indent=2)) say(f"\nOnly the active model answers at a time; switch with `llmhost switch ` or the dashboard.") def cmd_update(a): if (paths.SRC / ".git").exists(): subprocess.run(["git", "-C", str(paths.SRC), "pull", "--ff-only"], check=True) cfg = paths.load_config() args = [str(paths.SHIM), "setup", "--yes"] if not a.backend: args.append("--skip-backend") if cfg.get("active"): args += ["--default", cfg["active"]] os.execv(args[0], args) def cmd_uninstall(a): for name in service.NAMES: service.uninstall(name) for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"): shutil.rmtree(paths.DATA / d, ignore_errors=True) say("Removed services and backend environments.") if a.purge: shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True) shutil.rmtree(paths.DATA, ignore_errors=True) paths.SHIM.unlink(missing_ok=True) say("Removed config, API key and llm-host itself.") say(f"Downloaded models were kept in {paths.hf_hub_dir()} (delete with `hf cache rm`).") def cmd_run_model(a): cfg = _service_check() cat = paths.load_catalog() choice = next(m for m in cfg["models"] if m["name"] == cfg["active"]) entry = plan.catalog_entry(cat, cfg["active"]) service.trim_log("model") say(f"llm-host {VERSION}: starting {entry['name']} ({choice['repo']}, {choice['format']}) on {cfg['backend']}") if cfg["backend"] == "vllm": from .backends import vllm vllm.exec_server(cfg, plan.vllm_args(entry, choice, cfg["api_port"], cfg.get("tp", 1))) else: from .backends import mlx mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1)) def cmd_run_web(a): _service_check() service.trim_log("web") from .web import server server.serve() def main(argv=None): ap = argparse.ArgumentParser(prog="llmhost", description="Serve local LLMs over an OpenAI-compatible API, sized to this machine's hardware.") ap.add_argument("--version", action="version", version=f"llm-host {VERSION}") sub = ap.add_subparsers(dest="cmd", required=True, metavar="COMMAND") s = sub.add_parser("setup", help="detect hardware, install the backend and services, start serving") s.add_argument("--yes", "-y", action="store_true", help="don't ask for confirmation") s.add_argument("--default", help="model to serve first") s.add_argument("--prefer", choices=["balanced", "quality", "speed"], help="how to trade quality for speed when picking builds") s.add_argument("--api-port", type=int) s.add_argument("--web-port", type=int) s.add_argument("--no-start", action="store_true", help="install everything but don't start the services") s.add_argument("--opencode", action="store_true", help="install opencode without asking if it's missing") s.add_argument("--no-opencode", action="store_true", help="don't install or configure opencode") s.add_argument("--skip-backend", action="store_true", help=argparse.SUPPRESS) s.set_defaults(fn=cmd_setup) s = sub.add_parser("plan", help="show which models fit this (or simulated) hardware, without installing") s.add_argument("--simulate", metavar="SPEC", help="fake hardware: nvidia:VRAM_GIB[:COMPUTE_CAP[:COUNT]] or apple:RAM_GB") s.add_argument("--prefer", choices=["balanced", "quality", "speed"], default="balanced") s.add_argument("--json", action="store_true") s.set_defaults(fn=cmd_plan) sub.add_parser("detect", help="print detected hardware as JSON").set_defaults(fn=cmd_detect) sub.add_parser("status", help="show service state and URLs").set_defaults(fn=cmd_status) sub.add_parser("models", help="list models available on this machine").set_defaults(fn=cmd_models) s = sub.add_parser("switch", help="serve a different model") s.add_argument("model") s.set_defaults(fn=cmd_switch) for c in ("start", "stop", "restart"): sub.add_parser(c, help=f"{c} the model server").set_defaults(fn=cmd_ctl) s = sub.add_parser("logs", help="show model server logs") s.add_argument("-f", "--follow", action="store_true") s.add_argument("-n", type=int, default=100) s.add_argument("--web", action="store_true", help="dashboard logs instead") s.set_defaults(fn=cmd_logs) sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key) s = sub.add_parser("download", help="download a model ahead of time") s.add_argument("model") s.set_defaults(fn=cmd_download) s = sub.add_parser("opencode-setup", help="install opencode here if needed and add llm-host as a provider") s.add_argument("--yes", "-y", action="store_true", help="install opencode without asking") s.set_defaults(fn=cmd_opencode_setup) s = sub.add_parser("opencode-config", help="print opencode setup for another machine") s.add_argument("--host", help="hostname clients use (default: .local)") s.add_argument("--provider", help="opencode provider id") s.add_argument("--json", action="store_true", help="print only the JSON") s.set_defaults(fn=cmd_opencode) s = sub.add_parser("update", help="pull the latest llm-host and re-plan") s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend") s.set_defaults(fn=cmd_update) s = sub.add_parser("uninstall", help="remove services and backends (keeps downloaded models)") s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself") s.set_defaults(fn=cmd_uninstall) sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-web").set_defaults(fn=cmd_run_web) a = ap.parse_args(argv) a.fn(a)