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 server: a refused or failed request never stops the server; named part errors, harmless parts accepted, KYOJIN_IMAGE_PARTS (issue #222)
YanissAmzfddd48f986fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 443011d..4b4aa3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,7 +15,16 @@- Hy4-flash: online speculative draft-depth gate, `HY4_SPEC2_GATE=1` (default off), mode `HY4_SPEC2_MODE=learn` (default, the measured S7 arm O), KB 2, THETA 0.6 for the `static` mode.Base draft graph of 2 steps plus a confidence-gated third step. Fires counter per request: depth chosen per round and rounds where the gate changed the depth.The gate's tail graph uses the same bucket helper as `HY4_GRAPH_BUCKET_REL`. See `doc/env_vars.md`.-- Hy4-flash server: `KYOJIN_IMAGE_PARTS=reject|note` (default `reject`, the 400 of 1.9.2 is unchanged). With `note`, each image part (`image_url`, `input_image`, `image`) and audio part (`input_audio`, `audio`) of a message of any role (user, assistant, `tool`) becomes a one-line text note, so an agent that attaches a screenshot to a tool result does not stop on a 400 (issue #222); text parts keep their order, other part types are still a 400. CPU tests: `tests/test_hy4_image_parts.py`. See `doc/env_vars.md`.+- Hy4-flash server fixes of issue #222, also released as 1.9.2.1: see the 1.9.2.1 section below (no hang after a refused request, named part errors, harmless parts accepted, `KYOJIN_IMAGE_PARTS` default `note`).++## 1.9.2.1++Hy4-flash server: a refused request must never stop the server, and fewer harmless content parts are refused (issue #222).++- A worker that fails while it flushes its output (or dies without its end event) no longer leaves the request handler waiting with the generation lock held: the end event is always sent, the lock is released, and the client gets a 500 (or an SSE error event followed by `[DONE]`). An unexpected exception in a request parser or the chat template is one JSON 500 and the server keeps answering. Every request check (content parts, tools, effort, `max_tokens`, `stop`, context size, JSON) runs before the lock and before the SSE response starts.+- Content parts: the 400 names the message and the part (`message 7, part 2: type 'video' is not supported`; indexes start at 0). Accepted now: `refusal` (as text), `reasoning` / `thinking` / `reasoning_content` parts of an assistant message (they become its `reasoning_content`; dropped in other roles), `redacted_thinking` (dropped), bare string parts, empty text, extra keys such as `cache_control`. Unknown types are still a 400. One table (`PART_ACTIONS` in `tools/hy4/serve_core.py`) adds a type.+- New `KYOJIN_IMAGE_PARTS=note|reject` (default `note`): each image, audio or file part of any message (user, assistant, tool) becomes one line of text such as `[an image was attached; this model cannot see images]` and the request is served, so agent clients that keep screenshots in their history keep working. `reject` is the strict 400 of 1.9.2. Any other value is `note` with one warning line. See `doc/env_vars.md`.+- New CPU tests: `tests/test_hy4_request_error.py` (every refused request, then a normal one answers, streamed or not), `tests/test_hy4_content_parts.py`.## 1.9.2diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 74cf8a2..08b40d2 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1076,12 +1076,15 @@ reset at every request, so a repeated request repeats its decisions), `static` ((depth chosen per round; `changed` = rounds where the gate cut the chain below the shipped depth; 0 means the gate did not fire) and `fires {...}` (rounds, depth2, gate_skip, gate_run).Rollback: unset the flag. See `tools/hy4/depth_gate.py`.-#### `KYOJIN_IMAGE_PARTS` (default `reject`)--Hy4-flash server only. The model reads text only. `reject` answers a chat request that has an image part (`image_url`, `input_image`, `image`) or an audio part-(`input_audio`, `audio`) with a 400, as in 1.9.2. `note` replaces each such part by one line of text and serves the request: `[an image was attached; this model cannot see images]`-or `[audio was attached; this model cannot hear audio]`. The text parts stay in order. It applies to every role, including `tool` results and assistant messages.-Other part types (video, file) are still a 400. Any other value keeps `reject`. Read at each request. For agents that attach screenshots to tool results and must not stop.+#### `KYOJIN_IMAGE_PARTS` (default `note`)++Hy4-flash server only. The model reads text only. `note` (default) replaces each image part (`image_url`, `input_image`, `image`), audio part (`input_audio`, `audio`) and+file part (`file`, `input_file`) of a chat message by one line of text and serves the request: `[an image was attached; this model cannot see images]`,+`[audio was attached; this model cannot hear audio]` or `[a file was attached; this model cannot read files]`. The text parts stay in order. It applies to every role,+including `tool` results and assistant messages, so an agent client that keeps screenshots in its history keeps working. `reject` is the strict mode: such a part is a 400+that names the message and the part (`message 3, part 1: type 'image_url' is not supported ...`). Any other value is `note` (one warning line in the log). Read at each+request. Other part types: `text`, `input_text`, `output_text` and `refusal` are text; `reasoning`, `thinking` and `reasoning_content` parts of an assistant message become+its `reasoning_content`; `redacted_thinking` is dropped; extra keys such as `cache_control` are ignored; unknown types are a 400 (table `PART_ACTIONS` in `tools/hy4/serve_core.py`).#### Hy4-flash 1.9.1 levers (all on by default; `=0` restores 1.9.0)diff --git a/doc/hy4.md b/doc/hy4.mdindex a2d0477..d2c1d49 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -48,7 +48,7 @@ curl http://127.0.0.1:8300/v1/chat/completions -H 'content-type: application/jsoHy4-flash thinks first by default (`reasoning_effort` high): the reasoning is returned in `reasoning_content`, the answer in `content`, and a small `max_tokens` can end inside the reasoning with `content` empty. `"reasoning_effort": "no_think"` (or `"chat_template_kwargs": {"reasoning_effort": "no_think"}`) answers directly; otherwise leave room, for example `max_tokens` 1024.-Tool calling (1.9.2): `tools` / `tool_choice` / `tool_calls` / `tool` messages work as in the OpenAI API, streamed or not (README "Tool calling"). `python tools/hy4/tool_smoke.py --base http://127.0.0.1:8300` runs the served check. A client that closes a stream stops the generation. Not supported: `n` > 1, `response_format` `json_object` / `json_schema` (400, no constrained decoding), images and audio (a 400; `KYOJIN_IMAGE_PARTS=note` turns each image or audio part into a one-line text note instead, see `doc/env_vars.md`).+Tool calling (1.9.2): `tools` / `tool_choice` / `tool_calls` / `tool` messages work as in the OpenAI API, streamed or not (README "Tool calling"). `python tools/hy4/tool_smoke.py --base http://127.0.0.1:8300` runs the served check. A client that closes a stream stops the generation. Not supported: `n` > 1, `response_format` `json_object` / `json_schema` (400, no constrained decoding). Images, audio and files cannot be read: each such content part becomes a one-line text note (`KYOJIN_IMAGE_PARTS=reject` makes it a 400, see `doc/env_vars.md`).The 1.9.1 levers are listed with their rollback switches in the [env_vars.md](env_vars.md) table "Hy4-flash 1.9.1 levers". After updating from 1.9.0 run `bash tools/hy4/install_strix.sh` again (the Q3_K V2 kernel needs the rebuilt MoE extension; without it the old kernel runs).diff --git a/tests/test_hy4_compat_cpu.py b/tests/test_hy4_compat_cpu.pyindex e09dbf1..463a41c 100644--- a/tests/test_hy4_compat_cpu.py+++ b/tests/test_hy4_compat_cpu.py@@ -86,7 +86,8 @@ class Parser(unittest.TestCase):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"}):+ self.assertIn("an image was attached", text([{"type": "image_url", "image_url": {"url": "x"}}])) # KYOJIN_IMAGE_PARTS default: note+ for bad in ([{"type": "video"}], [{"type": "text", "text": 5}], [{}], 5, {"type": "text", "text": "x"}):with self.assertRaises(C.RequestError, msg=str(bad)):text(bad)diff --git a/tests/test_hy4_content_parts.py b/tests/test_hy4_content_parts.pynew file mode 100644index 0000000..0e14fad--- /dev/null+++ b/tests/test_hy4_content_parts.py@@ -0,0 +1,173 @@+"""Content parts of a chat message: which types are read, which are refused, and how the refusal names the part. CPU only, no model.+Run: python -m unittest tests/test_hy4_content_parts.py"""+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"))+import serve_core as C # noqa: E402+++def parse(*msgs):+ return C.parse_chat({"messages": list(msgs)})+++def user_text(parts):+ return parse({"role": "user", "content": parts})["messages"][-1]["content"]+++class AcceptedParts(unittest.TestCase):+ def test_text_names(self):+ for t in ("text", "input_text", "output_text"):+ self.assertEqual(user_text([{"type": t, "text": "hi"}]), "hi", t)++ def test_refusal_is_text(self):+ r = parse({"role": "user", "content": "q"}, {"role": "assistant", "content": [{"type": "refusal", "refusal": "I cannot"}]}, {"role": "user", "content": "ok"})+ self.assertEqual(r["messages"][1]["content"], "I cannot")++ def test_extra_keys_ignored(self):+ self.assertEqual(user_text([{"type": "text", "text": "a", "cache_control": {"type": "ephemeral"}, "annotations": [], "x": 1}]), "a")++ def test_bare_string_and_null_parts(self):+ self.assertEqual(user_text(["a", None, {"type": "text", "text": "b"}, "c"]), "abc")++ def test_empty_and_null_text(self):+ self.assertEqual(user_text([{"type": "text", "text": ""}, {"type": "text", "text": None}, {"type": "text"}, {"text": "z"}]), "z")++ def test_order_of_surviving_parts(self):+ parts = [{"type": "text", "text": "1"}, {"type": "thinking", "thinking": "skip"}, "2", {"type": "redacted_thinking", "data": "x"},+ {"type": "output_text", "text": "3"}, {"type": "refusal", "refusal": "4"}, {"type": "input_text", "text": "5"}]+ self.assertEqual(user_text(parts), "12345")++ def test_reasoning_parts_become_reasoning_content_of_an_assistant(self):+ for kind, key in (("reasoning", "text"), ("thinking", "thinking"), ("reasoning_content", "text")):+ r = parse({"role": "user", "content": "q"},+ {"role": "assistant", "content": [{"type": kind, key: "because"}, {"type": "text", "text": "answer"}]},+ {"role": "user", "content": "next"})+ m = r["messages"][1]+ self.assertEqual((m["content"], m.get("reasoning_content")), ("answer", "because"), kind)++ def test_explicit_reasoning_field_wins(self):+ r = parse({"role": "user", "content": "q"},+ {"role": "assistant", "content": [{"type": "thinking", "thinking": "part"}, {"type": "text", "text": "a"}], "reasoning_content": "field"},+ {"role": "user", "content": "n"})+ self.assertEqual(r["messages"][1]["reasoning_content"], "field")++ def test_reasoning_parts_dropped_in_other_roles(self):+ r = parse({"role": "user", "content": [{"type": "thinking", "thinking": "x"}, {"type": "text", "text": "q"}]})+ self.assertEqual(r["messages"][0]["content"], "q")+ self.assertNotIn("reasoning_content", r["messages"][0])++ def test_tool_result_with_parts(self):+ r = parse({"role": "user", "content": "go"},+ {"role": "assistant", "content": None, "tool_calls": [{"id": "c", "type": "function", "function": {"name": "f", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c", "content": [{"type": "text", "text": "out", "cache_control": {}}, "put"]},+ {"role": "user", "content": "k"})+ self.assertEqual(r["messages"][2]["content"], "output")++ def test_table_is_the_only_gate(self):+ """one line in PART_ACTIONS adds a type"""+ C.PART_ACTIONS["my_text"] = "text"+ try:+ self.assertEqual(user_text([{"type": "my_text", "text": "ok"}]), "ok")+ finally:+ del C.PART_ACTIONS["my_text"]+++class MediaParts(unittest.TestCase):+ def setUp(self):+ self.old = os.environ.pop("KYOJIN_IMAGE_PARTS", None)++ def tearDown(self):+ os.environ.pop("KYOJIN_IMAGE_PARTS", None)+ if self.old is not None:+ os.environ["KYOJIN_IMAGE_PARTS"] = self.old++ def test_default_is_note_in_every_role_and_order(self):+ img = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA"}}+ want = {"image_url": "image", "input_image": "image", "image": "image", "input_audio": "audio", "audio": "audio", "file": "file", "input_file": "file"}+ for kind, what in want.items():+ self.assertEqual(user_text(["a", {"type": kind}, {"type": "text", "text": "b"}]), "a" + C.MEDIA_NOTES[what] + "b", kind)+ r = parse({"role": "system", "content": [img]}, {"role": "user", "content": "q"},+ {"role": "assistant", "content": [{"type": "text", "text": "x"}, img]}, {"role": "user", "content": [img, "k"]})+ self.assertEqual([m["content"] for m in r["messages"]], [C.MEDIA_NOTES["image"], "q", "x" + C.MEDIA_NOTES["image"], C.MEDIA_NOTES["image"] + "k"])++ def test_file_note_text(self):+ self.assertEqual(user_text([{"type": "file", "file": {"file_id": "f"}}]), "[a file was attached; this model cannot read files]")++ def test_reject_is_the_strict_400(self):+ os.environ["KYOJIN_IMAGE_PARTS"] = "reject"+ for kind in C.MEDIA_PARTS:+ with self.assertRaises(C.RequestError) as cm:+ parse({"role": "user", "content": [{"type": "text", "text": "a"}, {"type": kind}]})+ self.assertIn(f"message 0, part 1: type '{kind}' is not supported", str(cm.exception))++ def test_typo_falls_back_to_note_with_one_warning(self):+ import contextlib+ import io+ os.environ["KYOJIN_IMAGE_PARTS"] = "rejct"+ C._WARNED_IMAGE_PARTS.clear()+ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ self.assertEqual(user_text([{"type": "image_url"}]), C.MEDIA_NOTES["image"])+ self.assertEqual(user_text([{"type": "image_url"}]), C.MEDIA_NOTES["image"])+ self.assertEqual(buf.getvalue().count("KYOJIN_IMAGE_PARTS"), 1)++ def test_unknown_types_still_400_in_note_mode(self):+ with self.assertRaises(C.RequestError):+ parse({"role": "user", "content": [{"type": "video_url"}]})+++class RefusedParts(unittest.TestCase):+ def setUp(self):+ self.old = os.environ.get("KYOJIN_IMAGE_PARTS")+ os.environ["KYOJIN_IMAGE_PARTS"] = "reject"++ def tearDown(self):+ os.environ.pop("KYOJIN_IMAGE_PARTS", None)+ if self.old is not None:+ os.environ["KYOJIN_IMAGE_PARTS"] = self.old++ def refused(self, *msgs):+ with self.assertRaises(C.RequestError) as cm:+ parse(*msgs)+ self.assertEqual(cm.exception.status, 400)+ return str(cm.exception)++ def test_error_names_message_and_part(self):+ msgs = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}] * 3 + [+ {"role": "user", "content": "q"},+ {"role": "assistant", "content": [{"type": "text", "text": "x"}, "y", {"type": "video", "url": "u"}]},+ {"role": "user", "content": "z"}]+ self.assertEqual(self.refused(*msgs), "message 7, part 2: type 'video' is not supported")++ def test_unknown_type(self):+ self.assertEqual(self.refused({"role": "user", "content": [{"type": "citation", "text": "x"}]}), "message 0, part 0: type 'citation' is not supported")++ def test_media_parts_are_refused_under_reject(self):+ for kind, what in (("image_url", "image"), ("input_image", "image"), ("image", "image"), ("input_audio", "audio"), ("audio", "audio"), ("file", "file"),+ ("input_file", "file")):+ m = self.refused({"role": "user", "content": [{"type": "text", "text": "a"}, {"type": kind}]})+ self.assertIn(f"message 0, part 1: type '{kind}' is not supported", m)+ self.assertIn(what, m)++ def test_media_in_every_role_under_reject(self):+ img = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA"}}+ self.assertIn("message 0, part 0", self.refused({"role": "system", "content": [img]}))+ self.assertIn("message 2, part 1", self.refused(+ {"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}, {"role": "tool", "content": ["x", img]}, {"role": "user", "content": "k"}))++ def test_no_type_and_no_text(self):+ self.assertIn("type None is not supported", self.refused({"role": "user", "content": [{"foo": 1}]}))++ def test_non_string_text(self):+ self.assertIn("message 0, part 0", self.refused({"role": "user", "content": [{"type": "text", "text": 5}]}))++ def test_bad_part_and_bad_content(self):+ self.assertIn("message 0, part 1: a part must be", self.refused({"role": "user", "content": ["a", 3]}))+ self.assertIn("message 0: content must be", self.refused({"role": "user", "content": 5}))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_hy4_image_parts.py b/tests/test_hy4_image_parts.pydeleted file mode 100644index bd4880f..0000000--- a/tests/test_hy4_image_parts.py+++ /dev/null@@ -1,89 +0,0 @@-"""CPU tests of KYOJIN_IMAGE_PARTS (tools/hy4/serve_core.py _content_text / parse_chat): `reject` (default) answers 400 for image and audio content-parts, `note` replaces each by a one-line text note. No GPU, no model, no server.-Run: python -m pytest tests/test_hy4_image_parts.py (needs jinja2)"""-import os-import sys-import unittest-from unittest import mock--HERE = os.path.dirname(os.path.abspath(__file__))-sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools", "hy4"))-import serve_core as C # noqa: E402--IMG = "[an image was attached; this model cannot see images]"-AUD = "[audio was attached; this model cannot hear audio]"-IMAGE_PARTS = ({"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, {"type": "input_image", "image_url": "x"}, {"type": "image", "source": {}})-AUDIO_PARTS = ({"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}}, {"type": "audio", "audio": {}})---def env(mode):- e = {k: v for k, v in os.environ.items() if k != "KYOJIN_IMAGE_PARTS"}- if mode is not None:- e["KYOJIN_IMAGE_PARTS"] = mode- return mock.patch.dict(os.environ, e, clear=True)---def chat(*msgs):- return C.parse_chat({"messages": list(msgs)})["messages"]---class ImageParts(unittest.TestCase):- def test_default_and_reject_are_a_400(self):- for mode in (None, "", "reject", "REJECT", "typo"):- with env(mode):- for part in IMAGE_PARTS + AUDIO_PARTS:- with self.assertRaises(C.RequestError, msg=f"{mode} {part}") as cm:- C._content_text([{"type": "text", "text": "a"}, part])- self.assertEqual(cm.exception.status, 400)- self.assertIn("only text content parts", str(cm.exception))-- def test_note_replaces_each_part_in_order(self):- with env("note"):- for part in IMAGE_PARTS:- self.assertEqual(C._content_text([part]), IMG)- for part in AUDIO_PARTS:- self.assertEqual(C._content_text([part]), AUD)- mixed = [{"type": "text", "text": "look: "}, IMAGE_PARTS[0], {"type": "text", "text": " and "}, AUDIO_PARTS[0], IMAGE_PARTS[1], None, "end"]- self.assertEqual(C._content_text(mixed), f"look: {IMG} and {AUD}{IMG}end")- self.assertEqual(C._content_text("plain"), "plain")- self.assertEqual(C._content_text(None), "")-- def test_note_mode_is_read_per_call(self):- part = [IMAGE_PARTS[0]]- with env("note"):- self.assertEqual(C._content_text(part), IMG)- with env("reject"), self.assertRaises(C.RequestError):- C._content_text(part)-- def test_unknown_parts_still_rejected_in_note_mode(self):- with env("note"):- for bad in ([{"type": "video_url", "video_url": {}}], [{"type": "file", "file": {}}], [{"type": "text", "text": 5}], [{}], [{"type": "image_url"}, {"type": "refusal"}], 5):- with self.assertRaises(C.RequestError, msg=str(bad)):- C._content_text(bad)-- def test_every_role_in_a_chat(self):- tool_call = {"id": "c1", "type": "function", "function": {"name": "shot", "arguments": "{}"}}- msgs = [{"role": "user", "content": [{"type": "text", "text": "what is this?"}, IMAGE_PARTS[0]]},- {"role": "assistant", "content": [{"type": "text", "text": "let me look"}, IMAGE_PARTS[1]], "tool_calls": [tool_call]},- {"role": "tool", "tool_call_id": "c1", "content": [IMAGE_PARTS[0], {"type": "text", "text": "screenshot"}, AUDIO_PARTS[0]]},- {"role": "user", "content": [{"type": "text", "text": "and now?"}]}]- with env("note"):- out = chat(*msgs)- self.assertEqual(out[0]["content"], f"what is this?{IMG}")- self.assertEqual(out[1]["content"], f"let me look{IMG}")- self.assertEqual(out[1]["tool_calls"][0]["function"]["name"], "shot")- self.assertEqual(out[2], {"role": "tool", "content": f"{IMG}screenshot{AUD}", "tool_call_id": "c1"})- self.assertEqual(out[3]["content"], "and now?")- with env(None): # default: the same chat is a 400, whichever role carries the part- for m in msgs[:3]:- with self.assertRaises(C.RequestError, msg=m["role"]):- chat({"role": "user", "content": "q"}, m, {"role": "user", "content": "x"})-- def test_system_message_with_image_part(self):- with env("note"):- out = chat({"role": "system", "content": [{"type": "text", "text": "rules "}, IMAGE_PARTS[0]]}, {"role": "user", "content": "hi"})- self.assertEqual(out[0], {"role": "system", "content": f"rules {IMG}"})---if __name__ == "__main__":- unittest.main()diff --git a/tests/test_hy4_request_error.py b/tests/test_hy4_request_error.pynew file mode 100644index 0000000..99c8708--- /dev/null+++ b/tests/test_hy4_request_error.py@@ -0,0 +1,276 @@+"""A request that fails (400 / 503 / client gone / engine error) must leave the server answering: the next normal request gets its reply.+CPU test of tools/hy4/serve.py with a fake engine (no GPU, no model). Every call has a timeout, so a stuck server fails the test fast.+Run: python -m unittest tests/test_hy4_request_error.py (needs aiohttp + jinja2 + tokenizers)"""+import asyncio+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+from test_hy4_serve_http import make_state # noqa: E402++try:+ from aiohttp.test_utils import TestClient, TestServer+except ImportError: # pragma: no cover+ TestClient = None++TMO = 10+IMG = {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}+TXT = {"type": "text", "text": "what is this"}+USER = {"role": "user", "content": "salut"}+NOTHINK = {"reasoning_effort": "no_think", "max_tokens": 50}+++def bad_cases():+ """(name, path, body): every one must be refused with a 400"""+ chat = "/v1/chat/completions"+ cases = [+ ("image_user", chat, {"messages": [{"role": "user", "content": [TXT, IMG]}]}),+ ("image_only", chat, {"messages": [{"role": "user", "content": [IMG]}]}),+ ("image_tool_result", chat, {"messages": [+ {"role": "user", "content": "go"},+ {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c1", "content": [TXT, IMG]},+ {"role": "user", "content": "and now"}]}),+ ("image_assistant", chat, {"messages": [{"role": "user", "content": "a"}, {"role": "assistant", "content": [TXT, IMG]}, {"role": "user", "content": "b"}]}),+ ("image_system", chat, {"messages": [{"role": "system", "content": [IMG]}, USER]}),+ ("audio_part", chat, {"messages": [{"role": "user", "content": [{"type": "input_audio", "input_audio": {"data": "AA", "format": "wav"}}]}]}),+ ("unknown_part", chat, {"messages": [USER, {"role": "assistant", "content": "a"}, {"role": "user", "content": [TXT, {"type": "video", "url": "u"}]}]}),+ ("content_number", chat, {"messages": [{"role": "user", "content": 5}]}),+ ("empty_messages", chat, {"messages": []}),+ ("no_messages", chat, {}),+ ("bad_tools", chat, {"messages": [USER], "tools": [1]}),+ ("tools_not_list", chat, {"messages": [USER], "tools": "x"}),+ ("tool_choice_needs_tools", chat, {"messages": [USER], "tool_choice": "required"}),+ ("bad_effort", chat, {"messages": [USER], "reasoning_effort": "ultra"}),+ ("bad_max_tokens", chat, {"messages": [USER], "max_tokens": "many"}),+ ("bad_stop", chat, {"messages": [USER], "stop": 5}),+ ("json_format", chat, {"messages": [USER], "response_format": {"type": "json_object"}}),+ ("oversize_prompt", chat, {"messages": [{"role": "user", "content": "x " * 20000}], "reasoning_effort": "no_think"}),+ ("oversize_max_tokens", chat, {"messages": [USER], "max_tokens": 999999}),+ ("completion_empty", "/v1/completions", {"prompt": ""}),+ ("completion_oversize", "/v1/completions", {"prompt": "x", "max_tokens": 99999}),+ ]+ out = []+ for name, path, body in cases:+ out.append((name, path, body))+ out.append((name + "_stream", path, dict(body, stream=True)))+ return out++[email protected](TestClient is None, "aiohttp not installed")+class RequestError(unittest.IsolatedAsyncioTestCase):+ async def asyncSetUp(self):+ self.old_mode = os.environ.get("KYOJIN_IMAGE_PARTS")+ os.environ["KYOJIN_IMAGE_PARTS"] = "reject" # the strict 400; the default (note) has its own tests below+ self.st = make_state("Bonjour le monde")+ self.st.lock = asyncio.Lock()+ self.client = TestClient(TestServer(S.build_app(self.st)))+ await self.client.start_server()++ async def asyncTearDown(self):+ await self.client.close()+ os.environ.pop("KYOJIN_IMAGE_PARTS", None)+ if self.old_mode is not None:+ os.environ["KYOJIN_IMAGE_PARTS"] = self.old_mode++ async def post(self, path, body=None, **kw):+ async def go():+ r = await self.client.post(path, json=body, **kw) if body is not None else await self.client.post(path, **kw)+ return r.status, await r.read()+ return await asyncio.wait_for(go(), TMO)++ async def normal(self, stream=False):+ """a normal chat request answers 200 with the reply, and the lock is free"""+ body = dict(messages=[USER], stream=stream, **NOTHINK)+ status, raw = await self.post("/v1/chat/completions", body)+ self.assertEqual(status, 200, raw[:300])+ if stream:+ text = "".join(c["choices"][0]["delta"].get("content", "") for c in (json.loads(l[6:]) for l in raw.decode().split("\n\n") if l.startswith("data: {")) if c["choices"])+ self.assertTrue(raw.rstrip().endswith(b"[DONE]"))+ else:+ text = json.loads(raw)["choices"][0]["message"]["content"]+ self.assertEqual(text, "Bonjour le monde")+ self.assertFalse(self.st.lock.locked())++ async def test_refused_request_then_normal(self):+ for name, path, body in bad_cases():+ with self.subTest(name):+ status, raw = await self.post(path, body)+ self.assertEqual(status, 400, raw[:300])+ self.assertIn(b"error", raw)+ self.assertFalse(self.st.lock.locked())+ await self.normal(stream=False)+ await self.normal(stream=True)+ self.assertEqual(self.st.engine.calls.__len__(), 2 * len(bad_cases())) # a refused request never reached the engine++ async def test_media_parts_answer_by_default(self):+ """KYOJIN_IMAGE_PARTS unset = note: the image / audio request is served, the model reads the note"""+ del os.environ["KYOJIN_IMAGE_PARTS"]+ n = 0+ for name, path, body in bad_cases():+ if not name.startswith(("image_", "audio_")):+ continue+ status, raw = await self.post(path, dict(body, max_tokens=50, reasoning_effort="no_think"))+ self.assertEqual(status, 200, (name, raw[:300]))+ n += 1+ self.assertEqual(n, 12)+ self.assertIn("an image was attached", self.st.vocab.decode(self.st.engine.calls[0][0]))+ await self.normal()++ async def test_omp_shaped_request_then_normal(self):+ """an agent client (omp): system + user text, an assistant tool call, a tool result that carries an image_url part, tools with JSON-schema parameters+ (nested objects, enums, anyOf, arrays). Served streamed and not, then a normal request answers; under reject the same request is a 400 and the next one answers"""+ del os.environ["KYOJIN_IMAGE_PARTS"]+ tools = [+ {"type": "function", "function": {"name": "read_file", "description": "read a file", "parameters": {+ "type": "object", "properties": {"path": {"type": "string"}, "range": {"type": "object", "properties": {+ "start": {"type": "integer"}, "end": {"anyOf": [{"type": "integer"}, {"type": "null"}]}}}}, "required": ["path"]}}},+ {"type": "function", "function": {"name": "screenshot", "description": "take a screenshot", "parameters": {+ "type": "object", "properties": {"target": {"type": "string", "enum": ["screen", "window", "region"]},+ "regions": {"type": "array", "items": {"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}}}}},+ "additionalProperties": False}}},+ ]+ msgs = [+ {"role": "system", "content": "You are a coding agent."},+ {"role": "user", "content": [{"type": "text", "text": "look at the screen"}]},+ {"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "screenshot", "arguments": "{\"target\": \"screen\"}"}}]},+ {"role": "tool", "tool_call_id": "call_1", "content": [{"type": "text", "text": "ok"}, IMG]},+ {"role": "user", "content": [IMG, {"type": "text", "text": "and now?"}]},+ ]+ for stream in (False, True):+ status, raw = await self.post("/v1/chat/completions", dict(messages=msgs, tools=tools, tool_choice="auto", stream=stream, **NOTHINK))+ self.assertEqual(status, 200, raw[:300])+ await self.normal(stream)+ prompt = self.st.vocab.decode(self.st.engine.calls[0][0])+ self.assertIn("an image was attached", prompt)+ self.assertIn("screenshot", prompt)+ os.environ["KYOJIN_IMAGE_PARTS"] = "reject"+ for stream in (False, True):+ status, raw = await self.post("/v1/chat/completions", dict(messages=msgs, tools=tools, stream=stream, **NOTHINK))+ self.assertEqual(status, 400, raw[:300])+ self.assertIn(b"message 3, part 1: type 'image_url' is not supported", raw)+ await self.normal(stream)++ async def test_accepted_parts_answer_and_refused_part_is_named(self):+ parts = [{"type": "text", "text": "salut", "cache_control": {"type": "ephemeral"}}, "!", {"type": "thinking", "thinking": "hm"}]+ history = [USER, {"role": "assistant", "content": [{"type": "refusal", "refusal": "no"}, {"type": "reasoning", "text": "r"}]}, {"role": "user", "content": parts}]+ for stream in (False, True):+ status, raw = await self.post("/v1/chat/completions", dict(messages=history, stream=stream, **NOTHINK))+ self.assertEqual(status, 200, raw[:300])+ status, raw = await self.post("/v1/chat/completions", dict(messages=history[:2] + [{"role": "user", "content": [TXT, {"type": "video"}]}]))+ self.assertEqual(status, 400)+ self.assertIn(b"message 2, part 1: type 'video' is not supported", raw)++ async def test_bad_json_then_normal(self):+ for stream in (False, True):+ status, raw = await self.post("/v1/chat/completions", data=b"{not json", headers={"Content-Type": "application/json"})+ self.assertEqual(status, 400, raw)+ await self.normal(stream)++ async def test_image_flood_then_normal(self):+ """many refused requests in a row, some at the same time as a good one"""+ bad = {"messages": [{"role": "user", "content": [TXT, IMG]}]}+ res = await asyncio.wait_for(asyncio.gather(*[self.post("/v1/chat/completions", dict(bad, stream=i % 2 == 0)) for i in range(20)]), TMO)+ self.assertTrue(all(s == 400 for s, _ in res))+ await self.normal()++ async def test_not_ready_then_normal(self):+ self.st.ready = False+ status, _ = await self.post("/v1/chat/completions", dict(messages=[USER], **NOTHINK))+ self.assertEqual(status, 503)+ self.st.ready = True+ await self.normal()++ async def test_engine_error_releases(self):+ """the engine raises: 500 (not streamed) or an error event (streamed), then a normal request answers"""+ good = self.st.engine.generate++ def boom(*a, **k):+ raise RuntimeError("engine exploded")+ self.st.engine.generate = boom+ status, raw = await self.post("/v1/chat/completions", dict(messages=[USER], **NOTHINK))+ self.assertEqual(status, 500, raw)+ status, raw = await self.post("/v1/chat/completions", dict(messages=[USER], stream=True, **NOTHINK))+ self.assertEqual(status, 200)+ self.assertIn(b"engine exploded", raw)+ self.assertIn(b"[DONE]", raw)+ self.st.engine.generate = good+ await self.normal()+ await self.normal(stream=True)++ async def test_output_flush_error_releases(self):+ """the output stream raises while the worker flushes (and the engine raised first): the handler still gets its end event, the lock comes back"""+ import serve_core as C+ flush = C.OutputStream.finish++ def bad_finish(self):+ raise ValueError("flush exploded")+ good = self.st.engine.generate++ def boom(*a, **k):+ raise RuntimeError("engine exploded")+ C.OutputStream.finish = bad_finish+ try:+ for engine in (boom, good):+ self.st.engine.generate = engine+ status, raw = await self.post("/v1/chat/completions", dict(messages=[USER], **NOTHINK))+ self.assertEqual(status, 500, raw)+ status, raw = await self.post("/v1/chat/completions", dict(messages=[USER], stream=True, **NOTHINK))+ self.assertIn(b"exploded", raw)+ self.assertIn(b"[DONE]", raw)+ self.assertFalse(self.st.lock.locked())+ finally:+ C.OutputStream.finish = flush+ self.st.engine.generate = good+ await self.normal()++ async def test_parser_bug_is_a_500_and_the_server_lives(self):+ """an unexpected exception in a request parser (not a RequestError) is one 500 JSON error, then a normal request answers"""+ import serve_core as C+ parse = C.parse_chat++ def bug(*a, **k):+ raise KeyError("oops")+ C.parse_chat = bug+ try:+ for path in ("/v1/chat/completions", "/apply-template", "/tokenize"):+ status, raw = await self.post(path, dict(messages=[USER], **NOTHINK))+ self.assertEqual(status, 500, raw)+ self.assertIn(b"server_error", raw)+ finally:+ C.parse_chat = parse+ await self.normal()++ async def test_client_disconnect_releases(self):+ """the client drops a streamed request mid-generation: the lock comes back and the next request answers"""+ slow = self.st.engine.generate+ gate = asyncio.Event()++ def slow_gen(ids, max_new, on_tokens, speculative=True, cancel=lambda: False):+ import time+ on_tokens(self.st.engine.ids[:1])+ t0 = time.time()+ while not cancel() and time.time() - t0 < 5:+ time.sleep(0.02)+ return slow(ids, 1, on_tokens, speculative, cancel)+ self.st.engine.generate = slow_gen+ resp = await self.client.post("/v1/chat/completions", json=dict(messages=[USER], stream=True, **NOTHINK))+ await asyncio.wait_for(resp.content.readany(), TMO)+ resp.close()+ del gate+ for _ in range(100):+ if not self.st.lock.locked():+ break+ await asyncio.sleep(0.1)+ self.assertFalse(self.st.lock.locked())+ self.st.engine.generate = slow+ await self.normal()+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_hy4_serve_core.py b/tests/test_hy4_serve_core.pyindex 814fb7e..b6df21f 100644--- a/tests/test_hy4_serve_core.py+++ b/tests/test_hy4_serve_core.py@@ -85,7 +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": [{"type": "video_url", "video_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.py b/tools/hy4/serve.pyindex 4bcc599..e22a942 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -239,18 +239,25 @@ def build_app(st: State):return out.donedef work():+ # the ("end",) event MUST reach the queue whatever happens here (the engine raises, the output flush raises): the handler holds st.lock until it reads ittry:- res["stats"] = st.engine.generate(ids, r["max_tokens"], on_tokens, speculative=r["speculative"], cancel=cancel.is_set)+ try:+ res["stats"] = st.engine.generate(ids, r["max_tokens"], on_tokens, speculative=r["speculative"], cancel=cancel.is_set)+ except Exception as e: # noqa: BLE001+ traceback.print_exc()+ res["error"] = f"{type(e).__name__}: {e}"+ finally:+ for ch, tx in out.finish():+ loop.call_soon_threadsafe(q.put_nowait, ("delta", ch, tx))except Exception as e: # noqa: BLE001traceback.print_exc()- res["error"] = f"{type(e).__name__}: {e}"+ res.setdefault("error", f"{type(e).__name__}: {e}")finally:- for ch, tx in out.finish():- loop.call_soon_threadsafe(q.put_nowait, ("delta", ch, tx))loop.call_soon_threadsafe(q.put_nowait, ("end",))async with st.lock:fut = loop.run_in_executor(None, work)+ fut.add_done_callback(lambda _f: q.put_nowait(("end",))) # belt and braces: a worker that died without its own end event still frees the handlerwatcher = watch_client(request, q)try:while True:@@ -361,6 +368,9 @@ def build_app(st: State):return web.Response(status=499)except RuntimeError as e:return _err(500, str(e), "server_error")+ except Exception as e: # noqa: BLE001 (a bug in a parser or a template: one 500, the server keeps answering)+ traceback.print_exc()+ return _err(500, f"{type(e).__name__}: {e}", "server_error")async def completions(request):try:@@ -399,6 +409,9 @@ def build_app(st: State):return web.Response(status=499)except RuntimeError as e:return _err(500, str(e), "server_error")+ except Exception as e: # noqa: BLE001 (a bug in a parser or a template: one 500, the server keeps answering)+ traceback.print_exc()+ return _err(500, f"{type(e).__name__}: {e}", "server_error")async def tokenize(request):try:@@ -411,6 +424,9 @@ def build_app(st: State):return web.json_response(serve_compat.tokenize_reply(ids, args.max_ctx))except C.RequestError as e:return _err(e.status, str(e), e.code)+ except Exception as e: # noqa: BLE001+ traceback.print_exc()+ return _err(500, f"{type(e).__name__}: {e}", "server_error")async def apply_template(request):try:@@ -419,6 +435,9 @@ def build_app(st: State):return web.json_response({"prompt": st.vocab.chat_prompt(r)[0]})except C.RequestError as e:return _err(e.status, str(e), e.code)+ except Exception as e: # noqa: BLE001+ traceback.print_exc()+ return _err(500, f"{type(e).__name__}: {e}", "server_error")app = web.Application(client_max_size=64 * 1024 * 1024)app.router.add_get("/health", health)diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.pyindex eb4f378..6a17c7f 100644--- a/tools/hy4/serve_core.py+++ b/tools/hy4/serve_core.py@@ -275,40 +275,90 @@ def parse_effort(body: dict) -> str:return EFFORT_MAP[v]-TEXT_PARTS = ("text", "input_text", "output_text")-IMAGE_PARTS = ("image_url", "input_image", "image")-AUDIO_PARTS = ("input_audio", "audio")-IMAGE_NOTE = "[an image was attached; this model cannot see images]"-AUDIO_NOTE = "[audio was attached; this model cannot hear audio]"---def _image_parts_note() -> bool:- """KYOJIN_IMAGE_PARTS=note: image / audio parts become a short text note. Anything else (unset, `reject`, a typo) keeps the 400. Read per call."""- return os.environ.get("KYOJIN_IMAGE_PARTS", "").strip().lower() == "note"---def _content_text(c: Any) -> str:- """OpenAI content (a string, null, or a list of {type: text} parts) -> text. Null parts and null / empty text are empty text.- Image and audio parts are a 400, or with KYOJIN_IMAGE_PARTS=note one short text note each (every role: user, assistant, tool)."""+# Content part types a chat message may carry -> what the server does with them. One line adds a type.+# text the part's text is kept, in order (any other key of the part, such as cache_control, is ignored)+# reasoning prior reasoning of an assistant message: it becomes the message's reasoning_content (the template decides what it shows); in other roles it is dropped+# drop ignored+# Image / audio / file parts (MEDIA_PARTS) cannot be read by the model: each becomes one line of text (KYOJIN_IMAGE_PARTS=note, the default) or a 400 that names the part (reject). A type that is in neither table is a 400 too.+PART_ACTIONS = {"text": "text", "input_text": "text", "output_text": "text", "refusal": "text",+ "reasoning": "reasoning", "thinking": "reasoning", "reasoning_content": "reasoning", "redacted_thinking": "drop"}+MEDIA_PARTS = {"image_url": "image", "input_image": "image", "image": "image", "input_audio": "audio", "audio": "audio", "file": "file", "input_file": "file"}+PART_TEXT_KEYS = ("text", "refusal", "thinking", "reasoning", "reasoning_content", "content")+++def _part_text(p: dict) -> str:+ """the text of a text / refusal / reasoning part: the first string among its text-like keys (null or missing = empty text)"""+ for k in PART_TEXT_KEYS:+ if isinstance(p.get(k), str):+ return p[k]+ return ""+++MEDIA_NOTES = {"image": "[an image was attached; this model cannot see images]",+ "audio": "[audio was attached; this model cannot hear audio]",+ "file": "[a file was attached; this model cannot read files]"}+_WARNED_IMAGE_PARTS: set = set()+++def image_parts_mode() -> str:+ """KYOJIN_IMAGE_PARTS: `note` (default) replaces each image / audio / file part by one line of text; `reject` is the strict 400. Any other value is `note`+ (one warning line per value). Read at each request."""+ v = os.environ.get("KYOJIN_IMAGE_PARTS", "").strip().lower()+ if v in ("", "note", "reject"):+ return v or "note"+ if v not in _WARNED_IMAGE_PARTS:+ _WARNED_IMAGE_PARTS.add(v)+ print(f"warning: KYOJIN_IMAGE_PARTS={v!r} is not note or reject: using note", flush=True)+ return "note"+++def _media_part(kind: str) -> str | None:+ """the text a media part of this kind (image, audio, file) is replaced by, or None to refuse it (KYOJIN_IMAGE_PARTS=reject)"""+ return MEDIA_NOTES[kind] if image_parts_mode() == "note" else None+++def _content(c: Any, where: str = "content") -> tuple[str, str]:+ """OpenAI content (a string, null, or a list of parts) -> (text, reasoning). `where` names the message in errors ("message 7").+ A part is a bare string, or a dict whose `type` is a PART_ACTIONS key (no type and a `text` key = text). Null parts are skipped. Null / empty text is empty text.+ A part that cannot be used is a RequestError naming the message and the part: "message 7, part 2: type 'video' is not supported"."""if c is None:- return ""+ return "", ""if isinstance(c, str):- return c- 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") 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 "")- elif isinstance(p, dict) and p.get("type") in IMAGE_PARTS + AUDIO_PARTS and _image_parts_note():- out.append(IMAGE_NOTE if p["type"] in IMAGE_PARTS else AUDIO_NOTE)- else:- raise RequestError("only text content parts are supported (no images / audio)")- return "".join(out)- raise RequestError("message content must be a string or a list of text parts")+ return c, ""+ if not isinstance(c, list):+ raise RequestError(f"{where}: content must be a string or a list of parts")+ text, reasoning = [], []+ for j, p in enumerate(c):+ if p is None:+ continue+ if isinstance(p, str):+ text.append(p)+ continue+ if not isinstance(p, dict):+ raise RequestError(f"{where}, part {j}: a part must be a string or an object")+ kind = p.get("type")+ if kind is None and "text" in p:+ kind = "text"+ action = PART_ACTIONS.get(kind) if isinstance(kind, str) else None+ if action == "text" and any(p.get(k) is not None and not isinstance(p[k], str) for k in PART_TEXT_KEYS[:2]):+ raise RequestError(f"{where}, part {j}: the text of a {kind!r} part must be a string")+ if action == "text":+ text.append(_part_text(p))+ elif action == "reasoning":+ reasoning.append(_part_text(p))+ elif action == "drop":+ continue+ elif isinstance(kind, str) and kind in MEDIA_PARTS and _media_part(MEDIA_PARTS[kind]) is not None:+ text.append(_media_part(MEDIA_PARTS[kind]))+ elif isinstance(kind, str) and kind in MEDIA_PARTS:+ raise RequestError(f"{where}, part {j}: type {kind!r} is not supported (this model reads text only: no {MEDIA_PARTS[kind]} parts)")+ else:+ raise RequestError(f"{where}, part {j}: type {kind!r} is not supported")+ return "".join(text), "".join(reasoning)+++def _content_text(c: Any, where: str = "content") -> str:+ return _content(c, where)[0]def _function_tool(t: Any, where: str) -> dict:@@ -436,8 +486,11 @@ def parse_chat(body: dict, default_max: int = 1024) -> dict: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- item = {"role": role, "content": _content_text(m.get("content"))}+ content, part_reasoning = _content(m.get("content"), f"message {i}")+ item = {"role": role, "content": content}rc = m.get("reasoning_content", m.get("reasoning"))+ if not (isinstance(rc, str) and rc) and role == "assistant":+ rc = part_reasoning # reasoning parts of the content (an explicit reasoning_content field wins)if role == "system":if item["content"]:system.append(item["content"])