llm-host/llmhost/cli.py
neil 16f096714e Handle busy ports and stop orphaning mlx_lm.server
On a Mac with port 8000 already taken, the proxy failed to bind after
mlx_lm.server had started, leaving an orphan each time launchd retried.
- setup now stops our own services, then moves the API/dashboard to the
  next free ports (or errors if a port was given explicitly)
- the MLX service binds its port before starting mlx_lm.server, always
  stops the child on exit, and cleans up leftovers from earlier crashes
- drop the nonexistent huggingface_hub[cli] extra

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
2026-11-02 04:45:36 -08:00

409 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""llmhost command-line interface."""
import argparse
import json
import os
import shutil
import socket
import subprocess
import sys
import time
import urllib.request
from . import hfcache, hw, 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)
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.)
if not a.no_start:
for name in service.NAMES:
service.stop(name)
# MLX needs two ports: the proxy, and mlx_lm.server on the next one.
api_span = 2 if p["backend"] == "mlx" else 1
api_port = choose_port("API", a.api_port, old.get("api_port", 8000), api_span, a.no_start, avoid=set())
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)))
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"}
Connect opencode: run `llmhost opencode-config` and follow what it prints.""")
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 choose_port(label, explicit, current, span, no_start, avoid):
"""Use the requested/saved port if it's free; otherwise move to the next free one."""
def ok(p):
return all(port_free(q) and q not in avoid for q in range(p, p + span))
if explicit:
if not ok(explicit) and not no_start:
raise SystemExit(f"{label} port {explicit} is in use by {port_owner(explicit)}.")
return explicit
if ok(current):
return current
busy = next(q for q in range(current, current + span) if not port_free(q) or q in avoid)
owner = "llm-host's API" if busy in avoid else port_owner(busy)
if no_start:
say(f"Note: {label} port {busy} is in use by {owner}; it must be free before you start llm-host.")
return current
for p in range(current + span, current + 100):
if ok(p):
say(f"Note: {label} port {busy} is in use by {owner}; using port {p} instead.")
return p
raise SystemExit(f"No free port near {current} for the {label}; pass --{'api' if label == 'API' else 'web'}-port.")
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"
models = {}
for m in cfg["models"]:
entry = {"name": f"{m['name']} ({host.split('.')[0]})", "tool_call": True,
"limit": {"context": m["est_context"], "output": min(65536, m["est_context"] // 2)}}
if m.get("reasoning"):
entry["reasoning"] = True
models[m["name"]] = entry
snippet = {
"$schema": "https://opencode.ai/config.json",
"provider": {prov: {
"npm": "@ai-sdk/openai-compatible", "name": f"llm-host ({host})",
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + keyfile + "}"},
"models": models}},
"model": f"{prov}/{cfg['active']}",
}
if a.json:
say(json.dumps(snippet, indent=2))
return
say(f"""On the 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 <name>` 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("--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-config", help="print opencode setup for connecting to this server")
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("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)