Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
fix(serve): safely handle malformed or partial tool call arguments in history
Pravesh Khatanad398d7c33f61
diff --git a/serve/frontend.py b/serve/frontend.pyindex 643962832..4d2310ce2 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -264,6 +264,23 @@ def _tool_list(value, wrapper: str | None) -> list[dict]:return tools+def tool_arguments(raw) -> dict:+ """A call's arguments from a client's history -> the mapping the template renders (both APIs). A JSON object+ (as text or already parsed) is used as it is; empty is {}; anything else (cut-off or malformed JSON, a list, a+ number) is kept as text under "arguments" instead of refusing the whole conversation (#510)."""+ if raw is None or (isinstance(raw, str) and not raw.strip()):+ return {}+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str):+ try:+ value = json.loads(raw)+ except ValueError:+ return {"arguments": raw}+ return value if isinstance(value, dict) else {"arguments": raw}+ return {"arguments": json.dumps(raw, ensure_ascii=False)}++def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:"""OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""messages = []@@ -280,10 +297,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:fn = c.get("function", c)if not isinstance(fn, dict):raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)")- args = fn.get("arguments")- if isinstance(args, str): # the template requires a mapping, not a JSON string- args = json.loads(args) if args.strip() else {}- calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}})+ calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}})out["tool_calls"] = callsmessages.append(out)tools = [t.get("function", t) if t.get("type") == "function" else t@@ -326,7 +340,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[delif kind == "thinking":reasoning.append(block.get("thinking", ""))elif kind == "tool_use":- calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}})+ calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))}})elif kind == "tool_result":messages.append({"role": "tool", "content": _text_of(block.get("content"))})if text or calls or reasoning:diff --git a/serve/server.py b/serve/server.pyindex 1048e9125..838068bd3 100644--- a/serve/server.py+++ b/serve/server.py@@ -3232,6 +3232,7 @@ def make_handler(svc: Service):else:self._json(404, {"error": {"message": "not found"}})except ValueError as e:+ print(f"[strata] 400 invalid request: {e}", flush=True)if path == "/v1/responses":self._json(400, responses_error_body(str(e)))else:diff --git a/serve/test_server.py b/serve/test_server.pyindex c2241ba28..e5c9e2c00 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -766,6 +766,42 @@ class ClientShapes(unittest.TestCase):with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"):openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]})+ def test_tool_call_malformed_arguments_fallback(self):+ from serve.frontend import openai_to_messages+ bad_call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{malformed_json"}}]+ msgs, tools, kwargs = openai_to_messages({"messages": [{"role": "user", "content": "u"},+ {"role": "assistant", "content": "", "tool_calls": bad_call}]})+ self.assertEqual(msgs[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"arguments": "{malformed_json"}}}])+ tpl = ChatTemplate(ROOT / "serve/chat_template.jinja")+ rendered = tpl.render(msgs, tools=tools, **kwargs)+ self.assertIn("<function=f>", rendered)+ self.assertIn("<parameter=arguments>\n{malformed_json", rendered)+++class ToolArguments(unittest.TestCase):+ """#510: one helper for both frontends; a history whose arguments are not a JSON object is kept, not a 500."""++ def test_helper(self):+ from serve.frontend import tool_arguments+ for raw, want in ((None, {}), ("", {}), (" ", {}), ({"a": 1}, {"a": 1}), ('{"a": 1}', {"a": 1}),+ ("{cut", {"arguments": "{cut"}), ("[1, 2]", {"arguments": "[1, 2]"}),+ ("5", {"arguments": "5"}), ([1, 2], {"arguments": "[1, 2]"}), (7, {"arguments": "7"})):+ with self.subTest(raw=raw):+ self.assertEqual(tool_arguments(raw), want)++ def test_both_frontends_render_it(self):+ from serve.frontend import anthropic_to_messages, openai_to_messages+ for bad in ("{cut", "[1]", "3"):+ with self.subTest(bad=bad):+ m = openai_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": "",+ "tool_calls": [{"id": "c", "type": "function", "function": {"name": "f", "arguments": bad}}]}]})[0]+ self.assertEqual(m[1]["tool_calls"][0]["function"]["arguments"], {"arguments": bad})+ for bad in ([1], 3, "{cut"):+ with self.subTest(anthropic=bad):+ m = anthropic_to_messages({"messages": [{"role": "user", "content": "u"}, {"role": "assistant", "content": [+ {"type": "tool_use", "id": "t", "name": "f", "input": bad}]}]})[0]+ self.assertIn("arguments", m[1]["tool_calls"][0]["function"]["arguments"])+class SamplingKeys(unittest.TestCase):"""The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used