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

@@ -13,6 +13,7 @@ from ..system_prompt import (
build_system_prompt,
load_agent_instructions,
reply_language_directive,
tool_honesty_reminder,
)
from ..tools.registry import run_tool_with_retries, generate_tools_description, generate_tools_json_schema, BUILTIN_TOOLS
from ..tools.builtin.stop import STOP_SIGNAL
@@ -33,6 +34,9 @@ from .planner import (
progress_nudge,
tool_steps_of,
tool_names_in_plan,
named_tool_steps,
parse_concrete_tool_step,
planner_tool_catalog,
plan_has_unresolved_tool_steps,
plan_requires_memory,
strip_memory_directives,
@@ -1241,15 +1245,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
debug_log("screen-share: site named — dropping webSearch so controlBrowser wins", "tools")
_planner_schema = generate_tools_json_schema(routed_tools, mcp_tools)
_planner_tool_catalog: list[tuple[str, str]] = []
for _schema in (_planner_schema or []):
_fn = _schema.get("function", {}) if isinstance(_schema, dict) else {}
if isinstance(_fn, dict):
_nm = _fn.get("name")
_desc = (_fn.get("description") or "").strip().splitlines()
_first = _desc[0] if _desc else ""
if _nm:
_planner_tool_catalog.append((str(_nm), _first[:120]))
_planner_tool_catalog = planner_tool_catalog(_planner_schema or [])
action_plan: list[str] = []
try:
@@ -1824,6 +1820,11 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
if _agent_instructions:
guidance.append("Additional instructions from the operator:\n" + _agent_instructions)
# Recency reinforcement for the tool honesty rules (see
# tool_honesty_reminder): placed after every context block so it is
# the last instruction before the language lock.
guidance.append(tool_honesty_reminder(list(allowed_tools)))
# Recency reinforcement: repeat the language lock at the very END too.
# In a ~5k-token prompt the front-placed rule gets "lost in the middle";
# bigger models (qwen2.5:7b) otherwise leak Chinese/Cyrillic mid-reply.
@@ -2048,6 +2049,15 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
# to the steps of the current plan.
_plan_steps_baseline = sum(1 for m in messages if m.get("tool_name"))
# Skipped-tool guard (native tool calling). Capable models sometimes answer
# without calling a tool the planner already chose: a made-up "24 degrees
# and sunny" instead of the weather tool (M0, 2026-11-10). When that happens
# the engine drops the answer and direct-executes the plan steps that name
# a callable tool (the same path small models use), then lets the model
# synthesise from the real result. Fires at most once per reply; a
# non-empty list means it fired. See planner.spec.md.
_forced_plan_steps: list[str] = []
while turn < max_turns:
turn += 1
debug_log(f"🔁 messages loop turn {turn}", "planning")
@@ -2065,12 +2075,12 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
# all plan tool steps are exhausted, at which point it synthesises
# a final reply from the accumulated results.
# See planner.spec.md.
if (
if _forced_plan_steps or (
use_text_tools
and len(action_plan) > 1
and not _plan_under_specified
):
_plan_tool_steps = tool_steps_of(action_plan)
_plan_tool_steps = _forced_plan_steps or tool_steps_of(action_plan)
_tool_results_so_far = (
sum(1 for m in messages if m.get("tool_name"))
- _plan_steps_baseline
@@ -2079,12 +2089,18 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
_plan_exec_handled = False
try:
_prior = list(invoked_tools_history)
_resolved = _resolve_plan_step(
cfg=cfg,
next_step_text=_plan_tool_steps[_tool_results_so_far],
prior_results=_prior,
tools_schema=tools_json_schema or [],
)
if _forced_plan_steps:
_resolved = parse_concrete_tool_step(
_plan_tool_steps[_tool_results_so_far],
tools_json_schema or [],
)
else:
_resolved = _resolve_plan_step(
cfg=cfg,
next_step_text=_plan_tool_steps[_tool_results_so_far],
prior_results=_prior,
tools_schema=tools_json_schema or [],
)
if _resolved is not None:
_name, _args = _resolved
try:
@@ -2107,6 +2123,20 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
and _name != "toolSearchTool"
and _cand_sig not in recent_tool_signatures
)
# The skipped-tool guard overrides the model's own
# choice, so it only runs a call whose arguments fit
# the tool: a planner that mapped "timer" onto an
# unrelated tool must not trigger that tool.
_plan_args_err = (
_validate_tool_args_against_schema(_name, _args, mcp_tools)
if _forced_plan_steps and _plan_exec_ok else None
)
if _plan_args_err:
debug_log(
f"skipped-tool guard: {_name} args rejected ({_plan_args_err})",
"planning",
)
_plan_exec_ok = False
if _plan_exec_ok:
debug_log(
f"planner: direct-executing plan step "
@@ -2179,22 +2209,33 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
)
_plan_text = f"Error: {_plan_err}"
_plan_tool_results_after = _tool_results_so_far + 1
if action_plan:
if action_plan and use_text_tools:
_plan_hint = progress_nudge(
action_plan,
_plan_tool_results_after,
)
else:
_plan_hint = ""
messages.append({
"role": "user",
"content": (
f"[Tool result: {_name}]\n"
f"{_plan_text}{_plan_hint}"
),
"tool_name": _name,
"tool_failed": not _plan_result.success,
})
if use_text_tools:
messages.append({
"role": "user",
"content": (
f"[Tool result: {_name}]\n"
f"{_plan_text}{_plan_hint}"
),
"tool_name": _name,
"tool_failed": not _plan_result.success,
})
else:
# Native protocol: answer the assistant
# tool_calls message with a role=tool result.
messages.append({
"role": "tool",
"tool_call_id": _plan_call_id,
"tool_name": _name,
"content": f"{_plan_text}{_plan_hint}",
"tool_failed": not _plan_result.success,
})
recent_tool_signatures.append(_cand_sig)
if len(recent_tool_signatures) > 5:
recent_tool_signatures = (
@@ -2218,6 +2259,16 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
)
if _plan_exec_handled:
continue
if _forced_plan_steps and _tool_results_so_far == 0:
# The guard could not run the planned tool after all
# (unresolvable step or arguments that do not fit). Fail
# open: deliver the answer it held back rather than ask
# the model again on the same messages.
debug_log("skipped-tool guard: planned tool not runnable, keeping the model answer", "planning")
messages.append(_guard_held_message)
reply = _guard_held_reply
last_candidate_reply = _guard_held_reply
break
# Update the system message with fresh context (time/location) before each LLM call
# Note: We update the first system message rather than appending a new one because
@@ -2693,6 +2744,30 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
candidate_reply = content
malformed_fallback = False
_guard_steps = [] if (use_text_tools or _forced_plan_steps or malformed_fallback) else (
named_tool_steps(
action_plan,
[n for n in allowed_tools if n not in ("stop", "toolSearchTool")],
)
)
if (
_guard_steps
and sum(1 for m in messages if m.get("tool_name")) == _plan_steps_baseline
):
# The model answered without calling the tool the plan chose, so
# the answer can only be a guess. Drop it (the synthesis turn must
# not anchor on it) and run the planned steps directly.
_guard_held_message = messages.pop()
_guard_held_reply = candidate_reply
_forced_plan_steps = _guard_steps
debug_log(
f"skipped-tool guard: model answered without the planned tool; "
f"direct-executing {len(_guard_steps)} plan step(s)",
"planning",
)
print(" 🧭 Planned tool skipped by the model, running it directly", flush=True)
continue
reply = candidate_reply
last_candidate_reply = candidate_reply
break

View File

@@ -229,6 +229,30 @@ _PROMPT_TEMPLATE = (
)
def planner_tool_catalog(tools_schema: Sequence[dict]) -> List[Tuple[str, str]]:
"""(name, one-line description) pairs for the planner's AVAILABLE TOOLS.
Each description ends with the tool's argument names, e.g.
``(args: location)``. Without them the planner guessed keys
(``get_weather location=...`` for a ``city`` tool, ``set_timer
duration=5minutes`` for ``minutes``), and a step with a guessed key
cannot be run as written by the skipped-tool guard.
"""
out: List[Tuple[str, str]] = []
for entry in tools_schema or []:
fn = entry.get("function", {}) if isinstance(entry, dict) else {}
if not isinstance(fn, dict) or not fn.get("name"):
continue
desc = (fn.get("description") or "").strip().splitlines()
line = desc[0][:120] if desc else ""
params = fn.get("parameters") or {}
props = params.get("properties") if isinstance(params, dict) else None
if isinstance(props, dict) and props:
line = f"{line} (args: {', '.join(props)})"
out.append((str(fn["name"]), line))
return out
def _build_user_message(
query: str,
dialogue_context: str,
@@ -371,6 +395,29 @@ def tool_names_in_plan(
return out
def named_tool_steps(
plan: Sequence[str], callable_names: Sequence[str],
) -> List[str]:
"""Plan steps that start with the name of a tool the model may call.
Unlike ``tool_steps_of`` this does not rely on step position: a planner
that emits a lone ``logMeal meal='banana'`` (no synthesis step) or
``searchMemory ...`` followed by a single ``getWeather`` still names a
tool to run. A step's head token is matched exactly against
``callable_names``, so synthesis prose ("Reply to the user.") and
hallucinated tool names never match. Used by the engine's skipped-tool
guard, which runs these steps when a native-tool model answers without
calling any tool.
"""
known = set(callable_names)
out: List[str] = []
for step in strip_memory_directives(plan):
m = _TOOL_NAME_HEAD_RE.match(step)
if m and m.group(1) in known:
out.append(step)
return out
def plan_has_unresolved_tool_steps(
plan: Sequence[str], known_names: Sequence[str],
) -> bool:
@@ -625,6 +672,30 @@ def _parse_plan_step_concrete(
return name, _normalise_url_args(args)
def parse_concrete_tool_step(
step_text: str, tools_schema: Sequence[dict],
) -> Optional[Tuple[str, dict]]:
"""Parse a fully concrete plan step against a tools schema, never via an LLM.
The skipped-tool guard overrides the chat model's own decision not to
call a tool, so it only runs what the planner literally wrote: a known
tool name with ``key='value'`` arguments the tool declares (or no
arguments). An LLM resolver could "repair" a wrong step into a valid but
unwanted call (a timer request remapped to starting the broadcast), so
prose-shaped or placeholder steps return ``None`` here.
"""
allowed_props: dict = {}
for entry in tools_schema or []:
fn = entry.get("function", {}) if isinstance(entry, dict) else {}
name = fn.get("name") if isinstance(fn, dict) else None
if not name:
continue
params = fn.get("parameters") or {}
props = params.get("properties") if isinstance(params, dict) else None
allowed_props[str(name)] = set(props.keys()) if isinstance(props, dict) else set()
return _parse_plan_step_concrete(step_text or "", list(allowed_props), allowed_props)
def resolve_next_tool_call(
cfg,
next_step_text: str,

View File

@@ -69,6 +69,12 @@ one turn's allow-list.
### Prompt contract (plan_query)
The planner's AVAILABLE TOOLS lines come from `planner_tool_catalog(schema)`:
the tool's first description line plus its argument names, e.g.
`getWeather: Weather only ... (args: location)`. Without the argument names
the planner guessed keys (`location=` for a `city` tool, `duration=5minutes`
for `minutes`), which made concrete steps unparseable.
The planner prompt instructs the model to emit:
- Short imperative sub-tasks, one per line.
@@ -157,6 +163,34 @@ The engine consumes the plan in two phases.
- The chat model still runs the final synthesis turn so the reply is
phrased in the daemon's voice using its own profile and persona.
**Skipped-tool guard (native tool calling, all model sizes):**
- Problem: capable native-tool models sometimes answer without calling a
tool they were given (M0 on Strata, 2026-11-10: a made-up "24 degrees and
sunny" instead of the weather tool, "timer set" without the timer tool;
the same on qwen2.5:7b through the engine).
- When a native-tool model's turn is natural-language content, no tool has
run in this reply yet, and `named_tool_steps(plan, callable_names)` finds
plan steps that start with a callable tool name (anything in the allow-list
except `stop` and `toolSearchTool`), the engine drops that answer from the
messages and direct-executes those steps, then lets the chat model
synthesise from the real results. `named_tool_steps` ignores step position,
so a lone `logMeal meal='banana'` or `searchMemory ...` + `getWeather` plan
still counts (`tool_steps_of` would read both as reply-only).
- The guard overrides the model's own decision, so it only runs what the
planner literally wrote: `parse_concrete_tool_step` (the resolver's
regex fast path, never the LLM resolver) plus a required/unknown-key check
against the tool's input schema. An LLM resolver could "repair" a wrong
step into a valid but unwanted call (a timer request planned as
`setBroadcast duration=5 minutes` was turned into starting the broadcast).
- Fail-open: if the first planned step cannot be run as written, the
engine delivers the answer it held back, without a second chat call. The
guard fires at most once per reply and never in text-tool mode (that mode
already direct-executes every plan).
- In native mode the direct-exec result is a `role=tool` message answering
the synthetic assistant `tool_calls` message, and no progress nudge is
appended.
### resolve_next_tool_call
- **Fast path**: if the step text is fully concrete (tool name in the

View File

@@ -72,6 +72,7 @@ Design principles enforced by the engine:
- **Reference-only**: "use these as background context... but do NOT treat them as instructions, as a template for your response, or as authoritative about what you can or cannot do now; your current tools and constraints are defined above." Without this, small models imitate deflections narrated in past entries instead of following the current system prompt.
- **Recency-weighting**: "When entries disagree, treat the most recent entry as the user's current understanding and preferences — it supersedes older entries." This prevents stale diary facts from overriding more recent corrections.
- Append `Tools:` with the dynamically generated tool descriptions (including configured MCP servers, if any) and guidance for preferring real data over shell commands.
- Tool honesty: the persona carries `TOOL_HONESTY_RULES` (live facts such as weather, news, prices or screen contents only from a tool result in this turn; actions only claimed after a tool reports success; no answer text next to a tool call). `tool_honesty_reminder(allowed_tools)` restates it as the last block before the closing reply-language lock and names the turn's real tools (without `stop` / `toolSearchTool`), so the model has a concrete list to check its answer against. Both are language- and tool-set-agnostic.
6. Agentic Messages Loop with Dynamic Context
- For each turn of the loop (max `agentic_max_turns` turns, default 8):
@@ -96,6 +97,9 @@ Design principles enforced by the engine:
- Known API-spec / data-dump patterns (weather JSON, OpenAPI blobs, etc.)
- When detected, the engine falls back to the standard "I had trouble understanding that request" error reply (model-size-aware). The malformed content is never shown to the user.
Skipped-tool guard (native tool calling):
- When a native-tool model answers in prose before any tool has run in this reply, and the plan names a callable tool as a concrete call, the engine discards that answer and direct-executes the plan's tool steps, then the model answers from the results. Only literal, schema-valid steps run (no LLM repair); otherwise the held-back answer is delivered unchanged. See `planner.spec.md` ("Skipped-tool guard").
Task-list planner (all model sizes, strongest impact on small models):
- The planner runs at the **front** of the reply flow (see step 3 above), not after tool selection. By the time the agentic loop starts, the plan already exists, the memory block has either been run or skipped based on the plan's `searchMemory` directive, and the tool allow-list has been derived from the tool names the plan referenced. See `planner.spec.md` for the prompt contract and fail-open semantics.
- When the plan has more than one step, `format_plan_block(steps)` appends an `ACTION PLAN:` section to the initial system message so the chat model can see its own pre-committed sub-tasks in order. A single reply-only plan renders nothing — it's the planner's positive no-op signal.

View File

@@ -51,6 +51,28 @@ def load_agent_instructions(agents_dir: Optional[str] = None) -> str:
return ""
# Tool honesty rules. Field and M0 measurements (2026-11-10, Strata) showed
# capable models skipping an available tool and answering anyway: a made-up
# "24 degrees and sunny" instead of calling the weather tool, and "timer set"
# without calling the timer tool. The rules name both failure shapes (live
# facts and actions) instead of listing tools, so they hold for any tool set
# and any reply language. Kept as one constant so the M0 kit can measure the
# exact production wording (see tests/test_m0_kit.py).
TOOL_HONESTY_RULES: str = (
"Tool rules (hard): facts that change over time — weather, temperature, rain, news, prices, "
"scores, traffic, opening hours, what is on the user's screen — must come from a tool result "
"in this turn. Never state such a value from memory, never estimate it, never make it up. "
"If one of your tools can fetch it, call that tool first; if none can, say you cannot check "
"it right now. When the user asks you to do something — set a timer or reminder, open a "
"website, navigate the browser, play or show something on screen, change a setting, send a "
"message — and one of your tools can do it, call that tool; saying it is done is never a "
"substitute for calling the tool. Only say an action happened after a tool result in this "
"turn reports success. If no tool can do it, or the tool failed, say so plainly; never "
"narrate a success that did not happen. A message that calls a tool contains only the tool "
"call: write no answer or confirmation next to it, and answer after you see the result."
)
_SYSTEM_PROMPT_TEMPLATE: str = (
"Persona: you are a British butler named {name} — polite, composed, quietly amused, and "
"quietly enjoying yourself. Default voice is dry, witty, and lightly sarcastic: you notice "
@@ -86,10 +108,7 @@ _SYSTEM_PROMPT_TEMPLATE: str = (
"should happen in the on-screen browser — opening a site, searching on a site "
"(controlBrowser action 'search' with the right site), clicking, typing — because only "
"controlBrowser is visible on the broadcast; webSearch shows nothing on screen. "
"Never claim you performed an action — opening a website, navigating the browser, "
"playing or showing something on screen, changing a setting, sending a message — unless a "
"tool actually did it this turn and reported success. If you have no tool for what was asked, "
"or the tool failed, say so plainly; do not narrate a success that did not happen. "
"{tool_rules} "
"Never answer with a bare greeting like 'Hey there!', 'Hi!', 'Hello, how can I help you?', "
"'I hope you have a relaxing time today', or 'I'm here and ready to chat'. Always engage "
"with the user's actual prompt, and when the 'Information the user has shared…' section is "
@@ -138,6 +157,28 @@ _SYSTEM_PROMPT_TEMPLATE: str = (
)
def tool_honesty_reminder(tool_names) -> str:
"""End-of-prompt restatement of the tool honesty rules for this turn.
The rules also sit in the persona, but in a long system prompt a rule in
the middle loses to the model's habit of answering straight away (the
same "lost in the middle" effect the reply-language lock is repeated
for). Naming the turn's real tools gives the model a concrete list to
check its answer against, which works for any tool set and language.
The engine's sentinels (``stop``, ``toolSearchTool``) are not listed:
neither fetches a fact nor performs an action.
"""
names = [n for n in (tool_names or []) if n not in ("stop", "toolSearchTool")]
listed = ", ".join(names) if names else "none"
return (
"Before you answer: any live fact in your reply, and any action you say you did, "
f"must come from a tool call in this turn. Your tools this turn: {listed}. If one of "
"them can fetch the fact or do the action, call it now instead of answering. If none "
"of them can, say plainly that you cannot check or do that; never say something was "
"done unless a tool result in this turn says so."
)
def build_system_prompt(
assistant_name: str = "Jarvis", output_language: Optional[str] = None
) -> str:
@@ -153,7 +194,7 @@ def build_system_prompt(
query language and leaks the other language back in.
"""
name = (assistant_name or "Jarvis").strip() or "Jarvis"
prompt = _SYSTEM_PROMPT_TEMPLATE.format(name=name)
prompt = _SYSTEM_PROMPT_TEMPLATE.format(name=name, tool_rules=TOOL_HONESTY_RULES)
lang = (output_language or "").strip()
if lang:
prompt = prompt.replace("in the user's language", f"in {lang}")