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 tool calling, and a quiet exit when the client leaves

YanissAmz945e6a023044
diff --git a/tests/test_hy4_tools_cpu.py b/tests/test_hy4_tools_cpu.py
new file mode 100644
index 0000000..a84014d
--- /dev/null
+++ b/tests/test_hy4_tools_cpu.py
@@ -0,0 +1,586 @@
+"""CPU tests of Hy4 tool calling (tools/hy4/serve_core.py + serve.py): the request side (tools, tool_choice, assistant tool_calls, tool messages), the prompt the chat
+template makes from them, the parser that reads the model's tool calls back out of the generated text (streamed in pieces of any size), the OpenAI response
+shapes (message.tool_calls, streamed delta.tool_calls, finish_reason), and a client that closes the stream. No GPU, no model: a fake engine replays a fixed text.
+Run: python -m pytest tests/test_hy4_tools_cpu.py (needs aiohttp + jinja2 + tokenizers)
+
+The tag format (every tag carries the template suffix, here ":6124c78e") is the one of tests/data/hy4_chat_template.jinja:
+ <tool_calls:S><tool_call:S>NAME<arg_key:S>K</arg_key:S><arg_value:S>V</arg_value:S>...</tool_call:S>...</tool_calls:S>
+and a tool result is written back as <|hy_start:S|>tool<|hy_middle:S|><tool_response:S>RESULT</tool_response:S><|hy_end:S|>."""
+import argparse
+import asyncio
+import contextlib
+import io
+import json
+import os
+import random
+import sys
+import threading
+import time
+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_serve_core import TK, tiny_meta # noqa: E402
+
+from aiohttp import ClientConnectionResetError, web # noqa: E402
+from aiohttp.test_utils import TestClient, TestServer # noqa: E402
+
+THINK, UNTHINK = f"<think{TK}>", f"</think{TK}>"
+START, MIDDLE, END = f"<|hy_start{TK}|>", f"<|hy_middle{TK}|>", f"<|hy_end{TK}|>"
+CALLS, ENDCALLS = f"<tool_calls{TK}>", f"</tool_calls{TK}>"
+TOOLS = [
+ {"type": "function", "function": {"name": "get_weather", "description": "Current weather of a city.",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "unit": {"type": "string", "enum": ["c", "f"]}},
+ "required": ["city"]}}},
+ {"type": "function", "function": {"name": "search", "description": "Web search.",
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"},
+ "other": {"type": "array"}, "safe": {"type": "boolean"}}, "required": ["query"]}}},
+]
+
+
+def tool_meta():
+ """tiny_meta + the tool tags as special tokens, like the real vocabulary (each tag is ONE token)"""
+ m = tiny_meta()
+ tags = [f"<{c}{n}{TK}>" for n in ("tool_calls", "tool_call", "arg_key", "arg_value", "tool_response") for c in ("", "/")]
+ m["tokenizer.ggml.tokens"] = m["tokenizer.ggml.tokens"] + tags
+ m["tokenizer.ggml.token_type"] = m["tokenizer.ggml.token_type"] + [3] * len(tags)
+ return m
+
+
+def call(name, **args):
+ """one call written the way the template writes it (strings raw, anything else as JSON)"""
+ body = "".join(f"<arg_key{TK}>{k}</arg_key{TK}><arg_value{TK}>{v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)}</arg_value{TK}>" for k, v in args.items())
+ return f"<tool_call{TK}>{name}{body}</tool_call{TK}>"
+
+
+def run_stream(vocab, text, in_think=False, step=3, eos=True, tools=TOOLS, parse_tools=True, stops=None):
+ """text -> tokens -> OutputStream in rounds of `step` tokens; -> (events, stream)"""
+ ids = vocab.encode(text)
+ o = C.OutputStream(vocab, in_think, stops, tools, parse_tools)
+ ev = []
+ for i in range(0, len(ids), step):
+ ev += o.push(ids[i:i + step])
+ if eos:
+ ev += o.push([vocab.eos_id])
+ ev += o.finish()
+ return ev, o
+
+
+def collect(ev):
+ return {"reasoning": "".join(p for c, p in ev if c == "reasoning"), "content": "".join(p for c, p in ev if c == "content"),
+ "calls": [(p["name"], json.loads(p["arguments"])) for c, p in ev if c == "tool_call"]}
+
+
+class Parser(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.vocabs = {"special tags": C.Vocab(tool_meta()), "tags as bytes": C.Vocab(tiny_meta())}
+
+ def each(self, text, **kw):
+ """the same text through every vocabulary and several round sizes: the result must not depend on how the tokens arrive"""
+ results = []
+ for name, v in self.vocabs.items():
+ for step in (1, 2, 3, 7, 1000):
+ ev, o = run_stream(v, text, step=step, **kw)
+ results.append((f"{name} step {step}", collect(ev), o))
+ first = results[0][1]
+ for label, got, _ in results:
+ self.assertEqual(got, first, label)
+ return first, results[0][2]
+
+ def test_tag_suffix_comes_from_the_vocabulary(self):
+ v = self.vocabs["special tags"]
+ self.assertEqual(v.tool_tags.suffix, TK)
+ self.assertEqual(v.tool_tags.call_open, f"<tool_call{TK}>")
+ self.assertEqual(C.ToolTags("").calls_close, "</tool_calls>")
+
+ def test_one_call_after_reasoning(self):
+ got, o = self.each(f"I should look.{UNTHINK}{CALLS}{call('get_weather', city='Paris', unit='c')}{ENDCALLS}", in_think=True)
+ self.assertEqual(got, {"reasoning": "I should look.", "content": "", "calls": [("get_weather", {"city": "Paris", "unit": "c"})]})
+ self.assertEqual((o.finish_reason, o.n_calls, o.final_reason()), ("stop", 1, "tool_calls"))
+
+ def test_content_then_parallel_calls(self):
+ text = f"Checking.\n{CALLS}{call('get_weather', city='Paris')}{call('search', query='rain', limit=3)}{ENDCALLS}"
+ got, _ = self.each(text)
+ self.assertEqual(got["content"], "Checking.")
+ self.assertEqual(got["calls"], [("get_weather", {"city": "Paris"}), ("search", {"query": "rain", "limit": 3})])
+
+ def test_arguments_are_typed_by_the_declared_schema(self):
+ text = f"{CALLS}{call('search', query='42', limit='42', other=[1, 2], safe=True, extra='7')}{ENDCALLS}"
+ got, _ = self.each(text)
+ self.assertEqual(got["calls"], [("search", {"query": "42", "limit": 42, "other": [1, 2], "safe": True, "extra": 7})]) # a string parameter keeps its text
+ got, _ = self.each(text, tools=None) # nothing declared: JSON when it parses
+ self.assertEqual(got["calls"][0][1]["query"], 42)
+
+ def test_unicode_and_quotes_in_arguments(self):
+ city = 'Zürich "centre" 東京'
+ got, _ = self.each(f"{CALLS}{call('get_weather', city=city)}{ENDCALLS}")
+ self.assertEqual(got["calls"], [("get_weather", {"city": city})])
+
+ def test_call_without_the_wrapper_and_wrapper_never_closed(self):
+ got, _ = self.each(f"ok{call('get_weather', city='Paris')}")
+ self.assertEqual((got["content"], got["calls"]), ("ok", [("get_weather", {"city": "Paris"})]))
+ got, o = self.each(f"{CALLS}{call('get_weather', city='Paris')}")
+ self.assertEqual((got["content"], got["calls"], o.final_reason()), ("", [("get_weather", {"city": "Paris"})], "tool_calls"))
+
+ def test_text_after_the_calls_is_content(self):
+ got, _ = self.each(f"{CALLS}{call('get_weather', city='Paris')}{ENDCALLS}done")
+ self.assertEqual((got["content"], len(got["calls"])), ("done", 1))
+
+ def test_a_call_inside_the_reasoning_is_reasoning_text(self):
+ c = call("get_weather", city="Paris")
+ got, o = self.each(f"maybe {c} ?{UNTHINK}final", in_think=True)
+ self.assertEqual((got["reasoning"], got["content"], got["calls"], o.final_reason()), (f"maybe {c} ?", "final", [], "stop"))
+
+ def test_malformed_blocks_stay_plain_content(self):
+ cut = f"<tool_call{TK}>get_weather<arg_key{TK}>city"
+ got, o = self.each(f"before {CALLS}{cut}", eos=False) # cut off by the length limit
+ self.assertEqual(got["calls"], [])
+ self.assertEqual(got["content"], f"before{cut}")
+ self.assertEqual(o.final_reason(), "length")
+ got, _ = self.each(f"{CALLS}{call('delete_everything', path='/')}{ENDCALLS}") # a function the request did not declare
+ self.assertEqual(got["calls"], [])
+ self.assertIn("delete_everything", got["content"])
+ got, _ = self.each(f"{CALLS}<tool_call{TK}><arg_key{TK}>a</arg_key{TK}><arg_value{TK}>1</arg_value{TK}></tool_call{TK}>{ENDCALLS}") # no name
+ self.assertEqual(got["calls"], [])
+ got, _ = self.each(f"{CALLS}stray words {call('get_weather', city='Paris')}{ENDCALLS}")
+ self.assertEqual((got["content"], len(got["calls"])), ("stray words", 1)) # text inside the wrapper is kept as content, the call still counts
+
+ def test_a_call_without_arguments(self):
+ got, _ = self.each(f"{CALLS}<tool_call{TK}>search</tool_call{TK}>{ENDCALLS}")
+ self.assertEqual(got["calls"], [("search", {})])
+
+ def test_tool_choice_none_leaves_the_tags_as_text(self):
+ c = call("get_weather", city="Paris")
+ got, o = self.each(f"{CALLS}{c}{ENDCALLS}", parse_tools=False)
+ self.assertEqual((got["content"], got["calls"], o.final_reason()), (f"{CALLS}{c}{ENDCALLS}", [], "stop"))
+
+ def test_a_stop_string_before_the_call_wins_and_after_it_does_not_cut_the_call(self):
+ got, o = self.each(f"one STOP two {CALLS}{call('get_weather', city='Paris')}{ENDCALLS}", stops=["STOP"])
+ self.assertEqual((got["content"], got["calls"], o.finish_reason), ("one ", [], "stop"))
+ got, _ = self.each(f"{CALLS}{call('get_weather', city='STOP')}{ENDCALLS}", stops=["STOP"])
+ self.assertEqual(got["calls"], [("get_weather", {"city": "STOP"})])
+
+ def test_whole_text_is_not_held_back_without_tools(self):
+ v = self.vocabs["special tags"]
+ ev, _ = run_stream(v, f"plain {CALLS}text\n", parse_tools=False, step=1)
+ self.assertEqual(collect(ev)["content"], f"plain {CALLS}text\n")
+ ev, _ = run_stream(v, "trailing space \n", parse_tools=True, step=1) # released at the end of the stream
+ self.assertEqual(collect(ev)["content"], "trailing space \n")
+
+ def test_calls_leave_as_soon_as_their_close_tag_arrives(self):
+ v = self.vocabs["special tags"]
+ first, second = call("get_weather", city="Paris"), call("search", query="x")
+ o = C.OutputStream(v, False, None, TOOLS, True)
+ seen = o.push(v.encode(f"{CALLS}{first}{second[:20]}"))
+ self.assertEqual([p["name"] for c, p in seen if c == "tool_call"], ["get_weather"])
+ seen = o.push(v.encode(second[20:] + ENDCALLS))
+ self.assertEqual([p["name"] for c, p in seen if c == "tool_call"], ["search"])
+
+ def test_random_piece_sizes(self):
+ text = f"plan{UNTHINK}Let me check.{CALLS}{call('get_weather', city='Paris')}{call('search', query='a b', limit=2)}{ENDCALLS}"
+ rng = random.Random(7)
+ want = None
+ for v in self.vocabs.values():
+ ids = v.encode(text)
+ for _ in range(20):
+ o, ev, i = C.OutputStream(v, True, None, TOOLS, True), [], 0
+ while i < len(ids):
+ n = rng.randint(1, 9)
+ ev += o.push(ids[i:i + n])
+ i += n
+ ev += o.push([v.eos_id]) + o.finish()
+ got = collect(ev)
+ want = want or got
+ self.assertEqual(got, want)
+ self.assertEqual(want["reasoning"], "plan")
+ self.assertEqual(want["content"], "Let me check.")
+ self.assertEqual([c[0] for c in want["calls"]], ["get_weather", "search"])
+
+
+class Request(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.v = C.Vocab(tool_meta())
+
+ def parse(self, **body):
+ return C.parse_chat({"messages": [{"role": "user", "content": "weather in Paris?"}], **body})
+
+ def test_no_tools_by_default(self):
+ r = self.parse()
+ self.assertEqual((r["tools"], r["parse_tools"], r["tool_choice"]), (None, False, "auto"))
+ r = self.parse(tool_choice="auto") # a client may send it without tools
+ self.assertFalse(r["parse_tools"])
+
+ def test_tools_nested_flat_and_legacy_functions(self):
+ want = [{"type": "function", "function": TOOLS[0]["function"]}]
+ self.assertEqual(self.parse(tools=[TOOLS[0]])["tools"], want)
+ flat = {"type": "function", **TOOLS[0]["function"]}
+ self.assertEqual(self.parse(tools=[flat])["tools"], want)
+ self.assertEqual(self.parse(functions=[TOOLS[0]["function"]])["tools"], want)
+ self.assertEqual(self.parse(tools=[], functions=[TOOLS[0]["function"]])["tools"], want)
+ self.assertEqual(self.parse(tools=[TOOLS[0]], strict_ignored=1)["parse_tools"], True)
+
+ def test_tool_choice(self):
+ self.assertEqual(self.parse(tools=TOOLS, tool_choice="required")["tool_choice"], "required")
+ r = self.parse(tools=TOOLS, tool_choice={"type": "function", "function": {"name": "search"}})
+ self.assertEqual((r["tool_choice"], r["tool_name"], [t["function"]["name"] for t in r["tools"]]), ("function", "search", ["search"]))
+ r = self.parse(tools=TOOLS, function_call={"name": "search"})
+ self.assertEqual(r["tool_name"], "search")
+ r = self.parse(tools=TOOLS, tool_choice="none")
+ self.assertEqual((r["tools"], r["parse_tools"]), (None, False))
+ r = self.parse(tools=TOOLS, function_call="auto")
+ self.assertEqual(r["tool_choice"], "auto")
+
+ def test_tool_choice_hint_goes_into_the_system_message(self):
+ r = self.parse(tools=TOOLS, tool_choice="required")
+ self.assertEqual(r["messages"][0]["role"], "system")
+ self.assertIn("must answer by calling", r["messages"][0]["content"])
+ msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "x"}]
+ r = C.parse_chat({"messages": msgs, "tools": TOOLS, "tool_choice": {"type": "function", "function": {"name": "search"}}})
+ self.assertTrue(r["messages"][0]["content"].startswith("Be brief.\n\n"))
+ self.assertIn("function search", r["messages"][0]["content"])
+ self.assertEqual(len(r["messages"]), 2)
+ self.assertEqual(self.parse(tools=TOOLS)["messages"][0]["role"], "user") # auto: the messages are untouched
+
+ def test_bad_tool_requests_are_a_400(self):
+ bad = [dict(tools="x"), dict(tools=[1]), dict(tools=[{"type": "function"}]), dict(tools=[{"type": "function", "function": {"name": "a b"}}]),
+ dict(tools=[{"type": "web_search"}]), dict(tools=[{"type": "function", "function": {"name": "f", "parameters": "x"}}]),
+ dict(tools=TOOLS, tool_choice="sometimes"), dict(tools=TOOLS, tool_choice=5), dict(tool_choice="required"),
+ dict(tools=TOOLS, tool_choice={"type": "function", "function": {"name": "nope"}}), dict(tools=TOOLS, tool_choice={"type": "function"})]
+ for b in bad:
+ with self.assertRaises(C.RequestError, msg=str(b)):
+ self.parse(**b)
+
+ def history(self, args, content=None):
+ return [{"role": "user", "content": "weather in Paris?"},
+ {"role": "assistant", "content": content, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": args}}]},
+ {"role": "tool", "tool_call_id": "call_1", "content": '{"temp": 18}'}]
+
+ def test_assistant_tool_calls_and_tool_messages(self):
+ for args in ('{"city": "Paris"}', {"city": "Paris"}):
+ r = C.parse_chat({"messages": self.history(args), "tools": TOOLS})
+ a, t = r["messages"][1], r["messages"][2]
+ self.assertEqual(a["tool_calls"], [{"type": "function", "id": "call_1", "function": {"name": "get_weather", "arguments": {"city": "Paris"}}}])
+ self.assertEqual((a["content"], t), ("", {"role": "tool", "content": '{"temp": 18}', "tool_call_id": "call_1"}))
+ for empty in ("", None, " "):
+ r = C.parse_chat({"messages": self.history(empty)})
+ self.assertEqual(r["messages"][1]["tool_calls"][0]["function"]["arguments"], {})
+
+ def test_legacy_function_call_and_function_role(self):
+ msgs = [{"role": "user", "content": "q"}, {"role": "assistant", "content": None, "function_call": {"name": "get_weather", "arguments": '{"city": "Rome"}'}},
+ {"role": "function", "name": "get_weather", "content": "sunny"}]
+ r = C.parse_chat({"messages": msgs, "functions": [TOOLS[0]["function"]]})
+ self.assertEqual(r["messages"][1]["tool_calls"][0]["function"], {"name": "get_weather", "arguments": {"city": "Rome"}})
+ self.assertEqual((r["messages"][2]["role"], r["messages"][2]["content"]), ("tool", "sunny"))
+
+ def test_bad_histories_are_a_400(self):
+ for args in ("{not json", "[1, 2]", 5, '"text"'):
+ with self.assertRaises(C.RequestError, msg=str(args)):
+ C.parse_chat({"messages": self.history(args)})
+ bad = [[{"role": "user", "content": "x"}, {"role": "assistant", "tool_calls": "x"}, {"role": "tool", "content": "r"}],
+ [{"role": "user", "content": "x"}, {"role": "assistant", "tool_calls": [{"function": {}}]}, {"role": "tool", "content": "r"}],
+ [{"role": "user", "content": "x"}, {"role": "assistant", "tool_calls": [1]}, {"role": "tool", "content": "r"}],
+ [{"role": "user", "content": "x"}, {"role": "tool", "tool_call_id": 5, "content": "r"}]]
+ for msgs in bad:
+ with self.assertRaises(C.RequestError, msg=str(msgs)):
+ C.parse_chat({"messages": msgs})
+
+ def render(self, **body):
+ r = C.parse_chat(body)
+ return self.v.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])
+
+ def test_the_prompt_carries_the_tools(self):
+ text = self.render(messages=[{"role": "user", "content": "weather?"}], tools=TOOLS)
+ self.assertIn("# Tools", text)
+ self.assertIn("<tools>\n" + json.dumps(TOOLS[0]["function"], ensure_ascii=False), text)
+ self.assertIn(json.dumps(TOOLS[1]["function"], ensure_ascii=False), text)
+ self.assertIn(f"you should first print {CALLS}", text)
+ self.assertTrue(text.endswith(f"{START}assistant{MIDDLE}{THINK}"))
+ text = self.render(messages=[{"role": "system", "content": "Be brief."}, {"role": "user", "content": "weather?"}], tools=TOOLS)
+ self.assertLess(text.index("# Tools"), text.index("Be brief."))
+ self.assertNotIn("# Tools", self.render(messages=[{"role": "user", "content": "x"}], tools=TOOLS, tool_choice="none"))
+ self.assertIn("function get_weather", self.render(messages=[{"role": "user", "content": "x"}], tools=TOOLS, tool_choice={"function": {"name": "get_weather"}}))
+
+ def test_multi_turn_history_is_rendered_back_in_the_template_format(self):
+ msgs = self.history('{"city": "Paris", "days": 2}', content="Let me check.")
+ text = self.render(messages=msgs, tools=TOOLS)
+ want = (f"{START}assistant{MIDDLE}{THINK}{UNTHINK}Let me check.{CALLS}<tool_call{TK}>get_weather<arg_key{TK}>city</arg_key{TK}><arg_value{TK}>Paris</arg_value{TK}>"
+ f"<arg_key{TK}>days</arg_key{TK}><arg_value{TK}>2</arg_value{TK}></tool_call{TK}>{ENDCALLS}{END}"
+ f"{START}tool{MIDDLE}<tool_response{TK}>{{\"temp\": 18}}</tool_response{TK}>{END}{START}assistant{MIDDLE}{THINK}")
+ self.assertIn(want, text)
+
+ def test_parallel_results_follow_the_order_of_the_calls(self):
+ calls = [{"id": f"c{i}", "type": "function", "function": {"name": "get_weather", "arguments": {"city": c}}} for i, c in enumerate(("Paris", "Rome"))]
+ msgs = [{"role": "user", "content": "both"}, {"role": "assistant", "content": "", "tool_calls": calls},
+ {"role": "tool", "tool_call_id": "c1", "content": "rome-result"}, {"role": "tool", "tool_call_id": "c0", "content": "paris-result"}]
+ text = self.render(messages=msgs, tools=TOOLS)
+ self.assertLess(text.index("paris-result"), text.index("rome-result"))
+ self.assertEqual(text.count(f"{START}tool{MIDDLE}"), 1)
+
+ def test_the_reasoning_of_a_call_turn_is_kept_when_tools_are_declared(self):
+ msgs = self.history('{"city": "Paris"}')
+ msgs[1]["reasoning_content"] = "I need the weather."
+ self.assertIn(f"{THINK}I need the weather.{UNTHINK}{CALLS}", self.render(messages=msgs, tools=TOOLS))
+
+ def test_a_template_that_cannot_read_a_message_is_a_400(self):
+ with self.assertRaises(C.RequestError):
+ self.v.template.render([{"role": "user", "content": "x"}, {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": "f", "arguments": "text"}}]},
+ {"role": "tool", "content": "r"}], None, True, reasoning_effort="high")
+
+ def test_response_bodies(self):
+ item = C.tool_call_item({"name": "get_weather", "arguments": '{"city": "Paris"}'}, "call_1")
+ self.assertEqual(item, {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}})
+ b = C.chat_response("id", "m", 1, "", "thinking", "tool_calls", {"total_tokens": 3}, [item])
+ msg = b["choices"][0]["message"]
+ self.assertEqual((msg["content"], msg["tool_calls"], msg["reasoning_content"], b["choices"][0]["finish_reason"]), (None, [item], "thinking", "tool_calls"))
+ self.assertEqual(C.chat_response("id", "m", 1, "Checking.", "", "tool_calls", {}, [item])["choices"][0]["message"]["content"], "Checking.")
+ self.assertNotIn("tool_calls", C.chat_response("id", "m", 1, "hi", "", "stop", {})["choices"][0]["message"])
+ d = C.tool_call_deltas(1, "call_1", {"name": "f", "arguments": "{}"})
+ self.assertEqual(d[0]["tool_calls"][0], {"index": 1, "id": "call_1", "type": "function", "function": {"name": "f", "arguments": ""}})
+ self.assertEqual(d[1]["tool_calls"][0], {"index": 1, "function": {"arguments": "{}"}})
+
+
+class FakeEngine:
+ """replays `reply` (then EOS) 3 tokens per round; with `delay` each round takes that long and looks at `cancel` like the real engine does"""
+
+ def __init__(self, vocab, reply, delay=0.0, eos=True):
+ self.ids = vocab.encode(reply) + ([vocab.eos_id] if eos else [])
+ self.delay, self.calls, self.cancelled, self.rounds = delay, [], threading.Event(), 0
+
+ def generate(self, ids, max_new, on_tokens, speculative=True, cancel=lambda: False):
+ self.calls.append((list(ids), max_new))
+ n, stop = 0, False
+ while n < min(max_new, len(self.ids)) and not stop:
+ if cancel():
+ self.cancelled.set()
+ break
+ if self.delay:
+ time.sleep(self.delay)
+ new = self.ids[n:n + 3][:max_new - n]
+ n += len(new)
+ self.rounds += 1
+ stop = on_tokens(new)
+ return {"prompt_tokens": len(ids), "prefill_s": 0.5, "prefill_trunk_s": 0.4, "prime_s": 0.1, "prime_mode": "fake", "decode_s": 0.25, "decode_tokens": n,
+ "ttft_s": 0.5, "rounds": self.rounds, "accept_hist": [0, 0, 0, self.rounds], "tau": n / max(self.rounds, 1), "speculative": speculative}
+
+
+class ProdServer(TestServer):
+ """the test server cancels a handler when the client goes away (handler_cancellation=True); web.run_app, which runs the real server, does not"""
+
+ async def _make_runner(self, **kwargs):
+ if "handler_cancellation" in kwargs:
+ kwargs["handler_cancellation"] = False
+ return await super()._make_runner(**kwargs)
+
+
+def make_state(reply, **kw):
+ st = S.State(argparse.Namespace(model_id="Hy4-test", max_ctx=8192, num_draft=3, default_max_tokens=256))
+ st.vocab = C.Vocab(tool_meta())
+ st.engine = FakeEngine(st.vocab, reply, **kw)
+ st.ready = True
+ st.lock = asyncio.Lock()
+ return st
+
+
+class Http(unittest.IsolatedAsyncioTestCase):
+ async def start(self, reply, server=ProdServer, **kw):
+ self.st = make_state(reply, **kw)
+ self.client = TestClient(server(S.build_app(self.st)))
+ await self.client.start_server()
+ self.addAsyncCleanup(self.client.close)
+ return self.st
+
+ def body(self, **kw):
+ return {"messages": [{"role": "user", "content": "weather in Paris?"}], "tools": TOOLS, "max_tokens": 200, "reasoning_effort": "no_think", **kw}
+
+ async def sse_chunks(self, **kw):
+ r = await self.client.post("/v1/chat/completions", json=self.body(stream=True, **kw))
+ self.assertEqual(r.status, 200)
+ events = [e[6:] for e in (await r.read()).decode().split("\n\n") if e.startswith("data: ")]
+ self.assertEqual(events[-1], "[DONE]")
+ return [json.loads(e) for e in events[:-1]]
+
+ async def test_non_stream_tool_call(self):
+ await self.start(f"{CALLS}{call('get_weather', city='Paris', unit='c')}{ENDCALLS}")
+ r = await self.client.post("/v1/chat/completions", json=self.body())
+ j = await r.json()
+ self.assertEqual(r.status, 200, j)
+ ch = j["choices"][0]
+ self.assertEqual(ch["finish_reason"], "tool_calls")
+ self.assertIsNone(ch["message"]["content"])
+ [tc] = ch["message"]["tool_calls"]
+ self.assertTrue(tc["id"].startswith("call_"))
+ self.assertEqual((tc["type"], tc["function"]["name"]), ("function", "get_weather"))
+ self.assertEqual(json.loads(tc["function"]["arguments"]), {"city": "Paris", "unit": "c"})
+ self.assertIsInstance(tc["function"]["arguments"], str)
+ prompt = self.st.vocab.decode(self.st.engine.calls[0][0])
+ self.assertIn("# Tools", prompt)
+ self.assertIn('"name": "get_weather"', prompt)
+
+ async def test_reasoning_stays_in_reasoning_content(self):
+ await self.start(f"I need the weather.{UNTHINK}Checking.{CALLS}{call('get_weather', city='Paris')}{ENDCALLS}")
+ r = await self.client.post("/v1/chat/completions", json=self.body(reasoning_effort="high"))
+ m = (await r.json())["choices"][0]["message"]
+ self.assertEqual((m["reasoning_content"], m["content"], len(m["tool_calls"])), ("I need the weather.", "Checking.", 1))
+
+ async def test_parallel_calls_get_distinct_ids(self):
+ await self.start(f"{CALLS}{call('get_weather', city='Paris')}{call('get_weather', city='Rome')}{ENDCALLS}")
+ j = await (await self.client.post("/v1/chat/completions", json=self.body())).json()
+ calls = j["choices"][0]["message"]["tool_calls"]
+ self.assertEqual([json.loads(c["function"]["arguments"])["city"] for c in calls], ["Paris", "Rome"])
+ self.assertEqual(len({c["id"] for c in calls}), 2)
+
+ async def test_plain_answer_with_tools_declared(self):
+ await self.start("It is sunny.")
+ j = await (await self.client.post("/v1/chat/completions", json=self.body())).json()
+ ch = j["choices"][0]
+ self.assertEqual((ch["message"]["content"], ch["finish_reason"]), ("It is sunny.", "stop"))
+ self.assertNotIn("tool_calls", ch["message"])
+
+ async def test_stream_tool_call(self):
+ await self.start(f"Checking.{CALLS}{call('get_weather', city='Paris')}{call('search', query='rain', limit=2)}{ENDCALLS}")
+ chunks = await self.sse_chunks(stream_options={"include_usage": True})
+ self.assertEqual(chunks[0]["choices"][0]["delta"]["role"], "assistant")
+ calls, text, finish = {}, "", []
+ for c in chunks:
+ if not c["choices"]:
+ continue
+ d = c["choices"][0]["delta"]
+ text += d.get("content") or ""
+ for tc in d.get("tool_calls", []):
+ slot = calls.setdefault(tc["index"], {"id": None, "name": "", "args": ""})
+ slot["id"] = tc.get("id", slot["id"])
+ slot["name"] += tc.get("function", {}).get("name", "")
+ slot["args"] += tc.get("function", {}).get("arguments", "")
+ if c["choices"][0]["finish_reason"]:
+ finish.append(c["choices"][0]["finish_reason"])
+ self.assertEqual(text, "Checking.")
+ self.assertEqual(finish, ["tool_calls"])
+ self.assertEqual(sorted(calls), [0, 1])
+ self.assertEqual((calls[0]["name"], json.loads(calls[0]["args"])), ("get_weather", {"city": "Paris"}))
+ self.assertEqual((calls[1]["name"], json.loads(calls[1]["args"])), ("search", {"query": "rain", "limit": 2}))
+ self.assertTrue(calls[0]["id"].startswith("call_") and calls[0]["id"] != calls[1]["id"])
+ first = [c["choices"][0]["delta"]["tool_calls"][0] for c in chunks if c["choices"] and c["choices"][0]["delta"].get("tool_calls")]
+ self.assertEqual(first[0]["function"], {"name": "get_weather", "arguments": ""}) # id + name first, the arguments in the next chunk
+ self.assertEqual(list(first[1]), ["index", "function"])
+ self.assertIn("usage", chunks[-1])
+
+ async def test_multi_turn_round_trip(self):
+ await self.start("It is 18 degrees and sunny.")
+ msgs = [{"role": "user", "content": "weather in Paris?"},
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "call_abc", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}]},
+ {"role": "tool", "tool_call_id": "call_abc", "content": '{"temp": 18, "sky": "sunny"}'}]
+ r = await self.client.post("/v1/chat/completions", json=self.body(messages=msgs))
+ j = await r.json()
+ self.assertEqual(r.status, 200, j)
+ self.assertEqual((j["choices"][0]["message"]["content"], j["choices"][0]["finish_reason"]), ("It is 18 degrees and sunny.", "stop"))
+ prompt = self.st.vocab.decode(self.st.engine.calls[0][0])
+ self.assertIn(f"{CALLS}<tool_call{TK}>get_weather<arg_key{TK}>city</arg_key{TK}><arg_value{TK}>Paris</arg_value{TK}></tool_call{TK}>{ENDCALLS}", prompt)
+ self.assertIn(f"<tool_response{TK}>{{\"temp\": 18, \"sky\": \"sunny\"}}</tool_response{TK}>", prompt)
+
+ async def test_malformed_blocks_are_content_never_a_500(self):
+ for reply in (f"{CALLS}<tool_call{TK}>get_weather<arg_key{TK}>city", f"{CALLS}{call('unknown_fn', a=1)}{ENDCALLS}", f"{CALLS}{ENDCALLS}{ENDCALLS}</tool_call{TK}>"):
+ await self.start(reply)
+ r = await self.client.post("/v1/chat/completions", json=self.body())
+ j = await r.json()
+ self.assertEqual(r.status, 200, (reply, j))
+ self.assertNotIn("tool_calls", j["choices"][0]["message"])
+ self.assertIn(j["choices"][0]["finish_reason"], ("stop", "length"))
+ await self.client.close()
+
+ async def test_tool_choice_none_is_plain_text(self):
+ reply = f"{CALLS}{call('get_weather', city='Paris')}{ENDCALLS}"
+ await self.start(reply)
+ j = await (await self.client.post("/v1/chat/completions", json=self.body(tool_choice="none"))).json()
+ ch = j["choices"][0]
+ self.assertEqual((ch["message"]["content"], ch["finish_reason"]), (reply, "stop"))
+ self.assertNotIn("# Tools", self.st.vocab.decode(self.st.engine.calls[0][0]))
+
+ async def test_bad_tool_requests_are_a_clean_400(self):
+ await self.start("x")
+ for extra in ({"tool_choice": "required", "tools": None}, {"tools": [{"type": "function"}]}, {"tool_choice": {"type": "function", "function": {"name": "nope"}}}):
+ body = self.body(**extra)
+ body = {k: v for k, v in body.items() if v is not None}
+ r = await self.client.post("/v1/chat/completions", json=body)
+ j = await r.json()
+ self.assertEqual(r.status, 400, (extra, j))
+ self.assertEqual(j["error"]["type"], "invalid_request_error")
+
+ async def test_apply_template_with_tools(self):
+ await self.start("x")
+ j = await (await self.client.post("/apply-template", json=self.body())).json()
+ self.assertIn("# Tools", j["prompt"])
+
+ # -- a client that closes the stream
+ async def test_a_failed_write_cancels_the_generation_quietly(self):
+ """the traceback of the report: resp.write raises ClientConnectionResetError ("Cannot write to closing transport")"""
+ st = await self.start("A" * 600, delay=0.01)
+ real, n = web.StreamResponse.write, {"n": 0}
+
+ async def flaky(self, data):
+ n["n"] += 1
+ if n["n"] >= 4:
+ raise ClientConnectionResetError("Cannot write to closing transport")
+ return await real(self, data)
+
+ out = io.StringIO()
+ web.StreamResponse.write = flaky
+ try:
+ with contextlib.redirect_stdout(out), self.assertNoLogs("aiohttp.server", level="ERROR"):
+ with contextlib.suppress(Exception):
+ r = await self.client.post("/v1/chat/completions", json=self.body(stream=True))
+ await r.read()
+ self.assertTrue(await asyncio.get_running_loop().run_in_executor(None, st.engine.cancelled.wait, 5))
+ finally:
+ web.StreamResponse.write = real
+ self.assertEqual(sum("generation cancelled" in line for line in out.getvalue().splitlines()), 1, out.getvalue())
+ self.assertNotIn("Traceback", out.getvalue())
+ self.assertLess(st.engine.rounds, 200) # 600 tokens = 200 rounds: stopped early
+ st.engine.delay = 0
+ r = await self.client.post("/v1/chat/completions", json=self.body()) # the lock was released: the next request is served
+ self.assertEqual(r.status, 200)
+
+ async def test_a_closed_stream_cancels_the_engine(self):
+ st = await self.start("B" * 900, delay=0.02)
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out), self.assertNoLogs("aiohttp.server", level="ERROR"):
+ r = await self.client.post("/v1/chat/completions", json=self.body(stream=True))
+ await r.content.readline()
+ await r.content.readline()
+ r.close() # the client goes away mid-stream
+ self.assertTrue(await asyncio.get_running_loop().run_in_executor(None, st.engine.cancelled.wait, 5))
+ await asyncio.sleep(0.2)
+ self.assertLess(st.engine.rounds, 300)
+ self.assertNotIn("Traceback", out.getvalue())
+ st.engine.delay = 0
+ r = await self.client.post("/v1/chat/completions", json=self.body())
+ self.assertEqual(r.status, 200)
+
+ async def closed_non_stream_request(self, server):
+ st = await self.start("C" * 900, delay=0.02, server=server)
+ task = asyncio.ensure_future(self.client.post("/v1/chat/completions", json=self.body()))
+ await asyncio.sleep(0.3)
+ task.cancel() # the client gives up while the server is still generating
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+ self.assertTrue(await asyncio.get_running_loop().run_in_executor(None, st.engine.cancelled.wait, 5))
+ self.assertLess(st.engine.rounds, 300)
+ st.engine.delay = 0
+ r = await self.client.post("/v1/chat/completions", json=self.body())
+ self.assertEqual(r.status, 200)
+
+ async def test_a_closed_non_stream_request_cancels_the_engine(self):
+ """as web.run_app serves it: nothing tells the handler the client left, the connection watcher does"""
+ await self.closed_non_stream_request(ProdServer)
+
+ async def test_a_cancelled_handler_cancels_the_engine(self):
+ """a server that cancels the handler when the connection drops (handler_cancellation=True)"""
+ await self.closed_non_stream_request(TestServer)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/hy4/serve.py b/tools/hy4/serve.py
index 5c6d17c..fdbc777 100644
--- a/tools/hy4/serve.py
+++ b/tools/hy4/serve.py
@@ -20,6 +20,7 @@ import sys
import threading
import time
import traceback
+from contextlib import aclosing
HERE = os.path.dirname(os.path.abspath(__file__))
TREE = os.path.dirname(os.path.dirname(HERE))
@@ -102,6 +103,25 @@ def apply_env(ctx: int, model: str = "", slots: int = 1) -> None:
os.environ.setdefault("HY4_MTP_HEAD_BIN", head)
+class ClientGone(Exception):
+ """the client closed its end of the connection: the generation is cancelled"""
+
+
+def client_gone(request) -> bool:
+ tr = getattr(request, "transport", None)
+ return request is not None and (tr is None or tr.is_closing())
+
+
+def watch_client(request, q: asyncio.Queue):
+ """task: puts ("gone",) on `q` when the client closes its end. A reply that is not streamed writes nothing before its end, so without this a closed socket
+ would go unseen and the engine would finish a generation nobody reads."""
+ async def watch():
+ while not client_gone(request):
+ await asyncio.sleep(0.5)
+ q.put_nowait(("gone",))
+ return asyncio.ensure_future(watch())
+
+
class State:
def __init__(self, args):
self.args = args
@@ -121,7 +141,7 @@ def _err(status: int, message: str, code: str = "invalid_request_error"):
def build_app(st: State):
- from aiohttp import web
+ from aiohttp import ClientConnectionError, web
args = st.args
async def health(_req):
@@ -147,7 +167,7 @@ def build_app(st: State):
def prompt_for_chat(body):
r = C.parse_chat(body, args.default_max_tokens)
- text = st.vocab.template.render(r["messages"], None, True, reasoning_effort=r["effort"])
+ text = st.vocab.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])
ids = st.vocab.encode(text)
v = st.vocab
r["in_think"] = r["effort"] != "no_think" and bool(v.think_begin) and text.rstrip().endswith(v.think_begin)
@@ -162,7 +182,7 @@ def build_app(st: State):
from mu_engine import Request
loop = asyncio.get_running_loop()
q: asyncio.Queue = asyncio.Queue()
- out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"])
+ out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"], tools=r.get("tools"), parse_tools=r.get("parse_tools", False))
def on_tokens(toks):
for ch, tx in out.push(toks):
@@ -172,20 +192,24 @@ def build_app(st: State):
req = Request(ids, r["max_tokens"], speculative=r["speculative"], on_tokens=on_tokens)
req.on_done = lambda: loop.call_soon_threadsafe(q.put_nowait, ("end",))
st.sched.submit(req)
+ watcher = watch_client(request, q)
try:
while True:
ev = await q.get()
if ev[0] == "end":
break
+ if ev[0] == "gone":
+ raise ClientGone()
yield ev
finally:
+ watcher.cancel()
req.cancel.set()
for ch, tx in out.finish():
yield ("delta", ch, tx)
if req.error:
raise RuntimeError(req.error)
stats = req.engine_stats(st.engine.k)
- finish = out.finish_reason or "length"
+ finish = out.final_reason()
st.served += 1
pf, dc = stats["prefill_s"], stats["decode_s"]
print(f"req {st.served}: prompt {stats['prompt_tokens']} tok ttft {pf:.2f} s (own prefill {stats['prefill_trunk_s']:.2f} s) | decode {stats['decode_tokens']} tok {dc:.2f} s = "
@@ -195,12 +219,13 @@ def build_app(st: State):
async def run_job(ids, r, in_think, request):
"""async generator of ("delta", channel, text) events, then ("end", stats, finish_reason, n_generated)"""
if st.sched is not None:
- async for ev in run_job_mu(ids, r, in_think, request):
- yield ev
+ async with aclosing(run_job_mu(ids, r, in_think, request)) as events:
+ async for ev in events:
+ yield ev
return
loop = asyncio.get_running_loop()
q: asyncio.Queue = asyncio.Queue()
- out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"])
+ out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"], tools=r.get("tools"), parse_tools=r.get("parse_tools", False))
cancel = threading.Event()
res: dict = {}
@@ -222,19 +247,23 @@ def build_app(st: State):
async with st.lock:
fut = loop.run_in_executor(None, work)
+ watcher = watch_client(request, q)
try:
while True:
ev = await q.get()
if ev[0] == "end":
break
+ if ev[0] == "gone":
+ raise ClientGone()
yield ev
finally:
+ watcher.cancel()
cancel.set()
await fut
if "error" in res:
raise RuntimeError(res["error"])
stats = res["stats"]
- finish = out.finish_reason or "length"
+ finish = out.final_reason()
st.served += 1
n_gen = out.n_tokens
pf, dc = stats["prefill_s"], stats["decode_s"]
@@ -250,12 +279,22 @@ def build_app(st: State):
tau=stats["tau"], accept_hist=stats["accept_hist"], ttft_ms=stats["ttft_s"] * 1000,
prefill_trunk_ms=stats.get("prefill_trunk_s", 0) * 1000, draft_fill_ms=stats.get("prime_s", 0) * 1000)
- async def sse(request, gen_chunks):
+ async def sse(request, chunks):
+ """stream `chunks` (an async generator of JSON-able chunks) as server-sent events. A client that closes the stream makes the write raise: that cancels the
+ generation (closing `chunks` runs run_job's cleanup, which stops the engine) and ends the request with one log line, not a traceback."""
resp = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
- await resp.prepare(request)
- async for chunk in gen_chunks:
- await resp.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
- await resp.write(b"data: [DONE]\n\n")
+ try:
+ await resp.prepare(request)
+ async for chunk in chunks:
+ await resp.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode() + b"\n\n")
+ await resp.write(b"data: [DONE]\n\n")
+ except (ConnectionError, ClientConnectionError, ClientGone) as e:
+ print(f"client closed the stream ({type(e).__name__}): generation cancelled", flush=True)
+ except asyncio.CancelledError:
+ print("client closed the stream (request cancelled): generation cancelled", flush=True)
+ raise
+ finally:
+ await chunks.aclose()
return resp
async def chat(request):
@@ -266,29 +305,41 @@ def build_app(st: State):
rid, created = C.new_id("chatcmpl"), int(time.time())
m = args.model_id
if not r["stream"]:
- content, reasoning, stats, finish, n_gen = [], [], None, "length", 0
- async for ev in run_job(ids, r, r["in_think"], request):
- if ev[0] == "delta":
- (reasoning if ev[1] == "reasoning" else content).append(ev[2])
- else:
- _, stats, finish, n_gen = ev
- return web.json_response(C.chat_response(rid, m, created, "".join(content), "".join(reasoning), finish,
- serve_compat.usage(len(ids), n_gen), timings=timings(stats), system_fingerprint="hy4-strix-graph-mtp"))
+ content, reasoning, calls, stats, finish, n_gen = [], [], [], None, "length", 0
+ async with aclosing(run_job(ids, r, r["in_think"], request)) as events:
+ async for ev in events:
+ if ev[0] != "delta":
+ _, stats, finish, n_gen = ev
+ elif ev[1] == "tool_call":
+ calls.append(C.tool_call_item(ev[2], C.new_call_id()))
+ else:
+ (reasoning if ev[1] == "reasoning" else content).append(ev[2])
+ return web.json_response(C.chat_response(rid, m, created, "".join(content), "".join(reasoning), finish, serve_compat.usage(len(ids), n_gen),
+ calls, timings=timings(stats), system_fingerprint="hy4-strix-graph-mtp"))
async def chunks():
yield C.chat_chunk(rid, m, created, {"role": "assistant", "content": ""})
- async for ev in run_job(ids, r, r["in_think"], request):
- if ev[0] == "delta":
- yield C.chat_chunk(rid, m, created, {"reasoning_content" if ev[1] == "reasoning" else "content": ev[2]})
- else:
- _, stats, finish, n_gen = ev
- yield C.chat_chunk(rid, m, created, {}, finish, timings=timings(stats))
- if r["include_usage"]:
- yield {"id": rid, "object": "chat.completion.chunk", "created": created, "model": m, "choices": [],
- "usage": serve_compat.usage(len(ids), n_gen)}
+ n_calls = 0
+ async with aclosing(run_job(ids, r, r["in_think"], request)) as events:
+ async for ev in events:
+ if ev[0] != "delta":
+ _, stats, finish, n_gen = ev
+ yield C.chat_chunk(rid, m, created, {}, finish, timings=timings(stats))
+ if r["include_usage"]:
+ yield {"id": rid, "object": "chat.completion.chunk", "created": created, "model": m, "choices": [],
+ "usage": serve_compat.usage(len(ids), n_gen)}
+ elif ev[1] == "tool_call":
+ for delta in C.tool_call_deltas(n_calls, C.new_call_id(), ev[2]):
+ yield C.chat_chunk(rid, m, created, delta)
+ n_calls += 1
+ else:
+ yield C.chat_chunk(rid, m, created, {"reasoning_content" if ev[1] == "reasoning" else "content": ev[2]})
return await sse(request, chunks())
except C.RequestError as e:
return _err(e.status, str(e), e.code)
+ except ClientGone:
+ print("client closed the connection: generation cancelled", flush=True)
+ return web.Response(status=499)
except RuntimeError as e:
return _err(500, str(e), "server_error")
@@ -301,27 +352,32 @@ def build_app(st: State):
rid, created, m = C.new_id("cmpl"), int(time.time()), args.model_id
if not r["stream"]:
text, stats, finish, n_gen = [], None, "length", 0
- async for ev in run_job(ids, r, False, request):
- if ev[0] == "delta":
- text.append(ev[2])
- else:
- _, stats, finish, n_gen = ev
+ async with aclosing(run_job(ids, r, False, request)) as events:
+ async for ev in events:
+ if ev[0] == "delta":
+ text.append(ev[2])
+ else:
+ _, stats, finish, n_gen = ev
body = C.completion_chunk(rid, m, created, "".join(text), finish)
body.update(usage=serve_compat.usage(len(ids), n_gen), timings=timings(stats))
return web.json_response(body)
async def chunks():
- async for ev in run_job(ids, r, False, request):
- if ev[0] == "delta":
- yield C.completion_chunk(rid, m, created, ev[2])
- else:
- _, stats, finish, n_gen = ev
- yield C.completion_chunk(rid, m, created, "", finish, timings=timings(stats))
- if r["include_usage"]:
- yield {"id": rid, "object": "text_completion", "created": created, "model": m, "choices": [], "usage": serve_compat.usage(len(ids), n_gen)}
+ async with aclosing(run_job(ids, r, False, request)) as events:
+ async for ev in events:
+ if ev[0] == "delta":
+ yield C.completion_chunk(rid, m, created, ev[2])
+ else:
+ _, stats, finish, n_gen = ev
+ yield C.completion_chunk(rid, m, created, "", finish, timings=timings(stats))
+ if r["include_usage"]:
+ yield {"id": rid, "object": "text_completion", "created": created, "model": m, "choices": [], "usage": serve_compat.usage(len(ids), n_gen)}
return await sse(request, chunks())
except C.RequestError as e:
return _err(e.status, str(e), e.code)
+ except ClientGone:
+ print("client closed the connection: generation cancelled", flush=True)
+ return web.Response(status=499)
except RuntimeError as e:
return _err(500, str(e), "server_error")
@@ -341,7 +397,7 @@ def build_app(st: State):
try:
need_ready()
r = C.parse_chat(await read_body(request), args.default_max_tokens)
- return web.json_response({"prompt": st.vocab.template.render(r["messages"], None, True, reasoning_effort=r["effort"])})
+ return web.json_response({"prompt": st.vocab.template.render(r["messages"], r["tools"], True, reasoning_effort=r["effort"])})
except C.RequestError as e:
return _err(e.status, str(e), e.code)
diff --git a/tools/hy4/serve_core.py b/tools/hy4/serve_core.py
index cda23c6..8eabec0 100644
--- a/tools/hy4/serve_core.py
+++ b/tools/hy4/serve_core.py
@@ -8,6 +8,7 @@
from __future__ import annotations
import json
+import math
import os
import re
import time
@@ -60,6 +61,8 @@ class ChatTemplate:
return self.tpl.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs)
except jinja2.exceptions.TemplateError as e:
raise RequestError(f"chat template: {e}") from e
+ except (TypeError, ValueError, AttributeError, KeyError, IndexError) as e: # a message shape the template cannot read (e.g. arguments that are not an object)
+ raise RequestError(f"chat template: {type(e).__name__}: {e}") from e
# ------------------------------------------------------------------------------------------------ tokenizer
@@ -94,6 +97,7 @@ class Vocab:
self.template = ChatTemplate(meta["tokenizer.chat_template"])
self.think_begin = next((t for t in toks if t.startswith("<think")), None)
self.think_end = next((t for t in toks if t.startswith("</think")), None)
+ self.tool_tags = ToolTags(tag_suffix(self.think_begin))
def encode(self, text: str) -> list[int]:
return self.tok.encode(text, add_special_tokens=False).ids
@@ -102,6 +106,104 @@ class Vocab:
return self.tok.decode(ids, skip_special_tokens=False)
+# ------------------------------------------------------------------------------------------------ tool calls
+def tag_suffix(think_begin: str | None) -> str:
+ """The suffix every control tag of the chat template carries (Hy4: ":6124c78e"), read from the think-open token `<think{suffix}>`."""
+ m = re.fullmatch(r"<think(.*)>", think_begin or "")
+ return m.group(1) if m else ""
+
+
+class ToolTags:
+ """The tool-call tags the chat template writes and the model reads back (GLM shape, every tag carries the template suffix):
+
+ <tool_calls:S><tool_call:S>NAME<arg_key:S>K</arg_key:S><arg_value:S>V</arg_value:S>...</tool_call:S>...</tool_calls:S>
+ """
+
+ def __init__(self, suffix: str = ""):
+ def tag(name: str, close: bool = False) -> str:
+ return f"<{'/' if close else ''}{name}{suffix}>"
+ self.suffix = suffix
+ self.calls_open, self.calls_close = tag("tool_calls"), tag("tool_calls", True)
+ self.call_open, self.call_close = tag("tool_call"), tag("tool_call", True)
+ self.args_re = re.compile(re.escape(tag("arg_key")) + r"(.*?)" + re.escape(tag("arg_key", True)) + r"\s*" + re.escape(tag("arg_value")) + r"(.*?)"
+ + re.escape(tag("arg_value", True)), re.S)
+ self.opens = (self.calls_open, self.call_open)
+
+
+_TOOL_NAME_RE = re.compile(r"\s*([^\s<]+)")
+
+
+def _reject_constant(name: str):
+ raise ValueError(name)
+
+
+def _loads(text: str) -> Any:
+ """json.loads that refuses NaN / Infinity (not JSON: the arguments string must stay valid JSON)"""
+ return json.loads(text, parse_constant=_reject_constant)
+
+
+def tool_schemas(tools: list | None) -> dict[str, dict]:
+ """declared tool name -> its `parameters.properties` (empty when the tool takes none)"""
+ out: dict[str, dict] = {}
+ for t in tools or []:
+ fn = t.get("function", t)
+ out[fn.get("name")] = (fn.get("parameters") or {}).get("properties") or {}
+ return out
+
+
+def coerce_arg(value: str, schema: dict | None) -> Any:
+ """One argument written as text -> a typed value. The declared type of the parameter wins: a string parameter keeps its text exactly ("3" stays "3");
+ without a declaration the value is JSON when it parses and text when not."""
+ if not schema:
+ try:
+ return _loads(value.strip())
+ except ValueError:
+ return value.strip()
+ kind = schema.get("type")
+ kinds = [k for k in (kind if isinstance(kind, list) else [kind]) if isinstance(k, str)]
+ text = value.strip()
+ if "string" in kinds and not (text == "null" and "null" in kinds):
+ return value
+ if "boolean" in kinds and text.lower() in ("true", "false"):
+ return text.lower() == "true"
+ if "null" in kinds and text in ("null", "None"):
+ return None
+ for want, conv in (("integer", int), ("number", float)):
+ if want in kinds:
+ try:
+ got = conv(text)
+ except ValueError:
+ continue
+ if isinstance(got, float) and not math.isfinite(got):
+ continue
+ return got
+ try:
+ return _loads(value)
+ except ValueError:
+ return value
+
+
+def parse_tool_call(body: str, tags: ToolTags, schemas: dict[str, dict]) -> dict | None:
+ """The text between <tool_call> and </tool_call> -> {"name", "arguments" (a JSON object string)}, or None when it is not a call: no name, or a name the
+ request did not declare (the request declared tools and this is not one of them)."""
+ m = _TOOL_NAME_RE.match(body)
+ if not m:
+ return None
+ name = m.group(1)
+ if schemas and name not in schemas:
+ return None
+ props = schemas.get(name) or {}
+ args = {}
+ for k, v in tags.args_re.findall(body[m.end():]):
+ k = k.strip()
+ args[k] = coerce_arg(v, props.get(k))
+ return {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}
+
+
+def new_call_id() -> str:
+ return f"call_{uuid.uuid4().hex[:24]}"
+
+
# ------------------------------------------------------------------------------------------------ request parsing
def _as_int(body: dict, key: str, default: int | None, lo: int = 0) -> int | None:
v = body.get(key, default)
@@ -174,28 +276,142 @@ def _content_text(c: Any) -> str:
raise RequestError("message content must be a string or a list of text parts")
+def _function_tool(t: Any, where: str) -> dict:
+ """one tool of the request -> {"type": "function", "function": {name, description?, parameters?}}. Both spellings are read: the nested one
+ ({"type": "function", "function": {...}}) and the flat one the template also takes ({"name": ..., "parameters": ...})."""
+ if not isinstance(t, dict):
+ raise RequestError(f"{where} must be an object")
+ if t.get("type", "function") != "function":
+ raise RequestError(f"{where}: only function tools are supported (type {t.get('type')!r})")
+ fn = t["function"] if isinstance(t.get("function"), dict) else t
+ name = fn.get("name")
+ if not isinstance(name, str) or not re.fullmatch(r"[^\s<>]+", name):
+ raise RequestError(f"{where}: the function needs a name (a string without spaces)")
+ if fn.get("parameters") is not None and not isinstance(fn["parameters"], dict):
+ raise RequestError(f"{where}: parameters must be a JSON schema object")
+ return {"type": "function", "function": {k: v for k, v in fn.items() if k != "type" and v is not None}}
+
+
+TOOL_HINTS = {"required": "You must answer by calling one or more of the provided functions.",
+ "function": "You must answer by calling the function {name}."}
+
+
+def parse_tools(body: dict) -> dict:
+ """`tools` (or the legacy `functions`) and `tool_choice` (or the legacy `function_call`) of a chat request ->
+ {tools: the declared function tools the prompt carries (None = none), tool_choice: none | auto | required | function, tool_name, parse_tools, tool_hint}.
+ The chat template has no switch for tool_choice: "none" leaves the tools out of the prompt and the output is plain text; a named function keeps only that
+ tool in the prompt; "required" and a named function add one instruction line to the system message (best effort, the model decides)."""
+ raw = body.get("tools")
+ if raw is None or raw == []:
+ raw = body.get("functions")
+ if raw is not None and not isinstance(raw, list):
+ raise RequestError("tools must be a list")
+ tools = [_function_tool(t, f"tools[{i}]") for i, t in enumerate(raw or [])]
+ choice = body.get("tool_choice")
+ if choice is None:
+ choice = body.get("function_call")
+ name = None
+ if choice is None:
+ mode = "auto"
+ elif isinstance(choice, str):
+ if choice not in ("none", "auto", "required"):
+ raise RequestError("tool_choice must be none, auto, required or a function")
+ mode = choice
+ elif isinstance(choice, dict):
+ fn = choice.get("function") if isinstance(choice.get("function"), dict) else choice
+ name = fn.get("name")
+ if choice.get("type", "function") != "function" or not isinstance(name, str) or not name:
+ raise RequestError("tool_choice must be none, auto, required or {\"type\": \"function\", \"function\": {\"name\": ...}}")
+ mode = "function"
+ else:
+ raise RequestError("tool_choice must be a string or an object")
+ if mode in ("required", "function") and not tools:
+ raise RequestError(f"tool_choice {mode if mode == 'required' else repr(name)} needs tools")
+ if mode == "function":
+ tools = [t for t in tools if t["function"]["name"] == name]
+ if not tools:
+ raise RequestError(f"tool_choice names the function {name!r}, which is not in tools")
+ if mode == "none":
+ tools = []
+ return {"tools": tools or None, "tool_choice": mode, "tool_name": name, "parse_tools": bool(tools),
+ "tool_hint": TOOL_HINTS.get(mode, "").format(name=name)}
+
+
+def _call_arguments(args: Any, where: str) -> dict:
+ """arguments of an assistant tool call: a JSON object string (OpenAI) or an object -> the object the template iterates"""
+ if args is None or (isinstance(args, str) and not args.strip()):
+ return {}
+ if isinstance(args, str):
+ try:
+ args = _loads(args)
+ except ValueError:
+ raise RequestError(f"{where}: function.arguments is not valid JSON") from None
+ if not isinstance(args, dict):
+ raise RequestError(f"{where}: function.arguments must be a JSON object")
+ return args
+
+
+def _assistant_calls(m: dict, where: str) -> list[dict]:
+ calls = m.get("tool_calls")
+ if calls is None and isinstance(m.get("function_call"), dict): # legacy single call
+ calls = [{"function": m["function_call"]}]
+ if calls is None:
+ return []
+ if not isinstance(calls, list):
+ raise RequestError(f"{where}: tool_calls must be a list")
+ out = []
+ for j, c in enumerate(calls):
+ w = f"{where}.tool_calls[{j}]"
+ fn = c.get("function") if isinstance(c, dict) else None
+ if not isinstance(fn, dict) or not isinstance(fn.get("name"), str) or not fn["name"]:
+ raise RequestError(f"{w}: needs function.name")
+ item = {"type": "function", "function": {"name": fn["name"], "arguments": _call_arguments(fn.get("arguments"), w)}}
+ if isinstance(c.get("id"), str) and c["id"]:
+ item["id"] = c["id"]
+ out.append(item)
+ return out
+
+
+CHAT_ROLES = {"system": "system", "developer": "system", "user": "user", "assistant": "assistant", "tool": "tool", "function": "tool"}
+
+
def parse_chat(body: dict, default_max: int = 1024) -> dict:
- """-> {messages, effort, max_tokens, stream, stop, include_usage, speculative, ...}. Raises RequestError."""
+ """-> {messages, effort, max_tokens, stream, stop, include_usage, speculative, tools, tool_choice, parse_tools, ...}. Raises RequestError.
+ Messages: assistant messages may carry tool_calls (arguments as a JSON string or an object), `tool` messages carry the result of a call (tool_call_id)."""
req = _common(body, default_max)
- if body.get("tools") or body.get("functions") or body.get("tool_choice") not in (None, "none"):
- raise RequestError("tool calling is not supported by this backend yet")
+ req.update(parse_tools(body))
msgs = body.get("messages")
if not isinstance(msgs, list) or not msgs:
raise RequestError("messages must be a non-empty list")
out = []
for i, m in enumerate(msgs):
- if not isinstance(m, dict) or m.get("role") not in ("system", "developer", "user", "assistant"):
- raise RequestError(f"messages[{i}]: role must be system, user or assistant")
- role = "system" if m["role"] == "developer" else m["role"]
+ 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")
item = {"role": role, "content": _content_text(m.get("content"))}
rc = m.get("reasoning_content", m.get("reasoning"))
- if role == "assistant" and isinstance(rc, str) and rc:
- item["reasoning_content"] = rc
+ if role == "assistant":
+ if isinstance(rc, str) and rc:
+ item["reasoning_content"] = rc
+ calls = _assistant_calls(m, f"messages[{i}]")
+ if calls:
+ item["tool_calls"] = calls
+ elif role == "tool":
+ tcid = m.get("tool_call_id")
+ if tcid is not None and not isinstance(tcid, str):
+ raise RequestError(f"messages[{i}]: tool_call_id must be a string")
+ if tcid:
+ item["tool_call_id"] = tcid
out.append(item)
if out[-1]["role"] == "assistant":
raise RequestError("the last message must come from the user")
+ if req["tool_hint"]:
+ if out[0]["role"] == "system":
+ out[0] = dict(out[0], content=(out[0]["content"] + "\n\n" if out[0]["content"] else "") + req["tool_hint"])
+ else:
+ out.insert(0, {"role": "system", "content": req["tool_hint"]})
req.update(messages=out, effort=parse_effort(body))
return req
@@ -255,22 +471,72 @@ def _hold(text: str, markers: list[str]) -> int:
class OutputStream:
- """Per request: token ids in, (channel, text) deltas out, channel = "reasoning" | "content".
+ """Per request: token ids in, (channel, payload) deltas out, channel = "reasoning" | "content" (payload: text) | "tool_call" (payload: {"name", "arguments"},
+ arguments = a JSON object string).
in_think: the prompt ended inside an open think block, so the text starts as reasoning until `think_end`.
- Stops on an EOS id (dropped) or a stop string (cut; only searched in the content channel)."""
+ Stops on an EOS id (dropped) or a stop string (cut; only searched in the content channel).
+ parse_tools: a tool block (<tool_calls> ... </tool_calls>, or a bare <tool_call> ... </tool_call>) in the content is held back and read call by call, each call
+ leaves as a "tool_call" delta the moment its </tool_call> arrives. `tools` (the declared tools) types the arguments and names the calls that count: a block
+ that is not a valid call (cut off, no name, a function the request did not declare) stays plain content. A tool block is only looked for after the reasoning."""
- def __init__(self, vocab: Vocab, in_think: bool = False, stops: list[str] | None = None):
+ def __init__(self, vocab: Vocab, in_think: bool = False, stops: list[str] | None = None, tools: list | None = None, parse_tools: bool = False):
self.v = vocab
self.dec = IncrementalDecoder(vocab)
self.in_think = bool(in_think and vocab.think_end)
self.stops = stops or []
+ self.tags = vocab.tool_tags
+ self.parse_tools = bool(parse_tools)
+ self.schemas = tool_schemas(tools)
+ self.tool_text: str | None = None # the tool block being read (None: not inside one); for <tool_calls> the text after the open tag
+ self.tool_wrapped = False
+ self.tool_pos = 0
+ self.n_calls = 0
self.buf = ""
self.done = False
self.finish_reason: str | None = None
self.n_tokens = 0 # generated tokens counted (EOS and anything after it excluded)
- def _drain(self, final: bool) -> list[tuple[str, str]]:
- out: list[tuple[str, str]] = []
+ def _tool_open(self) -> tuple[int, str]:
+ hits = [(i, t) for t in self.tags.opens for i in [self.buf.find(t)] if i >= 0]
+ return min(hits) if hits else (-1, "")
+
+ def _read_tool_block(self, out: list, final: bool) -> bool:
+ """read the held tool block as far as it is complete; True when the block ended (the text after it is content again)"""
+ tg = self.tags
+ self.tool_text += self.buf
+ self.buf = ""
+ while True:
+ t, pos = self.tool_text, self.tool_pos
+ end = t.find(tg.calls_close, pos) if self.tool_wrapped else -1
+ start = t.find(tg.call_open, pos)
+ if end >= 0 and (start < 0 or end < start):
+ if t[pos:end].strip():
+ out.append(("content", t[pos:end].strip()))
+ self.buf, self.tool_text = t[end + len(tg.calls_close):], None
+ return True
+ stop = t.find(tg.call_close, start + len(tg.call_open)) if start >= 0 else -1
+ if stop < 0:
+ break
+ if t[pos:start].strip():
+ out.append(("content", t[pos:start].strip()))
+ call = parse_tool_call(t[start + len(tg.call_open):stop], tg, self.schemas)
+ if call:
+ self.n_calls += 1
+ out.append(("tool_call", call))
+ else:
+ out.append(("content", t[start:stop + len(tg.call_close)]))
+ self.tool_pos = stop + len(tg.call_close)
+ if not self.tool_wrapped:
+ self.buf, self.tool_text = t[self.tool_pos:], None
+ return True
+ if final:
+ if t[pos:].strip():
+ out.append(("content", t[pos:].strip())) # a block cut off by the end of the stream
+ self.tool_text = None
+ return False
+
+ def _drain(self, final: bool) -> list[tuple[str, Any]]:
+ out: list[tuple[str, Any]] = []
while True:
if self.in_think:
i = self.buf.find(self.v.think_end)
@@ -285,20 +551,37 @@ class OutputStream:
out.append(("reasoning", self.buf[:len(self.buf) - k]))
self.buf = self.buf[len(self.buf) - k:]
break
+ if self.tool_text is not None:
+ if self._read_tool_block(out, final):
+ continue
+ break
cut = min((j for j in (self.buf.find(s) for s in self.stops) if j >= 0), default=-1)
- if cut >= 0:
+ at, tag = self._tool_open() if self.parse_tools else (-1, "")
+ if cut >= 0 and (at < 0 or cut < at):
if cut:
out.append(("content", self.buf[:cut]))
self.buf, self.done, self.finish_reason = "", True, "stop"
break
- k = 0 if final else _hold(self.buf, self.stops)
+ if at >= 0:
+ if self.buf[:at].rstrip():
+ out.append(("content", self.buf[:at].rstrip()))
+ self.tool_wrapped, self.tool_pos = tag == self.tags.calls_open, 0
+ self.tool_text = self.buf[at + len(tag):] if self.tool_wrapped else self.buf[at:]
+ self.buf = ""
+ continue
+ k = 0 if final else _hold(self.buf, self.stops + (list(self.tags.opens) if self.parse_tools else []))
+ if self.parse_tools and not final: # the whitespace before a tool block is dropped: wait for the next character
+ start = len(self.buf) - k
+ while start > 0 and self.buf[start - 1].isspace():
+ start -= 1
+ k = len(self.buf) - start
if len(self.buf) > k:
out.append(("content", self.buf[:len(self.buf) - k]))
self.buf = self.buf[len(self.buf) - k:]
break
return out
- def push(self, ids: list[int]) -> list[tuple[str, str]]:
+ def push(self, ids: list[int]) -> list[tuple[str, Any]]:
"""feed the tokens of one decode round; returns the deltas that are safe to send. `done` turns True on EOS or a stop string."""
if self.done:
return []
@@ -317,7 +600,7 @@ class OutputStream:
self.done, self.finish_reason = True, "stop"
return out
- def finish(self) -> list[tuple[str, str]]:
+ def finish(self) -> list[tuple[str, Any]]:
"""flush at the end of the stream when it ended on the length limit (nothing is left after EOS or a stop string)"""
if self.done:
return []
@@ -326,6 +609,11 @@ class OutputStream:
self.buf = ""
return out
+ def final_reason(self) -> str:
+ """finish_reason of the reply: tool_calls when the model ended its turn with calls, else stop / length"""
+ reason = self.finish_reason or "length"
+ return "tool_calls" if self.n_calls and reason == "stop" else reason
+
# ------------------------------------------------------------------------------------------------ response bodies
ABLIT_OFF = ("", "off", "0", "false", "no", "none")
@@ -356,10 +644,25 @@ def chat_chunk(rid: str, model: str, created: int, delta: dict, finish: str | No
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **extra}
-def chat_response(rid: str, model: str, created: int, content: str, reasoning: str, finish: str, usage: dict, **extra: Any) -> dict:
+def tool_call_item(call: dict, call_id: str) -> dict:
+ """{"name", "arguments"} of the parser -> an OpenAI tool_calls entry"""
+ return {"id": call_id, "type": "function", "function": {"name": call["name"], "arguments": call["arguments"]}}
+
+
+def tool_call_deltas(index: int, call_id: str, call: dict) -> list[dict]:
+ """the two streaming deltas of one call, as OpenAI sends them: id + name (empty arguments), then the arguments"""
+ return [{"tool_calls": [{"index": index, "id": call_id, "type": "function", "function": {"name": call["name"], "arguments": ""}}]},
+ {"tool_calls": [{"index": index, "function": {"arguments": call["arguments"]}}]}]
+
+
+def chat_response(rid: str, model: str, created: int, content: str, reasoning: str, finish: str, usage: dict, tool_calls: list[dict] | None = None, **extra: Any) -> dict:
msg: dict[str, Any] = {"role": "assistant", "content": content}
if reasoning:
msg["reasoning_content"] = reasoning
+ if tool_calls:
+ msg["tool_calls"] = tool_calls
+ if not content.strip():
+ msg["content"] = None
return {"id": rid, "object": "chat.completion", "created": created, "model": model,
"choices": [{"index": 0, "message": msg, "finish_reason": finish}], "usage": usage, **extra}