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: Claude Code works - /v1/messages?beta=true (#55), mid-conversation system messages (#56)
Niko1221c99cede026b1
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 54f9237af..7dbf4c12f 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -273,6 +273,9 @@ print(r.choices[0].message.content)15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing theconnection or pressing stop in your app really stops the model, so the next request starts at once.- **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key.+- **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and+ `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any+ `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one).- **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. A request whose`max_tokens` would run past the context is refused too (400); agents that always ask for their full output capcan instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-<model>.json` (or passdiff --git a/serve/frontend.py b/serve/frontend.pyindex dfa29817c..afe014089 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -129,6 +129,14 @@ def images_of(messages: list[dict]) -> list[str]:for item in m["content"] if item.get("type") == "image"]+def _late_system_to_user(messages: list[dict]) -> list[dict]:+ """The chat template takes a system message only at the start ("System message must be at the beginning").+ Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user+ turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place:+ merging them into the first one would change the prompt's start and cost the conversation cache every turn."""+ return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)]++def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:"""OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""messages = []@@ -161,7 +169,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:kwargs = {"enable_thinking": False}elif k == "reasoning_effort" and "enable_thinking" not in kwargs:kwargs.update(effort_kwargs(v))- return messages, tools, kwargs+ return _late_system_to_user(messages), tools, kwargsdef anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:@@ -210,7 +218,7 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dickwargs.update(effort_kwargs(effort))elif isinstance(thinking, dict) and thinking.get("budget_tokens"):kwargs.update(budget_effort(thinking["budget_tokens"]))- return messages, tools, kwargs+ return _late_system_to_user(messages), tools, kwargs# ------------------------------------------------------------------------------------------------ output parserdiff --git a/serve/server.py b/serve/server.pyindex 8d795aebe..62607019f 100644--- a/serve/server.py+++ b/serve/server.py@@ -1042,14 +1042,15 @@ def make_handler(svc: Service):def do_POST(self):if not self._authorized():return- if self.path.rstrip("/") == "/settings":+ path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true+ if path == "/settings":self._settings()returntry:req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")- if self.path.rstrip("/") == "/v1/chat/completions":+ if path == "/v1/chat/completions":self._openai(req)- elif self.path.rstrip("/") == "/v1/messages":+ elif path == "/v1/messages":self._anthropic(req)else:self._json(404, {"error": {"message": "not found"}})diff --git a/serve/test_server.py b/serve/test_server.pyindex c088abbcf..ed5e3e1e7 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -165,6 +165,83 @@ class FitMaxTokens(unittest.TestCase):self.assertIn("no room to answer", b["error"]["message"])+class ClientShapes(unittest.TestCase):+ """What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the+ conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message."""++ @classmethod+ def setUpClass(cls):+ tok = ByteTokenizer()+ cls.engine = RecordingPrompt(tok, "</think>\n\n2", max_context=CTX)+ cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ 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 post(self, path, body):+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})+ try:+ with urllib.request.urlopen(req, timeout=30) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ with e:+ return e.code, json.loads(e.read())++ def prompt_text(self):+ return bytes(i for i in self.engine.last_ids if i < 256).decode("utf-8", "replace")++ def test_query_string(self):+ body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]}+ for path in ("/v1/messages?beta=true", "/v1/chat/completions?api-version=1", "/v1/messages/?beta=true"):+ status, b = self.post(path, body)+ self.assertEqual(status, 200, (path, b))+ status, _ = self.post("/v1/nothing?beta=true", body)+ self.assertEqual(status, 404)++ def test_anthropic_mid_conversation_system(self):+ status, b = self.post("/v1/messages?beta=true", {+ "model": "x", "max_tokens": 50,+ "system": [{"type": "text", "text": "You are terse."}],+ "messages": [+ {"role": "user", "content": [{"type": "text", "text": "1+1? digits only"}]},+ {"role": "system", "content": [{"type": "text", "text": "<system-reminder>answer in digits</system-reminder>"}]}]})+ self.assertEqual(status, 200, b)+ text = self.prompt_text()+ self.assertIn("You are terse.", text)+ self.assertIn("<system-reminder>answer in digits</system-reminder>", text)+ self.assertLess(text.index("You are terse."), text.index("1+1?")) # the first system stays first+ self.assertLess(text.index("1+1?"), text.index("answer in digits")) # the late one stays in place++ def test_openai_late_developer_and_system(self):+ status, b = self.post("/v1/chat/completions", {+ "model": "x", "max_tokens": 50,+ "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "hi"}, {"role": "developer", "content": "Now use digits."},+ {"role": "system", "content": "Also this."}, {"role": "user", "content": "1+1?"}]})+ self.assertEqual(status, 200, b)+ text = self.prompt_text()+ for part in ("Be brief.", "Now use digits.", "Also this.", "1+1?"):+ self.assertIn(part, text)++ def test_leading_system_unchanged(self):+ from serve.frontend import anthropic_to_messages, openai_to_messages+ msgs, _, _ = openai_to_messages({"messages": [{"role": "developer", "content": "D"}, {"role": "user", "content": "u"}]})+ self.assertEqual([m["role"] for m in msgs], ["system", "user"])+ msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]})+ self.assertEqual([m["role"] for m in msgs], ["system", "user"])+++class RecordingPrompt(MockEngine):+ def generate(self, ids, max_new, sampling, cancel, embeddings=None):+ self.last_ids = list(ids)+ yield from super().generate(ids, max_new, sampling, cancel, embeddings)++class DyingEngine(MockEngine):"""Issue #27: an engine that dies after a few tokens of its first answer, and comes back when restarted."""