serve: add llama.cpp-compatible discovery endpoints
Expose loaded-model metadata through /models and /v1/models. Add /props and single-slot /slots responses with existing API-key enforcement and regression coverage. Validation: all 30 server tests pass. Pi 0.87.1 discovered the loaded model with 262144-token context and thinking support, and completed a chat smoke test successfully. Fixes #117. Co-authored-by: Codex (gpt-6-astra-medium) <noreply@openai.com>
This commit is contained in:
1 parent
6e1a7be257
commit
08f8d591da
4 files changed
+133
-6
No files matched your search
+5
-2
@@ -254,11 +254,14 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or
|
||||
| --- | --- |
|
||||
| OpenAI Chat Completions (stream and non-stream, tools) | `POST /v1/chat/completions` |
|
||||
| Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` |
|
||||
| Model list / health | `GET /v1/models`, `GET /health` |
|
||||
| What the model is doing right now | `GET /status` |
|
||||
| Model list / health | `GET /v1/models`, `GET /models`, `GET /health` |
|
||||
| Model properties | `GET /props` (also accepts `?model=<loaded-model-id>`) |
|
||||
| What the model is doing right now | `GET /status`, `GET /slots` (single slot, busy or idle) |
|
||||
| Everything the Monitor tab shows (engine, live state, last requests, hardware) | `GET /metrics` |
|
||||
| The MCP servers, their state and tools ([below](#tools-from-mcp-servers)) | `GET /mcp` |
|
||||
|
||||
`/models` and `/v1/models` list only the loaded model, with its context limit and input modalities. `/props` exposes the original chat template, context limit, configured generation defaults (shared settings take precedence), model path and engine version when available. Context means the full engine context, not the resident KV window. `n_predict: -1` means no fixed output cap. Unconfigured sampling fields are omitted. `autoload` has no effect; an unknown `model` returns 404. These metadata endpoints and `/slots` require the API key when one is configured. They do not load, unload or restart models.
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
|
||||
"model": "strata", "messages": [{"role": "user", "content": "Write a haiku about GPUs."}], "max_tokens": 512 }'
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ class ChatTemplate:
|
||||
env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"])
|
||||
env.filters["tojson"] = tojson
|
||||
env.globals["raise_exception"] = raise_exception
|
||||
self.template = env.from_string(Path(path).read_text(encoding="utf-8"))
|
||||
self.source = Path(path).read_text(encoding="utf-8")
|
||||
self.template = env.from_string(self.source)
|
||||
|
||||
def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,
|
||||
**kwargs) -> str:
|
||||
|
||||
+46
-3
@@ -4,7 +4,7 @@
|
||||
python -m serve.server --engine strata --config strata.json --port 8080 (the real engine, resident)
|
||||
|
||||
Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream and
|
||||
non-stream), GET /v1/models, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence).
|
||||
non-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence).
|
||||
Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests that
|
||||
ask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw.
|
||||
Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64
|
||||
@@ -37,6 +37,7 @@ import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Iterator, Protocol
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
@@ -149,6 +150,8 @@ class StrataEngine:
|
||||
def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,
|
||||
env: dict | None = None):
|
||||
self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27)
|
||||
paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}
|
||||
self.model_path = paths.get("--native") or paths.get("--pack", "pack/full")
|
||||
self.log_path = log
|
||||
self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL
|
||||
loading = threading.Event() # set once READY: the narrator below stops
|
||||
@@ -1188,9 +1191,24 @@ def make_handler(svc: Service):
|
||||
for k in ("started", "first_token"):
|
||||
s.pop(k, None)
|
||||
self._json(200, s)
|
||||
elif path == "/v1/models":
|
||||
elif path in ("/v1/models", "/models"):
|
||||
if self._authorized():
|
||||
self._json(200, {"object": "list", "data": [{"id": svc.model, "object": "model"}]})
|
||||
loaded = not hasattr(svc.engine, "alive") or svc.engine.alive()
|
||||
model = {"id": svc.model, "object": "model", "status": {"value": "loaded"},
|
||||
"meta": {"n_ctx": svc.engine.max_context},
|
||||
"architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"],
|
||||
"output_modalities": ["text"]}}
|
||||
self._json(200, {"object": "list", "data": [model] if loaded else []})
|
||||
elif path == "/props":
|
||||
if self._authorized():
|
||||
self._props()
|
||||
elif path == "/slots":
|
||||
if self._authorized():
|
||||
loaded = not hasattr(svc.engine, "alive") or svc.engine.alive()
|
||||
with svc.status_lock:
|
||||
busy = bool(svc.status.get("busy"))
|
||||
slot = {"id": 0, "n_ctx": svc.engine.max_context, "is_processing": busy}
|
||||
self._json(200, [slot] if loaded else [])
|
||||
else:
|
||||
self._json(404, {"error": {"message": "not found"}})
|
||||
|
||||
@@ -1214,6 +1232,31 @@ def make_handler(svc: Service):
|
||||
except EngineDied as e: # before the answer started (not streamed)
|
||||
self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}})
|
||||
|
||||
def _props(self):
|
||||
model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]
|
||||
if model != svc.model:
|
||||
self._json(404, {"error": {"message": "model not found"}})
|
||||
return
|
||||
if hasattr(svc.engine, "alive") and not svc.engine.alive():
|
||||
self._json(503, {"error": {"message": "the engine is not running"}})
|
||||
return
|
||||
defaults = {**svc.sampling_defaults, **svc.shared}
|
||||
names = {"repetition_penalty": "repeat_penalty", "penalty_last_n": "repeat_last_n"}
|
||||
params = {names.get(k, k): v for k, v in defaults.items()
|
||||
if k in ("temperature", "top_p", "top_k", "min_p", "seed", "repetition_penalty",
|
||||
"presence_penalty", "frequency_penalty", "penalty_last_n")}
|
||||
params["n_predict"] = svc.shared.get("max_tokens", -1)
|
||||
props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params},
|
||||
"total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source,
|
||||
"modalities": {"vision": svc.vision is not None}, "models_autoload": False,
|
||||
"is_sleeping": False}
|
||||
if getattr(svc.engine, "model_path", None):
|
||||
props["model_path"] = svc.engine.model_path
|
||||
version = getattr(svc.engine, "info", {}).get("version")
|
||||
if version:
|
||||
props["build_info"] = "Strata " + str(version)
|
||||
self._json(200, props)
|
||||
|
||||
def _own_page(self, what) -> bool:
|
||||
"""Only JSON (a form or a "simple" cross-site request can't send it without a CORS preflight, which this
|
||||
server never grants) and no foreign Origin: a web page elsewhere must not change settings or run tools."""
|
||||
|
||||
@@ -516,6 +516,86 @@ class WebApp(unittest.TestCase):
|
||||
self.assertEqual(m["live"]["state"], "idle")
|
||||
self.assertEqual(m["requests"][0]["output_tokens"], 5)
|
||||
|
||||
def test_model_discovery_and_props(self):
|
||||
svc = self.svc
|
||||
previous = svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared
|
||||
try:
|
||||
svc.engine.max_context = 262144
|
||||
svc.sampling_defaults = {"temperature": 1.0, "repetition_penalty": 1.1}
|
||||
svc.shared = {"temperature": 0.7, "max_tokens": 4096}
|
||||
for vision in (None, object()):
|
||||
svc.vision = vision
|
||||
for path in ("/models", "/v1/models"):
|
||||
code, _, body = self.get(path)
|
||||
self.assertEqual(code, 200)
|
||||
models = json.loads(body)["data"]
|
||||
self.assertEqual(len(models), 1)
|
||||
model = models[0]
|
||||
self.assertEqual(model["id"], svc.model)
|
||||
self.assertEqual(model["status"]["value"], "loaded")
|
||||
self.assertEqual(model["meta"]["n_ctx"], 262144)
|
||||
self.assertEqual(model["architecture"]["input_modalities"],
|
||||
["text", "image"] if vision else ["text"])
|
||||
code, _, body = self.get("/props?model=" + svc.model + "&autoload=false")
|
||||
self.assertEqual(code, 200)
|
||||
props = json.loads(body)
|
||||
self.assertEqual(props["default_generation_settings"]["n_ctx"], 262144)
|
||||
self.assertEqual(props["default_generation_settings"]["params"],
|
||||
{"temperature": 0.7, "repeat_penalty": 1.1, "n_predict": 4096})
|
||||
self.assertEqual(props["chat_template"], (ROOT / "serve/chat_template.jinja").read_text(encoding="utf-8"))
|
||||
self.assertEqual(props["modalities"]["vision"], vision is not None)
|
||||
self.assertEqual(props["total_slots"], 1)
|
||||
self.assertFalse(props["models_autoload"])
|
||||
svc.shared = {}
|
||||
props = json.loads(self.get("/props")[2])
|
||||
self.assertEqual(props["default_generation_settings"]["params"]["n_predict"], -1)
|
||||
self.assertEqual(self.get("/props?model=not-loaded&autoload=true")[0], 404)
|
||||
finally:
|
||||
svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared = previous
|
||||
|
||||
def test_discovery_needs_the_api_key(self):
|
||||
self.svc.api_key = "secret"
|
||||
try:
|
||||
for path in ("/models", "/v1/models", "/props", "/slots"):
|
||||
self.assertEqual(self.get(path)[0], 401)
|
||||
self.assertEqual(self.get(path, {"Authorization": "Bearer secret"})[0], 200)
|
||||
finally:
|
||||
self.svc.api_key = ""
|
||||
|
||||
def test_build_model_path_and_slot_status(self):
|
||||
engine = self.svc.engine
|
||||
engine.model_path = "models/example.gguf"
|
||||
engine.info = {"version": "0.1.21"}
|
||||
try:
|
||||
props = json.loads(self.get("/props")[2])
|
||||
self.assertEqual(props["model_path"], engine.model_path)
|
||||
self.assertEqual(props["build_info"], "Strata 0.1.21")
|
||||
for busy in (True, False):
|
||||
with self.svc.status_lock:
|
||||
self.svc.status["busy"] = busy
|
||||
code, _, body = self.get("/slots")
|
||||
self.assertEqual(code, 200)
|
||||
self.assertEqual(json.loads(body), [{"id": 0, "n_ctx": CTX, "is_processing": busy}])
|
||||
finally:
|
||||
with self.svc.status_lock:
|
||||
self.svc.status["busy"] = False
|
||||
del engine.model_path, engine.info
|
||||
props = json.loads(self.get("/props")[2])
|
||||
self.assertNotIn("build_info", props)
|
||||
self.assertNotIn("model_path", props)
|
||||
|
||||
def test_discovery_does_not_restart_a_dead_engine(self):
|
||||
self.svc.engine.alive = lambda: False
|
||||
try:
|
||||
for path in ("/models", "/v1/models"):
|
||||
code, _, body = self.get(path)
|
||||
self.assertEqual(code, 200)
|
||||
self.assertEqual(json.loads(body)["data"], [])
|
||||
self.assertEqual(self.get("/props")[0], 503)
|
||||
self.assertEqual(json.loads(self.get("/slots")[2]), [])
|
||||
finally:
|
||||
del self.svc.engine.alive
|
||||
|
||||
def test_metrics_need_the_key_when_one_is_set(self):
|
||||
self.svc.api_key = "secret"
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user