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

feat: add opt-in strict GLM tool-call parsing

bherald251b77bbea91
diff --git a/c/openai_server.py b/c/openai_server.py
index fdab0091..ee05a9d8 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -716,6 +716,65 @@ def parse_tool_calls(reply, tools=None):
return content, calls
+def parse_glm_tool_calls_strict(reply, tools):
+ """Parse complete GLM calls against declared schemas, without recovery or salvage.
+
+ A client can opt into this when executing a malformed call would be worse than
+ receiving a named model-output error. The default parser remains permissive.
+ """
+ def invalid(reason):
+ raise APIError(502, "Invalid GLM tool call: " + reason, code="invalid_model_tool_call",
+ error_type="server_error")
+
+ declared = {_tool_function(tool).get("name"): _tool_function(tool).get("parameters") or {}
+ for tool in tools}
+ calls = []
+ boxes = list(_BOX_RE.finditer(reply))
+ outside = _BOX_RE.sub("", reply)
+ if re.search(r"</?tool_call|</?arg_(?:key|value)", outside):
+ invalid("incomplete or stray tool marker")
+ for box in boxes:
+ inner = box.group(1)
+ name_match = _NAME_RE.match(inner)
+ if not name_match or name_match.group(1) not in declared:
+ invalid("undeclared function")
+ name = name_match.group(1)
+ params = declared[name]
+ properties = params.get("properties") or {}
+ args = {}
+ cursor = name_match.end()
+ while inner[cursor:].strip():
+ prefix = len(inner[cursor:]) - len(inner[cursor:].lstrip())
+ cursor += prefix
+ match = _ARG_RE.match(inner, cursor)
+ if not match:
+ invalid("malformed argument syntax")
+ key, value = match.groups()
+ if key not in properties or key in args or re.search(r"</?arg_(?:key|value)|</?tool_call", value):
+ invalid("unknown, duplicate, or malformed argument")
+ spec = properties[key] if isinstance(properties[key], dict) else {}
+ declared_type = spec.get("type")
+ if isinstance(declared_type, list):
+ declared_type = next((item for item in declared_type if item != "null"), None)
+ parsed = _coerce_arg(value, declared_type)
+ valid = (declared_type in (None, "string") or
+ (declared_type == "integer" and type(parsed) is int) or
+ (declared_type == "number" and type(parsed) in (int, float)) or
+ (declared_type == "boolean" and type(parsed) is bool) or
+ (declared_type == "array" and isinstance(parsed, list)) or
+ (declared_type == "object" and isinstance(parsed, dict)))
+ if not valid:
+ invalid("argument does not match its declared type")
+ args[key] = parsed
+ cursor = match.end()
+ if any(key not in args for key in params.get("required") or []):
+ invalid("missing required argument")
+ calls.append({"id": "call_" + uuid.uuid4().hex[:24], "type": "function",
+ "function": {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}})
+ content, _box_map, _content_map = _tool_call_content_spans(reply, None, False)
+ return content, calls
+
+
def parse_tool_calls_spans(reply, tools=None):
"""parse_tool_calls plus the tool-call stage's maps."""
return _parse_tool_calls(reply, tools, True)
@@ -6379,7 +6438,12 @@ class APIHandler(BaseHTTPRequestHandler):
# describe the string it produces. It reads nothing the tail writes.
content, calls, content_spans = None, [], None
if chat and tools:
- if engine_k:
+ if body.get("strict_tool_calls") and ARCH == "glm":
+ if stats["length_limited"] and BOX_START in text:
+ raise APIError(502, "GLM tool call ended at the generation limit.",
+ code="invalid_model_tool_call", error_type="server_error")
+ content, calls = parse_glm_tool_calls_strict(text, tools)
+ elif engine_k:
content, calls, _box_spans, tool_spans = parse_arch_tool_calls_spans(
text, tools, sideband.reply())
else:
@@ -6653,6 +6717,18 @@ class APIHandler(BaseHTTPRequestHandler):
"total_tokens": prompt + completion}
def chat_completion(self, body, request_id):
+ strict_tools = body.get("strict_tool_calls", False)
+ if not isinstance(strict_tools, bool):
+ raise APIError(400, "`strict_tool_calls` must be a boolean.", "strict_tool_calls")
+ if strict_tools and ARCH != "glm":
+ raise APIError(400, "`strict_tool_calls` currently supports GLM only.",
+ "strict_tool_calls", "unsupported_parameter")
+ if strict_tools and body.get("stream") is True:
+ raise APIError(400, "`strict_tool_calls` requires `stream: false`.",
+ "stream", "unsupported_parameter")
+ if strict_tools and body.get("logprobs"):
+ raise APIError(400, "`strict_tool_calls` does not support `logprobs` yet.",
+ "logprobs", "unsupported_parameter")
reasoning_effort = body.get("reasoning_effort")
efforts = (None, "none", "minimal", "low", "medium", "high", "xhigh")
if reasoning_effort not in efforts:
@@ -6691,6 +6767,17 @@ class APIHandler(BaseHTTPRequestHandler):
raise APIError(400, "`preserve_thinking` must be a boolean.", "preserve_thinking")
tools = body.get("tools") or body.get("functions") or None
tool_choice = body.get("tool_choice")
+ if strict_tools and (not isinstance(tools, list) or not tools or tool_choice == "none"):
+ raise APIError(400, "`strict_tool_calls` requires active `tools`.",
+ "strict_tool_calls", "unsupported_parameter")
+ if strict_tools:
+ for index, tool in enumerate(tools):
+ params = _tool_function(tool).get("parameters") or {}
+ if (not isinstance(params, dict) or
+ not isinstance(params.get("properties", {}), dict) or
+ not isinstance(params.get("required", []), list)):
+ raise APIError(400, "Strict tool schemas need object `parameters`, "
+ "object `properties` and array `required`.", f"tools.{index}")
audio_clips = [] if ARCH == "inkling" else None
messages, image = self.expand_images(body.get("messages"))
add_generation_prompt = resolve_generation_prompt(messages, body)
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 72eaf450..ee86dbd1 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -3624,6 +3624,66 @@ class UnclosedToolCallTest(unittest.TestCase):
self.assertEqual(content, "Done.")
+class StrictGLMToolCallTest(unittest.TestCase):
+ """Opt-in calls must be complete before a client can execute them."""
+
+ CALL = ("<tool_call>lookup_order<arg_key>order_id</arg_key>"
+ "<arg_value>00123</arg_value></tool_call>")
+
+ def test_complete_call_preserves_declared_string(self):
+ content, calls = openai_server.parse_glm_tool_calls_strict("Checking. " + self.CALL,
+ ORDER_TOOL)
+ self.assertEqual(content, "Checking.")
+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"order_id": "00123"})
+
+ def test_incomplete_duplicate_undeclared_and_invalid_calls_fail_closed(self):
+ bad = (self.CALL[:-len("</tool_call>")],
+ self.CALL.replace("</tool_call>",
+ "<arg_key>order_id</arg_key><arg_value>other</arg_value></tool_call>"),
+ self.CALL.replace("lookup_order", "other_function"),
+ self.CALL.replace("</tool_call>",
+ "<arg_key>qty</arg_key><arg_value>many</arg_value></tool_call>"),
+ self.CALL.replace("order_id", "other_key"),
+ "<tool_call>lookup_order</tool_call>")
+ for reply in bad:
+ with self.subTest(reply=reply), self.assertRaises(APIError) as caught:
+ openai_server.parse_glm_tool_calls_strict(reply, ORDER_TOOL)
+ self.assertEqual(caught.exception.code, "invalid_model_tool_call")
+
+ def test_http_refuses_length_limited_tool_and_unsupported_stream_before_dispatch(self):
+ engine = ScriptedEngine(chunks=(self.CALL,), length_limited=True)
+ base = _spawn_test_server(self, engine)
+ body = {"model": "test-model", "messages": [{"role": "user", "content": "order?"}],
+ "tools": ORDER_TOOL, "strict_tool_calls": True}
+ with patch.object(openai_server, "ARCH", "glm"):
+ status, error = _error_body(self, lambda: _post_chat(base, body))
+ self.assertEqual((status, error["code"]), (502, "invalid_model_tool_call"))
+ self.assertEqual(len(engine.calls), 1)
+ status, error = _error_body(self, lambda: _post_chat(base, {**body, "stream": True}))
+ self.assertEqual((status, error["code"]), (400, "unsupported_parameter"))
+ self.assertEqual(len(engine.calls), 1)
+ status, error = _error_body(self, lambda: _post_chat(base, {**body,
+ "strict_tool_calls": "true"}))
+ self.assertEqual((status, error["param"]), (400, "strict_tool_calls"))
+ self.assertEqual(len(engine.calls), 1)
+ status, error = _error_body(self, lambda: _post_chat(base, {**body, "tools": []}))
+ self.assertEqual((status, error["param"]), (400, "strict_tool_calls"))
+ self.assertEqual(len(engine.calls), 1)
+
+ def test_http_complete_call_finishes_with_tool_calls(self):
+ engine = ScriptedEngine(chunks=(self.CALL,))
+ base = _spawn_test_server(self, engine)
+ body = {"model": "test-model", "messages": [{"role": "user", "content": "order?"}],
+ "tools": ORDER_TOOL, "strict_tool_calls": True}
+ with patch.object(openai_server, "ARCH", "glm"):
+ with _post_chat(base, body) as response:
+ result = json.load(response)
+ choice = result["choices"][0]
+ self.assertEqual(choice["finish_reason"], "tool_calls")
+ self.assertEqual(json.loads(choice["message"]["tool_calls"][0]["function"]["arguments"]),
+ {"order_id": "00123"})
+
+
class ToolChoiceTest(unittest.TestCase):
def test_none_does_not_offer_the_tools(self):
prompt = render_chat([{"role": "user", "content": "hi"}], tools=ORDER_TOOL,
diff --git a/docs/api.md b/docs/api.md
index fce28398..e8cd2327 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -247,6 +247,15 @@ Protocol support does not guarantee that every quantized model emits valid
tool syntax; `COLI_TOOL_SALVAGE=1` is an opt-in recovery path for malformed GLM
int4 tool calls. DeepSeek V4 uses its strict native DSML parser instead.
+For GLM calls that will execute tools, an OpenAI chat request may set
+`"strict_tool_calls": true`. This opt-in accepts only complete `<tool_call>`
+blocks whose function and arguments match the declared tool schema. It returns
+HTTP 502 with code `invalid_model_tool_call` for incomplete, duplicate, unknown,
+or invalid arguments and for a tool call cut off by the generation limit. It
+never recovers or salvages a malformed call. The default recovery behavior is
+unchanged. Strict mode currently requires `stream: false` and does not support
+`logprobs`; these combinations receive HTTP 400 before generation.
+
When a reverse proxy or MagicDNS hostname preserves a public `Host` header,
trust that exact hostname with repeatable `--allowed-host` options. The
comma-separated `COLI_ALLOWED_HOSTS` environment variable is equivalent: