From 8695604e445b735fcf781303e6fb1e24a26482cd Mon Sep 17 00:00:00 2001 From: Will Briggs <10916802+subourbonite@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:15:28 -0500 Subject: [PATCH] [Engine] serve: keep the tool name on tool-result messages (#7051) Tool results reached the chat template without a name, so Inkling's tool-result header rendered empty. Resolve each result's name from the matching assistant call before call ids are dropped, and keep a client-sent name, on chat completions, /v1/messages, /v1/responses and the MCP loop. Ids repeated within one turn leave the result unnamed. Fixes #7051 Co-Authored-By: Claude Opus 5.5 --- terminal/serve/frontend.py | 22 ++++- terminal/serve/responses.py | 7 +- terminal/serve/server.py | 2 +- terminal/serve/test_anthropic_tool_results.py | 18 +++- terminal/serve/test_chat_tool_results.py | 82 ++++++++++++++++++- terminal/serve/test_mcp.py | 16 ++++ terminal/serve/test_responses.py | 6 +- terminal/serve/test_server.py | 4 +- 8 files changed, 144 insertions(+), 13 deletions(-) diff --git a/terminal/serve/frontend.py b/terminal/serve/frontend.py index e1c2b517475..6d6ecd1ffac 100644 --- a/terminal/serve/frontend.py +++ b/terminal/serve/frontend.py @@ -642,7 +642,8 @@ def _order_chat_tool_results(messages: list[dict]) -> None: """The template pairs results by position, so restore call order while IDs are still available. Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their - received order. IDs are private to this conversion and never reach the template. + received order. Each result is then named after its call (_name_tool_results). IDs are private to this + conversion and never reach the template. """ i = 0 while i < len(messages): @@ -660,12 +661,29 @@ def _order_chat_tool_results(messages: list[dict]) -> None: rank = {cid: n for n, cid in enumerate(calls)} messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]]) i = j + _name_tool_results(messages) for message in messages: message.pop("_call_id", None) for call in message.get("tool_calls") or []: call.pop("_call_id", None) +def _name_tool_results(messages: list[dict]) -> None: + """#7051: a tool result without a `name` takes the function name of the nearest earlier call with its `_call_id` + (Inkling's template heads the result with it); an id used twice in that call's turn is ambiguous and names + nothing. Run before the private ids are dropped.""" + names = {} + for message in messages: + cid = message.get("_call_id") + if message["role"] == "tool" and not message.get("name") and isinstance(cid, str) and names.get(cid): + message["name"] = names[cid] + ids = [c.get("_call_id") for c in message.get("tool_calls") or []] + for call in message.get("tool_calls") or []: + cid, name = call.get("_call_id"), call["function"].get("name") + if isinstance(cid, str) and cid: + names[cid] = name if isinstance(name, str) and name and ids.count(cid) == 1 else None + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -680,6 +698,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} if role == "tool": out["_call_id"] = m.get("tool_call_id") + if isinstance(m.get("name"), str) and m["name"]: + out["name"] = m["name"] if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): diff --git a/terminal/serve/responses.py b/terminal/serve/responses.py index 0acf30aba8e..09ca506eb04 100644 --- a/terminal/serve/responses.py +++ b/terminal/serve/responses.py @@ -31,7 +31,7 @@ import time import uuid -from serve.frontend import Event, _late_system_to_user, _parts_of, cut_arguments, declared_parameters, effort_kwargs +from serve.frontend import Event, _late_system_to_user, _name_tool_results, _parts_of, cut_arguments, declared_parameters, effort_kwargs ENCRYPTED_PREFIX = "strata.r1:" # our own reasoning replay strings; others' are ignored HOSTED_TOOLS = ("web_search", "web_search_preview", "file_search", "computer_use_preview", "computer_use", @@ -331,8 +331,8 @@ def turn(content=""): def _order_tool_results(messages): """The template places tool results by position: each run of tool messages is put in the order of the calls of - the assistant turn before it (a client may send the results in the order they finished), then the private call - ids are dropped.""" + the assistant turn before it (a client may send the results in the order they finished), each result is named + after its call (frontend._name_tool_results), then the private call ids are dropped.""" i = 0 while i < len(messages): if messages[i]["role"] != "tool": @@ -346,6 +346,7 @@ def _order_tool_results(messages): rank = {cid: k for k, cid in enumerate(order) if cid} messages[i:j] = sorted(messages[i:j], key=lambda m: rank.get(m.get("_call_id"), len(order))) i = j + _name_tool_results(messages) for m in messages: m.pop("_call_id", None) for c in m.get("tool_calls") or []: diff --git a/terminal/serve/server.py b/terminal/serve/server.py index 701d7f24571..dc692f068dd 100644 --- a/terminal/serve/server.py +++ b/terminal/serve/server.py @@ -6723,7 +6723,7 @@ def work(c=c, box=box): messages.append({"role": "assistant", "content": "".join(text).strip(), **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) - messages += [{"role": "tool", "content": r} for r in results] + messages += [{"role": "tool", "content": r, "name": c.name} for c, r in zip(calls, results)] # #7051 if rounds >= max_rounds: finalizing = True tools = None diff --git a/terminal/serve/test_anthropic_tool_results.py b/terminal/serve/test_anthropic_tool_results.py index dd6712f5452..841833709cb 100644 --- a/terminal/serve/test_anthropic_tool_results.py +++ b/terminal/serve/test_anthropic_tool_results.py @@ -58,15 +58,29 @@ def test_already_ordered_and_legacy_prompts_are_identical(self): block.pop("id") for block in legacy[2]["content"]: block.pop("tool_use_id") - self.assertEqual(normalized(ordered), normalized(legacy)) + # #7051: with ids each result also gets its tool_use's name; without ids there is nothing to name it from + named = normalized(ordered) + self.assertEqual([m.pop("name") for m in named[2:]], ["Grep", "Grep"]) + self.assertEqual(named, normalized(legacy)) self.assertEqual([m["content"] for m in normalized(ordered)[2:]], ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"]) def test_ids_never_reach_the_template(self): for raw in (history(), in_call_order()): messages = normalized(raw) - self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:])) + self.assertTrue(all(set(m) <= {"role", "content", "name"} for m in messages[2:])) self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"])) + def test_results_are_named_after_their_tool_use_in_the_inkling_prompt(self): + raw = history() + raw[1]["content"][1]["name"] = "Glob" + messages = normalized(raw) + self.assertEqual([(m["content"], m["name"]) for m in messages[2:]], + [("RESULT_FROM_SLOW", "Grep"), ("RESULT_FROM_FAST", "Glob")]) + inkling = ChatTemplate(Path(__file__).resolve().parents[1] / "tests" / "data" / "inkling" / "chat_template.jinja") + prompt = inkling.render(messages) + self.assertIn("<|message_tool|>Grep<|content_text|>RESULT_FROM_SLOW", prompt) + self.assertIn("<|message_tool|>Glob<|content_text|>RESULT_FROM_FAST", prompt) + def test_ambiguous_or_incomplete_ids_preserve_received_order(self): for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown", "list_call", "list_result", "empty_call", "empty_result", "partial"): diff --git a/terminal/serve/test_chat_tool_results.py b/terminal/serve/test_chat_tool_results.py index 9c99b2ee6e3..d499d44f179 100644 --- a/terminal/serve/test_chat_tool_results.py +++ b/terminal/serve/test_chat_tool_results.py @@ -43,7 +43,7 @@ def test_reversed_results_of_the_same_function_follow_call_ids(self): self.assertEqual(raw, before) messages = normalized(raw) self.assertEqual([m["content"] for m in messages[2:]], ["RESULT_FROM_A", "RESULT_FROM_B"]) - self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:])) + self.assertTrue(all(set(m) <= {"role", "content", "name"} for m in messages[2:])) self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"])) def test_already_ordered_and_legacy_prompts_are_identical(self): @@ -54,7 +54,10 @@ def test_already_ordered_and_legacy_prompts_are_identical(self): call.pop("id") for result in legacy[2:]: result.pop("tool_call_id") - self.assertEqual(normalized(ordered), normalized(legacy)) + # #7051: with ids each result also gets its call's name; without ids there is nothing to name it from + named = normalized(ordered) + self.assertEqual([m.pop("name") for m in named[2:]], ["read_file", "read_file"]) + self.assertEqual(named, normalized(legacy)) self.assertEqual(rendered(ordered), rendered(legacy)) def test_ambiguous_or_incomplete_ids_preserve_received_order(self): @@ -84,6 +87,8 @@ def test_ambiguous_or_incomplete_ids_preserve_received_order(self): with self.subTest(case=case): self.assertEqual([m["content"] for m in normalized(raw)[2:]], [m["content"] for m in raw[2:]]) + if case == "duplicate_call": # call_a twice in one turn: ambiguous, so neither result is named + self.assertEqual([m.get("name") for m in normalized(raw)[2:]], [None, None]) def test_each_tool_run_is_scoped_to_its_assistant_turn(self): raw = history() + history() @@ -129,5 +134,78 @@ def test_http_engine_receives_the_ordered_prompt(self): httpd.server_close() +DATA = Path(__file__).resolve().parents[1] / "tests" / "data" +INKLING = ChatTemplate(DATA / "inkling" / "chat_template.jinja") + + +def call(cid, name): + return {"id": cid, "type": "function", "function": {"name": name, "arguments": "{}"}} + + +def result(cid, content, **extra): + return {"role": "tool", "tool_call_id": cid, "content": content, **extra} + + +def names(messages): + return [m.get("name") for m in normalized(messages) if m["role"] == "tool"] + + +class ChatToolResultNames(unittest.TestCase): + """#7051: Inkling's template heads a tool result with its tool's name, from `name` or the matching call id.""" + + def test_a_result_is_named_after_its_call_in_the_inkling_prompt(self): + raw = [{"role": "user", "content": "Weather?"}, + {"role": "assistant", "content": "", "tool_calls": [call("call_1", "get_weather")]}, + result("call_1", "18 C")] + self.assertEqual(names(raw), ["get_weather"]) + self.assertIn("<|message_tool|>get_weather<|content_text|>18 C", INKLING.render(normalized(raw))) + + def test_a_client_name_is_kept(self): + raw = [{"role": "user", "content": "Weather?"}, + {"role": "assistant", "content": "", "tool_calls": [call("call_1", "get_weather")]}, + result("call_1", "18 C", name="weather_v2")] + self.assertEqual(names(raw), ["weather_v2"]) + raw[2]["name"] = 7 # not a name: resolved from the call instead + self.assertEqual(names(raw), ["get_weather"]) + + def test_an_unmatched_empty_or_missing_id_gets_no_name(self): + raw = [{"role": "user", "content": "Weather?"}, + {"role": "assistant", "content": "", "tool_calls": [call("", "get_weather"), call("call_2", None)]}, + result("call_9", "a"), result("", "b"), {"role": "tool", "content": "c"}, result("call_2", "d")] + self.assertEqual(names(raw), [None, None, None, None]) + + def test_parallel_results_take_their_own_calls_names(self): + raw = [{"role": "user", "content": "Weather and time?"}, + {"role": "assistant", "content": "", "tool_calls": [call("call_w", "get_weather"), call("call_t", "get_time")]}, + result("call_t", "noon"), result("call_w", "18 C")] + messages = normalized(raw) + self.assertEqual([(m["content"], m["name"]) for m in messages[2:]], [("18 C", "get_weather"), ("noon", "get_time")]) + # an incomplete run keeps its received order, and each result is still named by its id, not its position + raw = [{"role": "user", "content": "Three things?"}, + {"role": "assistant", "content": "", "tool_calls": [call("call_1", "a"), call("call_2", "b"), call("call_3", "c")]}, + result("call_3", "third"), result("call_1", "first")] + self.assertEqual([(m["content"], m["name"]) for m in normalized(raw)[2:]], [("third", "c"), ("first", "a")]) + + def test_a_reused_id_takes_the_nearest_earlier_call(self): + raw = [{"role": "user", "content": "Read, then write."}, + {"role": "assistant", "content": "", "tool_calls": [call("call_1", "read_file")]}, result("call_1", "old"), + {"role": "assistant", "content": "", "tool_calls": [call("call_1", "write_file")]}, result("call_1", "ok")] + self.assertEqual(names(raw), ["read_file", "write_file"]) + raw[3]["tool_calls"].append(call("call_1", "delete_file")) # twice in the second turn: that result is unnamed + self.assertEqual(names(raw), ["read_file", None]) + + def test_the_other_templates_render_the_same_with_names(self): + messages = normalized(history()) + unnamed = copy.deepcopy(messages) + for m in unnamed: + m.pop("name", None) + self.assertEqual([m.get("name") for m in messages[2:]], ["read_file", "read_file"]) + for path in (Path(__file__).with_name("chat_template.jinja"), DATA / "hy4" / "chat_template.jinja", + Path(__file__).resolve().parents[1] / "tools" / "qwen4_intake_fixtures" / "qwen3-0.6b.chat_template.jinja"): + with self.subTest(template=path.name, parent=path.parent.name): + template = ChatTemplate(path) + self.assertEqual(template.render(messages), template.render(unnamed)) + + if __name__ == "__main__": unittest.main() diff --git a/terminal/serve/test_mcp.py b/terminal/serve/test_mcp.py index efbd20cd199..459c1610df6 100644 --- a/terminal/serve/test_mcp.py +++ b/terminal/serve/test_mcp.py @@ -399,6 +399,22 @@ def test_a_call_the_output_ends_inside_is_not_run(self): self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + def test_results_are_named_after_their_calls(self): + """#7051: the template messages of the next round carry each result's tool name (Inkling's header reads it).""" + two = call_script("fake__add", a=2, b=3) + call_script("fake__echo", text="hi").split("Let me check.\n\n")[1] + self.start(two, "\n\nDone.") + seen = [] + encode = self.svc.encode_prompt + + def spy(messages, *args, **kwargs): + seen.append(json.loads(json.dumps(messages))) + return encode(messages, *args, **kwargs) + self.svc.encode_prompt = spy + code, text = self.post({"strata_mcp": True}, stream=False) + self.assertEqual(code, 200, text) + tools = [(m["name"], m["content"]) for m in seen[-1] if m["role"] == "tool"] + self.assertEqual(tools, [("fake__add", "5"), ("fake__echo", "hi")]) + def test_non_stream(self): self.start(call_script("fake__add", a=2, b=3), "\n\n5.") code, text = self.post({"strata_mcp": True}, stream=False) diff --git a/terminal/serve/test_responses.py b/terminal/serve/test_responses.py index f16a380e57d..9e5f0672270 100644 --- a/terminal/serve/test_responses.py +++ b/terminal/serve/test_responses.py @@ -80,10 +80,12 @@ def test_codex_history_becomes_one_assistant_turn_per_answer(self): {"role": "assistant", "content": "Looking.", "reasoning_content": "look first", "tool_calls": [ {"function": {"name": "exec_command", "arguments": {"cmd": "cat a"}}}, {"function": {"name": "multi_agent_v1.spawn_agent", "arguments": {}}}]}, - {"role": "tool", "content": "before"}, {"role": "tool", "content": "agent"}, + # #7051: each result is named after its call, for templates that head a result with it (Inkling) + {"role": "tool", "content": "before", "name": "exec_command"}, + {"role": "tool", "content": "agent", "name": "multi_agent_v1.spawn_agent"}, {"role": "assistant", "content": "", "reasoning_content": "now write", "tool_calls": [ {"function": {"name": "exec_command", "arguments": {"cmd": "w"}}}]}, - {"role": "tool", "content": "ok"}]) + {"role": "tool", "content": "ok", "name": "exec_command"}]) def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored(self): enc = ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": "hidden"}).encode()).decode() diff --git a/terminal/serve/test_server.py b/terminal/serve/test_server.py index 7af167660e3..8e0f7282c2c 100644 --- a/terminal/serve/test_server.py +++ b/terminal/serve/test_server.py @@ -530,10 +530,10 @@ def encode(self, source): m, _, _ = anthropic_to_messages({"messages": [{"role": "user", "content": [good]}]}) with self.assertRaises(ValueError): svc.prepare(m, None, {}) - # a text-only tool result renders exactly as before: one string + # a text-only tool result renders exactly as before: one string (named after its call, #7051) msgs = [{"role": "user", "content": "q"}, call, {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}] - self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"}) + self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r", "name": "Read"}) def test_the_whole_marker_in_text_before_images(self):