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.

Servers: always end a chat stream with finish_reason, honor max_completion_tokens

YanissAmz08bd41fe973b
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 734fb3e..a8318b5 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -67,7 +67,7 @@ Honored:
because the GLM template iterates them as a dict.
- `tools` — passed to the template verbatim (no server-side validation).
- `stream` (bool) — SSE or a single JSON body.
-- `max_tokens` (default **4096**), `temperature` (default **0.0** → greedy),
+- `max_completion_tokens` or `max_tokens` (the first wins; default **4096**), `temperature` (default **0.0** → greedy),
`top_p` (default 1.0), `stop` (string or array; also fed to EXL3 as stop conditions).
- `model` — must equal `--model-id` if present, else 400.
- `clear_thinking` — forwarded to the template as a Jinja variable.
@@ -90,6 +90,8 @@ name is emitted); frames are:
`usage: {prompt_tokens, completion_tokens, total_tokens}`;
5. `data: [DONE]`.
+If the engine fails mid-stream, the server sends a frame `{"error": {"message": ...}}`, a final frame with `finish_reason: "error"`, then `data: [DONE]`.
+
Every frame carries `id`, `object: chat.completion.chunk`, `created`, `model`.
Non-streaming returns `chat.completion` with `choices[0].message` holding `content`,
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 9379b1a..48e04f1 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -195,6 +195,15 @@ def stop_text(text: str, stop: list[str]) -> tuple[str, str | None]:
return text[:pos], match
+def token_limit(body: dict[str, Any], default: int = 4096) -> int:
+ """Reply token budget: max_completion_tokens (newer OpenAI field) wins over max_tokens."""
+ for key in ("max_completion_tokens", "max_tokens"):
+ value = body.get(key)
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 1:
+ return value
+ return default
+
+
def sse(data: dict[str, Any], event: str | None = None) -> bytes:
prefix = f"event: {event}\n" if event else ""
return (prefix + f"data: {json.dumps(data, ensure_ascii=False, separators=(',', ':'))}\n\n").encode()
@@ -421,7 +430,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
store.busy = True
async for delta in engine.generate(
body["_prompt"],
- max_tokens=body.get("max_tokens", 4096), temperature=body.get("temperature", 0.0),
+ max_tokens=token_limit(body), temperature=body.get("temperature", 0.0),
top_p=body.get("top_p", 1.0), stop=body.get("_stop", [])):
out.put_nowait(delta)
out.put_nowait(None)
@@ -485,7 +494,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def finish_for(message: dict[str, Any], raw: str) -> str:
# A reply cut by max_tokens is "length", not "stop" (clients use it to tell a truncated answer).
finish = message.pop("finish_reason", "stop")
- if finish == "stop" and engine.count_tokens(raw) >= body.get("max_tokens", 4096):
+ if finish == "stop" and engine.count_tokens(raw) >= token_limit(body):
finish = "length"
return finish
@@ -525,20 +534,33 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
done = pos + len(tag)
mode = {"</think>": "content", "<think>": "reasoning", TOOL_OPEN: "tool"}[tag]
- await response.write(sse(event({"role": "assistant", "content": ""})))
- async for delta in deltas():
- text += delta
- await flush(False)
- text, _ = stop_text(text, body["_stop"])
- await flush(True)
- message = parse_completion(text)
- if "tool_calls" in message:
- await response.write(sse(event({"tool_calls": [
- dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
- await response.write(sse(event({}, finish_for(message, text[len(prefix):])) |
- {"usage": usage(text[len(prefix):]), "timings": timings(text)}))
- await response.write(b"data: [DONE]\n\n")
- await response.write_eof()
+ try:
+ await response.write(sse(event({"role": "assistant", "content": ""})))
+ async for delta in deltas():
+ text += delta
+ await flush(False)
+ text, _ = stop_text(text, body["_stop"])
+ await flush(True)
+ message = parse_completion(text)
+ if "tool_calls" in message:
+ await response.write(sse(event({"tool_calls": [
+ dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
+ await response.write(sse(event({}, finish_for(message, text[len(prefix):])) |
+ {"usage": usage(text[len(prefix):]), "timings": timings(text)}))
+ await response.write(b"data: [DONE]\n\n")
+ await response.write_eof()
+ except (ConnectionResetError, asyncio.CancelledError):
+ raise # client left: nothing to send
+ except Exception as exc: # noqa: BLE001
+ # Fail inside the stream, but still end it the OpenAI way: clients such as OpenCode report
+ # "stream ended without finish_reason" and retry when the connection just drops.
+ try:
+ await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
+ await response.write(sse(event({}, "error")))
+ await response.write(b"data: [DONE]\n\n")
+ await response.write_eof()
+ except ConnectionError:
+ pass
return response
raw = "".join([d async for d in deltas()])
diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.py
index f5c8deb..04aae1e 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -54,6 +54,56 @@ class ServeTests(unittest.TestCase):
self.assertEqual(os.environ["EXL3_MTP_EH_FP16"], "/nope/x.safetensors")
self.assertNotIn("EXL3_MTP_EH_FP16", serve.SPEED_ENV)
+ def test_stream_engine_error_still_ends_with_finish_reason(self):
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class Boom(FakeEngine):
+ async def generate(self, prompt: str, **kwargs):
+ yield "partial "
+ raise RuntimeError("kaput")
+
+ async def check():
+ client = TestClient(TestServer(serve.create_app(Boom("x"), "m", self.template)))
+ await client.start_server()
+ r = await client.post("/v1/chat/completions", json={
+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})
+ raw = (await r.read()).decode()
+ await client.close()
+ return raw
+
+ raw = run(check())
+ self.assertTrue(raw.endswith("data: [DONE]\n\n"))
+ chunks = [json.loads(l[6:]) for l in raw.split("\n") if l.startswith("data: {")]
+ self.assertTrue(any("kaput" in c.get("error", {}).get("message", "") for c in chunks))
+ self.assertEqual(chunks[-1]["choices"][0]["finish_reason"], "error")
+
+ def test_max_completion_tokens_is_honored(self):
+ self.assertEqual(serve.token_limit({"max_completion_tokens": 7, "max_tokens": 9}), 7)
+ self.assertEqual(serve.token_limit({"max_tokens": 9}), 9)
+ self.assertEqual(serve.token_limit({"max_tokens": None}), 4096)
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class Spy(FakeEngine):
+ async def generate(self, prompt: str, **kwargs):
+ self.kwargs = kwargs
+ async for piece in super().generate(prompt, **kwargs):
+ yield piece
+
+ engine = Spy("one two three four")
+
+ async def check():
+ client = TestClient(TestServer(serve.create_app(engine, "m", self.template)))
+ await client.start_server()
+ r = await client.post("/v1/chat/completions", json={
+ "model": "m", "max_completion_tokens": 4, "messages": [{"role": "user", "content": "hi"}]})
+ body = await r.json()
+ await client.close()
+ return body
+
+ body = run(check())
+ self.assertEqual(engine.kwargs["max_tokens"], 4)
+ self.assertEqual(body["choices"][0]["finish_reason"], "length")
+
def test_template_rendering(self):
out = serve.render_prompt(self.template, [{"role": "user", "content": "hi"}], [{"type": "function"}])
self.assertEqual(out, "<|im_start|>user: hi<|im_end|>TOOLS=1")
diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.md
index 0cd601d..42509e3 100644
--- a/tools/mimo/SERVE.md
+++ b/tools/mimo/SERVE.md
@@ -37,7 +37,7 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
- `POST /v1/chat/completions` — `stream: true` (SSE `chat.completion.chunk`) and `false`.
`tools` / `tool_calls` / `tool` role messages, `reasoning_content` for `<think>` blocks,
- `stop` (string or list), `temperature`, `top_p`, `max_tokens`. Tool calls are emitted only
+ `stop` (string or list), `temperature`, `top_p`, `max_completion_tokens` or `max_tokens` (the first wins; default 4096). A reply cut by the limit reports `finish_reason: "length"`. An engine failure mid-stream ends with an `error` frame, `finish_reason: "error"` and `[DONE]`. Tool calls are emitted only
once the XML block closes, so a client never sees half a JSON payload.
- `GET /v1/models` — one entry, `MiMo-2.6-EXL3`.
- `GET /health` — `{"status","model","generator","spec_gate"}`; with the gate on, `spec_gate`
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 8f22a77..24afb7a 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -145,6 +145,15 @@ def stop_text(text: str, stop: list[str]) -> tuple[str, str | None]:
return text[:pos], match
+def token_limit(body: dict[str, Any], default: int = 4096) -> int:
+ """Reply token budget: max_completion_tokens (newer OpenAI field) wins over max_tokens."""
+ for key in ("max_completion_tokens", "max_tokens"):
+ value = body.get(key)
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 1:
+ return value
+ return default
+
+
def sse(data: dict[str, Any], event: str | None = None) -> bytes:
prefix = f"event: {event}\n" if event else ""
return (prefix + f"data: {json.dumps(data, ensure_ascii=False, separators=(',', ':'))}\n\n").encode()
@@ -302,7 +311,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
store.busy = True
async for delta in engine.generate(
body["_prompt"],
- max_tokens=body.get("max_tokens", 4096),
+ max_tokens=token_limit(body),
temperature=body.get("temperature", SERVE_DEFAULTS["temperature"]),
top_p=body.get("top_p", SERVE_DEFAULTS["top_p"]), stop=body.get("_stop", []),
reset_gate=body.get("_reset_gate", False)):
@@ -370,7 +379,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def finish_for(message: dict[str, Any], raw: str) -> str:
# A reply cut by max_tokens is "length", not "stop" (clients use it to tell a truncated answer).
finish = message.pop("finish_reason", "stop")
- if finish == "stop" and engine.count_tokens(raw) >= body.get("max_tokens", 4096):
+ if finish == "stop" and engine.count_tokens(raw) >= token_limit(body):
finish = "length"
return finish
@@ -414,20 +423,33 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
done = pos + len(tag)
mode = tag_mode[tag]
- await response.write(sse(event({"role": "assistant", "content": ""})))
- async for delta in deltas():
- text += delta
- await flush(False)
- text, _ = stop_text(text, body["_stop"])
- await flush(True)
- message = parse_completion(text)
- if "tool_calls" in message:
- await response.write(sse(event({"tool_calls": [
- dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
- await response.write(sse(event({}, finish_for(message, text)) |
- {"usage": usage(text), "timings": timings()}))
- await response.write(b"data: [DONE]\n\n")
- await response.write_eof()
+ try:
+ await response.write(sse(event({"role": "assistant", "content": ""})))
+ async for delta in deltas():
+ text += delta
+ await flush(False)
+ text, _ = stop_text(text, body["_stop"])
+ await flush(True)
+ message = parse_completion(text)
+ if "tool_calls" in message:
+ await response.write(sse(event({"tool_calls": [
+ dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
+ await response.write(sse(event({}, finish_for(message, text)) |
+ {"usage": usage(text), "timings": timings()}))
+ await response.write(b"data: [DONE]\n\n")
+ await response.write_eof()
+ except (ConnectionResetError, asyncio.CancelledError):
+ raise # client left: nothing to send
+ except Exception as exc: # noqa: BLE001
+ # Fail inside the stream, but still end it the OpenAI way: clients such as OpenCode report
+ # "stream ended without finish_reason" and retry when the connection just drops.
+ try:
+ await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
+ await response.write(sse(event({}, "error")))
+ await response.write(b"data: [DONE]\n\n")
+ await response.write_eof()
+ except ConnectionError:
+ pass
return response
raw = "".join([d async for d in deltas()])
diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.py
index 38e88db..c805f2c 100644
--- a/tools/mimo/test_serve.py
+++ b/tools/mimo/test_serve.py
@@ -211,6 +211,59 @@ class ServeTests(unittest.TestCase):
self.assertEqual(run(call("one two three four", 4, stream)), "length")
self.assertEqual(run(call("one two", 4, stream)), "stop")
+ def test_stream_engine_error_still_ends_with_finish_reason(self):
+ """An engine failure mid-stream ends with an error frame, finish_reason and [DONE], not a dropped connection."""
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class Boom(FakeEngine):
+ async def generate(self, prompt, **kwargs):
+ yield "partial "
+ raise RuntimeError("kaput")
+
+ async def check():
+ client = TestClient(TestServer(serve.create_app(Boom("x"), "m", TEMPLATE)))
+ await client.start_server()
+ r = await client.post("/v1/chat/completions", json={
+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})
+ raw = (await r.read()).decode()
+ await client.close()
+ return raw
+
+ raw = run(check())
+ self.assertTrue(raw.endswith("data: [DONE]\n\n"))
+ chunks = [json.loads(l[6:]) for l in raw.split("\n") if l.startswith("data: {")]
+ self.assertTrue(any("kaput" in c.get("error", {}).get("message", "") for c in chunks))
+ self.assertEqual(chunks[-1]["choices"][0]["finish_reason"], "error")
+
+ def test_max_completion_tokens_is_honored(self):
+ """The newer OpenAI field sets the budget (and the "length" verdict) like max_tokens."""
+ self.assertEqual(serve.token_limit({"max_completion_tokens": 7, "max_tokens": 9}), 7)
+ self.assertEqual(serve.token_limit({"max_tokens": 9}), 9)
+ self.assertEqual(serve.token_limit({"max_tokens": None}), 4096)
+ self.assertEqual(serve.token_limit({}), 4096)
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class Spy(FakeEngine):
+ async def generate(self, prompt, **kwargs):
+ self.kwargs = kwargs
+ async for piece in super().generate(prompt, **kwargs):
+ yield piece
+
+ engine = Spy("one two three four")
+
+ async def check():
+ client = TestClient(TestServer(serve.create_app(engine, "m", TEMPLATE)))
+ await client.start_server()
+ r = await client.post("/v1/chat/completions", json={
+ "model": "m", "max_completion_tokens": 4, "messages": [{"role": "user", "content": "hi"}]})
+ body = await r.json()
+ await client.close()
+ return body
+
+ body = run(check())
+ self.assertEqual(engine.kwargs["max_tokens"], 4)
+ self.assertEqual(body["choices"][0]["finish_reason"], "length")
+
def test_stop_string_cuts_stream(self):
from aiohttp.test_utils import TestClient, TestServer
engine = FakeEngine("alpha STOP beta")
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index edebaa0..c3a7c44 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -1094,6 +1094,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
job["cancel"].set()
try:
await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
+ # End the stream the OpenAI way: a bare drop makes clients report "stream ended without finish_reason".
+ await response.write(sse(event({}, "error")))
+ await response.write(b"data: [DONE]\n\n")
await response.write_eof()
except ConnectionError:
pass
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index ce914f8..0453f7d 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -422,6 +422,18 @@ class HttpTests(unittest.TestCase):
self.assertIn("kaput", body["error"]["message"])
+ def test_stream_engine_error_still_ends_with_finish_reason(self):
+ class Boom(FakeEngine):
+ async def generate(self, prompt, **kw):
+ yield "abc "
+ raise RuntimeError("kaput")
+ _, raw = self.chat(Boom(""), {"messages": [{"role": "user", "content": "hi"}]}, stream=True)
+ self.assertTrue(raw.endswith("data: [DONE]\n\n"))
+ ev = sse_events(raw)
+ self.assertIn("kaput", [e for e in ev if "error" in e][0]["error"]["message"])
+ self.assertEqual(ev[-1]["choices"][0]["finish_reason"], "error")
+
+
class MiscTests(unittest.TestCase):
def test_sse_framing_and_stop_text(self):
self.assertEqual(serve.sse({"a": 1}), b'data: {"a":1}\n\n')