install-newt now asks for the API's public URL first (--api-url) and records it; it names the Pangolin resource and refuses an endpoint on the same host. expose-dashboard records only that the dashboard is public. One rule (opencode.client_targets) decides which opencode-install.sh commands are shown -- local only without a tunnel; internet and local with one; internet only once the dashboard is public -- and setup's closing message, `llmhost opencode-config` and the dashboard's Connect dialog all use it. Setup's offer to install opencode now goes through opencode-install.sh --install-only, a new mode that only installs opencode; this machine's own provider is still configured by llm-host, which keeps it in sync on every switch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1084 lines
51 KiB
Python
1084 lines
51 KiB
Python
"""llmhost command-line interface."""
|
||
import argparse
|
||
import json
|
||
import os
|
||
import shutil
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.parse
|
||
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"
|
||
DEFAULT_API_PORT = 1134
|
||
DEFAULT_WEB_PORT = 11340
|
||
|
||
|
||
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 carried_settings(old, names):
|
||
"""Settings setup must not reset. The plan is setup's to rebuild, but the reasoning
|
||
setting belongs to the dashboard, which writes it into the same file -- without this an
|
||
`llmhost update` would quietly put every model back to "Model default". Models that no
|
||
longer fit lose their setting along with their plan."""
|
||
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
|
||
out = {"reasoning": kept} if kept else {}
|
||
for k in ("newt", "dashboard_auth", "dashboard_key_login", "dashboard_public"): # set by install-*/expose-dashboard
|
||
if old.get(k) is not None: # dashboard_key_login is False when it matters
|
||
out[k] = old[k]
|
||
return out
|
||
|
||
|
||
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.)
|
||
# Two ports: the proxy, and the model server behind it on the next one.
|
||
api_span = 2
|
||
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["web_port"]] if old.get("web_port") else [])
|
||
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", DEFAULT_API_PORT), api_span, a.no_start,
|
||
avoid=set(), pinned="api_port" in old)
|
||
web_port = choose_port("dashboard", a.web_port, old.get("web_port", DEFAULT_WEB_PORT), 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},
|
||
}
|
||
cfg.update(carried_settings(old, names))
|
||
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")
|
||
if cfg.get("newt") and service.installed("newt"):
|
||
from . import newt
|
||
if newt.ensure_binary(say):
|
||
service.restart("newt")
|
||
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 progress with: llmhost watch"}""")
|
||
if not a.no_opencode:
|
||
setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode)
|
||
say("\nOther machines: connect their opencode to this server with one line there. It installs\n"
|
||
"opencode if needed, asks for the API key (show it here with `llmhost key`), and adds the\n"
|
||
"server to opencode.json.")
|
||
for where, url in opencode.client_targets(cfg, host):
|
||
say(f" {where}:\n {opencode.remote_command(url)}")
|
||
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, prov, auth_cleared = opencode.configure(cfg)
|
||
if status in ("has-comments", "unparsable"):
|
||
why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON"
|
||
say(f"\n{path} {why}, so it was left as is.\n"
|
||
f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg, prov)}")
|
||
return
|
||
msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status]
|
||
label = f"{opencode.DISPLAY} ({opencode.LOCAL_LABEL})"
|
||
say(f"\nopencode: {msg} the `{prov}` provider \u2014 {label} \u2014 in {path} (http://localhost:{cfg['api_port']}/v1).")
|
||
if prov != opencode.PROVIDER:
|
||
say(f"(`{opencode.PROVIDER}` is taken by another provider, which was left alone.)")
|
||
if auth_cleared:
|
||
say(f"Cleared opencode's cached key for `{prov}` in {opencode.auth_file()}, so it reads\n"
|
||
f"{paths.KEY_FILE} instead. A cached copy goes stale whenever the key is\n"
|
||
f"regenerated, and opencode then asks for it interactively.")
|
||
if status == "added":
|
||
say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{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):
|
||
"""True if nothing is listening on the port, so a server could bind it now."""
|
||
# Something accepting connections on localhost means busy (covers 0.0.0.0 and 127.0.0.1).
|
||
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
c.settimeout(0.5)
|
||
try:
|
||
if c.connect_ex(("127.0.0.1", port)) == 0:
|
||
return False
|
||
except OSError:
|
||
pass
|
||
finally:
|
||
c.close()
|
||
# Then bind the way servers do, with SO_REUSEADDR: connections from a just-stopped server
|
||
# linger in TIME_WAIT for up to a minute, and a plain bind fails because of them even though
|
||
# the server will start fine. Check both addresses: another program may hold only one.
|
||
for addr in ("0.0.0.0", "127.0.0.1"):
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||
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 + tuple(n for n in service.OPTIONAL if service.installed(n)):
|
||
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']}")
|
||
d = cfg.get("dashboard_auth") or {}
|
||
if d.get("mode") == "oidc":
|
||
who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])])
|
||
say(f"sign-in OIDC via {d['issuer']} at {d['public_url']} ({who})")
|
||
else:
|
||
ways = (["API key"] if cfg.get("dashboard_key_login", True) or not paths.OTP_SECRET_FILE.exists() else []) \
|
||
+ (["authenticator code"] if paths.OTP_SECRET_FILE.exists() else [])
|
||
say(f"sign-in {' or '.join(ways)}")
|
||
if cfg.get("newt"):
|
||
api = cfg["newt"].get("api_url")
|
||
say(f"tunnel newt -> {cfg['newt']['endpoint']}" + (f"; API at {api}/v1" if api else ""))
|
||
say(f"dashboard {'public (expose-dashboard)' if cfg.get('dashboard_public') else 'local network only'}")
|
||
|
||
|
||
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")
|
||
if opencode.sync(cfg):
|
||
say(f"opencode's LLMHost (Local) provider now names {a.model} as the default model.")
|
||
say(f"Switched to {a.model}. Watch it load with: llmhost watch")
|
||
|
||
|
||
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()
|
||
name = "newt" if a.newt else "web" if a.web else "model"
|
||
if a.follow:
|
||
os.execvp(service.log_command(name)[0], service.log_command(name))
|
||
for line in service.logs(name, a.n):
|
||
say(line)
|
||
|
||
|
||
def _served_models(cfg, key):
|
||
try:
|
||
if urllib.request.urlopen(f"http://127.0.0.1:{cfg['api_port']}/health", timeout=2).status != 200:
|
||
return []
|
||
req = urllib.request.Request(f"http://127.0.0.1:{cfg['api_port']}/v1/models",
|
||
headers={"Authorization": f"Bearer {key}"})
|
||
return [m["id"] for m in json.load(urllib.request.urlopen(req, timeout=3))["data"]]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
def _fmt_secs(t):
|
||
t = int(t)
|
||
return f"{t // 3600}h{t % 3600 // 60:02d}m" if t >= 3600 else (f"{t // 60}m{t % 60:02d}s" if t >= 60 else f"{t}s")
|
||
|
||
|
||
def cmd_watch(a):
|
||
"""One live status line: download progress, then loading, until the model answers."""
|
||
cfg = _service_check()
|
||
key = paths.api_key()
|
||
name = cfg["active"]
|
||
m = next(x for x in cfg["models"] if x["name"] == name)
|
||
tty = sys.stdout.isatty()
|
||
start = time.time()
|
||
samples = [] # (time, GiB) over the last ~10 s, for the download rate
|
||
down_since = None # when the service was first seen stopped (it may just be restarting)
|
||
last_plain = (None, 0)
|
||
i = 0
|
||
|
||
def show(text, key_phase):
|
||
nonlocal last_plain
|
||
if tty:
|
||
sys.stdout.write("\r\033[K" + text)
|
||
sys.stdout.flush()
|
||
elif key_phase != last_plain[0] or time.time() - last_plain[1] >= 15:
|
||
print(text, flush=True)
|
||
last_plain = (key_phase, time.time())
|
||
|
||
def done(text, rc):
|
||
if tty:
|
||
sys.stdout.write("\r\033[K")
|
||
print(text, flush=True)
|
||
raise SystemExit(rc)
|
||
|
||
try:
|
||
while True:
|
||
now = time.time()
|
||
if name in _served_models(cfg, key):
|
||
done(f"\u2713 {name} is ready: http://{default_host()}:{cfg['api_port']}/v1 "
|
||
f"({_fmt_secs(now - start)})", 0)
|
||
st, _ = service.state("model")
|
||
if st in ("inactive", "failed"):
|
||
down_since = down_since or now
|
||
if now - down_since > 20:
|
||
lines = [l for l in service.logs("model", 400) if l.strip()][-15:]
|
||
done(f"The model server is {'not running' if st == 'inactive' else 'failing'}. "
|
||
f"Last log lines:\n " + "\n ".join(lines) +
|
||
"\nFull log: llmhost logs" + ("" if st == "failed" else " Start it: llmhost start"), 1)
|
||
else:
|
||
down_since = None
|
||
frame = Spinner.FRAMES[i % len(Spinner.FRAMES)] if tty else "-"
|
||
i += 1
|
||
total = m.get("weights_gib") or 0
|
||
if total and not hfcache.is_downloaded(m["repo"]):
|
||
got = hfcache.download_gib(m["repo"])
|
||
samples = [x for x in samples if now - x[0] <= 10] + [(now, got)]
|
||
rate = (got - samples[0][1]) / (now - samples[0][0]) if now > samples[0][0] else 0
|
||
frac = min(got / total, 0.999)
|
||
bar = "\u2588" * int(frac * 24) + "\u2591" * (24 - int(frac * 24))
|
||
extra = ""
|
||
if rate > 0.001:
|
||
extra = f" \u00b7 {rate * 1024 * 2**20 / 1e6:.0f} MB/s \u00b7 ~{_fmt_secs((total - got) / rate)} left"
|
||
show(f"{frame} Downloading {name} {bar} {got:.1f} / {total:.1f} GiB ({frac:.0%}){extra}",
|
||
"download")
|
||
else:
|
||
show(f"{frame} Loading {name} ({_fmt_secs(now - start)})", "load")
|
||
time.sleep(1)
|
||
except KeyboardInterrupt:
|
||
done("Stopped watching (the model server keeps going).", 130)
|
||
|
||
|
||
def cmd_key(a):
|
||
say(paths.api_key())
|
||
|
||
|
||
def _restart_if_running(name):
|
||
if service.state(name)[0] in ("active", "activating"):
|
||
if not service.restart(name):
|
||
say(f"Couldn't restart the {name} service; see `llmhost logs --{name}`.")
|
||
|
||
|
||
def lan_ip():
|
||
"""This machine's address on its default route -- what newt, running here, should dial
|
||
to reach the services. Connecting a UDP socket sends nothing."""
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
try:
|
||
s.connect(("192.0.2.1", 9)) # TEST-NET-1: never routed anywhere
|
||
return s.getsockname()[0]
|
||
except OSError:
|
||
return "127.0.0.1"
|
||
finally:
|
||
s.close()
|
||
|
||
|
||
def _ask(label, given, default=None, flag=None, secret=False, env=None):
|
||
"""A value from its flag, its env var, or a prompt (keeping `default` on Enter).
|
||
Without a terminal, a value that's still missing is an error naming the flag."""
|
||
if given:
|
||
return given
|
||
if env and os.environ.get(env):
|
||
return os.environ[env]
|
||
if not sys.stdin.isatty():
|
||
if default:
|
||
return default
|
||
sys.exit(f"missing {flag or ('$' + env)}" + (f" (or ${env})" if flag and env else ""))
|
||
hint = " [keep current]" if secret and default else (f" [{default}]" if default else "")
|
||
if secret:
|
||
import getpass
|
||
v = getpass.getpass(f"{label}{hint}: ").strip()
|
||
else:
|
||
v = input(f"{label}{hint}: ").strip()
|
||
v = v or default
|
||
if not v:
|
||
sys.exit(f"{label} is required")
|
||
return v
|
||
|
||
|
||
def _check_url(label, url, bare=True):
|
||
import urllib.parse
|
||
u = urllib.parse.urlsplit(url)
|
||
if u.scheme not in ("http", "https") or not u.netloc or (bare and u.path.strip("/")):
|
||
sys.exit(f"{label} should look like https://host.example.com, not {url!r}")
|
||
if u.scheme != "https":
|
||
sys.exit(f"{label} must be https:// -- this is the address people reach from the internet")
|
||
return url.rstrip("/")
|
||
|
||
|
||
def cmd_install_newt(a):
|
||
"""Reach the API from the internet through a Pangolin tunnel. The dashboard stays on
|
||
the LAN: publishing it is a separate, deliberate step (`llmhost expose-dashboard`)."""
|
||
from . import newt
|
||
cfg = _service_check()
|
||
old_n = cfg.get("newt") or {}
|
||
newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for
|
||
|
||
api_url = _ask("The API's public URL, as clients will reach it (e.g. https://llm-api.example.com)",
|
||
a.api_url, old_n.get("api_url"), "--api-url").strip().rstrip("/")
|
||
api_url = _check_url("API URL", api_url[:-3] if api_url.endswith("/v1") else api_url)
|
||
|
||
say("\nPangolin site (Pangolin: Sites -> Add Site -> Newt):")
|
||
endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint (your Pangolin server, not the API's URL)",
|
||
a.endpoint, old_n.get("endpoint"), "--endpoint"))
|
||
if urllib.parse.urlsplit(endpoint).netloc == urllib.parse.urlsplit(api_url).netloc:
|
||
sys.exit("The Pangolin endpoint is the Pangolin server itself; the API's URL is a resource on it, "
|
||
"so the two can't be the same.")
|
||
site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id")
|
||
have_secret = paths.NEWT_SECRET_FILE.exists() and old_n
|
||
newt_secret = _ask(" Newt secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
|
||
|
||
newt.ensure_binary(say)
|
||
if newt_secret != "keep":
|
||
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
|
||
cfg["newt"] = {"endpoint": endpoint, "id": site_id, "api_url": api_url}
|
||
paths.save_config(cfg)
|
||
service.install("newt")
|
||
if not service.restart("newt"):
|
||
say("newt didn't start; see `llmhost logs --newt`.")
|
||
ip = lan_ip()
|
||
say(f"""
|
||
Done. newt is running. In Pangolin, add an HTTP resource on this site for the API:
|
||
{urllib.parse.urlsplit(api_url).netloc} -> http://{ip}:{cfg['api_port']}
|
||
with Pangolin's own authentication off (llm-host checks the API key). Point it at {ip}, not
|
||
localhost: requests from localhost count as local here.
|
||
|
||
Clients then use {api_url}/v1 with the API key. To connect opencode on another machine, run
|
||
this there (it asks for the key, which `llmhost key` shows):
|
||
{opencode.remote_command(api_url)}
|
||
|
||
The dashboard stays on your local network. To put it online too, first give it a sign-in
|
||
that isn't the API key you hand out (`llmhost install-oidc` or `llmhost install-otp`), then
|
||
run `llmhost expose-dashboard`. Undo the tunnel with: llmhost remove-newt""")
|
||
|
||
|
||
def cmd_remove_newt(a):
|
||
"""Back to LAN-only: stop and remove newt. The dashboard's sign-in is left as it is."""
|
||
cfg = _service_check()
|
||
if service.installed("newt"):
|
||
service.uninstall("newt")
|
||
shutil.rmtree(paths.NEWT_DIR, ignore_errors=True)
|
||
paths.NEWT_SECRET_FILE.unlink(missing_ok=True)
|
||
had = bool(cfg.pop("newt", None))
|
||
cfg.pop("dashboard_public", None) # nothing is public without the tunnel
|
||
paths.save_config(cfg)
|
||
say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.")
|
||
|
||
|
||
def cmd_install_oidc(a):
|
||
"""Sign in to the dashboard through an OIDC provider instead of with the API key."""
|
||
from .web import oidc
|
||
cfg = _service_check()
|
||
old_d = cfg.get("dashboard_auth") or {}
|
||
say("Dashboard sign-in through OIDC (a client registered with your provider):")
|
||
public_url = _check_url("Dashboard URL", _ask(" Dashboard's URL, as browsers reach it", a.public_url,
|
||
old_d.get("public_url"), "--public-url"))
|
||
issuer = _check_url("Issuer", _ask(" OIDC issuer", a.issuer, old_d.get("issuer"), "--issuer"), bare=False)
|
||
client_id = _ask(" Client ID (from your provider's client config)", a.client_id,
|
||
old_d.get("client_id") or "llm-host", "--client-id")
|
||
have_secret = paths.OIDC_SECRET_FILE.exists() and old_d
|
||
secret = _ask(" Client secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_OIDC_SECRET")
|
||
groups, users = a.allow_group or [], a.allow_user or []
|
||
if not (groups or users):
|
||
# A re-run keeps the allow list unless it's given again.
|
||
groups, users = old_d.get("allowed_groups", []), old_d.get("allowed_users", [])
|
||
if not (groups or users):
|
||
groups = [g.strip() for g in _ask(" Groups allowed in (comma-separated)", None, None,
|
||
"--allow-group").split(",") if g.strip()]
|
||
if not (groups or users):
|
||
sys.exit("say who may sign in: --allow-group <group> and/or --allow-user <username>")
|
||
|
||
dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url,
|
||
"allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))}
|
||
try:
|
||
oidc.OIDC(dash, paths.oidc_secret() if secret == "keep" else secret).discovery()
|
||
except oidc.AuthError as e:
|
||
sys.exit(str(e))
|
||
if secret != "keep":
|
||
paths.save_secret(paths.OIDC_SECRET_FILE, secret)
|
||
cfg["dashboard_auth"] = dash
|
||
paths.save_config(cfg)
|
||
_restart_if_running("web")
|
||
extra = ("\nAuthenticator codes (install-otp) are unused while OIDC is on; they come back with remove-oidc."
|
||
if paths.OTP_SECRET_FILE.exists() else "")
|
||
say(f"""
|
||
Done. The dashboard now signs in through {issuer}; the API key no longer opens it (the API
|
||
itself still uses the key).
|
||
|
||
Register this redirect URI with your OIDC client: {public_url}/auth/callback
|
||
|
||
Sign-in happens at {public_url}, and visits by any other address are sent there, so the
|
||
dashboard has to be reachable at that URL -- see `llmhost expose-dashboard`. If you can't
|
||
get in, `llmhost remove-oidc` puts the API key back.{extra}""")
|
||
|
||
|
||
def cmd_remove_oidc(a):
|
||
cfg = _service_check()
|
||
had = bool(cfg.pop("dashboard_auth", None))
|
||
paths.OIDC_SECRET_FILE.unlink(missing_ok=True)
|
||
paths.save_config(cfg)
|
||
_restart_if_running("web")
|
||
after = "the API key" + (" or an authenticator code" if paths.OTP_SECRET_FILE.exists() else "")
|
||
say(f"OIDC sign-in is off; the dashboard takes {after} again." if had else "OIDC sign-in wasn't on.")
|
||
|
||
|
||
def _show_pairing(secret):
|
||
from . import otp, qr
|
||
uri = otp.pairing_uri(secret, default_host())
|
||
say("\nScan this with an authenticator app (Google Authenticator, 1Password, Aegis, ...):\n")
|
||
for row in qr.QR(uri).terminal():
|
||
say(" " + row)
|
||
say(f"\nOr enter this key by hand (time-based, 6 digits, 30 s): {otp.grouped(secret)}\n")
|
||
|
||
|
||
def cmd_install_otp(a):
|
||
"""Pair authenticator apps; their codes then also open the dashboard."""
|
||
from . import otp
|
||
cfg = _service_check()
|
||
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
||
sys.exit("install-otp shows a QR code and asks for a code back, so run it in a terminal")
|
||
existing = paths.OTP_SECRET_FILE.exists()
|
||
if a.show:
|
||
if not existing:
|
||
sys.exit("no authenticator is paired yet; run `llmhost install-otp`")
|
||
say("This is the existing pairing. Anyone who sees it can make codes, so keep it private.")
|
||
_show_pairing(paths.read_secret(paths.OTP_SECRET_FILE, "authenticator secret", "llmhost install-otp"))
|
||
say("Add it to as many apps or devices as you like; they all make the same codes.")
|
||
return
|
||
if existing and input("An authenticator is already paired. Replace it? Apps paired now stop working. "
|
||
"(To add another device instead: llmhost install-otp --show) [y/N] ").strip().lower() not in ("y", "yes"):
|
||
sys.exit("kept the existing pairing")
|
||
|
||
secret = otp.new_secret()
|
||
_show_pairing(secret)
|
||
for attempt in range(3):
|
||
code = input("Enter the 6-digit code the app shows, to confirm: ").strip()
|
||
if otp.matching_step(secret, code) is not None:
|
||
break
|
||
say("That code doesn't match. Check the phone's clock is set automatically, then try the current code.")
|
||
else:
|
||
sys.exit("not paired; nothing was changed")
|
||
paths.save_secret(paths.OTP_SECRET_FILE, secret)
|
||
cfg.pop("dashboard_key_login", None) # a new pairing starts with the key still working
|
||
paths.save_config(cfg)
|
||
_restart_if_running("web")
|
||
oidc_on = (cfg.get("dashboard_auth") or {}).get("mode") == "oidc"
|
||
say("""
|
||
Paired. The dashboard's sign-in now also takes a code from the app, alongside the API key.
|
||
To add another phone or app later: llmhost install-otp --show. To unpair: llmhost remove-otp."""
|
||
+ ("\nOIDC sign-in is on, which takes precedence; codes work once it's removed (remove-oidc)." if oidc_on else ""))
|
||
|
||
|
||
def cmd_remove_otp(a):
|
||
cfg = _service_check()
|
||
had = paths.OTP_SECRET_FILE.exists()
|
||
paths.OTP_SECRET_FILE.unlink(missing_ok=True)
|
||
cfg.pop("dashboard_key_login", None) # without codes, the key is the way in again
|
||
paths.save_config(cfg)
|
||
_restart_if_running("web")
|
||
say("Unpaired; the dashboard takes the API key again (apps can delete the llm-host entry)." if had
|
||
else "No authenticator was paired.")
|
||
|
||
|
||
def _confirm(question):
|
||
if not sys.stdin.isatty():
|
||
return False
|
||
return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
|
||
|
||
|
||
def cmd_expose_dashboard(a):
|
||
"""Walk through publishing the dashboard through newt, once it has a sign-in of its own."""
|
||
cfg = _service_check()
|
||
if not (cfg.get("newt") and service.installed("newt")):
|
||
sys.exit("""The dashboard is published through the newt tunnel, which isn't set up yet.
|
||
Run `llmhost install-newt` first, then come back here.""")
|
||
d = cfg.get("dashboard_auth") or {}
|
||
oidc_on = d.get("mode") == "oidc"
|
||
otp_on = paths.OTP_SECRET_FILE.exists()
|
||
key_on = cfg.get("dashboard_key_login", True)
|
||
|
||
if oidc_on:
|
||
say(f"Sign-in: OIDC through {d['issuer']} -- good; only allowed accounts get in.")
|
||
elif otp_on and not key_on:
|
||
say("Sign-in: authenticator codes only -- good; the API key you hand out doesn't open it.")
|
||
elif otp_on:
|
||
say("""Sign-in: authenticator codes, and still the API key.
|
||
Once the dashboard is public, anyone you've given the API key could also use it to stop,
|
||
start or switch the model. Turning the key off for the dashboard leaves codes as the only
|
||
way in there; the API itself keeps using the key.""")
|
||
if a.disable_key_login or _confirm("Turn off API-key sign-in on the dashboard?"):
|
||
cfg["dashboard_key_login"] = False
|
||
paths.save_config(cfg)
|
||
_restart_if_running("web")
|
||
key_on = False
|
||
say("Done: the dashboard now takes authenticator codes only.")
|
||
else:
|
||
say("""Sign-in: the API key only.
|
||
That's the same key you hand to API users. Once the dashboard is public, any of them --
|
||
or anyone the key leaks to -- could stop, start or switch the model. Give the dashboard
|
||
its own sign-in first:
|
||
llmhost install-oidc sign in through your OIDC provider (recommended)
|
||
llmhost install-otp codes from an authenticator app""")
|
||
if not (a.force or _confirm("Publish it anyway, behind the API key alone?")):
|
||
sys.exit("Not published. Set up a sign-in, then run `llmhost expose-dashboard` again.")
|
||
|
||
public_url = d.get("public_url") if oidc_on else None
|
||
if not public_url:
|
||
public_url = _check_url("Dashboard URL", _ask("Public address for the dashboard", a.public_url, None,
|
||
"--public-url"))
|
||
host = urllib.parse.urlsplit(public_url).netloc
|
||
ip = lan_ip()
|
||
pangolin_auth = ("off (llm-host signs people in through your OIDC provider; a second login in front would"
|
||
" get in the way)" if oidc_on else
|
||
"your choice: off, or on as an extra layer in front of llm-host's own sign-in")
|
||
say(f"""
|
||
In Pangolin, on the same site as the API, add an HTTP resource:
|
||
domain {host}
|
||
target http://{ip}:{cfg['web_port']} (this machine's LAN address, not localhost)
|
||
authentication {pangolin_auth}""")
|
||
if oidc_on:
|
||
say(f" and make sure your OIDC client allows the redirect URI {public_url}/auth/callback")
|
||
# Only that it's public, not where: what's handed to clients is the API's address, and
|
||
# a public dashboard is seen from outside, so it stops offering the LAN one.
|
||
cfg["dashboard_public"] = True
|
||
paths.save_config(cfg)
|
||
if not sys.stdin.isatty():
|
||
return
|
||
input("\nPress Enter once the resource is saved, to check it from here... ")
|
||
try:
|
||
with urllib.request.urlopen(public_url + "/auth/config", timeout=15) as r:
|
||
got = json.loads(r.read())
|
||
ok = got.get("mode") in ("key", "oidc")
|
||
except Exception as e:
|
||
ok, got = False, e
|
||
if ok:
|
||
say(f"It works: {public_url} reaches this dashboard.")
|
||
else:
|
||
say(f"Couldn't reach this dashboard at {public_url} yet ({got}). A new resource's certificate can take a"
|
||
f" minute; check the domain, the target and that the resource is enabled, then try the URL in a browser.")
|
||
|
||
|
||
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()
|
||
if a.host: # an address given explicitly: that one, as before
|
||
targets = [("", f"http://{a.host}:{cfg['api_port']}")]
|
||
else:
|
||
targets = opencode.client_targets(cfg, default_host())
|
||
base = targets[0][1]
|
||
host = urllib.parse.urlsplit(base).hostname
|
||
prov = a.provider or opencode.remote_provider(host)
|
||
keyfile = opencode.remote_key_file(prov)
|
||
snippet = {
|
||
"$schema": "https://opencode.ai/config.json",
|
||
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host, base_url=base + "/v1")},
|
||
"model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry
|
||
}
|
||
if a.json:
|
||
say(json.dumps(snippet, indent=2))
|
||
return
|
||
say("(On this machine itself, `llmhost opencode-setup` does all of this automatically.)\n\n"
|
||
"On another machine, run this there. It installs opencode if needed, asks for the API key\n"
|
||
"(`llmhost key` shows it here), and adds this server to opencode.json:")
|
||
for where, url in targets:
|
||
say(f" {where}:\n {opencode.remote_command(url)}" if where else f" {opencode.remote_command(url)}")
|
||
say(f"""
|
||
Or by hand, for {base}/v1:
|
||
|
||
1. Save the API key: paste the output of `llmhost key` into {keyfile} (mode 600), or
|
||
mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{default_host()} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile}
|
||
|
||
2. Merge this into ~/.config/opencode/opencode.json:
|
||
""")
|
||
say(json.dumps(snippet, indent=2))
|
||
say(f"""
|
||
It shows up in opencode as "{opencode.DISPLAY} ({host})". Only the active model answers at a
|
||
time; switch with `llmhost switch <name>` or the dashboard. If this server goes away, remove
|
||
the block there with: llmhost opencode-remove --host {host}""")
|
||
|
||
|
||
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 cached_catalog_models():
|
||
"""(repo, GiB) for every catalog build present in the HF cache. Only llm-host's own
|
||
models are considered; anything else in the cache is never touched."""
|
||
repos = {v["repo"] for m in paths.load_catalog()["models"] for v in m["variants"].values()}
|
||
return sorted((r, hfcache.disk_gib(r)) for r in repos if hfcache.repo_dir(r).exists())
|
||
|
||
|
||
def hf_cache_rm_cmd(repos):
|
||
# hf lives in the backend venv, which uninstall deletes; uv (installed by install.sh) stays.
|
||
# `uv tool run` rather than uvx: some uv installs don't ship the uvx shim.
|
||
uv = shutil.which("uv") or str(paths.BIN_DIR / "uv")
|
||
return [uv, "tool", "run", "--from", "huggingface_hub", "hf", "cache", "rm",
|
||
"--cache-dir", str(paths.hf_hub_dir()), *[f"model/{r}" for r in repos]]
|
||
|
||
|
||
def purge(keep_key=False):
|
||
"""Remove the config dir, the data dir and the launcher. With keep_key, the API key
|
||
survives, so a reinstall reuses it and clients configured with it keep working
|
||
(setup only mints a key when the file is absent). Returns the kept path, or None."""
|
||
keep = paths.KEY_FILE.read_text() if keep_key and paths.KEY_FILE.exists() else None
|
||
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
|
||
shutil.rmtree(paths.DATA, ignore_errors=True)
|
||
paths.SHIM.unlink(missing_ok=True)
|
||
if keep is None:
|
||
return None
|
||
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||
fd = os.open(paths.KEY_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
with os.fdopen(fd, "w") as f:
|
||
f.write(keep)
|
||
return paths.KEY_FILE
|
||
|
||
|
||
def cmd_uninstall(a):
|
||
# Read the catalog now: --purge deletes it along with the rest of llm-host.
|
||
cached = cached_catalog_models()
|
||
cfg = paths.load_config() or {}
|
||
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
|
||
service.uninstall(name)
|
||
# Stopping returns before the processes have exited (launchd especially). Wait, so a
|
||
# reinstall right after this finds the ports free instead of moving to other ones.
|
||
if cfg.get("api_port"):
|
||
span = 2 # the proxy and the model server behind it
|
||
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
|
||
with Spinner("Waiting for the services to exit"):
|
||
wait_ports_free(ours, timeout=30)
|
||
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test", "newt"):
|
||
shutil.rmtree(paths.DATA / d, ignore_errors=True)
|
||
say("Removed services and backend environments.")
|
||
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
|
||
oc_status, oc_path, oc_removed, oc_model = opencode.remove(local=True)
|
||
if oc_status == "removed":
|
||
say(f"opencode: removed {', '.join('`' + r + '`' for r in oc_removed)} from {oc_path}."
|
||
+ (f" Its default model is now {oc_model}." if oc_model else ""))
|
||
elif oc_status in ("has-comments", "unparsable"):
|
||
why = "has comments" if oc_status == "has-comments" else "isn't valid JSON"
|
||
say(f"opencode: {oc_path} {why}, so it was left alone; remove the llm-host provider by hand.")
|
||
if a.purge:
|
||
kept = purge(a.keep_key)
|
||
if kept is None:
|
||
say("Removed config, API key and llm-host itself.")
|
||
say("A reinstall mints a new API key, so clients elsewhere will need the new one\n"
|
||
"(`llmhost opencode-config`). Keep the current key instead with: --purge --keep-key")
|
||
else:
|
||
say(f"Removed config and llm-host itself; kept the API key at {kept},\n"
|
||
"so a reinstall reuses it and clients elsewhere keep working.")
|
||
if not cached:
|
||
return
|
||
total = sum(g for _, g in cached)
|
||
delete = a.models
|
||
if not delete and sys.stdin.isatty():
|
||
say(f"\nDownloaded models ({total:.1f} GiB):")
|
||
for repo, gib in cached:
|
||
say(f" {repo} {gib:.1f} GiB")
|
||
delete = input("Delete them too? [y/N] ").strip().lower() in ("y", "yes")
|
||
cmd = hf_cache_rm_cmd([r for r, _ in cached])
|
||
if delete:
|
||
# hf cache rm also frees blobs kept in the shared hub/blobs directory.
|
||
try:
|
||
ok = subprocess.run(cmd + ["--yes"]).returncode == 0
|
||
except OSError:
|
||
ok = False
|
||
say(f"Deleted {len(cached)} model(s), {total:.1f} GiB." if ok else
|
||
"Deleting models failed. Remove them with:\n " + " ".join(cmd).replace(str(paths.HOME), "~"))
|
||
else:
|
||
say(f"\nKept {len(cached)} downloaded model(s) ({total:.1f} GiB). To delete them later:\n "
|
||
+ " ".join(cmd).replace(str(paths.HOME), "~"))
|
||
|
||
|
||
def cmd_opencode_remove(a):
|
||
explicit = bool(a.provider or a.host or a.all)
|
||
status, path, removed, new_model = opencode.remove(
|
||
prov_ids=[a.provider] if a.provider else None,
|
||
local=not explicit, host=a.host, every=a.all)
|
||
if status in ("has-comments", "unparsable"):
|
||
why = "has comments" if status == "has-comments" else "isn't valid JSON"
|
||
raise SystemExit(f"{path} {why}; edit it by hand.")
|
||
if status == "none":
|
||
say(f"No matching llm-host provider in {path}.")
|
||
return
|
||
say(f"Removed {', '.join('`' + r + '`' for r in removed)} from {path}.")
|
||
if new_model:
|
||
say(f"opencode's default model is now {new_model}.")
|
||
|
||
|
||
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.run_server(cfg, entry, choice, plan.vllm_args(entry, choice, cfg["api_port"] + 1, 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_newt(a):
|
||
from . import newt
|
||
newt.run()
|
||
|
||
|
||
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.add_argument("--newt", action="store_true", help="tunnel logs instead")
|
||
s.set_defaults(fn=cmd_logs)
|
||
sub.add_parser("watch", help="show download and loading progress until the model is ready"
|
||
).set_defaults(fn=cmd_watch)
|
||
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
||
s = sub.add_parser("install-newt", help="reach the API from the internet through a Pangolin tunnel (dashboard stays local)")
|
||
s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com")
|
||
s.add_argument("--api-url", help="the API's public address, e.g. https://llm-api.example.com (a resource on Pangolin)")
|
||
s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)")
|
||
s.set_defaults(fn=cmd_install_newt)
|
||
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt)
|
||
s = sub.add_parser("install-oidc", help="sign in to the dashboard through an OIDC provider instead of the API key")
|
||
s.add_argument("--public-url", help="the dashboard's address, e.g. https://llm-dash.example.com")
|
||
s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com")
|
||
s.add_argument("--client-id", help="OIDC client ID (secret: prompted, or $LLMHOST_OIDC_SECRET)")
|
||
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed in (repeatable)")
|
||
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed in (repeatable)")
|
||
s.set_defaults(fn=cmd_install_oidc)
|
||
sub.add_parser("remove-oidc", help="undo install-oidc: the dashboard takes the API key again"
|
||
).set_defaults(fn=cmd_remove_oidc)
|
||
s = sub.add_parser("install-otp", help="pair authenticator apps; their codes also open the dashboard")
|
||
s.add_argument("--show", action="store_true", help="show the existing pairing again, to add another device")
|
||
s.set_defaults(fn=cmd_install_otp)
|
||
sub.add_parser("remove-otp", help="undo install-otp: unpair authenticator apps").set_defaults(fn=cmd_remove_otp)
|
||
s = sub.add_parser("expose-dashboard", help="walk through publishing the dashboard through newt (after install-newt and a sign-in)")
|
||
s.add_argument("--public-url", help="the dashboard's public address")
|
||
s.add_argument("--disable-key-login", action="store_true", help="with authenticator codes set up, stop the API key opening the dashboard")
|
||
s.add_argument("--force", action="store_true", help="publish even with only the API key protecting it")
|
||
s.set_defaults(fn=cmd_expose_dashboard)
|
||
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: <hostname>.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("opencode-remove", help="remove llm-host providers from this machine's opencode config")
|
||
s.add_argument("--host", help="remove the provider pointing at this host (a retired remote server)")
|
||
s.add_argument("--provider", help="remove this provider id")
|
||
s.add_argument("--all", action="store_true", help="remove every llm-host provider, local and remote")
|
||
s.set_defaults(fn=cmd_opencode_remove)
|
||
|
||
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 (asks before deleting models)")
|
||
s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself")
|
||
s.add_argument("--models", action="store_true", help="also delete downloaded models without asking")
|
||
s.add_argument("--keep-key", action="store_true", help="with --purge, keep the API key so a reinstall reuses it")
|
||
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)
|
||
sub.add_parser("run-newt").set_defaults(fn=cmd_run_newt)
|
||
|
||
a = ap.parse_args(argv)
|
||
a.fn(a)
|