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 server: a refused or failed request never stops the server; named part errors, harmless parts accepted, KYOJIN_IMAGE_PARTS (issue #222)

YanissAmz4088947e3f46
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ffb4616..07eda55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,14 @@
# Changelog
+## Unreleased (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.2
Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, request-parser fixes, Strix install fixes, docs.
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 22740e3..fabaddf 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1063,6 +1063,16 @@ weights. `on` (also `1`, `preset`, `true`, `yes`) loads the preset bundled in th
spec. Unset, empty, `0`, `off`, `false`, `no` and `none`: no edit is installed. A malformed spec or a missing file stops
the load. The preset is in `presets/hy4-uncensor/`. See [hy4.md](hy4.md).
+#### `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)
Hy4-flash server only. `tools/hy4/serve.py` sets these in `SHIPPED_ENV` without overriding a value you set, so `HY4_<FLAG>=0 python tools/hy4/serve.py ...` is the rollback of one lever to the 1.9.0 behaviour. The levers are independent of each other. Guide: [hy4.md](hy4.md).
diff --git a/doc/hy4.md b/doc/hy4.md
index b759667..a6739a9 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/jso
Hy4-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.
+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.py
index 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.py
new file mode 100644
index 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_request_error.py b/tests/test_hy4_request_error.py
new file mode 100644
index 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.py
index 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.py
index 36a6b0d..0020529 100644
--- a/tools/hy4/serve.py
+++ b/tools/hy4/serve.py
@@ -235,18 +235,25 @@ def build_app(st: State):
return out.done
def 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 it
try:
- 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: BLE001
traceback.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 handler
watcher = watch_client(request, q)
try:
while True:
@@ -352,6 +359,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:
@@ -390,6 +400,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:
@@ -402,6 +415,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:
@@ -410,6 +426,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.py
index 9450dd3..6a17c7f 100644
--- a/tools/hy4/serve_core.py
+++ b/tools/hy4/serve_core.py
@@ -275,28 +275,90 @@ 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 (a string, null, or a list of {type: text} parts) -> text. Null parts and null / empty text are empty text."""
+# 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 "")
- 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:
@@ -424,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"])