Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Tests the shared healer that promotes text-form tool calls to structured calls on passthrough."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from core.inference.passthrough_healing import ( # noqa: E402
StreamToolCallHealer,
heal_gate,
heal_openai_message,
nudge_enabled,
nudge_messages,
native_tool_format,
nudge_should_retry,
response_has_promotable_calls,
)
TOOLS = [
{"type": "function", "function": {"name": "Bash", "parameters": {}}},
{"type": "function", "function": {"name": "Read", "parameters": {}}},
]
BASH_COMMAND_TOOL = {
"type": "function",
"function": {
"name": "Bash",
"parameters": {
"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"],
},
},
}
XML_BASH = '<tool_call>{"name":"Bash","arguments":{"cmd":"ls"}}</tool_call>'
XML_UNDECLARED = '<tool_call>{"name":"Nuke","arguments":{}}</tool_call>'
def _events_text(events):
return "".join(text for kind, text in events if kind == "text")
def _events_calls(events):
return [call for kind, call in events if kind == "tool_call"]
class TestHealGate:
def test_returns_declared_names(self):
assert heal_gate(None, TOOLS) == {"Bash", "Read"}
assert heal_gate(True, TOOLS) == {"Bash", "Read"}
def test_opt_out_and_no_tools(self):
assert heal_gate(False, TOOLS) is None
assert heal_gate(None, []) is None
assert heal_gate(None, None) is None
def test_malformed_tool_entries_ignored(self):
assert heal_gate(None, ["nonsense", {"function": "x"}, {}]) is None
def test_tool_choice_none_disables(self):
assert heal_gate(None, TOOLS, "none") is None
def test_tool_choice_forced_function_narrows_allowlist(self):
forced = {"type": "function", "function": {"name": "Bash"}}
assert heal_gate(None, TOOLS, forced) == {"Bash"}
def test_tool_choice_forced_undeclared_function_disables(self):
forced = {"type": "function", "function": {"name": "Nuke"}}
assert heal_gate(None, TOOLS, forced) is None
def test_tool_choice_auto_and_required_keep_full_set(self):
assert heal_gate(None, TOOLS, "auto") == {"Bash", "Read"}
assert heal_gate(None, TOOLS, "required") == {"Bash", "Read"}
def test_tool_choice_unrecognized_dict_keeps_full_set(self):
assert heal_gate(None, TOOLS, {"type": "function"}) == {"Bash", "Read"}
class TestHealOpenaiMessage:
def test_promotes_xml_and_strips_content(self):
msg = {"role": "assistant", "content": XML_BASH}
assert heal_openai_message(msg, {"Bash"}) is True
assert msg["content"] is None
(call,) = msg["tool_calls"]
assert call["function"]["name"] == "Bash"
assert json.loads(call["function"]["arguments"]) == {"cmd": "ls"}
def test_keeps_surrounding_prose(self):
msg = {"role": "assistant", "content": f"Let me check.\n{XML_BASH}"}
assert heal_openai_message(msg, {"Bash"}) is True
assert msg["content"] == "Let me check."
def test_undeclared_name_not_promoted(self):
msg = {"role": "assistant", "content": XML_UNDECLARED}
assert heal_openai_message(msg, {"Bash"}) is False
assert msg["content"] == XML_UNDECLARED
assert "tool_calls" not in msg
def test_structured_calls_untouched(self):
msg = {"role": "assistant", "content": XML_BASH, "tool_calls": [{"id": "x"}]}
assert heal_openai_message(msg, {"Bash"}) is False
assert msg["content"] == XML_BASH
def test_prose_only_untouched(self):
msg = {"role": "assistant", "content": "just an answer"}
assert heal_openai_message(msg, {"Bash"}) is False
def test_bare_string_arguments_use_schema_key(self):
msg = {
"role": "assistant",
"content": '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>',
}
assert heal_openai_message(msg, {"Bash"}, [BASH_COMMAND_TOOL]) is True
args = json.loads(msg["tool_calls"][0]["function"]["arguments"])
assert args == {"command": "echo hi"}
def test_bare_string_arguments_decline_ambiguous_schema(self):
msg = {
"role": "assistant",
"content": '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>',
}
assert heal_openai_message(msg, {"Bash"}, TOOLS) is False
assert "tool_calls" not in msg
def test_mixed_declared_and_undeclared_promotes_declared_keeps_undeclared_text(self):
content = f"pre {XML_BASH} mid {XML_UNDECLARED} post"
msg = {"role": "assistant", "content": content}
assert heal_openai_message(msg, {"Bash"}) is True
(call,) = msg["tool_calls"]
assert call["function"]["name"] == "Bash"
assert XML_UNDECLARED in msg["content"]
assert "pre" in msg["content"] and "post" in msg["content"]
assert XML_BASH not in msg["content"]
def test_multiple_declared_calls_all_promoted(self):
content = f"{XML_BASH} and {XML_BASH}"
msg = {"role": "assistant", "content": content}
assert heal_openai_message(msg, {"Bash"}) is True
assert len(msg["tool_calls"]) == 2
def test_mixed_formats_promote_in_document_order(self):
func_read = "<function=Read><parameter=path>a.txt</parameter></function>"
content = f"{func_read} then {XML_BASH}"
msg = {"role": "assistant", "content": content}
assert heal_openai_message(msg, {"Bash", "Read"}) is True
assert [call["function"]["name"] for call in msg["tool_calls"]] == ["Read", "Bash"]
assert msg["content"] == "then"
def test_unparseable_closed_block_not_deleted(self):
garbage = "<tool_call>not json at all</tool_call>"
content = f"{XML_BASH} {garbage}"
msg = {"role": "assistant", "content": content}
assert heal_openai_message(msg, {"Bash"}) is True
assert garbage in msg["content"]
class TestStreamHealer:
def test_plain_text_passes_through(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed("hello ") + healer.feed("world") + healer.finalize()
assert _events_text(events) == "hello world"
assert not _events_calls(events)
def test_complete_call_in_one_chunk(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(f"On it. {XML_BASH}") + healer.finalize()
assert _events_text(events) == "On it. "
(call,) = _events_calls(events)
assert call["function"]["name"] == "Bash"
assert healer.healed
def test_signal_split_across_chunks(self):
healer = StreamToolCallHealer({"Bash"})
events = []
for piece in ["<tool", '_call>{"name":"Bash",', '"arguments":{}}</tool_call>']:
events += healer.feed(piece)
events += healer.finalize()
assert _events_text(events) == ""
assert len(_events_calls(events)) == 1
def test_closed_malformed_tool_block_flushes_immediately(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed("<tool_call>not json</tool_call> after")
assert _events_text(events) == "<tool_call>not json</tool_call> after"
assert not _events_calls(events)
def test_mixed_formats_stream_in_document_order(self):
healer = StreamToolCallHealer({"Bash", "Read"})
func_read = "<function=Read><parameter=path>a.txt</parameter></function>"
events = healer.feed(f"{func_read} then {XML_BASH}") + healer.finalize()
assert [call["function"]["name"] for call in _events_calls(events)] == ["Read", "Bash"]
assert _events_text(events).strip() == "then"
def test_false_alarm_html_flushes(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed("use the <div> tag") + healer.finalize()
assert _events_text(events) == "use the <div> tag"
assert not _events_calls(events)
def test_partial_signal_tail_held_then_flushed_at_end(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed("trailing <tool")
assert _events_text(events) == "trailing "
events += healer.finalize()
assert _events_text(events) == "trailing <tool"
def test_mixed_calls_promote_declared_flush_undeclared_in_order(self):
healer = StreamToolCallHealer({"Bash"})
text = f"{XML_BASH} then {XML_UNDECLARED} post"
events = healer.feed(text) + healer.finalize()
assert [k for k, _ in events if k == "tool_call"] == ["tool_call"]
assert events[0][0] == "tool_call"
joined = _events_text(events)
assert XML_UNDECLARED in joined
assert "then" in joined and "post" in joined
def test_text_between_two_healed_calls_keeps_document_order(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(f"{XML_BASH} middle {XML_BASH}") + healer.finalize()
kinds = [k for k, _ in events]
assert kinds == ["tool_call", "text", "tool_call"]
assert events[1][1] == " middle "
def test_undeclared_then_declared_keeps_document_order(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(f"{XML_UNDECLARED} then {XML_BASH}") + healer.finalize()
kinds = [k for k, _ in events]
assert kinds.index("tool_call") == len(kinds) - 1
(call,) = _events_calls(events)
assert call["function"]["name"] == "Bash"
assert XML_UNDECLARED in _events_text(events)
def test_declared_promoted_then_late_undeclared_flushes_raw(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(f"{XML_BASH} then ")
assert len(_events_calls(events)) == 1
events += healer.feed(XML_UNDECLARED) + healer.finalize()
assert XML_UNDECLARED in _events_text(events)
assert len(_events_calls(events)) == 1
def test_undeclared_tool_flushes_raw(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(XML_UNDECLARED) + healer.finalize()
assert _events_text(events) == XML_UNDECLARED
assert not _events_calls(events)
def test_two_calls_and_text_between(self):
healer = StreamToolCallHealer({"Bash", "Read"})
xml_read = '<tool_call>{"name":"Read","arguments":{"path":"f"}}</tool_call>'
events = healer.feed(f"{XML_BASH} then {xml_read}") + healer.finalize()
calls = _events_calls(events)
assert [c["function"]["name"] for c in calls] == ["Bash", "Read"]
assert [c["id"] for c in calls] == ["call_0", "call_1"]
assert _events_text(events).strip() == "then"
def test_mistral_array_multiple_calls_all_promoted_in_stream(self):
# A [TOOL_CALLS] array carries several calls under one signal; promote all in one pass.
healer = StreamToolCallHealer({"get_weather", "get_time"})
array = (
'[TOOL_CALLS][{"name":"get_weather","arguments":{"city":"Paris"}},'
'{"name":"get_time","arguments":{"tz":"UTC"}}]'
)
events = healer.feed(array) + healer.finalize()
calls = _events_calls(events)
assert [c["function"]["name"] for c in calls] == ["get_weather", "get_time"]
assert [c["id"] for c in calls] == ["call_0", "call_1"]
assert _events_text(events) == ""
def test_mistral_array_multiple_calls_promoted_char_by_char(self):
healer = StreamToolCallHealer({"get_weather", "get_time"})
array = (
'[TOOL_CALLS][{"name":"get_weather","arguments":{"city":"Paris"}},'
'{"name":"get_time","arguments":{"tz":"UTC"}}]'
)
events = []
for ch in array:
events += healer.feed(ch)
events += healer.finalize()
calls = _events_calls(events)
assert [c["function"]["name"] for c in calls] == ["get_weather", "get_time"]
assert _events_text(events) == ""
def test_mistral_array_undeclared_middle_kept_as_text_others_promoted(self):
healer = StreamToolCallHealer({"a", "c"})
array = (
'[TOOL_CALLS][{"name":"a","arguments":{}},'
'{"name":"b","arguments":{}},{"name":"c","arguments":{}}]'
)
events = healer.feed(array) + healer.finalize()
assert [c["function"]["name"] for c in _events_calls(events)] == ["a", "c"]
assert '"b"' in _events_text(events)
def test_mistral_array_then_trailing_prose(self):
healer = StreamToolCallHealer({"a", "b"})
array = '[TOOL_CALLS][{"name":"a","arguments":{}},{"name":"b","arguments":{}}]'
events = healer.feed(f"{array} all done") + healer.finalize()
assert [c["function"]["name"] for c in _events_calls(events)] == ["a", "b"]
assert "all done" in _events_text(events)
def test_incomplete_call_healed_at_finalize(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed('<tool_call>{"name":"Bash","arguments":{"cmd":"ls"}}')
assert events == []
events = healer.finalize()
(call,) = _events_calls(events)
assert call["function"]["name"] == "Bash"
def test_teaching_text_flushes_at_finalize(self):
healer = StreamToolCallHealer({"Bash"})
events = healer.feed("<tool_call> is the marker syntax") + healer.finalize()
assert _events_text(events) == "<tool_call> is the marker syntax"
assert not _events_calls(events)
def test_hold_bound_flushes(self):
healer = StreamToolCallHealer({"Bash"})
blob = "<tool_call>" + "x" * (64 * 1024 + 10)
events = healer.feed(blob) + healer.finalize()
assert _events_text(events) == blob
assert not _events_calls(events)
def test_dormant_after_structured_delta(self):
healer = StreamToolCallHealer({"Bash"})
held = healer.feed("prefix <tool")
flush = healer.structured_tool_call_seen()
after = healer.feed(XML_BASH) + healer.finalize()
assert _events_text(held + flush + after) == f"prefix <tool{XML_BASH}"
assert not _events_calls(after)
def test_stream_keeps_a_bracket_call_inside_an_open_block_in_its_arguments():
text = (
'<tool_call><function=Bash><parameter=command>run [TOOL_CALLS]Bash[ARGS]{"command": "rm"} '
"li</parameter></function></tool_call>"
)
healer = StreamToolCallHealer({"Bash"})
events = []
for start in range(0, len(text), 7):
events += healer.feed(text[start : start + 7])
events += healer.finalize()
(call,) = _events_calls(events)
assert "rm" in json.loads(call["function"]["arguments"])["command"]
assert "run " in json.loads(call["function"]["arguments"])["command"]
@pytest.mark.parametrize("step", [1, 5])
def test_stream_drops_the_tool_call_wrapper_around_a_function_call(step):
def call(command):
return (
"<tool_call>\n<function=Bash>\n<parameter=command>\n"
f"{command}\n</parameter>\n</function>\n</tool_call>"
)
text = f"Listing.\n\n{call('ls')}\n{call('pwd')}\nDone."
healer = StreamToolCallHealer({"Bash"})
events = []
for start in range(0, len(text), step):
events += healer.feed(text[start : start + step])
events += healer.finalize()
calls = _events_calls(events)
assert [json.loads(c["function"]["arguments"]) for c in calls] == [
{"command": "ls"},
{"command": "pwd"},
]
assert len({c["id"] for c in calls}) == 2
assert _events_text(events) == "Listing.\n\n\n\nDone."
def test_an_unclosed_wrapper_still_streams_past_the_hold_limit():
healer = StreamToolCallHealer({"Bash"})
events = healer.feed(
"<tool_call>\n<function=Bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
)
for _ in range(8000):
events += healer.feed("more text ")
assert _events_calls(events), "the call must not wait for finalize past the hold limit"
assert len(healer._buffer) < 70000
events += healer.finalize()
(call,) = _events_calls(events)
assert json.loads(call["function"]["arguments"]) == {"command": "ls"}
def test_stream_delivers_a_bracket_call_wrapped_in_a_closed_block():
healer = StreamToolCallHealer({"Bash"})
events = healer.feed('<tool_call>[TOOL_CALLS]Bash[ARGS]{"command": "ls"}</tool_call>')
events += healer.finalize(promote = False)
(call,) = _events_calls(events)
assert json.loads(call["function"]["arguments"]) == {"command": "ls"}
class TestNudgeHelpers:
def _resp(
self,
content,
tool_calls = None,
):
msg = {"role": "assistant", "content": content}
if tool_calls:
msg["tool_calls"] = tool_calls
return {"choices": [{"message": msg, "finish_reason": "stop"}]}
def test_retry_on_unparseable_signal(self):
data = self._resp("<tool_call>call Bash somehow???")
assert nudge_should_retry(data, {"Read"}) is True
def test_no_retry_on_clean_prose(self):
assert nudge_should_retry(self._resp("all done"), {"Bash"}) is False
def test_no_retry_when_heal_would_succeed(self):
assert nudge_should_retry(self._resp(XML_BASH), {"Bash"}) is False
def test_no_retry_with_structured_calls(self):
data = self._resp("", tool_calls = [{"id": "x"}])
assert nudge_should_retry(data, {"Bash"}) is False
def test_no_retry_when_healing_disabled(self):
assert nudge_should_retry(self._resp("<tool_call>???"), None) is False
def test_nudge_messages_shape(self):
data = self._resp("<tool_call>garbage")
suffix = nudge_messages(data, {"Bash", "Read"})
assert [m["role"] for m in suffix] == ["assistant", "user"]
assert suffix[0]["content"] == "<tool_call>garbage"
assert "`Bash` or `Read`" in suffix[1]["content"]
def test_retry_with_undeclared_structured_call_is_not_an_improvement(self):
undeclared = [
{"id": "x", "type": "function", "function": {"name": "Nuke", "arguments": "{}"}}
]
declared = [
{"id": "y", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}
]
assert response_has_promotable_calls(self._resp("", undeclared), {"Bash"}) is False
assert response_has_promotable_calls(self._resp("", declared), {"Bash"}) is True
def test_retry_with_mixed_structured_calls_is_not_an_improvement(self):
# The caller forwards the whole list (a parallel cap keeps the first): all must be declared.
mixed = [
{"id": "x", "type": "function", "function": {"name": "Nuke", "arguments": "{}"}},
{"id": "y", "type": "function", "function": {"name": "Bash", "arguments": "{}"}},
]
assert response_has_promotable_calls(self._resp("", mixed), {"Bash"}) is False
assert (
response_has_promotable_calls(self._resp("", list(reversed(mixed))), {"Bash"}) is False
)
@pytest.mark.parametrize(
"data",
[
None,
"not a dict",
{},
{"choices": []},
{"choices": [{}]},
{"choices": [{"message": None}]},
{"choices": [{"message": "not a dict"}]},
{"choices": [{"message": {"content": None}}]},
{"error": {"message": "boom"}},
],
)
def test_malformed_response_shapes_never_raise(self, data):
assert nudge_should_retry(data, {"Bash"}) is False
assert response_has_promotable_calls(data, {"Bash"}) is False
suffix = nudge_messages(data, {"Bash"})
assert suffix[0] == {"role": "assistant", "content": ""}
import asyncio # noqa: E402
import threading # noqa: E402
from types import SimpleNamespace # noqa: E402
import httpx # noqa: E402
from core.inference.api_monitor import ApiMonitor # noqa: E402
from models.inference import ChatCompletionRequest, ChatMessage # noqa: E402
from routes.inference import ( # noqa: E402
_openai_passthrough_non_streaming,
_openai_passthrough_stream,
)
LOOKUP_TOOL = {
"type": "function",
"function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}},
}
LOOKUP_XML = '<tool_call>{"name":"lookup","arguments":{"q":"x"}}</tool_call>'
OTHER_TOOL = {
"type": "function",
"function": {"name": "other", "parameters": {"type": "object", "properties": {}}},
}
OTHER_XML = '<tool_call>{"name":"other","arguments":{}}</tool_call>'
def _payload(**kwargs):
defaults = dict(
model = "default",
messages = [ChatMessage(role = "user", content = "hi")],
tools = [LOOKUP_TOOL],
)
defaults.update(kwargs)
return ChatCompletionRequest(**defaults)
def _llama_backend():
return SimpleNamespace(
base_url = "http://llama.test",
context_length = 4096,
_request_reasoning_kwargs = lambda *_args, **_kwargs: None,
)
def _upstream_message(
content,
tool_calls = None,
finish_reason = "stop",
usage = None,
):
message = {"role": "assistant", "content": content}
if tool_calls is not None:
message["tool_calls"] = tool_calls
return {
"id": "chatcmpl-up",
"object": "chat.completion",
"created": 1,
"model": "gguf",
"choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],
"usage": usage or {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
}
class ScriptedClient:
"""Fake upstream client returning scripted JSON bodies, counting POSTs."""
def __init__(self, bodies):
self.bodies = list(bodies)
self.posts = []
self.closed = False
async def post(
self,
_url,
json = None,
timeout = None,
headers = None,
):
self.posts.append(json)
return httpx.Response(200, json = self.bodies[min(len(self.posts) - 1, len(self.bodies) - 1)])
async def aclose(self):
self.closed = True
async def _drive_non_streaming(monkeypatch, payload, bodies):
import routes.inference as inf_mod
client = ScriptedClient(bodies)
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
response = await _openai_passthrough_non_streaming(
_llama_backend(), payload, "gguf", monitor_id = None
)
return client, json.loads(response.body)
async def _drive_stream(monkeypatch, payload, lines):
import routes.inference as inf_mod
class Request:
async def is_disconnected(self):
return False
async def fake_send(*_args, **_kwargs):
return httpx.Response(200, content = b"")
async def fake_items(*_args, **_kwargs):
for line in lines:
yield line
monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
response = await _openai_passthrough_stream(
Request(),
threading.Event(),
_llama_backend(),
payload,
"gguf",
"chatcmpl-test",
monitor_id = None,
)
return [chunk async for chunk in response.body_iterator]
def _stream_payloads(chunks):
out = []
for chunk in chunks:
for line in chunk.splitlines():
if line.startswith("data: ") and line[6:] != "[DONE]":
out.append(json.loads(line[6:]))
return out
class TestOpenaiNonStreamingRoute:
def test_heals_xml_to_tool_calls(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
monkeypatch, _payload(), [_upstream_message(LOOKUP_XML)]
)
choice = data["choices"][0]
assert choice["finish_reason"] == "tool_calls"
(call,) = choice["message"]["tool_calls"]
assert call["function"]["name"] == "lookup"
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
assert choice["message"]["content"] is None
assert data["usage"]["total_tokens"] == 3
assert len(client.posts) == 1
asyncio.run(_run())
def test_bare_string_uses_client_schema_key(self, monkeypatch):
async def _run():
content = '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>'
_, data = await _drive_non_streaming(
monkeypatch,
_payload(tools = [BASH_COMMAND_TOOL]),
[_upstream_message(content)],
)
(call,) = data["choices"][0]["message"]["tool_calls"]
assert json.loads(call["function"]["arguments"]) == {"command": "echo hi"}
asyncio.run(_run())
def test_opt_out_relays_verbatim(self, monkeypatch):
async def _run():
_, data = await _drive_non_streaming(
monkeypatch,
_payload(auto_heal_tool_calls = False),
[_upstream_message(LOOKUP_XML)],
)
choice = data["choices"][0]
assert choice["message"]["content"] == LOOKUP_XML
assert "tool_calls" not in choice["message"]
assert choice["finish_reason"] == "stop"
asyncio.run(_run())
def test_no_tools_untouched(self, monkeypatch):
async def _run():
_, data = await _drive_non_streaming(
monkeypatch, _payload(tools = None), [_upstream_message(LOOKUP_XML)]
)
assert data["choices"][0]["message"]["content"] == LOOKUP_XML
asyncio.run(_run())
def test_undeclared_tool_not_promoted(self, monkeypatch):
async def _run():
xml = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
_, data = await _drive_non_streaming(monkeypatch, _payload(), [_upstream_message(xml)])
assert data["choices"][0]["message"]["content"] == xml
assert "tool_calls" not in data["choices"][0]["message"]
asyncio.run(_run())
def test_structured_calls_untouched(self, monkeypatch):
async def _run():
native = [
{
"id": "call_up",
"type": "function",
"function": {"name": "lookup", "arguments": "{}"},
}
]
_, data = await _drive_non_streaming(
monkeypatch,
_payload(),
[_upstream_message("", tool_calls = native, finish_reason = "tool_calls")],
)
assert data["choices"][0]["message"]["tool_calls"] == native
asyncio.run(_run())
def test_length_finish_reason_preserved(self, monkeypatch):
async def _run():
# length is never upgraded to tool_calls: the client must see the truncation.
_, data = await _drive_non_streaming(
monkeypatch,
_payload(),
[_upstream_message(LOOKUP_XML, finish_reason = "length")],
)
choice = data["choices"][0]
assert choice["finish_reason"] == "length"
(call,) = choice["message"]["tool_calls"]
assert call["function"]["name"] == "lookup"
asyncio.run(_run())
def test_call_cut_at_length_stays_text(self, monkeypatch):
async def _run():
cut = "<tool_call><function=lookup><parameter=q>line1\nli"
_, data = await _drive_non_streaming(
monkeypatch,
_payload(),
[_upstream_message(LOOKUP_XML + cut, finish_reason = "length")],
)
choice = data["choices"][0]
assert choice["finish_reason"] == "length"
(call,) = choice["message"]["tool_calls"]
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
assert choice["message"]["content"] == cut
asyncio.run(_run())
def test_tool_choice_none_relays_verbatim(self, monkeypatch):
async def _run():
_, data = await _drive_non_streaming(
monkeypatch,
_payload(tool_choice = "none"),
[_upstream_message(LOOKUP_XML)],
)
message = data["choices"][0]["message"]
assert message["content"] == LOOKUP_XML
assert "tool_calls" not in message
asyncio.run(_run())
def test_tool_choice_forcing_other_function_not_promoted(self, monkeypatch):
async def _run():
_, data = await _drive_non_streaming(
monkeypatch,
_payload(tool_choice = {"type": "function", "function": {"name": "other"}}),
[_upstream_message(LOOKUP_XML)],
)
message = data["choices"][0]["message"]
assert message["content"] == LOOKUP_XML
assert "tool_calls" not in message
asyncio.run(_run())
def test_forced_function_is_sent_as_its_one_tool_under_required(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
monkeypatch,
_payload(
tools = [LOOKUP_TOOL, OTHER_TOOL],
tool_choice = {"type": "function", "function": {"name": "lookup"}},
),
[_upstream_message(OTHER_XML)],
)
(body,) = client.posts
assert [t["function"]["name"] for t in body["tools"]] == ["lookup"]
assert body["tool_choice"] == "required"
message = data["choices"][0]["message"]
assert message["content"] == OTHER_XML
assert "tool_calls" not in message
asyncio.run(_run())
def test_mixed_declared_and_undeclared_promotes_and_keeps_text(self, monkeypatch):
async def _run():
rogue = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
mixed = f"{LOOKUP_XML} also {rogue}"
_, data = await _drive_non_streaming(
monkeypatch, _payload(), [_upstream_message(mixed)]
)
choice = data["choices"][0]
(call,) = choice["message"]["tool_calls"]
assert call["function"]["name"] == "lookup"
assert rogue in choice["message"]["content"]
assert choice["finish_reason"] == "tool_calls"
asyncio.run(_run())
def test_healed_then_native_stream_indexes_disjoint(self, monkeypatch):
async def _run():
# Clients merge deltas by index, so the native call must shift off index 0.
native_line = (
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
'[{"index":0,"id":"call_native","type":"function","function":'
'{"name":"lookup","arguments":"{}"}}]}}]}'
)
lines = [
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":'
+ json.dumps(LOOKUP_XML)
+ "}}]}",
native_line,
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
indexes = {}
for payload_data in _stream_payloads(chunks):
for ch in payload_data.get("choices", []):
for tc in (ch.get("delta") or {}).get("tool_calls") or []:
indexes.setdefault(tc["index"], tc.get("id"))
assert indexes.get(0, "").startswith("call_") and indexes[0] != "call_native"
assert indexes.get(1) == "call_native"
asyncio.run(_run())
def test_role_delta_precedes_healed_stream_content(self, monkeypatch):
async def _run():
lines = [
'data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":'
+ json.dumps(LOOKUP_XML)
+ "}}]}",
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
payloads = _stream_payloads(chunks)
first_delta = payloads[0]["choices"][0]["delta"]
assert first_delta == {"role": "assistant"}
assert "tool_calls" in payloads[1]["choices"][0]["delta"]
asyncio.run(_run())
def test_same_chunk_role_content_finish_delays_finish_until_after_healed_tool(
self, monkeypatch
):
async def _run():
lines = [
'data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":'
+ json.dumps(LOOKUP_XML)
+ '},"finish_reason":"stop"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
payloads = _stream_payloads(chunks)
assert payloads[0]["choices"][0]["finish_reason"] is None
assert payloads[0]["choices"][0]["delta"] == {"role": "assistant"}
assert "tool_calls" in payloads[1]["choices"][0]["delta"]
assert payloads[-1]["choices"][0]["finish_reason"] == "tool_calls"
asyncio.run(_run())
GARBAGE_SIGNAL = "<tool_call>call lookup somehow???"
class TestNudgeRetryOpenai:
def test_retry_recovers_call(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
monkeypatch,
_payload(nudge_tool_calls = True),
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(LOOKUP_XML)],
)
assert len(client.posts) == 2
# Prefix byte-identical (KV-cache reuse), nudge suffix appended.
original, retry = client.posts
assert retry["messages"][: len(original["messages"])] == original["messages"]
suffix = retry["messages"][len(original["messages"]) :]
assert [m["role"] for m in suffix] == ["assistant", "user"]
assert suffix[0]["content"] == GARBAGE_SIGNAL
(call,) = data["choices"][0]["message"]["tool_calls"]
assert call["function"]["name"] == "lookup"
assert data["choices"][0]["finish_reason"] == "tool_calls"
asyncio.run(_run())
def test_retry_usage_includes_both_generation_attempts(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
monitor = ApiMonitor(max_entries = 3)
monkeypatch.setattr(inf_mod, "api_monitor", monitor)
monitor_id = monitor.start(
endpoint = "/v1/chat/completions",
method = "POST",
model = "gguf",
prompt = "hi",
)
first = _upstream_message(
GARBAGE_SIGNAL,
usage = {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10},
)
retry = _upstream_message(
LOOKUP_XML,
usage = {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25},
)
client = ScriptedClient([first, retry])
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
response = await _openai_passthrough_non_streaming(
_llama_backend(),
_payload(nudge_tool_calls = True),
"gguf",
monitor_id = monitor_id,
)
data = json.loads(response.body)
assert data["usage"] == {
"prompt_tokens": 20,
"completion_tokens": 8,
"total_tokens": 28,
}
[entry] = monitor.snapshot()
assert entry["prompt_tokens"] == 20
assert entry["completion_tokens"] == 8
assert entry["total_tokens"] == 28
asyncio.run(_run())
def test_retry_still_garbage_returns_original(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
monkeypatch,
_payload(nudge_tool_calls = True),
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(GARBAGE_SIGNAL + "2")],
)
assert len(client.posts) == 2
assert data["choices"][0]["message"]["content"] == GARBAGE_SIGNAL
assert "tool_calls" not in data["choices"][0]["message"]
asyncio.run(_run())
def test_expected_cancel_during_nudge_retry_is_not_absorbed(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
class ImmediateClient:
async def post(self, *_args, **_kwargs):
return httpx.Response(200, json = _upstream_message(GARBAGE_SIGNAL))
async def aclose(self):
return None
class HangingClient:
def __init__(self):
self.started = asyncio.Event()
self.closed = asyncio.Event()
async def post(self, *_args, **_kwargs):
self.started.set()
await self.closed.wait()
raise httpx.ReadError("client closed")
async def aclose(self):
self.closed.set()
class Request:
async def is_disconnected(self):
return False
hanging = HangingClient()
clients = iter((ImmediateClient(), hanging))
monkeypatch.setattr(
inf_mod,
"_cancelable_nonstreaming_client",
lambda: next(clients),
)
cancel_event = threading.Event()
task = asyncio.create_task(
inf_mod._openai_passthrough_non_streaming_upstream(
_llama_backend(),
_payload(nudge_tool_calls = True),
"gguf",
request = Request(),
cancel_event = cancel_event,
)
)
# Waits only bound a hang, so keep them generous (0.2 s timed out on a saturated CI
# runner); an absorbed cancel still fails, since the task never raises.
await asyncio.wait_for(hanging.started.wait(), 10)
cancel_event.set()
with pytest.raises(inf_mod._NonStreamingRequestCancelled):
await asyncio.wait_for(task, 10)
assert hanging.closed.is_set()
asyncio.run(_run())
def test_default_off_single_post(self, monkeypatch):
async def _run():
client, _ = await _drive_non_streaming(
monkeypatch, _payload(), [_upstream_message(GARBAGE_SIGNAL)]
)
assert len(client.posts) == 1
asyncio.run(_run())
def test_no_retry_on_clean_prose(self, monkeypatch):
async def _run():
client, _ = await _drive_non_streaming(
monkeypatch,
_payload(nudge_tool_calls = True),
[_upstream_message("all done")],
)
assert len(client.posts) == 1
asyncio.run(_run())
def test_no_retry_when_heal_succeeds(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
monkeypatch,
_payload(nudge_tool_calls = True),
[_upstream_message(LOOKUP_XML)],
)
assert len(client.posts) == 1
assert data["choices"][0]["message"]["tool_calls"]
asyncio.run(_run())
def test_heal_opt_out_disables_nudge_too(self, monkeypatch):
async def _run():
client, _ = await _drive_non_streaming(
monkeypatch,
_payload(auto_heal_tool_calls = False, nudge_tool_calls = True),
[_upstream_message(GARBAGE_SIGNAL)],
)
assert len(client.posts) == 1
asyncio.run(_run())
class TestNudgeRetryAnthropic:
async def _drive(
self,
monkeypatch,
bodies,
nudge = None,
):
import routes.inference as inf_mod
from routes.inference import _anthropic_passthrough_non_streaming
client = ScriptedClient(bodies)
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
response = await _anthropic_passthrough_non_streaming(
_llama_backend(),
[{"role": "user", "content": "hi"}],
[LOOKUP_TOOL],
0.7,
0.95,
None,
256,
"msg_test",
"gguf",
nudge_tool_calls = nudge,
)
return client, json.loads(response.body)
def test_retry_recovers_tool_use(self, monkeypatch):
async def _run():
client, data = await self._drive(
monkeypatch,
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(LOOKUP_XML)],
nudge = True,
)
assert len(client.posts) == 2
(block,) = [b for b in data["content"] if b["type"] == "tool_use"]
assert block["name"] == "lookup"
assert data["stop_reason"] == "tool_use"
asyncio.run(_run())
def test_discarded_retry_usage_still_counts_generated_tokens(self, monkeypatch):
async def _run():
first = _upstream_message(
GARBAGE_SIGNAL,
usage = {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10},
)
retry = _upstream_message(
GARBAGE_SIGNAL + "2",
usage = {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25},
)
client, data = await self._drive(
monkeypatch,
[first, retry],
nudge = True,
)
assert len(client.posts) == 2
assert data["content"][0]["text"] == GARBAGE_SIGNAL
assert data["usage"]["input_tokens"] == 20
assert data["usage"]["output_tokens"] == 8
asyncio.run(_run())
def test_healed_tool_use_precedes_trailing_text(self, monkeypatch):
async def _run():
_, data = await self._drive(monkeypatch, [_upstream_message(f"{LOOKUP_XML} done")])
assert [block["type"] for block in data["content"]] == ["tool_use", "text"]
assert data["content"][1]["text"] == "done"
asyncio.run(_run())
def test_default_off(self, monkeypatch):
async def _run():
client, _ = await self._drive(monkeypatch, [_upstream_message(GARBAGE_SIGNAL)])
assert len(client.posts) == 1
asyncio.run(_run())
class TestAnthropicForcedToolChoice:
def test_forced_tool_is_sent_as_its_one_tool_under_required(self, monkeypatch):
import routes.inference as inf_mod
from routes.inference import _anthropic_passthrough_non_streaming
client = ScriptedClient([_upstream_message(OTHER_XML)])
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
async def _run():
response = await _anthropic_passthrough_non_streaming(
_llama_backend(),
[{"role": "user", "content": "hi"}],
[LOOKUP_TOOL, OTHER_TOOL],
0.7,
0.95,
None,
256,
"msg_test",
"gguf",
tool_choice = {"type": "function", "function": {"name": "lookup"}},
)
return json.loads(response.body)
data = asyncio.run(_run())
(body,) = client.posts
assert [t["function"]["name"] for t in body["tools"]] == ["lookup"]
assert body["tool_choice"] == "required"
assert "tool_use" not in [block["type"] for block in data["content"]]
class TestAnthropicPassthroughHealingText:
"""Non-streaming Anthropic passthrough relays undeclared text-form calls as text, not stripped."""
async def _drive(self, monkeypatch, upstream):
import routes.inference as inf_mod
from routes.inference import _anthropic_passthrough_non_streaming
client = ScriptedClient([upstream])
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
response = await _anthropic_passthrough_non_streaming(
_llama_backend(),
[{"role": "user", "content": "hi"}],
[LOOKUP_TOOL],
0.7,
0.95,
None,
256,
"msg_test",
"gguf",
)
return json.loads(response.body)
def test_mixed_declared_and_undeclared_relays_undeclared_as_text(self, monkeypatch):
async def _run():
content = f"Running now. {LOOKUP_XML} then {XML_UNDECLARED} done."
data = await self._drive(monkeypatch, _upstream_message(content))
(tool_use,) = [b for b in data["content"] if b["type"] == "tool_use"]
assert tool_use["name"] == "lookup"
text = " ".join(b["text"] for b in data["content"] if b["type"] == "text")
assert XML_UNDECLARED in text
assert "Running now." in text and "done." in text
assert LOOKUP_XML not in text
asyncio.run(_run())
def test_call_cut_at_max_tokens_is_not_runnable(self, monkeypatch):
async def _run():
cut = "<tool_call><function=lookup><parameter=q>line1\nli"
data = await self._drive(
monkeypatch, _upstream_message(LOOKUP_XML + cut, finish_reason = "length")
)
(tool_use,) = [b for b in data["content"] if b["type"] == "tool_use"]
assert tool_use["input"] == {"q": "x"}
text = "".join(b["text"] for b in data["content"] if b["type"] == "text")
assert text == cut
assert data["stop_reason"] == "max_tokens"
asyncio.run(_run())
def test_cut_call_healed_upstream_keeps_its_text(self):
import routes.inference as inf
cut = "<tool_call><function=lookup><parameter=q>line1\nli"
response = inf._anthropic_message_from_openai_completion(
{"choices": [{"message": {"content": cut}, "finish_reason": "length"}]},
"msg_1",
"m",
openai_tools = [LOOKUP_TOOL],
allowed_tools = None,
disable_parallel_tool_use = False,
response_format = None,
parse_think = True,
)
data = json.loads(response.body)
assert [(b["type"], b["text"]) for b in data["content"]] == [("text", cut)]
assert data["stop_reason"] == "max_tokens"
def test_call_quoted_inside_cut_call_is_not_runnable(self, monkeypatch):
async def _run():
cut = '<tool_call><function=lookup><parameter=q>run [TOOL_CALLS]lookup[ARGS]{"q": "rm"} li'
data = await self._drive(monkeypatch, _upstream_message(cut, finish_reason = "length"))
assert [b["type"] for b in data["content"]] == ["text"]
assert data["content"][0]["text"] == cut
assert data["stop_reason"] == "max_tokens"
asyncio.run(_run())
class TestAnthropicEmitterHealing:
def _events(
self,
emitter,
chunks,
finish = True,
):
lines = []
for chunk in chunks:
lines += emitter.feed_chunk(chunk)
if finish:
lines += emitter.finish()
return [json.loads(ln.split("data: ", 1)[1]) for ln in lines if "data: " in ln]
def _emitter(
self,
allowed = ("lookup",),
**kwargs,
):
from core.inference.anthropic_compat import AnthropicPassthroughEmitter
emitter = AnthropicPassthroughEmitter()
emitter.enable_healing(set(allowed), **kwargs)
return emitter
def _chunk(
self,
content = None,
tool_calls = None,
finish_reason = None,
):
delta = {}
if content is not None:
delta["content"] = content
if tool_calls is not None:
delta["tool_calls"] = tool_calls
return {"choices": [{"delta": delta, "finish_reason": finish_reason}]}
def test_xml_becomes_tool_use_block_and_stop_reason(self):
events = self._events(
self._emitter(),
[
self._chunk(content = LOOKUP_XML),
self._chunk(finish_reason = "stop"),
],
)
starts = [e for e in events if e.get("type") == "content_block_start"]
(tool_start,) = [e for e in starts if e["content_block"]["type"] == "tool_use"]
assert tool_start["content_block"]["name"] == "lookup"
assert tool_start["content_block"]["id"].startswith("toolu_")
(args,) = [
e["delta"]["partial_json"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "input_json_delta"
]
assert json.loads(args) == {"q": "x"}
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
assert message_delta["delta"]["stop_reason"] == "tool_use"
def test_mid_block_signal_closes_text_block_first(self):
events = self._events(
self._emitter(),
[
self._chunk(content = f"Let me check {LOOKUP_XML}"),
self._chunk(finish_reason = "stop"),
],
)
kinds = [
(e["type"], (e.get("content_block") or e.get("delta") or {}).get("type"))
for e in events
if e["type"].startswith("content_block")
]
assert kinds[0] == ("content_block_start", "text")
assert kinds[1] == ("content_block_delta", "text_delta")
assert kinds[2] == ("content_block_stop", None)
assert kinds[3] == ("content_block_start", "tool_use")
texts = [
e["delta"]["text"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert "".join(texts) == "Let me check "
def test_false_alarm_streams_as_text(self):
events = self._events(
self._emitter(),
[self._chunk(content = "use the <div> tag"), self._chunk(finish_reason = "stop")],
)
texts = [
e["delta"]["text"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert "".join(texts) == "use the <div> tag"
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
assert message_delta["delta"]["stop_reason"] == "end_turn"
def test_signal_split_across_chunks(self):
events = self._events(
self._emitter(),
[
self._chunk(content = "<tool"),
self._chunk(content = '_call>{"name":"lookup","arguments":{}}'),
self._chunk(finish_reason = "stop"),
],
)
starts = [e for e in events if e.get("type") == "content_block_start"]
assert [e["content_block"]["type"] for e in starts] == ["tool_use"]
texts = [
e
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert texts == []
def test_max_tokens_wins_over_healed_stop_reason(self):
events = self._events(
self._emitter(),
[self._chunk(content = LOOKUP_XML), self._chunk(finish_reason = "length")],
)
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
assert message_delta["delta"]["stop_reason"] == "max_tokens"
def test_call_cut_at_max_tokens_is_not_runnable(self):
cut = (
"<tool_call><function=Write><parameter=file_path>app.py</parameter>"
"<parameter=content>line1\nline2\nli"
)
events = self._events(
self._emitter(allowed = ("Write",)),
[self._chunk(content = cut), self._chunk(finish_reason = "length")],
)
starts = [e for e in events if e.get("type") == "content_block_start"]
assert [e["content_block"]["type"] for e in starts] == ["text"]
texts = [
e["delta"]["text"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert "".join(texts) == cut
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
assert message_delta["delta"]["stop_reason"] == "max_tokens"
def test_call_quoted_inside_cut_call_is_not_runnable(self):
cut = (
"<tool_call><function=Write><parameter=file_path>app.py</parameter>"
'<parameter=content>run [TOOL_CALLS]Write[ARGS]{"file_path": "x"} li'
)
events = self._events(
self._emitter(allowed = ("Write",)),
[self._chunk(content = cut), self._chunk(finish_reason = "length")],
)
starts = [e for e in events if e.get("type") == "content_block_start"]
assert [e["content_block"]["type"] for e in starts] == ["text"]
def test_structured_deltas_disable_healing_and_flush(self):
structured = [
{
"index": 0,
"id": "call_up",
"function": {"name": "lookup", "arguments": "{}"},
}
]
events = self._events(
self._emitter(),
[
self._chunk(content = "held <tool"),
self._chunk(tool_calls = structured),
self._chunk(finish_reason = "tool_calls"),
],
)
texts = [
e["delta"]["text"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert "".join(texts) == "held <tool"
starts = [e for e in events if e.get("type") == "content_block_start"]
assert [e["content_block"]["type"] for e in starts] == ["text", "tool_use"]
def test_disable_parallel_caps_healed_calls(self):
two = LOOKUP_XML + '<tool_call>{"name":"lookup","arguments":{"q":"y"}}</tool_call>'
events = self._events(
self._emitter(disable_parallel_tool_use = True),
[self._chunk(content = two), self._chunk(finish_reason = "stop")],
)
starts = [
e
for e in events
if e.get("type") == "content_block_start" and e["content_block"]["type"] == "tool_use"
]
assert len(starts) == 1
def test_disable_parallel_drops_native_after_healed(self):
structured = [
{
"index": 0,
"id": "call_up",
"function": {"name": "lookup", "arguments": "{}"},
}
]
events = self._events(
self._emitter(disable_parallel_tool_use = True),
[
self._chunk(content = LOOKUP_XML),
self._chunk(tool_calls = structured),
self._chunk(finish_reason = "tool_calls"),
],
)
starts = [
e
for e in events
if e.get("type") == "content_block_start" and e["content_block"]["type"] == "tool_use"
]
assert len(starts) == 1
def test_no_healing_means_verbatim_text(self):
from core.inference.anthropic_compat import AnthropicPassthroughEmitter
emitter = AnthropicPassthroughEmitter()
events = self._events(
emitter,
[self._chunk(content = LOOKUP_XML), self._chunk(finish_reason = "stop")],
)
texts = [
e["delta"]["text"]
for e in events
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
]
assert "".join(texts) == LOOKUP_XML
class TestAnthropicNonStreamingRoute:
async def _drive(
self,
monkeypatch,
bodies,
auto_heal = None,
tools = None,
tool_choice = "auto",
):
import routes.inference as inf_mod
from routes.inference import _anthropic_passthrough_non_streaming
client = ScriptedClient(bodies)
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
response = await _anthropic_passthrough_non_streaming(
_llama_backend(),
[{"role": "user", "content": "hi"}],
tools if tools is not None else [LOOKUP_TOOL],
0.7,
0.95,
None,
256,
"msg_test",
"gguf",
tool_choice = tool_choice,
auto_heal_tool_calls = auto_heal,
)
return client, json.loads(response.body)
def test_promotes_xml_to_tool_use(self, monkeypatch):
async def _run():
_, data = await self._drive(monkeypatch, [_upstream_message(LOOKUP_XML)])
(block,) = [b for b in data["content"] if b["type"] == "tool_use"]
assert block["name"] == "lookup"
assert block["input"] == {"q": "x"}
assert data["stop_reason"] == "tool_use"
assert not any(b["type"] == "text" for b in data["content"])
asyncio.run(_run())
def test_opt_out_keeps_legacy_strip(self, monkeypatch):
async def _run():
_, data = await self._drive(
monkeypatch, [_upstream_message(f"plan {LOOKUP_XML}")], auto_heal = False
)
assert data["stop_reason"] == "end_turn"
(block,) = data["content"]
assert block["type"] == "text"
assert block["text"] == "plan"
asyncio.run(_run())
def test_undeclared_tool_not_promoted(self, monkeypatch):
async def _run():
xml = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
_, data = await self._drive(monkeypatch, [_upstream_message(xml)])
assert data["stop_reason"] == "end_turn"
assert not any(b["type"] == "tool_use" for b in data["content"])
(text_block,) = [b for b in data["content"] if b["type"] == "text"]
assert text_block["text"] == xml
asyncio.run(_run())
def test_mixed_undeclared_text_preserved_after_heal(self, monkeypatch):
async def _run():
rogue = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
_, data = await self._drive(monkeypatch, [_upstream_message(f"{LOOKUP_XML} {rogue}")])
(tool_block,) = [b for b in data["content"] if b["type"] == "tool_use"]
assert tool_block["name"] == "lookup"
(text_block,) = [b for b in data["content"] if b["type"] == "text"]
assert rogue in text_block["text"]
assert data["stop_reason"] == "tool_use"
asyncio.run(_run())
def test_length_beats_tool_use(self, monkeypatch):
async def _run():
_, data = await self._drive(
monkeypatch, [_upstream_message(LOOKUP_XML, finish_reason = "length")]
)
assert data["stop_reason"] == "max_tokens"
assert any(b["type"] == "tool_use" for b in data["content"])
asyncio.run(_run())
def test_tool_choice_none_keeps_legacy_strip(self, monkeypatch):
async def _run():
_, data = await self._drive(
monkeypatch,
[_upstream_message(f"plan {LOOKUP_XML}")],
tool_choice = "none",
)
assert data["stop_reason"] == "end_turn"
(block,) = data["content"]
assert block["type"] == "text"
assert block["text"] == "plan"
asyncio.run(_run())
class TestOpenaiStreamingRoute:
def test_heals_streamed_xml(self, monkeypatch):
async def _run():
pieces = ["<tool_call>", '{"name":"lookup",', '"arguments":{"q":"x"}}', "</tool_call>"]
lines = [
'data: {"id":"c1","model":"gguf","created":1,"choices":[{"index":0,"delta":{"content":%s}}]}'
% json.dumps(p)
for p in pieces
]
lines += [
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(), lines)
payloads = _stream_payloads(chunks)
tool_deltas = [
tc
for p in payloads
for c in p.get("choices", [])
for tc in (c.get("delta") or {}).get("tool_calls") or []
]
(call,) = tool_deltas
assert call["function"]["name"] == "lookup"
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
finishes = [
c["finish_reason"]
for p in payloads
for c in p.get("choices", [])
if c.get("finish_reason")
]
assert finishes == ["tool_calls"]
text = "".join(
(c.get("delta") or {}).get("content") or ""
for p in payloads
for c in p.get("choices", [])
)
assert "<tool_call>" not in text
assert chunks[-1] == "data: [DONE]\n\n"
asyncio.run(_run())
@pytest.mark.parametrize("finish_on_content", [False, True])
def test_call_cut_at_length_stays_text(self, monkeypatch, finish_on_content):
async def _run():
cut = "<tool_call><function=lookup><parameter=q>line1\nli"
head = {"id": "c1", "model": "gguf", "created": 1}
content = {"index": 0, "delta": {"content": LOOKUP_XML + cut}}
finish = {"index": 0, "delta": {}, "finish_reason": "length"}
choices = (
[[{**content, "finish_reason": "length"}]]
if finish_on_content
else [[content], [finish]]
)
lines = ["data: " + json.dumps({**head, "choices": c}) for c in choices]
chunks = await _drive_stream(monkeypatch, _payload(), lines + ["data: [DONE]"])
found = [c for p in _stream_payloads(chunks) for c in p.get("choices", [])]
(call,) = [tc for c in found for tc in (c.get("delta") or {}).get("tool_calls") or []]
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
assert "".join((c.get("delta") or {}).get("content") or "" for c in found) == cut
assert [c["finish_reason"] for c in found if c.get("finish_reason")] == ["length"]
asyncio.run(_run())
def test_parallel_cap_drops_native_after_healed(self, monkeypatch):
async def _run():
# The upstream SSE cap keeps native index 0, so the route must drop it itself.
xml = '<tool_call>{"name":"lookup","arguments":{"q":"x"}}</tool_call>'
native = (
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
'[{"index":0,"id":"call_up","type":"function","function":'
'{"name":"lookup","arguments":"{}"}}]}}]}'
)
lines = [
'data: {"id":"c1","model":"gguf","created":1,"choices":'
'[{"index":0,"delta":{"content":%s}}]}' % json.dumps(xml),
native,
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(parallel_tool_calls = False), lines)
payloads = _stream_payloads(chunks)
tool_deltas = [
tc
for p in payloads
for c in p.get("choices", [])
for tc in (c.get("delta") or {}).get("tool_calls") or []
]
(call,) = tool_deltas
assert call["id"] == "call_0"
asyncio.run(_run())
def test_false_alarm_text_flushes(self, monkeypatch):
async def _run():
lines = [
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":"use the <div> tag"}}]}',
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(), lines)
payloads = _stream_payloads(chunks)
text = "".join(
(c.get("delta") or {}).get("content") or ""
for p in payloads
for c in p.get("choices", [])
)
assert text == "use the <div> tag"
finishes = [
c["finish_reason"]
for p in payloads
for c in p.get("choices", [])
if c.get("finish_reason")
]
assert finishes == ["stop"]
asyncio.run(_run())
def test_incomplete_xml_healed_at_done(self, monkeypatch):
async def _run():
lines = [
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":"<tool_call>{\\"name\\":\\"lookup\\",\\"arguments\\":{}}"}}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(), lines)
payloads = _stream_payloads(chunks)
tool_deltas = [
tc
for p in payloads
for c in p.get("choices", [])
for tc in (c.get("delta") or {}).get("tool_calls") or []
]
assert len(tool_deltas) == 1
finishes = [
c["finish_reason"]
for p in payloads
for c in p.get("choices", [])
if c.get("finish_reason")
]
assert finishes == ["tool_calls"]
asyncio.run(_run())
def test_structured_upstream_calls_relay_verbatim(self, monkeypatch):
async def _run():
line = (
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
'[{"index":0,"id":"call_up","type":"function","function":'
'{"name":"lookup","arguments":"{}"}}]}}]}'
)
lines = [
line,
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
"data: [DONE]",
]
chunks = await _drive_stream(monkeypatch, _payload(), lines)
assert chunks[0] == line + "\n\n"
asyncio.run(_run())
class TestHealerSignalAlignment:
"""The healer buffers only promotable formats; a bare [ARGS] signal would stall prose uselessly."""
def test_prose_with_bare_args_marker_streams_through(self):
healer = StreamToolCallHealer({"Bash"})
chunks = [
"Use the pattern foo",
"[ARGS] in templates when calling tools, ",
"and remember to close it.",
]
streamed = ""
for chunk in chunks:
streamed += _events_text(healer.feed(chunk))
assert streamed == "".join(chunks)
final = healer.finalize()
assert not _events_calls(final)
assert not healer.healed
def test_bracket_tool_calls_still_promote_in_stream(self):
healer = StreamToolCallHealer({"web_search"})
events = healer.feed('[TOOL_CALLS]web_search{"query": "unsloth docs"}') + healer.finalize()
(call,) = _events_calls(events)
assert call["function"]["name"] == "web_search"
assert healer.healed
_XML_BASH = "<function=Bash>\n<parameter=command>\nls\n</parameter>\n</function>"
_GLM = "<tool_call>Bash<arg_key>command</arg_key><arg_value>ls</arg_value></tool_call>"
_KIMI = (
"<|tool_calls_section_begin|><|tool_call_begin|>functions.Bash:0<|tool_call_argument_begin|>"
'{"command": "ls"}<|tool_call_end|><|tool_calls_section_end|>'
)
_MINIMAX = (
'<minimax:tool_call><invoke name="Bash"><parameter name="command">ls</parameter></invoke>'
"</minimax:tool_call>"
)
_SEED = f"<seed:tool_call>\n{_XML_BASH}\n</seed:tool_call>"
_DEEPSEEK = (
'<|tool▁calls▁begin|><|tool▁call▁begin|>Bash<|tool▁sep|>{"command": "ls"}'
"<|tool▁call▁end|><|tool▁calls▁end|>"
)
# Format -> (template marker, a block calling Bash(command="ls")).
_NATIVE = {
"glm": ("<arg_key>", _GLM),
"minimax": ("<minimax:tool_call>", _MINIMAX),
"kimi": ("<|tool_calls_section_begin|>", _KIMI),
"deepseek": ("<|tool▁calls▁begin|>", _DEEPSEEK),
"seed": ("<seed:tool_call>", _SEED),
}
_LS = ("Bash", {"command": "ls"})
_JSON_LS = '{"command": "ls"}'
def _named(calls):
return [(c["function"]["name"], json.loads(c["function"]["arguments"])) for c in calls]
def _heal_native(
name,
text,
allowed = ("Bash", "Write"),
tools = None,
):
"""Calls and text from the stream at several chunk sizes and from the message path, which agree."""
native = native_tool_format(_NATIVE[name][0])
results = []
for step in (1, 7, len(text)):
healer = StreamToolCallHealer(set(allowed), tools, native = native)
events = [e for i in range(0, len(text), step) for e in healer.feed(text[i : i + step])]
events += healer.finalize()
results.append((_named(_events_calls(events)), _events_text(events)))
assert results.count(results[0]) == len(results)
calls, relayed = results[0]
msg = {"content": text}
heal_openai_message(msg, set(allowed), tools, native = native)
assert _named(msg.get("tool_calls") or []) == calls
assert msg["content"] == ((relayed.strip() or None) if calls else text)
return results[0]
class TestNativeToolFormats:
"""In-process models: the template's own call blocks are promoted, as llama-server parses them."""
def test_detects_the_format_from_the_template(self):
for marker, block in _NATIVE.values():
fmt = native_tool_format(f"{{% if tools %}}{marker}{{% endif %}}")
assert block.startswith(fmt.open) and block.endswith(fmt.close)
assert native_tool_format({"tool_use": "<minimax:tool_call>"}).open == "<minimax:tool_call>"
assert native_tool_format("<tool_call>\n<function=", None) is None
@pytest.mark.parametrize("name", _NATIVE)
def test_each_format_is_promoted_with_no_markup_left(self, name):
block = _NATIVE[name][1]
text = f"On it.\n{block}\n{block}\nDone."
assert _heal_native(name, text) == ([_LS, _LS], "On it.\n\n\nDone.")
@pytest.mark.parametrize(
"name, text",
[
("minimax", _MINIMAX.replace("</invoke>", '</invoke><invoke name="Read"></invoke>')),
("minimax", _MINIMAX.replace("</invoke>", '</invoke><invoke\nname="Bash"><parameter>')),
("kimi", _KIMI.replace(_JSON_LS, "{command: ls}")),
("seed", f"<seed:tool_call><function=Bash>{_JSON_LS}</function></seed:tool_call>"),
("minimax", _MINIMAX.replace('<parameter name="command">ls</parameter>', _JSON_LS)),
("glm", f"<tool_call>Bash\n{_JSON_LS}</tool_call>"),
(
"glm",
f'<tool_call>{json.dumps({"name": "Write", "arguments": {"c": _GLM}})}</tool_call>',
),
(
"minimax",
f"<function=Write>\n<parameter=content>\n{_MINIMAX}\n</parameter>\n</function>",
),
("kimi", f'<|tool_call>call:Write{{c:<|"|>a<tool_call|>{_KIMI}<|"|>}}<tool_call|>'),
("glm", f"<|tool_call_begin|>functions.Write:0<|tool_call_argument_begin|>{_GLM}"),
("glm", f'<function\n name="Write"><parameter name="c">{_GLM}</parameter></function>'),
("kimi", f"{_KIMI} then {_XML_BASH}"),
("kimi", f"see <seed:tool_call> then {_KIMI}"),
(
"minimax",
_MINIMAX.replace(">ls<", '><invoke name="Bash"></invoke><').replace(
'"><parameter name="command">',
f'">{_JSON_LS}</invoke><invoke name="Bash"><parameter name="command">',
1,
),
),
("kimi", f"<think>{_XML_BASH}</think>{_KIMI}"),
("kimi", "<function=Write><|tool_calls_section_begin|>x"),
("kimi", f"<|tool_calls_section_begin|>x<|tool_calls_section_end|> see {_KIMI[28:]}"),
("kimi", _KIMI.replace(_JSON_LS, '{"x": ' + "[" * 1100 + "]" * 1100 + "}")),
("seed", _SEED.replace("ls", "</seed:tool_call>" * 3200)),
*(
("kimi", f"<|tool_calls_section_begin|>{wrapper}{_KIMI[28:]}</parameter>")
for wrapper in (
"<function=Write><parameter=c>",
'<function\n name="Write"><parameter name="c">',
)
),
(
"kimi",
f'<|tool_calls_section_begin|><function name="Write"><parameter name="c">'
+ _KIMI[28:].replace('"ls"', json.dumps('<function name="Write">')),
),
],
)
def test_a_reply_that_is_not_all_declared_well_formed_blocks_stays_text(self, name, text):
assert _heal_native(name, text, ("Bash",)) == ([], text)
@pytest.mark.parametrize(
"name, text, calls",
[
(
"kimi",
_KIMI.replace('"ls"', '"<|tool_calls_section_end|>"'),
[("Bash", {"command": "<|tool_calls_section_end|>"})],
),
(
"kimi",
_KIMI.replace('"ls"', '"<|tool_call_begin|>"'),
[("Bash", {"command": "<|tool_call_begin|>"})],
),
(
"seed",
_SEED.replace("\nls\n", "\n<function=x>\n"),
[("Bash", {"command": "<function=x>"})],
),
("minimax", _MINIMAX.replace("<invoke ", "<invoke\n"), [_LS]),
(
"minimax",
_MINIMAX.replace("<invoke", '<invoke name="Bash"></invoke><invoke').replace(
"parameter", "param"
),
[("Bash", {}), _LS],
),
(
"minimax",
_MINIMAX.replace(">ls<", '><invoke name="x">y</invoke><'),
[("Bash", {"command": '<invoke name="x">y</invoke>'})],
),
("glm", f"<think>maybe [/THINK] {_GLM}</think>{_GLM}", [_LS]),
(
"minimax",
f"{_MINIMAX.replace('>ls<', '><think><')}{_MINIMAX}",
[("Bash", {"command": "<think>"}), _LS],
),
("minimax", f"[THINK]maybe </think> {_MINIMAX}[/THINK]{_MINIMAX}", [_LS]),
("glm", json.dumps({"a": [_GLM, "<function=x>"]}) + _GLM, [_LS]),
("glm", "[" * 100000 + _GLM, [_LS]),
],
)
def test_argument_and_reasoning_text_is_data(self, name, text, calls):
assert _heal_native(name, text)[0] == calls
def test_kimi_call_ids_replay_through_its_template(self):
native = native_tool_format(_NATIVE["kimi"][0])
two = _KIMI + _KIMI.replace(":0", ":1")
for text, ids in (
(two, ["functions.Bash:0", "functions.Bash:1"]),
(_KIMI * 2, ["call_0", "call_1"]),
):
msg = {"content": text}
heal_openai_message(msg, {"Bash"}, native = native)
healer = StreamToolCallHealer({"Bash"}, native = native)
events = healer.feed(text) + healer.finalize()
assert (
[c["id"] for c in msg["tool_calls"]]
== [c["id"] for c in _events_calls(events)]
== ids
)
def test_a_block_relays_once_if_its_calls_are_un_promoted(self):
block = _MINIMAX.replace("</invoke>", '</invoke><invoke name="Bash"></invoke>')
healer = StreamToolCallHealer({"Bash"}, native = native_tool_format("<minimax:tool_call>"))
assert _events_calls(healer.feed(block) + healer.finalize())
assert (healer.promoted_source("call_0"), healer.promoted_source("call_1")) == (block, "")
def test_glm_values_are_typed_by_the_tools_schema(self):
tools = [_client_tool("Write", {"c": {"type": "string"}, "o": {"type": "object"}})]
text = '<tool_call>Write<arg_key>c</arg_key><arg_value>{"on":true}</arg_value>'
text += '<arg_key>o</arg_key><arg_value>{"a": 1}</arg_value></tool_call>'
calls = [("Write", {"c": '{"on":true}', "o": {"a": 1}})]
assert _heal_native("glm", text, ("Write",), tools)[0] == calls
def test_a_cut_off_block_promotes_only_when_incomplete_calls_may(self):
cut = _DEEPSEEK[: -len("<|tool▁calls▁end|>")]
assert _heal_native("deepseek", cut)[0] == [_LS]
native = native_tool_format(_NATIVE["deepseek"][0])
generic = f'<tool_call>{{"name": "Bash", "arguments": {_JSON_LS}}}'
for native, text, calls in (
(native, cut, []),
(native, f"{_DEEPSEEK} and the", [_LS]),
(None, generic, []),
):
msg = {"content": text}
heal_openai_message(msg, {"Bash"}, allow_incomplete = False, native = native)
healer = StreamToolCallHealer({"Bash"}, native = native)
events = healer.feed(text) + healer.finalize(promote = False)
assert _named(msg.get("tool_calls") or []) == _named(_events_calls(events)) == calls
def test_the_stream_holds_no_more_than_the_hold_limit(self):
native = native_tool_format("<seed:tool_call>")
text = _SEED.replace("\nls\n", "x" * (70 * 1024)).replace("Bash", "Write") + _SEED
healer = StreamToolCallHealer({"Bash", "Write"}, native = native)
events = [e for i in range(0, len(text), 4096) for e in healer.feed(text[i : i + 4096])]
assert _events_text(events + healer.finalize()) == text
assert heal_openai_message({"content": text}, {"Bash", "Write"}, native = native)
def _client_tool(name, properties):
return {
"type": "function",
"function": {"name": name, "parameters": {"type": "object", "properties": properties}},
}
GREP_TOOL = _client_tool(
"Grep",
{
"pattern": {"type": "string"},
"multiline": {"type": "boolean"},
"head_limit": {"type": "integer"},
"timeout": {"type": "integer"},
},
)
FETCH_TOOL = _client_tool("WebFetch", {"url": {"type": "string"}, "timeout": {"type": "string"}})
CLIENT_TOOLS = [FETCH_TOOL, GREP_TOOL]
CLIENT_NAMES = {"WebFetch", "Grep"}
def _healed_arguments(content):
msg = {"role": "assistant", "content": content}
assert heal_openai_message(msg, CLIENT_NAMES, CLIENT_TOOLS) is True
(call,) = msg["tool_calls"]
return json.loads(call["function"]["arguments"])
class TestClientToolSchemaTyping:
def test_xml_parameters_arrive_as_their_declared_types(self):
"""Both spell "false": the declared flag becomes a boolean, the search text stays text."""
arguments = _healed_arguments(
"<function=Grep>"
"<parameter=pattern>false</parameter>"
"<parameter=head_limit>25</parameter>"
"<parameter=multiline>false</parameter>"
"</function>"
)
assert arguments == {"pattern": "false", "head_limit": 25, "multiline": False}
def test_each_call_is_typed_through_its_own_tools_schema(self):
"""The same key is milliseconds on Grep but a duration on WebFetch, so type each call by its
tool."""
call = (
"<function=%s><parameter=%s>x</parameter><parameter=timeout>30</parameter></function>"
)
assert _healed_arguments(call % ("WebFetch", "url")) == {"url": "x", "timeout": "30"}
assert _healed_arguments(call % ("Grep", "pattern")) == {"pattern": "x", "timeout": 30}
_SCHEMA = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
_CONTRACT = {"type": "json_schema", "json_schema": {"name": "c", "schema": _SCHEMA}}
def test_a_contract_withdraws_both_post_decode_reinterpreters():
tools = [{"type": "function", "function": {"name": "lookup"}}]
assert heal_gate(True, tools) == {"lookup"}
assert heal_gate(True, tools, response_format = {"type": "text"}) == {"lookup"}
assert nudge_enabled(True, response_format = {"type": "text"}) is True
for constraining in (_CONTRACT, {"type": "json_object"}, {"type": "text", "x": 1}, True, "x"):
assert heal_gate(True, tools, response_format = constraining) is None, constraining
assert nudge_enabled(True, response_format = constraining) is False, constraining
def test_every_post_decode_reinterpreter_is_handed_the_request_s_own_contract():
import ast
from pathlib import Path
names = ("heal_gate", "nudge_enabled")
forwards = (
'body.get("response_format")',
"_extract_response_format(payload)",
"_sf_response_format",
)
source = (Path(__file__).resolve().parents[1] / "routes/inference.py").read_text(
encoding = "utf-8"
)
tree = ast.parse(source)
# The MLX name may hold None only where _response_format_beside_tools sets the contract aside.
sources = [
ast.get_source_segment(source, getattr(node.value, "func", node.value))
for node in ast.walk(tree)
if isinstance(node, ast.Assign)
and any(getattr(t, "id", None) == "_sf_response_format" for t in node.targets)
]
assert sources == ["_response_format_beside_tools"], sources
calls, missing = [], []
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
if (getattr(node.func, "attr", None) or getattr(node.func, "id", None)) not in names:
continue
calls.append(node)
kwargs = {k.arg: ast.get_source_segment(source, k.value) or "" for k in node.keywords}
if kwargs.get("response_format") not in forwards:
missing.append(node.lineno)
assert len(calls) >= 9, f"expected 9 {names} sites, found {len(calls)}"
assert not missing, f"heal_gate/nudge_enabled not handed the contract at {missing}"