Pi Agent 与 llama.cpp 本地模型
用真实本机模型验证路由、资源管理和 Pi 客户端接入。
学完这一章,你能够
- 用真实本机模型验证路由、资源管理和 Pi 客户端接入。
Pi 与推理进程分别做什么
Pi 管理终端交互和工具,llama.cpp 在本机执行模型推理。它可用 CPU,也可在合适的构建和驱动下用 CUDA、Metal 或 Vulkan。量化通常减少权重占用,实际总占用还包括上下文缓存和运行时。下面的流程图依据本站 CPU、真实路由器和 Pi 实测绘制。
选择单模型或路由方式
支持路由的 llama-server 可用 --models-dir 扫描 GGUF。在新版发行方式也可由 llama serve 启动。指定 -m 或 --model 时改为单模型服务。--no-models-autoload 保留手工加载,--jinja 依赖模型的对话模板,-ngl 控制 GPU 卸载。-c 设置请求的上下文资源,实际每个槽还受模型训练长度和并行设置影响。
先用 /health 检查服务是否可达,再用 /models 观察发现与加载状态。本站逐项验证未加载、加载、实际生成和卸载。单模型模式也能列出一个推理模型,但调用路由器的 /models/load 返回 404。
连接本机路由器与选择模型
交互模式的 /login llama.cpp 可保存路由器 URL 和可选密钥。默认地址是本机 8080 端口。需要密钥时让客户端与服务配置一致。也可以只为本次进程设置 LLAMA_BASE_URL 与 LLAMA_API_KEY。本站用隔离配置和临时密钥测试。
用 /llama 查看模型,回车加载,卸载操作需确认。可从 Download model… 搜索模型,下载或加载过程支持取消。模型选择器可见性取决于已加载状态、休眠状态和自动加载策略。使用 /model 或 Ctrl+L 查看可选模型,Ctrl+P 按当前清单循环。本站实际在 WinPTY 操作了加载、查看和确认卸载。
比较模型和实际资源占用
不同版本、量化和上下文配置会改变内存需求。同一模型的 FP 与低位量化文件大小差异很大。下表保留原课程提到的模型家族和用途供比较,表中粗估用于呈现规模差异,不作为最低硬件保证。以真实硬件测量判断能否运行。本地执行可减少对外部网络的依赖,生成质量需按实际任务观察。
服务器从配置目录或预设发现模型,由服务端执行实际下载。大型 GGUF 可能需要数 GB 甚至更多空间。多分片或多模态模型保留配套文件与目录结构。本站小模型仅用于验证路由和推理通路。
以兼容 API 或扩展接入
对本机、非默认端口或获授权的远程服务,都要把客户端地址与服务器监听设置对应起来。只需兼容的聊天接口时,可给 models.json 的提供商填 /v1 基址。内置 llama.cpp 路由配置使用服务根地址,客户端会构造推理路径。本站成功通过 OpenAI 兼容配置取得由本机 CPU 生成的文本。
需要自定义发现时,扩展可注册独立提供商并根据当前 API 获取模型元数据。可见性、真正的上下文长度、模型输入类型和推理能力应来自实际元数据及请求。扩展需用目标 Pi 版本支持的注册接口,试跑后再放入相应扩展目录。常规路由器配合内置 /llama 可完成模型管理。
辨认输出、能力和失败原因
检查四个条件。工具调用取决于模型与对话模板。CPU 推理速度取决于模型和硬件。上下文即使配置 512 token 仍可能被模型限制到 128,本机曾收到真实的超限响应。推理等级只在声明支持的模型生效。
模型输出一段看起来像读取文件的文字时,查看实际工具事件和返回值。需要读取时只用有明确工具结果的输出作为依据。可缩小任务或换用支持工具调用的模型再验证。
可用本地模型处理合适的普通任务,再依据复杂度、资源和数据范围选择其他模型。使用 Ctrl+P 换模型后,核对模型名和相应的上下文与工具能力。本站极小的故事模型主要用来观察真实推理链。
本地模型家族与选择条件
| 家族 | 来源列举的规模 | 使用场景 | 资源核对 |
| Qwen2.5-Coder | 7B、14B、32B | 多语言代码生成和解释。 | 常见粗估依次约 8、16、32 GB。量化、上下文及可用显存影响实际占用。 |
| DeepSeek-Coder-V2 | 16B、236B | 较复杂的编程任务。 | 粗估约 16 GB 和 128 GB 以上。MoE 活跃参数量与权重存储分别考虑。 |
| Code Llama | 7B、13B、34B | 代码补全和常见编程任务。 | 粗估依次约 8、16、32 GB。确认变体、上下文和量化兼容性。 |
| Mistral | 7B | 轻量文本和部分编程辅助。 | 粗估约 8 GB。结合量化权重大小与缓存计划选择平台。 |
运行本机 CPU 路由、推理与 Pi 验证
展开查看收起
"""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))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地复跑
使用 README 指定的引擎和已验证校验值的 GGUF,复跑服务器、客户端和终端观察。
本章附件与实例包
常见错误与边界检查
- 绑定需要的监听地址。
- 按实际模型和运行时的窗口结果配置上下文。
技术规范与官方资料
练习与参考解答
查看参考解答
继续读取 /models,核对目录、加载状态与自动加载设置,然后在 Pi 的 /llama 中加载。