DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): reject tool calls whose required arguments never arrived (#779)
Bingxi Zhao (Frank)b28a1a7b0106
diff --git a/deeptutor/core/agentic/tool_arg_guard.py b/deeptutor/core/agentic/tool_arg_guard.pynew file mode 100644index 000000000..80311c17b--- /dev/null+++ b/deeptutor/core/agentic/tool_arg_guard.py@@ -0,0 +1,139 @@+"""Pre-dispatch validation of model-authored tool arguments.++Under a large tool surface and a long history, models intermittently emit a+native function call whose ``arguments`` is empty (or partial) even though+the schema marks fields required — reproduced on several OpenAI-compatible+providers (issue #779).++Before this guard those calls were dispatched as-is, so the *tool* was left+to reject them: ``exec`` raised ``ValueError: exec requires a non-empty+command`` and ``write_note`` answered ``Unknown mode ''``. Neither reads as+"you forgot an argument", so the model re-emitted the same malformed call+until the loop budget ran out — one report saw 5 of 7 ``write_note`` calls+in a single turn arrive empty and retried 5–7 times.++The guard converts that into one self-correcting round: the call is never+dispatched, and the ``role=tool`` body names exactly which required+arguments were missing and what shape they take, which is what the next+iteration needs to re-emit a well-formed call.++Deliberately free of dispatcher, registry, and stream concerns: it maps a+:class:`~deeptutor.core.tool_protocol.ToolDefinition` plus the prepared+kwargs to a list of missing arguments and a corrective message, so any call+site that dispatches model-authored tool calls can reuse it and the rules+stay unit-testable on their own.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from deeptutor.core.tool_protocol import ToolDefinition+++@dataclass(frozen=True)+class RequiredArg:+ """A required parameter, reduced to what the corrective message needs."""++ name: str+ type: str = ""+ enum: tuple[str, ...] = ()++ def describe(self) -> str:+ parts = [self.type or "value"]+ if self.enum:+ parts.append("one of: " + " | ".join(self.enum))+ return f"{self.name} ({', '.join(parts)})"+++def _is_supplied(value: Any) -> bool:+ """Whether a kwarg counts as actually provided.++ ``None`` and a blank string are treated as absent because that is how a+ provider serialises "the model left this out" in practice. Empty+ collections are left alone: ``[]`` / ``{}`` can be a deliberate value+ for an array or object parameter, and rejecting them would refuse calls+ that used to work.+ """+ if value is None:+ return False+ if isinstance(value, str) and not value.strip():+ return False+ return True+++def required_args(definition: ToolDefinition) -> list[RequiredArg]:+ """Required parameters of a tool, excluding any that carry a default.++ A parameter with a default is satisfiable without the model naming it,+ so treating it as required would reject calls the tool can serve.++ Handles both schema flavours: ``raw_parameters`` (verbatim JSON Schema,+ used by MCP adapters) and the :class:`ToolParameter` rows built-ins+ declare.+ """+ raw = definition.raw_parameters+ if raw is not None:+ names = raw.get("required")+ if not isinstance(names, list):+ return []+ properties = raw.get("properties")+ properties = properties if isinstance(properties, dict) else {}+ args: list[RequiredArg] = []+ for name in names:+ if not isinstance(name, str) or not name:+ continue+ prop = properties.get(name)+ prop = prop if isinstance(prop, dict) else {}+ if "default" in prop:+ continue+ enum = prop.get("enum")+ args.append(+ RequiredArg(+ name=name,+ type=str(prop.get("type") or ""),+ enum=tuple(str(v) for v in enum) if isinstance(enum, list) else (),+ )+ )+ return args++ return [+ RequiredArg(+ name=p.name,+ type=p.type,+ enum=tuple(str(v) for v in p.enum) if p.enum else (),+ )+ for p in definition.parameters+ if p.required and p.default is None+ ]+++def missing_required_args(+ definition: ToolDefinition,+ args: dict[str, Any],+) -> list[RequiredArg]:+ """Required parameters the call failed to supply.++ ``args`` must be the *prepared* kwargs — i.e. after server-side+ augmentation — so an argument the pipeline injects on the model's behalf+ counts as supplied.+ """+ return [arg for arg in required_args(definition) if not _is_supplied(args.get(arg.name))]+++def missing_args_message(tool_name: str, missing: list[RequiredArg]) -> str:+ """Corrective ``role=tool`` body for a call that was never dispatched.++ Names the missing arguments and their accepted shape, and says plainly+ that repeating the same call will fail again — the model's failure mode+ here is retrying verbatim, not misreading the schema.+ """+ named = ", ".join(f"`{arg.name}`" for arg in missing)+ shapes = "; ".join(arg.describe() for arg in missing)+ return (+ f"(tool call not dispatched — `{tool_name}` was called without its required "+ f"argument(s): {named}. Expected: {shapes}. Re-emit the call with those "+ "arguments filled in; an identical call with empty arguments will be "+ "rejected again without running.)"+ )diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.pyindex 40a6a599a..c9acf2a86 100644--- a/deeptutor/core/agentic/tool_dispatch.py+++ b/deeptutor/core/agentic/tool_dispatch.py@@ -26,6 +26,10 @@ import jsonimport loggingfrom typing import Any+from deeptutor.core.agentic.tool_arg_guard import (+ missing_args_message,+ missing_required_args,+)from deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBusfrom deeptutor.core.tool_protocol import ToolLookup, provider_identity@@ -156,6 +160,17 @@ async def dispatch_tool_calls(tool_name=prepared[tool_index][1],)_tcid, tool_name, exec_args = prepared[tool_index]+ rejection = await _reject_if_args_missing(+ registry=registry,+ tool_name=tool_name,+ exec_args=exec_args,+ stream=stream,+ source=source,+ stage=stage,+ trace_meta=per_tool_trace_meta[tool_index],+ )+ if rejection is not None:+ return rejectionreturn await execute_tool_call(registry=registry,tool_name=tool_name,@@ -261,6 +276,73 @@ def _duplicate_stub_result(}+async def _reject_if_args_missing(+ *,+ registry: ToolLookup,+ tool_name: str,+ exec_args: dict[str, Any],+ stream: StreamBus,+ source: str,+ stage: str,+ trace_meta: dict[str, Any] | None,+) -> dict[str, Any] | None:+ """Short-circuit a call whose required arguments never arrived.++ Returns ``None`` when the call is well-formed (dispatch proceeds), or a+ synthetic failed result whose text tells the model which arguments to+ fill in. See :mod:`deeptutor.core.agentic.tool_arg_guard` for why the+ tool itself is the wrong place to catch this.++ Unknown tool names and definitions that fail to build are passed+ through untouched: the registry owns those errors and reports them with+ the context this layer lacks.+ """+ try:+ tool = registry.get(tool_name)+ definition = tool.get_definition() if tool is not None else None+ except Exception: # pragma: no cover - defensive: never block dispatch+ logger.debug("Arg guard skipped for %s (definition unavailable)", tool_name, exc_info=True)+ return None+ if definition is None:+ return None++ missing = missing_required_args(definition, exec_args)+ if not missing:+ return None++ message = missing_args_message(tool_name, missing)+ logger.warning(+ "Rejected %s before dispatch: missing required args %s",+ tool_name,+ [arg.name for arg in missing],+ )+ if trace_meta is not None:+ # Close the sub-trace with a terminal state, as the raising path in+ # ``execute_tool_call`` does — a rejected call must not leave a row+ # that reads as still running. ``progress`` (not ``error``): this is+ # a recoverable per-call correction, and a stream ERROR makes a+ # partner turn re-run the whole turn on its backup model.+ await stream.progress(+ f"{tool_name} not dispatched: missing {', '.join(arg.name for arg in missing)}",+ source=source,+ stage=stage,+ metadata=derive_trace_metadata(+ trace_meta,+ trace_kind="call_status",+ call_state="error",+ error=message,+ ),+ )+ return {+ "result_text": message,+ "success": False,+ "sources": [],+ "metadata": {"error": "missing_required_arguments"},+ "terminate_turn": False,+ "pause_for_user": None,+ }++def _prepare_tool_args(tool_calls: list[dict[str, Any]],context: UnifiedContext,diff --git a/tests/core/agentic/test_tool_arg_guard.py b/tests/core/agentic/test_tool_arg_guard.pynew file mode 100644index 000000000..ea4852f27--- /dev/null+++ b/tests/core/agentic/test_tool_arg_guard.py@@ -0,0 +1,260 @@+"""Required-argument guard in front of tool dispatch (issue #779).++Under a large tool surface and long history, providers intermittently emit a+function call whose ``arguments`` is ``{}`` even though the schema marks+fields required. The tool used to be the one to reject it — ``exec`` raised+``exec requires a non-empty command``, ``write_note`` answered ``Unknown mode+''`` — neither of which reads as "an argument is missing", so the model+re-emitted the same empty call until the loop budget ran out.++Two things are pinned here: the guard's rules (what counts as missing, and+what must NOT be treated as missing so working calls keep working), and that+dispatch short-circuits without touching the tool.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from deeptutor.core.agentic.tool_arg_guard import (+ missing_args_message,+ missing_required_args,+ required_args,+)+from deeptutor.core.agentic.tool_dispatch import dispatch_tool_calls+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.tool_protocol import (+ BaseTool,+ ToolDefinition,+ ToolParameter,+ ToolResult,+)+++def _write_note_definition() -> ToolDefinition:+ """``write_note``'s shape, reduced to what the guard reads."""+ return ToolDefinition(+ name="write_note",+ description="Save or edit a notebook record.",+ parameters=[+ ToolParameter(name="mode", type="string", enum=["append", "edit"]),+ ToolParameter(name="notebook_id", type="string"),+ ToolParameter(name="title", type="string", required=False),+ ],+ )+++def test_empty_arguments_report_every_required_param() -> None:+ missing = missing_required_args(_write_note_definition(), {})+ assert [arg.name for arg in missing] == ["mode", "notebook_id"]+++def test_optional_params_are_never_reported() -> None:+ definition = _write_note_definition()+ missing = missing_required_args(definition, {"mode": "append", "notebook_id": "nb1"})+ assert missing == []+++def test_required_param_with_a_default_is_satisfiable_without_the_model() -> None:+ """A default means the tool can serve the call, so rejecting it would+ refuse work that used to succeed."""+ definition = ToolDefinition(+ name="t",+ description="",+ parameters=[ToolParameter(name="limit", type="integer", default=10)],+ )+ assert required_args(definition) == []+ assert missing_required_args(definition, {}) == []+++def test_blank_string_counts_as_missing() -> None:+ """How providers serialise "the model left this out" in practice —+ ``exec``'s empty ``command`` arrived this way."""+ definition = ToolDefinition(+ name="exec",+ description="",+ parameters=[ToolParameter(name="command", type="string")],+ )+ assert [arg.name for arg in missing_required_args(definition, {"command": " "})] == [+ "command"+ ]+++def test_empty_collections_are_left_alone() -> None:+ """``[]`` / ``{}`` can be a deliberate value for an array or object+ parameter; treating them as absent would reject valid calls."""+ definition = ToolDefinition(+ name="t",+ description="",+ parameters=[+ ToolParameter(name="items", type="array"),+ ToolParameter(name="spec", type="object"),+ ],+ )+ assert missing_required_args(definition, {"items": [], "spec": {}}) == []+++def test_server_injected_argument_counts_as_supplied() -> None:+ """The guard runs on the *prepared* kwargs, so anything the pipeline+ injects on the model's behalf satisfies the schema."""+ definition = ToolDefinition(+ name="write_note",+ description="",+ parameters=[ToolParameter(name="conversation_history", type="string")],+ )+ assert missing_required_args(definition, {"conversation_history": "Q: hi"}) == []+++def test_raw_json_schema_required_is_honoured() -> None:+ """MCP adapters carry verbatim JSON Schema rather than ToolParameter rows."""+ definition = ToolDefinition(+ name="mcp_fs_read",+ description="",+ raw_parameters={+ "type": "object",+ "properties": {+ "path": {"type": "string"},+ "encoding": {"type": "string", "default": "utf-8"},+ "mode": {"type": "string", "enum": ["text", "binary"]},+ },+ "required": ["path", "encoding", "mode"],+ },+ )+ # ``encoding`` declares a default, so only the other two are the model's job.+ assert [arg.name for arg in missing_required_args(definition, {})] == ["path", "mode"]+++def test_schema_without_required_list_reports_nothing() -> None:+ definition = ToolDefinition(+ name="mcp_loose",+ description="",+ raw_parameters={"type": "object", "properties": {"q": {"type": "string"}}},+ )+ assert required_args(definition) == []+++def test_message_names_the_missing_args_and_their_accepted_values() -> None:+ missing = missing_required_args(_write_note_definition(), {})+ message = missing_args_message("write_note", missing)+ assert "`mode`" in message and "`notebook_id`" in message+ # The enum is what turns "Unknown mode ''" into a one-round fix.+ assert "one of: append | edit" in message+ # And the model must be told that retrying verbatim is pointless.+ assert "rejected again" in message+++class _WriteNote(BaseTool):+ """Records whether it was ever reached."""++ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ def get_definition(self) -> ToolDefinition:+ return _write_note_definition()++ async def execute(self, **kwargs: Any) -> ToolResult:+ self.calls.append(kwargs)+ return ToolResult(content="saved", success=True)+++class _Registry:+ """The read-only slice of a registry the dispatcher actually uses."""++ def __init__(self, tool: _WriteNote) -> None:+ self._tool = tool++ def get(self, name: str) -> BaseTool | None:+ return self._tool if name == "write_note" else None++ async def execute(self, name: str, **kwargs: Any) -> ToolResult:+ kwargs.pop("event_sink", None)+ return await self._tool.execute(**kwargs)+++async def _run_dispatch(+ tool_calls: list[dict[str, Any]],+ registry: Any,+) -> list[StreamEvent]:+ bus = StreamBus()+ events: list[StreamEvent] = []++ async def _consume() -> None:+ async for event in bus.subscribe():+ events.append(event)++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=UnifiedContext(session_id="s1", user_message="hi"),+ stream=bus,+ source="chat",+ stage="responding",+ iteration_index=0,+ registry=registry,+ )+ await bus.close()+ await consumer+ return events+++def _call_states(events: list[StreamEvent]) -> list[str]:+ return [+ str((e.metadata or {}).get("call_state") or "")+ for e in events+ if (e.metadata or {}).get("trace_kind") == "call_status"+ ]+++async def test_call_with_empty_arguments_never_reaches_the_tool() -> None:+ tool = _WriteNote()+ events = await _run_dispatch(+ [{"id": "c1", "name": "write_note", "arguments": "{}"}],+ _Registry(tool),+ )++ assert tool.calls == [], "a malformed call must not run"+ result = next(e for e in events if e.type == StreamEventType.TOOL_RESULT)+ assert "`mode`" in result.content and "`notebook_id`" in result.content+ # The sub-trace closes with a terminal state rather than reading as running…+ assert _call_states(events) == ["error"]+ # …on a PROGRESS event: a rejected call is recoverable, and a stream ERROR+ # makes a partner turn re-run the whole turn on its backup model.+ assert [e for e in events if e.type == StreamEventType.ERROR] == []+++async def test_well_formed_call_is_dispatched_untouched() -> None:+ tool = _WriteNote()+ events = await _run_dispatch(+ [+ {+ "id": "c1",+ "name": "write_note",+ "arguments": json.dumps({"mode": "append", "notebook_id": "nb1"}),+ }+ ],+ _Registry(tool),+ )++ assert [c["mode"] for c in tool.calls] == ["append"]+ assert _call_states(events) == ["running", "complete"]+++async def test_unknown_tool_still_reaches_the_registry() -> None:+ """The registry owns unknown-name errors; the guard must not pre-empt them."""+ tool = _WriteNote()+ events = await _run_dispatch(+ [{"id": "c1", "name": "nope", "arguments": "{}"}],+ _Registry(tool),+ )++ assert _call_states(events) == ["running", "complete"]