Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
serve: recover a tool call whose closing tag never arrives (#401)
JustVugge2cad79b1260
diff --git a/c/openai_server.py b/c/openai_server.pyindex bad9788e..50afe2f0 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -214,6 +214,8 @@ _BOX_RE = re.compile(re.escape(BOX_START) + r"(.*?)" + re.escape(BOX_END), re.D_ARG_RE = re.compile(r"<arg_key>([^<]*)</arg_key><arg_value>(.*?)</arg_value>", re.DOTALL)_NAME_RE = re.compile(r"\s*([A-Za-z0-9_.\-]+)")_TAG_RE = re.compile(r"</?arg_key>|</?arg_value>")+# A closing tag the model started but never finished ("</tool_cal", "</tool"), at end of reply.+_PARTIAL_END_RE = re.compile(r"<(?:/(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l)?)?)?)?)?)?)?)?)?\Z")# De-mangler: opt-in recovery for heavily-quantized models that drop the# <arg_key>K</arg_key><arg_value> structure. Default OFF (never rewrites well-formed output).@@ -275,14 +277,41 @@ def _coerce_arg(value, declared):return parsed+def _unclosed_tail(reply, tools):+ """Body of a trailing <tool_call> that was never closed, or None.++ Only returned when the recovery is unambiguous, so ordinary prose that merely mentions+ "<tool_call>" can never be turned into a call. Both conditions must hold:+ * the last BOX_START is not followed by a BOX_END (a closed box is the strict parser's job);+ * the tail carries a complete <arg_key>..</arg_value> pair, OR it is exactly the name of a+ tool the client declared (the zero-argument case).+ """+ start = reply.rfind(BOX_START)+ if start < 0 or BOX_END in reply[start:]:+ return None+ inner = _PARTIAL_END_RE.sub("", reply[start + len(BOX_START):])+ if _ARG_RE.search(inner):+ return inner+ declared = {(t.get("function", t) if isinstance(t, dict) else {}).get("name")+ for t in (tools or []) if isinstance(t, dict)}+ return inner if inner.strip() in declared else None++def parse_tool_calls(reply, tools=None):"""Return (content, tool_calls). Strict GLM parse; optional de-mangler (COLI_TOOL_SALVAGE=1)rescues malformed int4 output by mapping a lone payload onto the tool's primary parameter."""param_order = _tool_param_order(tools)param_types = _tool_param_types(tools)calls, salvaged = [], []- for match in _BOX_RE.finditer(reply):- inner = match.group(1)+ # #401: a box the model opened but never closed -- it ran out of budget, or the closing tag+ # came out mangled ("</tool_cal"). The call itself is often perfectly well-formed, but the+ # strict regex needs BOTH tags, so the client used to get *zero* tool_calls. Recover the tail,+ # but only when it is unambiguous (see _unclosed_tail) so prose can never fabricate a call.+ boxes = [m.group(1) for m in _BOX_RE.finditer(reply)]+ tail = _unclosed_tail(reply, tools)+ if tail is not None:+ boxes.append(tail)+ for inner in boxes:name_match = _NAME_RE.match(inner)name = name_match.group(1) if name_match else inner.strip()args = {}@@ -314,13 +343,17 @@ def parse_tool_calls(reply, tools=None):"parsed -- output may be quantization-mangled; try COLI_TOOL_SALVAGE=1\n")sys.stderr.flush()text = _BOX_RE.sub("", reply)+ if tail is not None: # drop the recovered tail from the visible content+ text = text[:text.rindex(BOX_START)]if THINK_CLOSE in text:text = text.split(THINK_CLOSE, 1)[1]text = text.replace(THINK_OPEN, "").replace(THINK_CLOSE, "")if calls:- dm = len(salvaged)- sys.stderr.write("[api] tool-calls: %d total, %d strict, %d de-mangled [%s]%s\n"- % (len(calls), len(calls) - dm, dm, "CLEAN" if dm == 0 else "DE-MANGLED",+ dm, rec = len(salvaged), (1 if tail is not None else 0)+ sys.stderr.write("[api] tool-calls: %d total, %d strict, %d unclosed-recovered, "+ "%d de-mangled [%s]%s\n"+ % (len(calls), max(0, len(calls) - dm - rec), rec, dm,+ "CLEAN" if dm == 0 and rec == 0 else "RECOVERED",(" -> " + ", ".join(salvaged)) if dm else ""))sys.stderr.flush()return text.strip(), callsdiff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex 7b0bb2bc..98da4c18 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -706,6 +706,65 @@ class EngineErrorFrameTest(unittest.TestCase):err = _engine_error(["CONTEXT_EXCEEDED"], "CONTEXT_EXCEEDED")self.assertIsInstance(err, APIError)self.assertEqual(err.status, 400)+class UnclosedToolCallTest(unittest.TestCase):+ """#401: the model opens <tool_call>, emits a well-formed call, then stops without the+ closing tag (budget ran out, or quantization mangled it). The strict regex needs both tags,+ so the client used to get zero tool_calls -- a total failure from a recoverable output."""++ NO_ARG_TOOL = ORDER_TOOL + [{"type": "function",+ "function": {"name": "list_orders", "parameters": {}}}]++ def _calls(self, reply, tools=ORDER_TOOL):+ return parse_tool_calls(reply, tools)++ def test_unclosed_box_is_recovered(self):+ content, calls = self._calls("<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>A-1</arg_value>")+ self.assertEqual(len(calls), 1)+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"order_id": "A-1"})+ self.assertEqual(content, "")++ def test_mangled_closing_tag_is_recovered(self):+ _, calls = self._calls("<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>A-1</arg_value></tool_cal")+ self.assertEqual(len(calls), 1)+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"order_id": "A-1"})++ def test_leading_prose_is_kept_as_content(self):+ content, calls = self._calls("Let me check.\n<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>A-1</arg_value>")+ self.assertEqual(len(calls), 1)+ self.assertEqual(content, "Let me check.")++ def test_closed_call_followed_by_an_unclosed_one(self):+ _, calls = self._calls("<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>A-1</arg_value></tool_call>"+ "<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>B-2</arg_value>")+ self.assertEqual([json.loads(c["function"]["arguments"])["order_id"] for c in calls],+ ["A-1", "B-2"])++ def test_bare_declared_name_recovers_a_zero_argument_call(self):+ _, calls = self._calls("<tool_call>list_orders", self.NO_ARG_TOOL)+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0]["function"]["name"], "list_orders")+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {})++ def test_prose_mentioning_the_marker_does_not_fabricate_a_call(self):+ content, calls = self._calls("To call a tool, write <tool_call> and then the name.")+ self.assertEqual(calls, [])+ self.assertIn("<tool_call>", content)++ def test_undeclared_name_without_arguments_is_not_recovered(self):+ _, calls = self._calls("<tool_call>drop_all_tables")+ self.assertEqual(calls, [])++ def test_well_formed_output_is_untouched(self):+ content, calls = self._calls("Done.<tool_call>lookup_order"+ "<arg_key>order_id</arg_key><arg_value>A-1</arg_value>"+ "</tool_call>")+ self.assertEqual(len(calls), 1)+ self.assertEqual(content, "Done.")class ToolChoiceTest(unittest.TestCase):diff --git a/c/tests/test_openai_tools_e2e.py b/c/tests/test_openai_tools_e2e.pyindex d921843b..c6c43e69 100644--- a/c/tests/test_openai_tools_e2e.py+++ b/c/tests/test_openai_tools_e2e.py@@ -51,6 +51,10 @@ while True:elif "weather in Rome" in prompt:reply(rid, "<tool_call>get_weather<arg_key>city</arg_key>""<arg_value>Rome</arg_value></tool_call>")+ elif "weather in Naples" in prompt:+ # #401: a well-formed call whose closing tag never arrives (budget ran out, or+ # quantization mangled it). Strict parsing loses the whole call.+ reply(rid, "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Naples</arg_value>")elif "weather in Milan" in prompt:# split across many tiny DATA chunks: streamed marker suppression must# hold even when a marker straddles a chunk boundary@@ -170,6 +174,36 @@ class ToolCallingE2E(unittest.TestCase):self.assertIn("# Tools", rendered)self.assertIn('"get_weather"', rendered)+ def test_unclosed_tool_call_still_reaches_the_client(self):+ """#401: the closing </tool_call> never arrives. Before the recovery the client got+ finish_reason=stop with the raw markers dumped into content -- a total failure from+ an otherwise perfectly well-formed call."""+ r = self.post({"model": MODEL_ID, "tools": TOOLS,+ "messages": [{"role": "user",+ "content": "What is the weather in Naples?"}]})+ choice = r["choices"][0]+ self.assertEqual(choice["finish_reason"], "tool_calls")+ calls = choice["message"]["tool_calls"]+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0]["function"]["name"], "get_weather")+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"city": "Naples"})+ self.assertNotIn("<tool_call>", choice["message"].get("content") or "")++ def test_unclosed_tool_call_streamed(self):+ """Same recovery on the streaming path -- this is the shape coding clients use."""+ events = self.post({"model": MODEL_ID, "tools": TOOLS, "stream": True,+ "messages": [{"role": "user",+ "content": "What is the weather in Naples?"}]},+ stream=True)+ deltas = [e["choices"][0]["delta"] for e in events if e["choices"]]+ self.assertNotIn("<tool_call>", "".join(d.get("content") or "" for d in deltas))+ calls = [d["tool_calls"] for d in deltas if d.get("tool_calls")]+ self.assertEqual(len(calls), 1)+ self.assertEqual(json.loads(calls[0][0]["function"]["arguments"]), {"city": "Naples"})+ finish = [e["choices"][0]["finish_reason"] for e in events+ if e["choices"] and e["choices"][0].get("finish_reason")]+ self.assertEqual(finish, ["tool_calls"])+def test_no_tools_plain_text(self):r = self.post({"model": MODEL_ID,"messages": [{"role": "user", "content": "Hi!"}]})diff --git a/c/tools/try_tool_calling.py b/c/tools/try_tool_calling.pynew file mode 100644index 00000000..c1e46958--- /dev/null+++ b/c/tools/try_tool_calling.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""Manual end-to-end tool-calling probe against a running colibri server (#401).++Runs a real two-turn loop against the OpenAI-compatible endpoint: declare a tool, let the+model call it, execute it locally, feed the result back, and check the model uses it.+No client library and no dependencies -- stdlib only.++ python3 tools/try_tool_calling.py # default http://127.0.0.1:8080+ python3 tools/try_tool_calling.py --url http://host:port+ python3 tools/try_tool_calling.py --raw # also dump the raw model text++Exit status is 0 only if every stage passed, so it can be used as a smoke test.+"""+import argparse+import json+import sys+import urllib.error+import urllib.request++WEATHER_TOOL = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get the current weather in a given city.",+ "parameters": {+ "type": "object",+ "properties": {+ "city": {"type": "string", "description": "City name, e.g. Rome"},+ "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},+ },+ "required": ["city"],+ },+ },+}++# What the tool "really" returns, so the second turn has a fact the model could not invent.+FAKE_WEATHER = {"city": "Rome", "temp_c": 31, "conditions": "sunny"}+++def discover_model(url, timeout):+ """Ask the server which model it is serving, so the caller never has to guess the id."""+ with urllib.request.urlopen(url + "/v1/models", timeout=timeout) as resp:+ data = json.loads(resp.read()).get("data") or []+ if not data:+ raise RuntimeError("server reports no models")+ return data[0]["id"]+++def post(url, body, timeout):+ req = urllib.request.Request(url + "/v1/chat/completions",+ data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return json.loads(resp.read())+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--url", default="http://127.0.0.1:8080", help="server base URL")+ ap.add_argument("--timeout", type=int, default=1800, help="seconds per request")+ ap.add_argument("--raw", action="store_true", help="print raw message objects")+ ap.add_argument("--tool-choice", default=None, help='e.g. "required" to force a call')+ ap.add_argument("--model", default=None, help="model id (default: ask the server)")+ args = ap.parse_args()+ url = args.url.rstrip("/")++ try:+ model = args.model or discover_model(url, 30)+ except (urllib.error.URLError, OSError) as e:+ print(f"FAIL: cannot reach {url} -- is the server running? ({e})")+ return 2+ print(f"server: {url} model: {model}")++ messages = [{"role": "user", "content": "What's the weather in Rome right now? "+ "Use the tool, don't guess."}]+ body = {"model": model, "messages": messages, "tools": [WEATHER_TOOL],+ "temperature": 0, "max_tokens": 256}+ if args.tool_choice:+ body["tool_choice"] = (args.tool_choice if args.tool_choice in ("auto", "none", "required")+ else {"type": "function", "function": {"name": args.tool_choice}})++ print("== turn 1: asking the model to call the tool ==")+ try:+ out = post(url, body, args.timeout)+ except urllib.error.URLError as e:+ print(f"FAIL: cannot reach {url} -- is the server running? ({e})")+ return 2+ msg = out["choices"][0]["message"]+ if args.raw:+ print(json.dumps(msg, indent=2, ensure_ascii=False))++ calls = msg.get("tool_calls") or []+ if not calls:+ print("FAIL: the model returned no tool_calls.")+ print(f" content: {(msg.get('content') or '')[:400]!r}")+ print(" If the content shows <tool_call> markers, the parse is the problem -- "+ "check the server's stderr line starting with '[api]'.")+ return 1++ call = calls[0]+ name = call["function"]["name"]+ try:+ parsed = json.loads(call["function"]["arguments"])+ except json.JSONDecodeError:+ print(f"FAIL: arguments are not valid JSON: {call['function']['arguments']!r}")+ return 1+ print(f" tool_calls: {len(calls)} name={name} arguments={parsed}")++ if name != "get_weather":+ print(f"FAIL: model called {name!r}, not the declared tool.")+ return 1+ if "city" not in parsed:+ print(f"FAIL: required parameter 'city' missing from {parsed}.")+ return 1+ if "rom" not in str(parsed["city"]).lower():+ print(f"WARN: city is {parsed['city']!r}, expected Rome -- continuing anyway.")++ print("== turn 2: feeding the tool result back ==")+ messages.append({"role": "assistant", "content": msg.get("content"), "tool_calls": calls})+ messages.append({"role": "tool", "tool_call_id": call["id"], "name": name,+ "content": json.dumps(FAKE_WEATHER)})+ body["messages"] = messages+ body.pop("tool_choice", None)+ out2 = post(url, body, args.timeout)+ reply = (out2["choices"][0]["message"].get("content") or "").strip()+ if args.raw:+ print(json.dumps(out2["choices"][0]["message"], indent=2, ensure_ascii=False))+ print(f" reply: {reply[:400]!r}")++ if "31" not in reply:+ print("FAIL: the reply does not mention 31 -- the model ignored the tool result.")+ return 1+ print("\nPASS: tool declared -> called with valid arguments -> result consumed in the answer.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())