Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 serve: merge system messages, allow a prefill, 400 for json response_format, SSE error event
YanissAmz54708bf09b11
diff --git a/tests/test_hy4_compat_cpu.py b/tests/test_hy4_compat_cpu.pyindex 9e5aec8..ddcea81 100644--- a/tests/test_hy4_compat_cpu.py+++ b/tests/test_hy4_compat_cpu.py@@ -67,25 +67,15 @@ class Parser(unittest.TestCase):def test_response_format(self):for rf in (None, {"type": "text"}):self.assertEqual(parse(response_format=rf)["messages"], USER)- r = parse(response_format={"type": "json_object"})- self.assertEqual(r["messages"][0], {"role": "system", "content": C.JSON_HINT})- self.assertEqual(r["messages"][1:], USER)- self.assertIn(C.JSON_HINT, self.render(r))- schema = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}- r = C.parse_chat({"messages": [{"role": "system", "content": "Be brief."}, *USER],- "response_format": {"type": "json_schema", "json_schema": {"name": "x", "schema": schema}}})- self.assertTrue(r["messages"][0]["content"].startswith("Be brief.\n\n" + C.JSON_SCHEMA_HINT))- self.assertIn(json.dumps(schema), r["messages"][0]["content"])- for bad in ("json", {"type": "xml"}, {}, {"type": "json_schema"}, {"type": "json_schema", "json_schema": {"name": "x"}}):+ for rf in ({"type": "json_object"}, {"type": "json_schema", "json_schema": {"name": "x", "schema": {"type": "object"}}}):+ with self.assertRaises(C.RequestError, msg=str(rf)) as cm: # no constrained decoding: a clean 400, not a reply that silently is not JSON+ parse(response_format=rf)+ self.assertIn("not supported yet", str(cm.exception))+ self.assertEqual(cm.exception.status, 400)+ for bad in ("json", {"type": "xml"}, {}, 5):with self.assertRaises(C.RequestError, msg=str(bad)):parse(response_format=bad)- def test_response_format_and_tool_choice_share_one_instruction_block(self):- tools = [{"type": "function", "function": {"name": "f", "parameters": {"type": "object", "properties": {}}}}]- r = parse(tools=tools, tool_choice="required", response_format={"type": "json_object"})- self.assertEqual(len(r["messages"]), 2)- self.assertEqual(r["messages"][0]["content"], C.TOOL_HINTS["required"] + "\n\n" + C.JSON_HINT)-# -- content partsdef test_null_and_empty_content_parts(self):def text(content):@@ -109,16 +99,55 @@ class Parser(unittest.TestCase):def test_system_and_developer_roles(self):r = C.parse_chat({"messages": [{"role": "developer", "content": "Be brief."}, *USER]})self.assertEqual(r["messages"][0], {"role": "system", "content": "Be brief."})- r = C.parse_chat({"messages": [{"role": "system", "content": "Rule one."}, {"role": "developer", "content": "Rule two."}, *USER]})- self.assertEqual([m["role"] for m in r["messages"]], ["system", "system", "user"])+ self.assertEqual(len(r["messages"]), 2)++ def test_several_system_messages_become_one_leading_message(self):+ msgs = [{"role": "system", "content": "Rule one."}, {"role": "developer", "content": [{"type": "text", "text": "Rule two."}]}, *USER,+ {"role": "assistant", "content": "hello"}, {"role": "system", "content": "Switch to French."}, {"role": "user", "content": "again"}]+ r = C.parse_chat({"messages": msgs})+ self.assertEqual([m["role"] for m in r["messages"]], ["system", "user", "assistant", "user"])+ self.assertEqual(r["messages"][0]["content"], "Rule one.\n\nRule two.\n\nSwitch to French.")text = self.render(r)+ self.assertEqual(text.count("hy_start:6124c78e|>system"), 1)self.assertLess(text.index("Rule one."), text.index("Rule two."))- self.assertLess(text.index("Rule two."), text.index("|>hi"))- r = C.parse_chat({"messages": [*USER, {"role": "assistant", "content": "hello"}, {"role": "developer", "content": "Switch to French."}, {"role": "user", "content": "again"}]})- self.assertEqual([m["role"] for m in r["messages"]], ["user", "assistant", "system", "user"]) # a system message in the middle is rendered where it stands- text = self.render(r)- self.assertLess(text.index("hello"), text.index("Switch to French."))- self.assertLess(text.index("Switch to French."), text.index("again"))+ self.assertLess(text.index("Rule two."), text.index("Switch to French."))+ self.assertLess(text.index("Switch to French."), text.index("|>hi"))++ def test_system_messages_without_text_add_nothing(self):+ r = C.parse_chat({"messages": [{"role": "system", "content": None}, {"role": "developer", "content": ""}, *USER]})+ self.assertEqual([m["role"] for m in r["messages"]], ["user"])+ self.assertEqual(r["messages"], USER)++ def test_system_messages_merge_with_the_tool_instruction(self):+ tools = [{"type": "function", "function": {"name": "f", "parameters": {"type": "object", "properties": {}}}}]+ r = C.parse_chat({"messages": [{"role": "system", "content": "Be brief."}, *USER, {"role": "developer", "content": "Late rule."}], "tools": tools, "tool_choice": "required"})+ self.assertEqual(len(r["messages"]), 2)+ self.assertEqual(r["messages"][0]["content"], "Be brief.\n\nLate rule.\n\n" + C.TOOL_HINTS["required"])++ def test_only_system_messages_is_a_400(self):+ with self.assertRaises(C.RequestError):+ C.parse_chat({"messages": [{"role": "system", "content": "Be brief."}]})++ # -- prefill: a last assistant message+ def test_last_assistant_message_is_a_prefill(self):+ r = C.parse_chat({"messages": [*USER, {"role": "assistant", "content": "Sure, the answer is"}]})+ self.assertTrue(r["prefill"])+ text = self.v.template.render_chat(r)+ self.assertTrue(text.endswith("|>assistant<|hy_middle:6124c78e|>Sure, the answer is")) # the turn stays open: no end marker, no generation prompt+ self.assertFalse(parse()["prefill"])+ self.assertTrue(self.v.template.render_chat(parse()).endswith("<think:6124c78e>"))++ def test_an_empty_last_assistant_message_is_dropped(self):+ for empty in ("", None, [None]):+ r = C.parse_chat({"messages": [*USER, {"role": "assistant", "content": empty}]})+ self.assertEqual((r["prefill"], r["messages"]), (False, USER))++ def test_bad_prefills_are_a_400(self):+ calls = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}]+ for msgs in ([{"role": "assistant", "content": "x"}], [*USER, {"role": "assistant", "content": "", "tool_calls": calls}],+ [{"role": "system", "content": "s"}, {"role": "assistant", "content": "x"}]):+ with self.assertRaises(C.RequestError, msg=str(msgs)):+ C.parse_chat({"messages": msgs})def test_unknown_role_is_a_400(self):with self.assertRaises(C.RequestError):@@ -159,11 +188,22 @@ class Http(unittest.IsolatedAsyncioTestCase):events = [e[6:] for e in (await r.read()).decode().split("\n\n") if e.startswith("data: ")]self.assertTrue(all("usage" not in json.loads(e) for e in events[:-1]))- async def test_json_object_adds_the_instruction_to_the_prompt(self):- r = await self.chat(response_format={"type": "json_object"}, messages=[{"role": "developer", "content": "Be brief."}, *USER])- self.assertEqual(r.status, 200)- prompt = self.st.vocab.decode(self.st.engine.calls[-1][0])- self.assertIn("Be brief.\n\n" + C.JSON_HINT, prompt)+ async def test_json_response_format_is_a_clean_400(self):+ for rf in ({"type": "json_object"}, {"type": "json_schema", "json_schema": {"name": "x", "schema": {}}}):+ r = await self.chat(response_format=rf)+ j = await r.json()+ self.assertEqual((r.status, j["error"]["type"]), (400, "invalid_request_error"))+ self.assertIn("not supported yet", j["error"]["message"])+ self.assertEqual((await self.chat(response_format={"type": "text"})).status, 200)++ async def test_prefill_continues_the_last_assistant_message(self):+ self.st.engine = type(self.st.engine)(self.st.vocab, " forty-two.")+ r = await self.client.post("/v1/chat/completions", json={"messages": [*USER, {"role": "assistant", "content": "The answer is"}], "max_tokens": 50})+ j = await r.json()+ self.assertEqual(r.status, 200, j)+ self.assertEqual(j["choices"][0]["message"]["content"], " forty-two.") # the continuation only, no reasoning split: the turn is already past its think block+ self.assertNotIn("reasoning_content", j["choices"][0]["message"])+ self.assertTrue(self.st.vocab.decode(self.st.engine.calls[0][0]).endswith("The answer is"))async def test_developer_and_null_parts_are_served(self):r = await self.chat(messages=[{"role": "developer", "content": [{"type": "text", "text": "Be brief."}, None]}, {"role": "user", "content": None}])diff --git a/tests/test_hy4_tools_cpu.py b/tests/test_hy4_tools_cpu.pyindex a84014d..39bbe3d 100644--- a/tests/test_hy4_tools_cpu.py+++ b/tests/test_hy4_tools_cpu.py@@ -515,6 +515,43 @@ class Http(unittest.IsolatedAsyncioTestCase):j = await (await self.client.post("/apply-template", json=self.body())).json()self.assertIn("# Tools", j["prompt"])+ # -- an engine error+ async def test_engine_error_after_the_stream_began_is_an_error_event(self):+ st = await self.start("hello world")++ class Boom(FakeEngine):+ def generate(self, ids, max_new, on_tokens, speculative=True, cancel=lambda: False):+ on_tokens(self.ids[:3])+ raise RuntimeError("HIP error: device lost")++ st.engine = Boom(st.vocab, "hello world")+ out = io.StringIO()+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):+ r = await asyncio.wait_for(self.client.post("/v1/chat/completions", json=self.body(stream=True, tools=None)), 10)+ raw = (await asyncio.wait_for(r.read(), 10)).decode()+ self.assertEqual(r.status, 200)+ events = [e[6:] for e in raw.split("\n\n") if e.startswith("data: ")]+ self.assertEqual(events[-1], "[DONE]")+ err = json.loads(events[-2])+ self.assertEqual((err["error"]["type"], "device lost" in err["error"]["message"]), ("server_error", True))+ self.assertIn("stream failed", out.getvalue())+ st.engine = FakeEngine(st.vocab, "ok") # the lock was released+ r = await self.client.post("/v1/chat/completions", json=self.body(tools=None))+ self.assertEqual(r.status, 200)++ async def test_engine_error_without_a_stream_is_a_500_body(self):+ st = await self.start("hello world")++ class Boom(FakeEngine):+ def generate(self, ids, max_new, on_tokens, speculative=True, cancel=lambda: False):+ raise RuntimeError("HIP error: device lost")++ st.engine = Boom(st.vocab, "x")+ with contextlib.redirect_stderr(io.StringIO()):+ r = await asyncio.wait_for(self.client.post("/v1/chat/completions", json=self.body()), 10)+ j = await r.json()+ self.assertEqual((r.status, j["error"]["type"]), (500, "server_error"))+# -- a client that closes the streamasync def test_a_failed_write_cancels_the_generation_quietly(self):"""the traceback of the report: resp.write raises ClientConnectionResetError ("Cannot write to closing transport")"""diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex fdbc777..a8f7cd8 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -167,10 +167,10 @@ def build_app(st: State):def prompt_for_chat(body):r = C.parse_chat(body, args.default_max_tokens)- text = st.vocab.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])+ text = st.vocab.template.render_chat(r)ids = st.vocab.encode(text)v = st.vocab- r["in_think"] = r["effort"] != "no_think" and bool(v.think_begin) and text.rstrip().endswith(v.think_begin)+ r["in_think"] = not r["prefill"] and r["effort"] != "no_think" and bool(v.think_begin) and text.rstrip().endswith(v.think_begin)return r, idsdef check_len(n, max_new):@@ -279,14 +279,24 @@ def build_app(st: State):tau=stats["tau"], accept_hist=stats["accept_hist"], ttft_ms=stats["ttft_s"] * 1000,prefill_trunk_ms=stats.get("prefill_trunk_s", 0) * 1000, draft_fill_ms=stats.get("prime_s", 0) * 1000)+ def event(chunk: dict) -> bytes:+ return b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n"+async def sse(request, chunks):"""stream `chunks` (an async generator of JSON-able chunks) as server-sent events. A client that closes the stream makes the write raise: that cancels the- generation (closing `chunks` runs run_job's cleanup, which stops the engine) and ends the request with one log line, not a traceback."""+ generation (closing `chunks` runs run_job's cleanup, which stops the engine) and ends the request with one log line, not a traceback. An error after the+ stream began (the engine failed) cannot become a second response: it is sent as an error event, then [DONE]."""resp = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})try:await resp.prepare(request)- async for chunk in chunks:- await resp.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")+ try:+ async for chunk in chunks:+ await resp.write(event(chunk))+ except (ConnectionError, ClientConnectionError, ClientGone, asyncio.CancelledError):+ raise+ except Exception as e: # noqa: BLE001+ print(f"stream failed: {type(e).__name__}: {e}", flush=True)+ await resp.write(event(C.error_body(str(e), "server_error")))await resp.write(b"data: [DONE]\n\n")except (ConnectionError, ClientConnectionError, ClientGone) as e:print(f"client closed the stream ({type(e).__name__}): generation cancelled", flush=True)@@ -397,7 +407,7 @@ def build_app(st: State):try:need_ready()r = C.parse_chat(await read_body(request), args.default_max_tokens)- return web.json_response({"prompt": st.vocab.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])})+ return web.json_response({"prompt": st.vocab.template.render_chat(r)})except C.RequestError as e:return _err(e.status, str(e), e.code)diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.pyindex f20ccf0..174f7f4 100644--- a/tools/hy4/serve_core.py+++ b/tools/hy4/serve_core.py@@ -56,6 +56,10 @@ class ChatTemplate:self.source = sourceself.tpl = env.from_string(source)+ def render_chat(self, r: dict) -> str:+ """the prompt of a parsed chat request (parse_chat): its tools and effort; a prefill keeps the last assistant turn open"""+ return self.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"], **({"raw_last_assistant": True} if r.get("prefill") else {}))+def render(self, messages: list[dict], tools: list | None = None, add_generation_prompt: bool = True, **kwargs: Any) -> str:try:return self.tpl.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs)@@ -302,25 +306,17 @@ def _function_tool(t: Any, where: str) -> dict:return {"type": "function", "function": {k: v for k, v in fn.items() if k != "type" and v is not None}}-JSON_HINT = "Respond with a single valid JSON object and nothing else (no code fences, no commentary)."-JSON_SCHEMA_HINT = "Respond with a single valid JSON object that matches this JSON schema, and nothing else (no code fences, no commentary): "---def response_format_hint(body: dict) -> str:- """`response_format` -> the instruction line it adds to the system message. The decoder has no grammar: json_object and json_schema are best effort- (the model is told to answer with JSON), text is the default."""+def check_response_format(body: dict) -> None:+ """`response_format`: text is the default. json_object and json_schema need constrained decoding, which this decoder does not have: a clean 400 beats a reply+ that silently is not JSON."""rf = body.get("response_format")if rf is None:- return ""+ returnkind = rf.get("type") if isinstance(rf, dict) else None- if kind not in ("text", "json_object", "json_schema"):+ if kind in ("json_object", "json_schema"):+ raise RequestError(f"response_format {kind} is not supported yet (no constrained decoding): ask for JSON in the prompt instead")+ if kind != "text":raise RequestError("response_format.type must be text, json_object or json_schema")- if kind == "json_schema":- schema = (rf.get("json_schema") or {}).get("schema") if isinstance(rf.get("json_schema"), dict) else None- if not isinstance(schema, dict):- raise RequestError("response_format.json_schema.schema must be a JSON schema object")- return JSON_SCHEMA_HINT + json.dumps(schema, ensure_ascii=False)- return JSON_HINT if kind == "json_object" else ""TOOL_HINTS = {"required": "You must answer by calling one or more of the provided functions.",@@ -407,20 +403,27 @@ CHAT_ROLES = {"system": "system", "developer": "system", "user": "user", "assistdef parse_chat(body: dict, default_max: int = 1024) -> dict:- """-> {messages, effort, max_tokens, stream, stop, include_usage, speculative, tools, tool_choice, parse_tools, ...}. Raises RequestError.- Messages: assistant messages may carry tool_calls (arguments as a JSON string or an object), `tool` messages carry the result of a call (tool_call_id)."""+ """-> {messages, effort, max_tokens, stream, stop, include_usage, speculative, tools, tool_choice, parse_tools, prefill, ...}. Raises RequestError.+ Messages: assistant messages may carry tool_calls (arguments as a JSON string or an object), `tool` messages carry the result of a call (tool_call_id).+ All system / developer messages (and the instruction line of tool_choice) are merged into ONE leading system message, in order.+ A last assistant message is a prefill: the model continues it (`prefill` True; the template's raw_last_assistant); an empty one is dropped."""req = _common(body, default_max)req.update(parse_tools(body))+ check_response_format(body)msgs = body.get("messages")if not isinstance(msgs, list) or not msgs:raise RequestError("messages must be a non-empty list")- out = []+ system, out = [], []for i, m in enumerate(msgs):if not isinstance(m, dict) or m.get("role") not in CHAT_ROLES:raise RequestError(f"messages[{i}]: role must be system, user, assistant or tool")- role = CHAT_ROLES[m["role"]] # developer = system; the template renders a system message wherever it stands+ role = CHAT_ROLES[m["role"]] # developer = systemitem = {"role": role, "content": _content_text(m.get("content"))}rc = m.get("reasoning_content", m.get("reasoning"))+ if role == "system":+ if item["content"]:+ system.append(item["content"])+ continueif role == "assistant":if isinstance(rc, str) and rc:item["reasoning_content"] = rc@@ -434,15 +437,21 @@ def parse_chat(body: dict, default_max: int = 1024) -> dict:if tcid:item["tool_call_id"] = tcidout.append(item)- if out[-1]["role"] == "assistant":+ while out and out[-1]["role"] == "assistant" and not out[-1]["content"] and "tool_calls" not in out[-1]:+ out.pop() # an empty trailing assistant message is not a prefill+ if not out:+ raise RequestError("messages must contain a user message")+ prefill = out[-1]["role"] == "assistant"+ if prefill and "tool_calls" in out[-1]:+ raise RequestError("the last assistant message has tool_calls: add a tool message with each result")+ if prefill and len(out) < 2:raise RequestError("the last message must come from the user")- hint = "\n\n".join(h for h in (req.pop("tool_hint"), response_format_hint(body)) if h)- if hint: # instructions the template has no switch for: one block at the end of the leading system message- if out[0]["role"] == "system":- out[0] = dict(out[0], content=(out[0]["content"] + "\n\n" if out[0]["content"] else "") + hint)- else:- out.insert(0, {"role": "system", "content": hint})- req.update(messages=out, effort=parse_effort(body))+ if req["tool_hint"]:+ system.append(req["tool_hint"])+ if system:+ out.insert(0, {"role": "system", "content": "\n\n".join(system)})+ req.pop("tool_hint")+ req.update(messages=out, effort=parse_effort(body), prefill=prefill)return req