fix(reply): stop models answering past an available tool

M0 on Strata caught both v2 models skipping a tool they had been given:
the recommended model made up "24 degrees, sunny" instead of calling the
weather tool, and the fast model said "timer set" without calling the
timer tool (3 of 3 each). qwen2.5:7b does the same through the engine.

- Prompt: TOOL_HONESTY_RULES in the persona (live facts only from a tool
  result this turn, actions only claimed after a tool reports success, no
  answer text next to a tool call), restated at the end of the system
  message by tool_honesty_reminder() with the turn's real tool names.
- Engine: skipped-tool guard. When a native-tool model answers before any
  tool has run and the plan names a callable tool as a concrete call, the
  answer is dropped and the plan steps are direct-executed, then the model
  answers from the results. Only literal, schema-valid steps run (regex
  fast path, no LLM repair); otherwise the held-back answer is delivered.
- Planner: the AVAILABLE TOOLS lines now carry argument names
  (planner_tool_catalog), so concrete steps use the tool's real keys.
- Eval evals/test_tool_skip_confabulation.py; on qwen2.5:7b, 3 runs each,
  available-tool cases went from 0/12 to 9/12 calling the tool.
- M0 kit: tools_fast / tools_recommended stages (run_m0_tools.bat) rerun
  tool calling before and after the fix on the real models, loading the
  production system_prompt.py and planner.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-10 15:05:40 +09:00
parent 73fa93f346
commit 903e0eb9de
18 changed files with 916 additions and 44 deletions

View File

