"""Run a small fixed GGUF with a real localhost llama.cpp router."""
import argparse
import json
import os
from pathlib import Path
import shutil
import socket
import subprocess
import tempfile
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, ProxyHandler, build_opener
KEY = "mbsky-local-router-fixture"
PROMPT = "Once upon a time there was a little fox"
NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
def config_env(profile):
names = ("PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "TEMP", "TMP",
"USERPROFILE", "LOCALAPPDATA", "APPDATA")
env = {key: os.environ[key] for key in names if key in os.environ}
env.update(PI_CODING_AGENT_DIR=str(profile), PI_OFFLINE="1", PI_SKIP_VERSION_CHECK="1",
PI_TELEMETRY="0", NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost")
return env
def reserve_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def observe_menu(node, pi, root, env, model_id, state):
from queue import Empty, Queue
import re
from threading import Thread
from winpty import PtyProcess
ansi = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*?(?:\x07|\x1b\\)|[@-_])")
terminal_env = dict(env, TERM="xterm-256color", COLORTERM="truecolor", FORCE_COLOR="1")
terminal = PtyProcess.spawn([str(node), str(pi), "--tui-mode", "regular", "--no-session", "--no-mcp",
"--no-builtin-tools", "--no-context-files", "--no-skills", "--no-themes", "--no-prompt-templates",
"--provider", "local-llama", "--model", model_id],
cwd=str(root), env=terminal_env, dimensions=(33, 120))
received = Queue()
raw = ""
def read_output():
try:
while True:
received.put(terminal.read(8192))
except (EOFError, OSError):
received.put(None)
def see(predicate, after=0, label="terminal"):
nonlocal raw
until = time.monotonic() + 10
while time.monotonic() < until:
text = ansi.sub("", raw[after:]).lower()
if predicate(text):
return text
try:
item = received.get(timeout=0.25)
except Empty:
continue
if item is None:
break
raw += item
raise RuntimeError(label + " absent: " + repr(ansi.sub("", raw[-1300:])))
def submit(command):
marker = len(raw)
terminal.write(command)
time.sleep(0.18)
terminal.write("\r")
return marker
def wait_state(wanted):
deadline = time.monotonic() + 12
while time.monotonic() < deadline:
value = state()
if value == wanted:
return value
time.sleep(0.15)
raise RuntimeError(f"Router did not enter {wanted} after the terminal action")
def menu_visible(text):
return model_id in text and "download model" in text and "load/unload/download" in text
Thread(target=read_output, daemon=True).start()
try:
see(lambda text: "v1.5.0" in text and model_id in text, label="startup")
marker = submit("/llama")
see(menu_visible, marker, "unloaded model in /llama")
first = state()
marker = len(raw)
terminal.write("\r")
loaded = wait_state("loaded")
see(menu_visible, marker, "refreshed menu after loading")
terminal.write("\x1b")
time.sleep(0.28)
marker = submit("/model")
selector = see(lambda text: "llama.cpp" in text and model_id in text, marker, "loaded model in /model")
terminal.write("\x1b")
time.sleep(0.28)
marker = submit("/llama")
see(menu_visible, marker, "reopen /llama")
marker = len(raw)
terminal.write("\r")
see(lambda text: "unload model?" in text and "yes" in text and "no" in text, marker, "unload confirmation")
assert state() == "loaded"
terminal.write("\r")
final = wait_state("unloaded")
see(menu_visible, marker, "refreshed menu after unloading")
terminal.write("\x1b")
time.sleep(0.28)
submit("/quit")
until = time.monotonic() + 6
while terminal.isalive() and time.monotonic() < until:
time.sleep(0.12)
return [first, loaded, "llama.cpp" in selector, final, not terminal.isalive()]
finally:
if terminal.isalive():
terminal.terminate(force=True)
def stop_process(process):
if process.poll() is not None:
return
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=4)
def observe_single_model(server_exe, fixture, root, env):
port = reserve_port()
address = f"http://127.0.0.1:{port}"
opener = build_opener(ProxyHandler({}))
args = [str(server_exe), "-m", str(fixture), "--host", "127.0.0.1", "--port", str(port),
"--api-key", KEY, "-t", "2", "-ngl", "0", "-c", "512", "-np", "1"]
with (root / "single-model.log").open("wb") as log:
process = subprocess.Popen(args, cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT,
creationflags=NO_WINDOW)
try:
deadline = time.monotonic() + 12
while time.monotonic() < deadline:
try:
with opener.open(address + "/health", timeout=2) as healthy:
if healthy.status == 200:
break
except (OSError, URLError):
if process.poll() is not None:
break
time.sleep(0.20)
else:
raise RuntimeError("Single-model server did not become ready")
headers = {"Authorization": f"Bearer {KEY}"}
with opener.open(Request(address + "/v1/models", headers=headers), timeout=4) as reply:
data = json.load(reply)["data"]
probe = Request(address + "/models/load", data=b'{"model":"gallery-stories"}',
headers={**headers, "Content-Type":"application/json"})
try:
with opener.open(probe, timeout=4) as result:
load_status = result.status
except HTTPError as exc:
load_status = exc.code
return [len(data), bool(data[0]["id"]), load_status]
finally:
stop_process(process)
def run(server_exe, model, node, pi, terminal_ui=False):
cases = []
def check(name, inputs, expected, actual):
if actual != expected:
raise AssertionError(f"{name}: {actual!r} != {expected!r}")
cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))
with tempfile.TemporaryDirectory(prefix="mbsky-pi-llama-router-") as directory:
root = Path(directory)
profile = root / "profile"
models = root / "models"
profile.mkdir()
models.mkdir()
fixture = models / "gallery-stories.gguf"
shutil.copyfile(model, fixture)
env = config_env(profile)
single = observe_single_model(server_exe, fixture, root, env)
check("single_model_startup_does_not_expose_router_load", {"modelFlag": "-m"},
[1, True, 404], single)
port = reserve_port()
address = f"http://127.0.0.1:{port}"
opener = build_opener(ProxyHandler({}))
def request(path, body=None, auth=True, timeout=7):
headers = {"Authorization": f"Bearer {KEY}"} if auth else {}
data = None
if body is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(body).encode()
req = Request(address + path, data=data, headers=headers)
code, raw = None, None
try:
with opener.open(req, timeout=timeout) as response:
code, raw = response.status, response.read()
except HTTPError as exc:
code, raw = exc.code, exc.read()
return code, json.loads(raw)
def wait_for(predicate, seconds=18):
until = time.monotonic() + seconds
while time.monotonic() < until:
if child.poll() is not None:
break
try:
if predicate():
return True
except (OSError, ValueError, URLError):
pass
time.sleep(0.20)
return False
log = root / "server.log"
server_version = subprocess.run([str(server_exe), "--version"],
text=True, capture_output=True, timeout=10,
creationflags=NO_WINDOW, check=True)
version = (server_version.stdout + server_version.stderr).strip().splitlines()[0]
args = [str(server_exe), "--models-dir", str(models), "--no-models-autoload", "--host", "127.0.0.1",
"--port", str(port), "--api-key", KEY, "-t", "2", "-ngl", "0", "-c", "512", "-np", "1"]
with log.open("wb") as output:
child = subprocess.Popen(args, cwd=root, env=env, stdout=output, stderr=subprocess.STDOUT,
creationflags=NO_WINDOW)
model_id = None
try:
if not wait_for(lambda: request("/health")[0] == 200):
raise RuntimeError(log.read_bytes().decode("utf8","replace")[-2600:])
health, _ = request("/health")
code, catalog = request("/models")
rows = [row for row in catalog.get("data", []) if "gallery-stories" in row.get("id", "")]
assert len(rows) == 1, catalog
model_id = rows[0]["id"]
def state():
_, value = request("/models")
matches = [row for row in value["data"] if row["id"] == model_id]
status = matches[0]["status"]
return status.get("value") if isinstance(status, dict) else status
check("real_router_health_discovers_one_unloaded_model", {"autoload":False, "host":"127.0.0.1"},
[200,200,"unloaded"], [health,code,state()])
denied, _ = request("/v1/chat/completions", {"model":model_id,"messages":[{"role":"user","content":PROMPT}]},
auth=False)
check("real_router_rejects_missing_key", {"request":"POST /v1/chat/completions without authorization"}, 401, denied)
start, _ = request("/models/load", {"model":model_id}, timeout=12)
assert wait_for(lambda: state() == "loaded"), log.read_bytes().decode("utf8","replace")[-3000:]
check("real_model_load_changes_router_state", {"model":model_id}, [200,"loaded"], [start,state()])
text_code, text = request("/completion", {"model":model_id,"prompt":PROMPT,"n_predict":7,
"temperature":0,"seed":42}, timeout=14)
completion = text.get("content", "")
check("real_cpu_inference_returns_generated_content", {"model":model_id,"n_predict":7,"temperature":0},
[200,True,True], [text_code, bool(completion.strip()), text.get("tokens_predicted",0)>0])
props_code, props = request("/props?model=" + model_id)
effective_ctx = props.get("default_generation_settings", {}).get("n_ctx")
check("actual_model_context_accepts_full_pi_prompt", {"requested": 512}, [200, 512],
[props_code, effective_ctx])
(profile / "models.json").write_text(json.dumps({"providers":{"local-llama":{
"baseUrl":address + "/v1","api":"openai-completions","apiKey":KEY,
"models":[{"id":model_id,"contextWindow":512,"maxTokens":24}]}}}),encoding="utf8")
cli = subprocess.run([str(node),str(pi),"--no-session","--no-mcp","--no-builtin-tools",
"--no-context-files","--no-skills","--no-themes","--no-prompt-templates",
"--provider","local-llama","--model",model_id,"--thinking","off","--mode","json",
"--system-prompt","Finish a short story.",
"-p","Continue: Once upon a time."],
env=env,cwd=root,capture_output=True,encoding="utf8",timeout=28,
creationflags=NO_WINDOW)
if cli.returncode:
raise RuntimeError((cli.stderr + cli.stdout)[-3200:])
events = [json.loads(row) for row in cli.stdout.splitlines() if row.strip()]
assistant = [row["message"] for row in events if row.get("type")=="message_end"
and row.get("message",{}).get("role")=="assistant"]
assert assistant, events[-10:]
response = assistant[-1]
if response.get("errorMessage"):
raise RuntimeError(response["errorMessage"])
pieces = [part["text"] for part in response.get("content",[]) if part.get("type")=="text"]
check("pi_compatible_provider_reaches_loaded_local_model", {"provider":"local-llama","mode":"json","model":model_id},
["local-llama",model_id,True], [response.get("provider"),response.get("model"),bool("".join(pieces).strip())])
stop, _ = request("/models/unload", {"model":model_id}, timeout=15)
assert wait_for(lambda: state() == "unloaded")
check("real_model_unload_restores_discovery_state", {"model":model_id}, [200,"unloaded"], [stop,state()])
if terminal_ui:
env.update(LLAMA_BASE_URL=address, LLAMA_API_KEY=KEY)
observed = observe_menu(node, pi, root, env, model_id, state)
check("pi_native_llama_menu_loads_unloads_and_lists_real_model", {"menus":["/llama","/model"]},
["unloaded","loaded",True,"unloaded",True], observed)
finally:
if child.poll() is None and model_id:
try:
request("/models/unload", {"model":model_id}, timeout=5)
except (OSError, ValueError, URLError):
pass
stop_process(child)
return dict(server_version=version,cases=cases)
if __name__ == "__main__":
parser=argparse.ArgumentParser()
for name in ("server","gguf","node","pi"):
parser.add_argument(name,type=Path)
parser.add_argument("--terminal-ui", action="store_true")
args=parser.parse_args()
values=[getattr(args,name).resolve(strict=True) for name in ("server","gguf","node","pi")]
print(json.dumps(run(*values,terminal_ui=args.terminal_ui),ensure_ascii=False))
本例需在 Windows、llama.cpp b12758、Node.js 24.22.3、Pi 1.5.0、小型公开 GGUF 和 WinPTY。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、llama.cpp b12758、Node.js 24.22.3、Pi 1.5.0、小型公开 GGUF 和 WinPTY。
入口文件:projects/pi-agent-llama-lab/llama-router-and-pi.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
llama-router-and-pi.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、llama.cpp b12758、Node.js 24.22.3、Pi 1.5.0、小型公开 GGUF 和 WinPTY。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a280.zip