Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

Apply the implicit GLM stop sequences on /v1/messages too

bharathgnana033df1af9530
diff --git a/c/openai_server.py b/c/openai_server.py
index 496de3c0..cf2f5279 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1989,6 +1989,10 @@ class APIHandler(BaseHTTPRequestHandler):
def anthropic_generation(self, body, prompt, request_id, tools, enable_thinking):
maximum, temperature, top_p, grammar, _stop_sequences = generation_options(
body, self.server.max_tokens)
+ # Same policy as /v1/chat/completions: `body` is the translated OpenAI-shaped
+ # request, and anthropic_messages() has already refused a client `stop_sequences`,
+ # so this resolves to the implicit GLM role boundaries.
+ stop_sequences, ignore_leading_stop = stop_policy(body, True)
cache_slot = body.get("cache_slot")
if (cache_slot is not None and
(isinstance(cache_slot, bool) or not isinstance(cache_slot, int) or
@@ -2028,9 +2032,11 @@ class APIHandler(BaseHTTPRequestHandler):
queue_headers = {"x-colibri-queue-wait-ms": str(round(queue_wait * 1000))}
if not stream:
output = []
+ stop_filter = StopFilter(stop_sequences, output.append, ignore_leading_stop)
stats = self.server.engine.generate(
- prompt, maximum, temperature, top_p, output.append, cache_slot,
- self.client_disconnected, grammar=grammar)
+ prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,
+ self.client_disconnected, grammar=grammar, stopped=stop_filter.stopped)
+ stop_filter.finish()
content, stop_reason = blocks_and_stop("".join(output), stats)
self.send_json(200, {
"id": message_id, "type": "message", "role": "assistant",
@@ -2147,9 +2153,11 @@ class APIHandler(BaseHTTPRequestHandler):
raw.append(chunk)
(split.feed if split else emit_answer)(chunk)
+ stop_filter = StopFilter(stop_sequences, on_text, ignore_leading_stop)
stats = self.server.engine.generate(
- prompt, maximum, temperature, top_p, on_text, cache_slot,
- lambda: not connected[0], grammar=grammar)
+ prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,
+ lambda: not connected[0], grammar=grammar, stopped=stop_filter.stopped)
+ stop_filter.finish()
if split:
split.finish()
close_thinking() # budget exhaustion before </think>
diff --git a/c/tests/test_anthropic_messages.py b/c/tests/test_anthropic_messages.py
index b34c00a3..fcb7088f 100644
--- a/c/tests/test_anthropic_messages.py
+++ b/c/tests/test_anthropic_messages.py
@@ -28,10 +28,14 @@ class FakeEngine:
self.prompts = []
def generate(self, prompt, maximum, temperature, top_p, on_text, cache_slot=0,
- cancelled=None, grammar=None):
+ cancelled=None, grammar=None, stopped=None, on_accept=None):
self.prompts.append(prompt)
+ self.emitted = 0
for chunk in self.script:
on_text(chunk)
+ self.emitted += 1
+ if stopped is not None and stopped():
+ break # the gateway hit a stop sequence
return {"prompt_tokens": 11, "completion_tokens": 3,
"length_limited": self.length_limited}
@@ -182,6 +186,37 @@ class MessagesHTTPTest(unittest.TestCase):
self.assertEqual(payloads[-2]["delta"]["stop_reason"], "end_turn")
self.assertEqual(payloads[-2]["usage"]["output_tokens"], 3)
+ def test_role_marker_ends_the_turn(self):
+ """/v1/messages must apply the same implicit GLM stop sequences as
+ /v1/chat/completions. In serve mode the engine arms only <|endoftext|>
+ (#401/#549), so <|user|> arrives as ordinary text; without the filter it is
+ detokenized into the reply and generation runs on to max_tokens."""
+ script = ("ready", "<|user|>", "the user asks about cake")
+ self.engine.script = script
+ with self.post(self.base_body()) as response:
+ payload = json.load(response)
+ self.assertEqual(payload["content"], [{"type": "text", "text": "ready"}])
+ self.assertEqual(payload["stop_reason"], "end_turn")
+ self.assertEqual(self.engine.emitted, 2) # tail cancelled, not merely hidden
+
+ def test_role_marker_ends_a_streamed_turn(self):
+ self.engine.script = ("ready", "<|user|>", "the user asks about cake")
+ with self.post(self.base_body(stream=True)) as response:
+ raw = response.read().decode()
+ self.assertNotIn("<|user|>", raw)
+ deltas = [json.loads(line[len("data: "):]) for line in raw.splitlines()
+ if line.startswith("data: ")]
+ text = "".join(d["delta"]["text"] for d in deltas
+ if d["type"] == "content_block_delta" and "text" in d["delta"])
+ self.assertEqual(text, "ready")
+ self.assertEqual(self.engine.emitted, 2)
+
+ def test_marker_split_across_chunks_is_still_caught(self):
+ self.engine.script = ("read", "y<|", "user|>", "cake")
+ with self.post(self.base_body()) as response:
+ payload = json.load(response)
+ self.assertEqual(payload["content"], [{"type": "text", "text": "ready"}])
+
def test_tool_call_becomes_tool_use_block(self):
self.engine.script = ("Sure. <tool_call>get_weather<arg_key>city</arg_key>"
"<arg_value>Rome</arg_value></tool_call>",)