serve: model aliases - the config's aliases in /v1/models and accepted as model names (#297)

`"aliases": [...]` (or a comma-separated string) in strata-<model>.json: /v1/models lists the model with an
`aliases` field and each alias as its own entry (`alias_of`), /props?model= accepts them, and a request naming
an alias is answered under that name (OpenAI, streamed or not, and Anthropic). Any other name is still served
under the model's own name, as before; without aliases the responses are unchanged. Documented in DETAILS.md.
Test: ModelAliases (serve/test_server.py).
This commit is contained in:
Niko1221 committed 2026-10-01 08:37:46 +02:00
1 parent 2282393234
commit d85ff9dfe9
3 files changed
+118 -4

No files matched your search

+3
View File
@@ -434,6 +434,9 @@ print(r.choices[0].message.content)
`max_tokens` would run past the context is refused too (400); agents that always ask for their full output cap
can instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-<model>.json` (or pass
`--fit-max-tokens` to `serve/server.py`). A prompt that leaves no room at all is still refused.
- **Model aliases** (0.1.32). `"aliases": ["qwen", "local-model"]` in `strata-<model>.json` lists the model under
those names too in `/v1/models` (each with its own `id`, and in the model's `aliases`), like llama-server's
`--alias`; a request naming one is answered under that name. Any other name is still served, as before.
- **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise:
run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and
`"api_key": "..."` to `strata-<model>.json`). The server window then prints this PC's addresses
+39 -4
View File
@@ -642,6 +642,7 @@ class Service:
fit_max_tokens: bool = False):
self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision
self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400
self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`)
self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block
self.shared = {} # the web app's Chat settings for every client (POST /settings)
self.shared_path = None # where they are kept between starts (next to the config)
@@ -672,6 +673,30 @@ class Service:
def loaded(self) -> bool:
return not hasattr(self.engine, "alive") or self.engine.alive()
def set_aliases(self, aliases) -> None:
"""#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias.
ValueError for anything else."""
if aliases is None:
aliases = []
if isinstance(aliases, str):
aliases = aliases.split(",")
if not isinstance(aliases, list) or not all(isinstance(x, str) for x in aliases):
raise ValueError(f"aliases={aliases!r}: expected a list of model names")
names = []
for x in (x.strip() for x in aliases):
if x and x != self.model and x not in names:
names.append(x)
self.aliases = names
def model_names(self) -> list[str]:
return [self.model, *self.aliases]
def model_for(self, req) -> str:
"""The name to answer with: the request's own when it is the model's name or an alias (#297), else the model's.
Other names are still served, as before."""
asked = req.get("model") if isinstance(req, dict) else None
return asked if isinstance(asked, str) and asked in self.aliases else self.model
def reasoning_budget(self, req) -> int | None:
"""#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the
config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for
@@ -1300,9 +1325,10 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel
"""`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with
an empty delta and a `strata_mcp` field, which only the web app reads."""
cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time())
model = svc.model_for(req)
def chunk(delta, finish=None):
return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": svc.model,
return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model,
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
yield chunk({"role": "assistant", "content": ""})
@@ -1399,7 +1425,7 @@ def openai_collect(chunks) -> dict:
def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel):
mid = "msg_" + uuid.uuid4().hex[:24]
yield "message_start", {"type": "message_start", "message": {
"id": mid, "type": "message", "role": "assistant", "model": svc.model, "content": [],
"id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [],
"stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": len(ids), "output_tokens": 0}}}
index, open_kind, used_tool = -1, None, False
@@ -1603,7 +1629,10 @@ def make_handler(svc: Service):
if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)):
model["status"] = {"value": "unloaded"} # like llama-server's router: listed, loads on use
loaded = True
self._json(200, {"object": "list", "data": [model] if loaded else []})
if svc.aliases: # #297: the aliases, and each one listed under its own id
model["aliases"] = list(svc.aliases)
data = [model, *({**model, "id": x, "alias_of": svc.model} for x in svc.aliases)]
self._json(200, {"object": "list", "data": data if loaded else []})
elif path == "/props":
if self._authorized():
self._props()
@@ -1657,7 +1686,7 @@ def make_handler(svc: Service):
def _props(self):
model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]
if model != svc.model:
if model not in svc.model_names():
self._json(404, {"error": {"message": "model not found"}})
return
if not svc.loaded() and not getattr(svc.engine, "unloaded", False):
@@ -2029,6 +2058,12 @@ def main() -> int:
model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision,
sampling_defaults=sampling_defaults,
fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)
try:
svc.set_aliases(cfg.get("aliases")) # #297: other names the model answers to
except ValueError as e:
raise SystemExit(f"[strata] config {e}")
if svc.aliases:
print(f"[strata] model aliases: {', '.join(svc.aliases)}", flush=True)
if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key="
for i, x in enumerate(sys.argv)):
# #213: an empty key would switch authentication off without a word
+76
View File
@@ -1468,5 +1468,81 @@ class RestartWindow(unittest.TestCase):
httpd.server_close()
class ModelAliases(unittest.TestCase):
"""#297: the config's `aliases` are listed by /v1/models and accepted as model names (answered under that name)."""
@classmethod
def setUpClass(cls):
tok = ByteTokenizer()
cls.svc = Service(MockEngine(tok, "</think>\n\nok", max_context=CTX), tok,
ChatTemplate(ROOT / "serve/chat_template.jinja"), model_name="qwen3.8-flash-next-iq3_xxs")
cls.svc.set_aliases(["qwen", "local-model", "qwen", " ", "qwen3.8-flash-next-iq3_xxs"])
cls.httpd = serve(cls.svc, port=0)
cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
@classmethod
def tearDownClass(cls):
cls.httpd.shutdown()
cls.httpd.server_close()
def get(self, path):
with urllib.request.urlopen(self.base + path, timeout=30) as r:
return json.loads(r.read())
def post(self, path, body):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=30) as r:
return r.read().decode()
def test_set_aliases(self):
self.assertEqual(self.svc.aliases, ["qwen", "local-model"]) # duplicates, blanks and the name itself
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
svc.set_aliases("a, b")
self.assertEqual(svc.aliases, ["a", "b"])
svc.set_aliases(None)
self.assertEqual(svc.aliases, [])
for bad in (3, ["a", 1], {"a": 1}):
with self.assertRaises(ValueError):
svc.set_aliases(bad)
def test_models_lists_them(self):
data = self.get("/v1/models")["data"]
self.assertEqual([m["id"] for m in data], ["qwen3.8-flash-next-iq3_xxs", "qwen", "local-model"])
self.assertEqual(data[0]["aliases"], ["qwen", "local-model"])
self.assertEqual(data[1]["alias_of"], "qwen3.8-flash-next-iq3_xxs")
self.assertEqual(self.get("/props?model=local-model")["model_alias"], "qwen3.8-flash-next-iq3_xxs")
def test_requests_are_answered_under_the_alias(self):
msgs = [{"role": "user", "content": "hi"}]
for asked, want in (("qwen", "qwen"), ("local-model", "local-model"),
("qwen3.8-flash-next-iq3_xxs", "qwen3.8-flash-next-iq3_xxs"),
("something-else", "qwen3.8-flash-next-iq3_xxs")): # still served, as before
with self.subTest(asked=asked):
out = json.loads(self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8}))
self.assertEqual(out["model"], want)
text = self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8,
"stream": True})
first = json.loads(text.split("data: ", 2)[1].strip())
self.assertEqual(first["model"], want)
out = json.loads(self.post("/v1/messages", {"model": asked, "messages": msgs, "max_tokens": 8}))
self.assertEqual(out["model"], want)
def test_without_aliases_nothing_changes(self):
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
httpd = serve(svc, port=0)
try:
with urllib.request.urlopen(f"http://127.0.0.1:{httpd.server_address[1]}/v1/models", timeout=30) as r:
data = json.loads(r.read())["data"]
self.assertEqual(len(data), 1)
self.assertNotIn("aliases", data[0])
self.assertEqual(svc.model_for({"model": "x"}), svc.model)
finally:
httpd.shutdown()
httpd.server_close()
if __name__ == "__main__":
unittest.main()