@@ -0,0 +1,184 @@
"""Skipped-tool guard: a native-tool model must not answer past a planned tool.
M0 measurements on the v2 gaming PC (2026-11-10, Strata) caught capable
models answering without calling a tool they had been given: a made-up
"24 degrees and sunny" instead of calling the weather tool, and "timer set"
without calling the timer tool. When the planner already named a concrete
tool for the turn, the engine must run that tool itself instead of
delivering the model's tool-less answer, and the synthesis turn must not
see the made-up answer.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
LARGE_NATIVE_MODEL = "gpt-oss:20b" # LARGE -> native tool calling, no text-tool direct-exec
FABRICATED = "It is 24 degrees and sunny in Seoul right now."
GROUNDED = "Seoul is 13 degrees and clear."
QUERY = "do I need an umbrella in Seoul right now?"
def _content(text: str) -> dict:
return {"message": {"role": "assistant", "content": text}}
def _native_call(name: str, args: dict) -> dict:
return {"message": {"role": "assistant", "content": "", "tool_calls": [
{"id": "call_1", "type": "function", "function": {"name": name, "arguments": args}}]}}
def _run(mock_config, db, dialogue_memory, *, plan, chat_replies, allowed):
from jarvis.reply import engine as engine_mod
from jarvis.tools.types import ToolExecutionResult
mock_config.ollama_chat_model = LARGE_NATIVE_MODEL
mock_config.evaluator_enabled = False
seen_messages: list[list[dict]] = []
replies = iter(chat_replies)
def fake_chat(*args, **kwargs):
msgs = kwargs.get("messages") or (args[2] if len(args) > 2 else [])
seen_messages.append([dict(m) for m in msgs])
return next(replies)
invoked: list[tuple[str, dict]] = []
def fake_tool(db, cfg, tool_name, tool_args, **kwargs):
invoked.append((tool_name, dict(tool_args or {})))
return ToolExecutionResult(success=True, reply_text="Seoul: 13C, clear sky, no rain.",
error_message=None)
with patch.object(engine_mod, "run_tool_with_retries", side_effect=fake_tool), \
patch.object(engine_mod, "chat_with_messages", side_effect=fake_chat), \
patch.object(engine_mod, "select_tools", return_value=allowed), \
patch.object(engine_mod, "extract_search_params_for_memory", return_value={"keywords": []}), \
patch.object(engine_mod, "plan_query", return_value=plan):
reply = engine_mod.run_reply_engine(db=db, cfg=mock_config, tts=None, text=QUERY,
dialogue_memory=dialogue_memory)
return reply, invoked, seen_messages
WEATHER_PLAN = ["getWeather location='Seoul'", "Reply to the user with the weather."]
def test_tool_less_answer_is_replaced_by_running_the_planned_tool(mock_config, db, dialogue_memory):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=WEATHER_PLAN,
chat_replies=[_content(FABRICATED), _content(GROUNDED)],
allowed=["getWeather", "stop"],
)
assert invoked == [("getWeather", {"location": "Seoul"})]
assert reply == GROUNDED
# The synthesis turn reads the tool result, never the made-up answer.
final_turn = seen[-1]
assert not any(FABRICATED in (m.get("content") or "") for m in final_turn)
assert any(m.get("role") == "tool" and "13C" in (m.get("content") or "") for m in final_turn)
def test_model_that_calls_the_tool_itself_is_left_alone(mock_config, db, dialogue_memory):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=WEATHER_PLAN,
chat_replies=[_native_call("getWeather", {"location": "Seoul"}), _content(GROUNDED)],
allowed=["getWeather", "stop"],
)
assert invoked == [("getWeather", {"location": "Seoul"})]
assert reply == GROUNDED
assert len(seen) == 2
def test_reply_only_plan_delivers_the_first_answer(mock_config, db, dialogue_memory):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=["Reply to the user."],
chat_replies=[_content("Good evening.")],
allowed=["getWeather", "stop"],
)
assert invoked == []
assert reply == "Good evening."
assert len(seen) == 1
def test_plan_naming_a_tool_that_does_not_exist_does_not_retry(mock_config, db, dialogue_memory):
# No timer tool exists: the guard has nothing to run, so it must not burn a
# second chat call; the honesty rules in the prompt cover what is said.
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=["setTimer minutes='5'", "Reply to the user."],
chat_replies=[_content("I have no timer, so I cannot set one.")],
allowed=["getWeather", "stop"],
)
assert invoked == []
assert reply == "I have no timer, so I cannot set one."
assert len(seen) == 1
# Planners often emit just the tool step (no synthesis step), or a memory
# directive plus one tool step. Both still name the tool to run.
@pytest.mark.parametrize("plan", [
["getWeather location='Seoul'"],
["searchMemory topic='user location'", "getWeather location='Seoul'"],
], ids=["lone tool step", "memory directive then tool step"])
def test_single_step_tool_plan_is_still_enforced(mock_config, db, dialogue_memory, plan):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=plan,
chat_replies=[_content(FABRICATED), _content(GROUNDED)],
allowed=["getWeather", "stop"],
)
assert invoked == [("getWeather", {"location": "Seoul"})]
assert reply == GROUNDED
def test_planned_call_with_arguments_the_tool_does_not_take_is_not_forced(mock_config, db, dialogue_memory):
# A weak planner mapped "set a timer" onto setBroadcast with a made-up
# argument. The guard must not trigger that tool; the model's answer stands
# and no second chat call is spent.
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=["setBroadcast duration='5 minutes'"],
chat_replies=[_content("I have no timer, so I cannot set one.")],
allowed=["setBroadcast", "stop"],
)
assert invoked == []
assert reply == "I have no timer, so I cannot set one."
assert len(seen) == 1
def test_prose_shaped_step_is_not_reinterpreted_into_some_other_call(mock_config, db, dialogue_memory):
# "setBroadcast duration=5 minutes" is not a call setBroadcast takes. The
# guard must not ask an LLM to repair it (that turned a timer request into
# starting the broadcast); the model's answer stands.
from jarvis.reply import engine as engine_mod
with patch.object(engine_mod, "_resolve_plan_step", return_value=("setBroadcast", {"action": "start"})):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=["setBroadcast duration=5 minutes"],
chat_replies=[_content("I have no timer, so I cannot set one.")],
allowed=["setBroadcast", "stop"],
)
assert invoked == []
assert reply == "I have no timer, so I cannot set one."
def test_system_message_ends_with_the_tool_reminder_for_this_turns_tools(mock_config, db, dialogue_memory):
reply, invoked, seen = _run(
mock_config, db, dialogue_memory, plan=["Reply to the user."],
chat_replies=[_content("Good evening.")],
allowed=["getWeather", "stop"],
)
system = seen[0][0]["content"]
reminder = system[system.rindex("Before you answer:"):]
listed = reminder.split("Your tools this turn:")[1].split(".")[0]
assert "getWeather" in listed
assert "stop" not in listed.split(", ")
# Nothing but the reply-language lock (if any) may follow it.
from jarvis.system_prompt import ENGLISH_ONLY_DIRECTIVE
tail = reminder.split("\n", 1)[1].strip() if "\n" in reminder else ""
assert tail in ("", ENGLISH_ONLY_DIRECTIVE) or tail.startswith("CRITICAL OUTPUT RULE")

View File

@@ -244,3 +244,65 @@ def test_virtual_display_names_are_read_from_utf16_buffers():
text = "Parsec Virtual Display Adapter".encode("utf-16-le")
winvdd.ctypes.memmove(winvdd.ctypes.addressof(dd) + winvdd.DISPLAY_DEVICEW.DeviceString.offset, text, len(text))
assert winvdd.wstr(dd.DeviceString) == "Parsec Virtual Display Adapter"
# ---------------------------------------------------------------------------
# Tool-calling re-check with the Jarvis fix (m0lib/tool_fix.py)
class _ScriptedClient:
"""Answers chat calls from a script; records what was sent."""
model = "scripted"
def __init__(self, answers):
self.answers = list(answers)
self.sent = []
def chat(self, messages, **kwargs):
self.sent.append((messages, kwargs))
text, calls = self.answers.pop(0)
return {"text": text, "tool_calls": calls, "first_tool": None, "ttft": 0.1, "finish": "stop"}
def test_kit_uses_the_production_prompt_rules_and_planner():
from jarvis import system_prompt
from m0lib import tool_fix
sp, planner = tool_fix.load_jarvis(tool_fix.jarvis_src(), _ScriptedClient([]))
assert sp.TOOL_HONESTY_RULES == system_prompt.TOOL_HONESTY_RULES
assert sp.tool_honesty_reminder(["get_weather"]) == system_prompt.tool_honesty_reminder(["get_weather"])
assert planner.__file__.endswith("planner.py") and hasattr(planner, "plan_query")
# The real jarvis package stays importable next to the kit's private copy.
import jarvis.reply.planner as real_planner
assert real_planner.named_tool_steps is not planner.named_tool_steps
def test_skipped_tool_is_run_from_the_plan_and_the_answer_uses_its_result():
from m0lib import tool_fix
prompt, want, check, result = tool_fix.FIX_CASES[0] # 서울 날씨
client = _ScriptedClient([
("get_weather city='서울'\nReply to the user with the weather.", []), # planner
("서울은 24도, 맑음입니다.", []), # model skips the tool
("서울은 13도이고 비가 옵니다.", []), # answer from the result
])
_, planner = tool_fix.load_jarvis(tool_fix.jarvis_src(), client)
row = tool_fix.run_case(client, "system", planner, prompt, want, check, result)
assert row["model_ok"] is False and row["guard_ran"] is True and row["ok"] is True
assert row["final_uses_result"] is True
final_messages = client.sent[-1][0]
assert final_messages[-1]["role"] == "tool" and "13" in final_messages[-1]["content"]
def test_model_that_calls_the_tool_is_scored_without_the_guard():
from m0lib import tool_fix
prompt, want, check, result = tool_fix.FIX_CASES[3] # 5분 타이머
client = _ScriptedClient([
("set_timer minutes='5'", []),
("", [{"name": "set_timer", "arguments": "{\"minutes\": 5}"}]),
("5분 타이머를 맞췄습니다.", []),
])
_, planner = tool_fix.load_jarvis(tool_fix.jarvis_src(), client)
row = tool_fix.run_case(client, "system", planner, prompt, want, check, result)
assert row["model_ok"] is True and row["guard_ran"] is False and row["ok"] is True
assert row["text_with_call"] is False

View File

@@ -788,3 +788,49 @@ class TestPlanHasUnresolvedToolSteps:
assert plan_has_unresolved_tool_steps(
plan, ["chrome-devtools__navigate_page"]
) is False
class TestNamedToolSteps:
"""named_tool_steps picks plan steps that start with a callable tool name,
whatever their position in the plan."""
def test_lone_tool_step_and_memory_prefixed_step_are_found(self):
from jarvis.reply.planner import named_tool_steps
assert named_tool_steps(["logMeal meal='banana'"], ["logMeal"]) == ["logMeal meal='banana'"]
assert named_tool_steps(
["searchMemory topic='home'", "getWeather", "Reply to the user."], ["getWeather"]
) == ["getWeather"]
def test_prose_and_unknown_names_are_not_tool_steps(self):
from jarvis.reply.planner import named_tool_steps
assert named_tool_steps(["Reply to the user."], ["getWeather"]) == []
assert named_tool_steps(["controlTimer duration=5", "Reply to the user."], ["getWeather"]) == []
class TestParseConcreteToolStep:
SCHEMA = [{"type": "function", "function": {"name": "logMeal", "parameters": {
"type": "object", "properties": {"meal": {"type": "string"}}}}}]
def test_concrete_step_parses(self):
from jarvis.reply.planner import parse_concrete_tool_step
assert parse_concrete_tool_step("logMeal meal='banana'", self.SCHEMA) == ("logMeal", {"meal": "banana"})
assert parse_concrete_tool_step("logMeal", self.SCHEMA) == ("logMeal", {})
def test_unknown_keys_prose_and_placeholders_do_not_parse(self):
from jarvis.reply.planner import parse_concrete_tool_step
assert parse_concrete_tool_step("logMeal food='banana'", self.SCHEMA) is None
assert parse_concrete_tool_step("logMeal the banana I ate", self.SCHEMA) is None
assert parse_concrete_tool_step("logMeal meal='<meal from step 1>'", self.SCHEMA) is None
assert parse_concrete_tool_step("getWeather", self.SCHEMA) is None
class TestPlannerToolCatalog:
def test_descriptions_carry_the_argument_names(self):
from jarvis.reply.planner import planner_tool_catalog
schema = [
{"type": "function", "function": {"name": "getWeather", "description": "Weather only.\nMore.",
"parameters": {"type": "object", "properties": {"location": {"type": "string"}}}}},
{"type": "function", "function": {"name": "stop", "description": "End.",
"parameters": {"type": "object", "properties": {}}}},
]
assert planner_tool_catalog(schema) == [("getWeather", "Weather only. (args: location)"), ("stop", "End.")]

View File

@@ -197,3 +197,24 @@ class TestLoadAgentInstructions:
f.write_text("x", encoding="utf-8")
# Pointed at a file, not a directory → fail-open.
assert load_agent_instructions(str(f)) == ""
class TestToolHonestyRules:
"""The persona carries the tool honesty rules (live facts and actions only
from tool results) for every name and language lock."""
def test_rules_are_in_every_rendered_prompt(self):
from jarvis.system_prompt import TOOL_HONESTY_RULES
for prompt in (build_system_prompt("Jarvis"), build_system_prompt("Friday", "Korean")):
assert TOOL_HONESTY_RULES in prompt
def test_reminder_names_the_turns_tools_but_not_the_sentinels(self):
from jarvis.system_prompt import tool_honesty_reminder
text = tool_honesty_reminder(["getWeather", "logMeal", "stop", "toolSearchTool"])
assert "getWeather, logMeal." in text
assert "stop" not in text.split("this turn:")[1].split(".")[0]
assert "toolSearchTool" not in text
def test_reminder_without_tools_says_none(self):
from jarvis.system_prompt import tool_honesty_reminder
assert "Your tools this turn: none." in tool_honesty_reminder(["stop"])