Skip to content

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.

Hy4 serve: OpenAI compatibility sweep of the chat request parser

YanissAmz04b3128c1686
diff --git a/tests/test_hy4_compat_cpu.py b/tests/test_hy4_compat_cpu.py
new file mode 100644
index 0000000..9e5aec8
--- /dev/null
+++ b/tests/test_hy4_compat_cpu.py
@@ -0,0 +1,174 @@
+"""CPU tests of the OpenAI-compatibility of the Hy4 chat request parser (tools/hy4/serve_core.py parse_chat) and of the server routes that use it:
+max_completion_tokens, stream_options, n, response_format, null / empty content parts, system and developer messages. No GPU, no model.
+Run: python -m pytest tests/test_hy4_compat_cpu.py (needs aiohttp + jinja2 + tokenizers)"""
+import json
+import os
+import sys
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools", "hy4"))
+sys.path.insert(0, HERE)
+import serve as S # noqa: E402
+import serve_core as C # noqa: E402
+from test_hy4_tools_cpu import ProdServer, make_state, tool_meta # noqa: E402
+from aiohttp.test_utils import TestClient # noqa: E402
+
+USER = [{"role": "user", "content": "hi"}]
+
+
+def parse(**body):
+ return C.parse_chat({"messages": USER, **body}, 99)
+
+
+class Parser(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.v = C.Vocab(tool_meta())
+
+ def render(self, r):
+ return self.v.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])
+
+ # -- max_completion_tokens
+ def test_max_completion_tokens_is_the_alias_of_max_tokens(self):
+ self.assertEqual(parse(max_completion_tokens=7)["max_tokens"], 7)
+ self.assertEqual(parse(max_tokens=8)["max_tokens"], 8)
+ self.assertEqual(parse(max_completion_tokens=7, max_tokens=8)["max_tokens"], 7) # the newer name wins
+ self.assertEqual(parse(max_completion_tokens=None, max_tokens=8)["max_tokens"], 8) # an explicit null does not hide max_tokens
+ self.assertEqual(parse(max_completion_tokens=None, max_tokens=None)["max_tokens"], 99)
+ for bad in (0, -1, "7", 1.5, True):
+ with self.assertRaises(C.RequestError, msg=str(bad)):
+ parse(max_completion_tokens=bad)
+ self.assertEqual(C.parse_completion({"prompt": "x", "max_completion_tokens": 5}, None)["max_tokens"], 5)
+
+ # -- stream_options
+ def test_stream_options(self):
+ self.assertTrue(parse(stream=True, stream_options={"include_usage": True})["include_usage"])
+ self.assertFalse(parse(stream=True, stream_options={"include_usage": False})["include_usage"])
+ self.assertFalse(parse(stream=True, stream_options=None)["include_usage"])
+ self.assertFalse(parse(stream=True, stream_options={})["include_usage"])
+ for bad in ("yes", ["include_usage"], 1):
+ with self.assertRaises(C.RequestError, msg=str(bad)): # was an AttributeError, so a 500
+ parse(stream=True, stream_options=bad)
+
+ # -- n
+ def test_n_above_one_is_a_clean_400(self):
+ self.assertEqual(parse(n=1)["max_tokens"], 99)
+ self.assertEqual(parse(n=None)["max_tokens"], 99)
+ for bad in (2, 0, -1, "2", 1.5):
+ with self.assertRaises(C.RequestError, msg=str(bad)) as cm:
+ parse(n=bad)
+ self.assertEqual((cm.exception.status, cm.exception.code), (400, "invalid_request_error"))
+ with self.assertRaises(C.RequestError) as cm:
+ parse(n=3)
+ self.assertIn("one choice", str(cm.exception))
+
+ # -- response_format
+ 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"}}):
+ 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 parts
+ def test_null_and_empty_content_parts(self):
+ def text(content):
+ return C.parse_chat({"messages": [{"role": "user", "content": content}]})["messages"][0]["content"]
+ self.assertEqual(text(None), "")
+ self.assertEqual(text(""), "")
+ self.assertEqual(text([]), "")
+ self.assertEqual(text([None, {"type": "text", "text": ""}, {"type": "text", "text": None}, {"type": "text"}]), "")
+ self.assertEqual(text([{"type": "text", "text": "a"}, None, {"type": "text", "text": "b"}, "c"]), "abc")
+ self.assertEqual(text([{"type": "input_text", "text": "a"}, {"type": "output_text", "text": "b"}, {"text": "c"}]), "abc")
+ for bad in ([{"type": "image_url", "image_url": {"url": "x"}}], [{"type": "audio"}], [{"type": "text", "text": 5}], [{}], 5, {"type": "text", "text": "x"}):
+ with self.assertRaises(C.RequestError, msg=str(bad)):
+ text(bad)
+
+ def test_empty_messages_still_render(self):
+ r = C.parse_chat({"messages": [{"role": "system", "content": None}, {"role": "user", "content": [None]}, {"role": "assistant", "content": ""},
+ {"role": "user", "content": ""}]})
+ self.assertTrue(self.render(r).endswith("<think:6124c78e>"))
+
+ # -- system and developer
+ 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"])
+ text = self.render(r)
+ 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"))
+
+ def test_unknown_role_is_a_400(self):
+ with self.assertRaises(C.RequestError):
+ C.parse_chat({"messages": [{"role": "robot", "content": "x"}, *USER]})
+
+
+class Http(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self):
+ self.st = make_state("Bonjour le monde")
+ self.client = TestClient(ProdServer(S.build_app(self.st)))
+ await self.client.start_server()
+
+ async def asyncTearDown(self):
+ await self.client.close()
+
+ async def chat(self, **body):
+ return await self.client.post("/v1/chat/completions", json={"messages": USER, "reasoning_effort": "no_think", **body})
+
+ async def test_max_completion_tokens_reaches_the_engine(self):
+ r = await self.chat(max_completion_tokens=4)
+ j = await r.json()
+ self.assertEqual((r.status, j["choices"][0]["message"]["content"], j["usage"]["completion_tokens"]), (200, "Bonj", 4))
+ self.assertEqual(self.st.engine.calls[-1][1], 4)
+
+ async def test_n_and_stream_options_errors_are_400_bodies(self):
+ for body in ({"n": 2}, {"stream": True, "stream_options": "yes"}, {"response_format": {"type": "xml"}}):
+ r = await self.chat(**body)
+ j = await r.json()
+ self.assertEqual(r.status, 400, body)
+ self.assertEqual(j["error"]["type"], "invalid_request_error")
+
+ async def test_stream_usage_chunk(self):
+ r = await self.chat(stream=True, stream_options={"include_usage": True})
+ events = [e[6:] for e in (await r.read()).decode().split("\n\n") if e.startswith("data: ")]
+ last = json.loads(events[-2])
+ self.assertEqual((last["choices"], last["usage"]["completion_tokens"]), ([], len("Bonjour le monde")))
+ r = await self.chat(stream=True)
+ 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_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}])
+ self.assertEqual(r.status, 200, await r.text())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_hy4_serve_core.py b/tests/test_hy4_serve_core.py
index 374c360..814fb7e 100644
--- a/tests/test_hy4_serve_core.py
+++ b/tests/test_hy4_serve_core.py
@@ -85,8 +85,7 @@ class Core(unittest.TestCase):
{"messages": [{"role": "user", "content": "x"}], "tools": [{"type": "function"}]},
{"messages": [{"role": "user", "content": "x"}], "max_tokens": 0},
{"messages": [{"role": "user", "content": "x"}], "stop": ["a"] * 9},
- {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "x"}}]}]},
- {"messages": [{"role": "user", "content": "x"}, {"role": "system", "content": "late"}]}]
+ {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "x"}}]}]}]
for b in bad:
with self.assertRaises(C.RequestError, msg=str(b)):
C.parse_chat(b)
diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.py
index 8eabec0..f20ccf0 100644
--- a/tools/hy4/serve_core.py
+++ b/tools/hy4/serve_core.py
@@ -229,15 +229,20 @@ def _common(body: dict, default_max: int) -> dict:
if not isinstance(body, dict):
raise RequestError("the body must be a JSON object")
if _as_int(body, "n", 1, 1) != 1:
- raise RequestError("n must be 1")
- mt = body.get("max_completion_tokens", body.get("max_tokens"))
+ raise RequestError("n must be 1: this server returns one choice per request")
+ mt = body.get("max_completion_tokens") # the newer name wins; an explicit null falls back to max_tokens
+ if mt is None:
+ mt = body.get("max_tokens")
max_tokens = default_max if mt is None else _as_int({"max_tokens": mt}, "max_tokens", default_max, 1)
for k in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
v = body.get(k)
if v is not None and (isinstance(v, bool) or not isinstance(v, (int, float))):
raise RequestError(f"{k} must be a number")
+ opts = body.get("stream_options")
+ if opts is not None and not isinstance(opts, dict):
+ raise RequestError("stream_options must be an object")
return {"max_tokens": max_tokens, "stream": bool(body.get("stream", False)), "stop": _stops(body),
- "include_usage": bool((body.get("stream_options") or {}).get("include_usage", False)),
+ "include_usage": bool((opts or {}).get("include_usage", False)),
# the speculative decoder is greedy: sampling parameters are accepted and ignored; reported back in the reply
"sampling_ignored": body.get("temperature") not in (None, 0, 0.0),
"speculative": body.get("speculative", True) is not False}
@@ -257,8 +262,11 @@ def parse_effort(body: dict) -> str:
return EFFORT_MAP[v]
+TEXT_PARTS = ("text", "input_text", "output_text")
+
+
def _content_text(c: Any) -> str:
- """OpenAI content (string, or a list of {type: text} parts) -> text"""
+ """OpenAI content (a string, null, or a list of {type: text} parts) -> text. Null parts and null / empty text are empty text."""
if c is None:
return ""
if isinstance(c, str):
@@ -266,10 +274,12 @@ def _content_text(c: Any) -> str:
if isinstance(c, list):
out = []
for p in c:
+ if p is None:
+ continue
if isinstance(p, str):
out.append(p)
- elif isinstance(p, dict) and p.get("type") == "text" and isinstance(p.get("text"), str):
- out.append(p["text"])
+ elif isinstance(p, dict) and (p.get("type") in TEXT_PARTS or (p.get("type") is None and "text" in p)) and (p.get("text") is None or isinstance(p["text"], str)):
+ out.append(p.get("text") or "")
else:
raise RequestError("only text content parts are supported (no images / audio)")
return "".join(out)
@@ -292,6 +302,27 @@ 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."""
+ rf = body.get("response_format")
+ if rf is None:
+ return ""
+ kind = rf.get("type") if isinstance(rf, dict) else None
+ if kind not in ("text", "json_object", "json_schema"):
+ 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.",
"function": "You must answer by calling the function {name}."}
@@ -387,9 +418,7 @@ def parse_chat(body: dict, default_max: int = 1024) -> dict:
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"]]
- if role == "system" and i != 0:
- raise RequestError(f"messages[{i}]: a system message is only allowed first")
+ role = CHAT_ROLES[m["role"]] # developer = system; the template renders a system message wherever it stands
item = {"role": role, "content": _content_text(m.get("content"))}
rc = m.get("reasoning_content", m.get("reasoning"))
if role == "assistant":
@@ -407,11 +436,12 @@ def parse_chat(body: dict, default_max: int = 1024) -> dict:
out.append(item)
if out[-1]["role"] == "assistant":
raise RequestError("the last message must come from the user")
- if req["tool_hint"]:
+ 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 "") + req["tool_hint"])
+ out[0] = dict(out[0], content=(out[0]["content"] + "\n\n" if out[0]["content"] else "") + hint)
else:
- out.insert(0, {"role": "system", "content": req["tool_hint"]})
+ out.insert(0, {"role": "system", "content": hint})
req.update(messages=out, effort=parse_effort(body))
return req