Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: /props reports chat_template_caps so Zed offers tools; a failing template probe never stops the start (#986, #987)
Niko1221111d62ae9697
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex eaeadf08d..d031f541e 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -540,6 +540,16 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or`/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.+`chat_template_caps` uses llama.cpp's field names. Strata checks them when loading the active template by rendering+small requests; a rejected or omitted feature is `false`, and a template that fails a probe in any way only turns that+feature off (the server still starts). `supports_tools` checks tool definitions and XML call+instructions; `supports_tool_calls` checks that calls in the history use Strata's XML format and keep tool results.+`supports_parallel_tool_calls` checks multiple calls in one assistant turn, and `supports_system_role` checks a+leading system message. `supports_preserve_reasoning` means older assistant turns keep their `reasoning_content`+in the rendered prompt. It does not describe whether a new reply returns reasoning. These are compatibility hints+for clients, not a guarantee that the model will follow a request. Zed's llama.cpp provider reads this object to+offer tools.+```bashcurl 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 }'@@ -615,6 +625,8 @@ print(r.choices[0].message.content)sends nothing, and that is on purpose: its only line arrives once the prompt is read, because the last tokens gothrough the verify windows rather than the batched path, so it stops up to `--short-read` tokens short of the end.- **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key.+ Zed's llama.cpp provider reads `/props` and offers tools from `chat_template_caps`. Its generic OpenAI-compatible+ provider does not: add `"capabilities": {"tools": true, "chat_completions": true}` on that model in Zed's settings.- **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the fieldnames are OpenCode's, so check its config docs if your version differs:diff --git a/serve/frontend.py b/serve/frontend.pyindex fe104b509..d2d90f6cd 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas ofrom __future__ import annotationsimport json+import loggingimport osimport reimport uuid@@ -25,6 +26,8 @@ from pathlib import Pathimport jinja2from jinja2.sandbox import ImmutableSandboxedEnvironment+LOGGER = logging.getLogger(__name__)+# ------------------------------------------------------------------------------------------------ templateclass TemplateRequestError(jinja2.exceptions.TemplateError, ValueError):@@ -47,6 +50,7 @@ class ChatTemplate:env.globals["raise_exception"] = raise_exceptionself.source = Path(path).read_text(encoding="utf-8")self.template = env.from_string(self.source)+ self.caps = self._detect_caps()def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,**kwargs) -> str:@@ -59,6 +63,53 @@ class ChatTemplate:return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt,**kwargs)+ def _detect_caps(self) -> dict[str, bool]:+ """llama.cpp's capability names, checked at load time against this template and Strata's tool-call format.+ These are rendering hints, not a guarantee that the model will follow a request."""+ def render(messages, tools=None):+ try:+ return self.render(messages, tools=tools)+ except Exception as exc: # noqa: BLE001 - a hint only: never stop the server for a probe+ # A template may reject a role or feature (a custom one may fail in any way): the feature is off,+ # discovery still answers for the others, and the start-up goes on.+ LOGGER.debug("chat template capability probe failed: %s", exc, exc_info=True)+ return ""++ user = {"role": "user", "content": "strata_caps_user"}+ tools = [{"name": f"strata_caps_call_{i}", "description": "strata_caps_description",+ "parameters": {"type": "object", "properties": {"arg": {"type": "string"}}}}+ for i in range(2)]+ tool_prompt = render([user], tools)++ def calls_supported(count):+ calls = [{"name": f"strata_caps_call_{i}", "arguments": {"arg": f"strata_caps_arg_{i}"}}+ for i in range(count)]+ messages = [user, {"role": "assistant", "content": "",+ "tool_calls": [{"function": call} for call in calls]}]+ replies = [f"strata_caps_result_{i}" for i in range(count)]+ messages += [{"role": "tool", "content": reply} for reply in replies] + [user]+ prompt = render(messages, tools)+ # Instructions include example XML and literal tag names, which are not model output. Parse only+ # complete calls to our probe functions, using the same body parser as OutputParser.+ bodies = re.findall(r"<tool_call>\s*(<function=strata_caps_call_\d+>.*?</function>)\s*</tool_call>",+ prompt, re.S)+ try:+ parsed = [parse_tool_call(body) for body in bodies]+ except ValueError:+ return False+ return [{"name": call.name, "arguments": call.arguments} for call in parsed] == calls \+ and all(reply in prompt for reply in replies)++ history = [user, {"role": "assistant", "content": "strata_caps_answer",+ "reasoning_content": "strata_caps_reasoning"}, user]+ return {"supports_tools": all(s in tool_prompt for s in+ ("strata_caps_call_0", "strata_caps_description", "<tool_call>", "<function=")),+ "supports_tool_calls": calls_supported(1),+ "supports_system_role": "strata_caps_system" in render(+ [{"role": "system", "content": "strata_caps_system"}, user]),+ "supports_parallel_tool_calls": calls_supported(2),+ "supports_preserve_reasoning": "strata_caps_reasoning" in render(history)}+# ------------------------------------------------------------------------------------------------ requestsdef _text_of(content) -> str:diff --git a/serve/server.py b/serve/server.pyindex 30e8f85ce..ab1706963 100644--- a/serve/server.py+++ b/serve/server.py@@ -4115,6 +4115,7 @@ def make_handler(svc: Service):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,+ "chat_template_caps": svc.template.caps,"modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"),"is_sleeping": not svc.loaded()}if getattr(svc.engine, "model_path", None):diff --git a/serve/test_server.py b/serve/test_server.pyindex 34f608021..b74ad92c7 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -2123,6 +2123,20 @@ class SharedSettings(unittest.TestCase):self.svc.trusted_origins = []+class TemplateCaps(unittest.TestCase):+ def test_probe_errors_are_logged_and_swallowed(self):+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "chat_template.jinja"+ path.write_text("{{ missing_global() }}", encoding="utf-8")+ with self.assertLogs("serve.frontend", level="DEBUG") as logs:+ caps = ChatTemplate(path).caps+ self.assertFalse(any(caps.values()))+ self.assertTrue(any("missing_global" in line for line in logs.output))+ with mock.patch.object(ChatTemplate, "render", side_effect=RuntimeError("render bug")):+ caps = ChatTemplate(path).caps # any error of a probe is a feature that is off, not a crash+ self.assertFalse(any(caps.values()))++class WebApp(unittest.TestCase):"""The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics."""@@ -2204,6 +2218,9 @@ class WebApp(unittest.TestCase):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"))+ for key in ("supports_tools", "supports_tool_calls", "supports_system_role",+ "supports_parallel_tool_calls", "supports_preserve_reasoning"):+ self.assertIs(props["chat_template_caps"][key], True)self.assertEqual(props["modalities"]["vision"], vision is not None)self.assertEqual(props["total_slots"], 1)self.assertFalse(props["models_autoload"])@@ -2214,6 +2231,64 @@ class WebApp(unittest.TestCase):finally:svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared = previous+ def test_props_caps_follow_the_active_template(self):+ source = self.svc.template.source+ cases = [("{# tools tool_calls reasoning_content <tool_call> <function= #}{{ messages[-1].content }}",+ {"supports_tools": False, "supports_tool_calls": False, "supports_system_role": False,+ "supports_parallel_tool_calls": False, "supports_preserve_reasoning": False}),+ ("{% set preserve_thinking = false %}" + source, {"supports_preserve_reasoning": False}),+ ("{% for m in messages %}{% if m.tool_calls and m.tool_calls|length > 1 %}"+ "{{ raise_exception('Only one tool call is supported.') }}{% endif %}{% endfor %}" + source,+ {"supports_tool_calls": True, "supports_parallel_tool_calls": False}),+ ("{% if tools or messages[0].role == 'system' %}{{ raise_exception('Unsupported.') }}{% endif %}"+ "{{ messages[-1].content }}",+ {"supports_tools": False, "supports_tool_calls": False, "supports_system_role": False,+ "supports_parallel_tool_calls": False, "supports_preserve_reasoning": False}),+ ("{% for m in messages %}{{ m.content }}{% if m.tool_calls %}"+ "<tool_call>{{ m.tool_calls|tojson }}</tool_call>{% endif %}{% endfor %}",+ {"supports_tools": False, "supports_tool_calls": False, "supports_system_role": True,+ "supports_parallel_tool_calls": False, "supports_preserve_reasoning": False}),+ ("{% for m in messages %}{% if m.tool_calls %}{% for c in m.tool_calls %}"+ "{% set fn = c.function if c.function is defined else c %}"+ "{% if not tools or fn.name not in tools|map(attribute='name')|list %}"+ "{{ raise_exception('Tool calls require matching tool definitions.') }}"+ "{% endif %}{% endfor %}{% endif %}{% endfor %}" + source,+ {"supports_tools": True, "supports_tool_calls": True, "supports_parallel_tool_calls": True})]+ original = self.svc.template+ try:+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "chat_template.jinja"+ for text, expected in cases:+ with self.subTest(expected=expected):+ path.write_text(text, encoding="utf-8")+ self.svc.template = ChatTemplate(path)+ code, _, body = self.get("/props")+ self.assertEqual(code, 200)+ props = json.loads(body)+ self.assertEqual(props["chat_template"], text)+ for key, value in expected.items():+ self.assertIs(props["chat_template_caps"][key], value)+ finally:+ self.svc.template = original++ def test_props_caps_are_ready_for_concurrent_requests(self):+ from concurrent.futures import ThreadPoolExecutor++ original = self.svc.template+ try:+ self.svc.template = ChatTemplate(ROOT / "serve/chat_template.jinja")+ with mock.patch.object(self.svc.template, "render", side_effect=AssertionError("render during request")):+ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(lambda _: self.get("/props"), range(4)))+ for code, _, body in results:+ self.assertEqual(code, 200)+ caps = json.loads(body)["chat_template_caps"]+ for key in ("supports_tools", "supports_tool_calls", "supports_system_role",+ "supports_parallel_tool_calls", "supports_preserve_reasoning"):+ self.assertIs(caps[key], True)+ finally:+ self.svc.template = original+def test_discovery_needs_the_api_key(self):self.svc.api_key = "secret"try: