Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): recover hallucinated PDF tool calls for attached sources (#1333)

AoHanBeieb49228d8fe5
diff --git a/deeptutor/runtime/agentic/tool_dispatch.py b/deeptutor/runtime/agentic/tool_dispatch.py
index 69c7a0b89..e23fcbde2 100644
--- a/deeptutor/runtime/agentic/tool_dispatch.py
+++ b/deeptutor/runtime/agentic/tool_dispatch.py
@@ -119,7 +119,12 @@ async def dispatch_tool_calls(
)
tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]
- prepared, raw_args = _prepare_tool_args(tool_calls, context, kwarg_augmenter)
+ prepared, raw_args = _prepare_tool_args(
+ tool_calls,
+ context,
+ kwarg_augmenter,
+ registry=registry,
+ )
# Collapse duplicates within this parallel batch. Models occasionally
# emit repeated tool_calls in one assistant message. For most tools,
# "duplicate" means same tool + same JSON-normalised args. For
@@ -224,7 +229,16 @@ async def dispatch_tool_calls(
if duplicate_of.get(index) is not None:
continue
call_id, name, _stale = prepared[index]
- prepared[index] = (call_id, name, kwarg_augmenter(name, raw_args[index], context))
+ canonical_name, resolved_args = _resolve_tool_request(
+ registry,
+ name,
+ raw_args[index],
+ )
+ prepared[index] = (
+ call_id,
+ name,
+ kwarg_augmenter(canonical_name, resolved_args, context),
+ )
# Three ordered stages around one concurrent middle. Every call in a round
# has its args bound before any of them runs, so a tool that *changes what
@@ -431,6 +445,8 @@ def _prepare_tool_args(
tool_calls: list[dict[str, Any]],
context: UnifiedContext,
kwarg_augmenter: KwargAugmenter | None,
+ *,
+ registry: ToolLookup | None = None,
) -> tuple[list[tuple[str, str, dict[str, Any]]], list[dict[str, Any]]]:
"""Bind each call's execution args, keeping the model's originals.
@@ -449,16 +465,43 @@ def _prepare_tool_args(
)
if not isinstance(tool_args, dict):
tool_args = {}
+ canonical_name, resolved_args = _resolve_tool_request(registry, tool_name, tool_args)
exec_args = (
- kwarg_augmenter(tool_name, tool_args, context)
+ kwarg_augmenter(canonical_name, resolved_args, context)
if kwarg_augmenter is not None
- else dict(tool_args)
+ else resolved_args
)
prepared.append((tool_call_id, tool_name, exec_args))
raw_args.append(dict(tool_args))
return prepared, raw_args
+def _resolve_tool_request(
+ registry: ToolLookup | None,
+ tool_name: str,
+ tool_args: dict[str, Any],
+) -> tuple[str, dict[str, Any]]:
+ """Resolve aliases and their defaults before server-owned augmentation.
+
+ Execution retains the model-provided name so trace rows remain faithful.
+ Registries without alias support keep the original name and arguments.
+ """
+ if registry is None:
+ return tool_name, dict(tool_args)
+ resolver = getattr(registry, "resolve_request", None)
+ if callable(resolver):
+ try:
+ resolved_name, resolved_args = resolver(tool_name, tool_args)
+ return str(resolved_name or tool_name), dict(resolved_args)
+ except Exception:
+ return tool_name, dict(tool_args)
+ try:
+ tool = registry.get(tool_name)
+ except Exception:
+ return tool_name, dict(tool_args)
+ return str(getattr(tool, "name", "") or tool_name), dict(tool_args)
+
+
def _build_per_tool_trace_meta(
prepared: list[tuple[str, str, dict[str, Any]]],
*,
diff --git a/deeptutor/runtime/registry/tool_registry.py b/deeptutor/runtime/registry/tool_registry.py
index 6176d5454..973a6f9a9 100644
--- a/deeptutor/runtime/registry/tool_registry.py
+++ b/deeptutor/runtime/registry/tool_registry.py
@@ -85,6 +85,14 @@ class ToolRegistry:
return resolved_name, merged_kwargs
+ def resolve_request(
+ self,
+ name: str,
+ kwargs: dict[str, Any] | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ """Return the canonical tool name and alias-defaulted arguments."""
+ return self._resolve_request(name, kwargs)
+
def get(self, name: str) -> BaseTool | None:
resolved_name, _ = self._resolve_request(name)
return self._tools.get(resolved_name) or self._load_builtin(resolved_name)
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index cee030edd..e0b9b6afd 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -549,18 +549,21 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
)
async def execute(self, **kwargs: Any) -> ToolResult:
- source_id = str(kwargs.get("source_id") or "").strip()
- if not source_id:
- return ToolResult(
- content="Error: source_id is required.",
- success=False,
- )
source_index = kwargs.get("source_index")
if not isinstance(source_index, dict) or not source_index:
return ToolResult(
content=("Error: no attached sources are available for this turn."),
success=False,
)
+ source_id = str(kwargs.get("source_id") or "").strip()
+ if not source_id:
+ if len(source_index) == 1:
+ source_id = next(iter(source_index))
+ else:
+ return ToolResult(
+ content="Error: source_id is required when multiple sources are available.",
+ success=False,
+ )
full_text = source_index.get(source_id)
if not full_text:
available = ", ".join(sorted(source_index.keys()))
diff --git a/deeptutor/tools/builtin_specs.py b/deeptutor/tools/builtin_specs.py
index fd275b84e..cd458504f 100644
--- a/deeptutor/tools/builtin_specs.py
+++ b/deeptutor/tools/builtin_specs.py
@@ -210,6 +210,7 @@ BUILTIN_TOOL_SPEC_BY_NAME: dict[str, BuiltinToolSpec] = {
}
TOOL_ALIASES: dict[str, tuple[str, dict[str, object]]] = {
+ "pdf": ("read_source", {}),
"rag_hybrid": ("rag", {"mode": "hybrid"}),
"rag_naive": ("rag", {"mode": "naive"}),
"rag_search": ("rag", {}),
diff --git a/tests/tools/test_read_source.py b/tests/tools/test_read_source.py
new file mode 100644
index 000000000..5e086ac91
--- /dev/null
+++ b/tests/tools/test_read_source.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import asyncio
+
+from deeptutor.core.context import UnifiedContext
+from deeptutor.runtime.agentic.tool_dispatch import _prepare_tool_args
+from deeptutor.runtime.registry.tool_registry import ToolRegistry
+
+
+def _registry() -> ToolRegistry:
+ registry = ToolRegistry()
+ registry.load_builtins()
+ return registry
+
+
+def test_pdf_alias_reads_the_only_attached_source() -> None:
+ result = asyncio.run(
+ _registry().execute(
+ "pdf",
+ source_index={"at-pdf-1": "Algebra worksheet contents"},
+ )
+ )
+
+ assert result.success is True
+ assert result.content == "Algebra worksheet contents"
+ assert result.metadata["source_id"] == "at-pdf-1"
+
+
+def test_pdf_alias_does_not_guess_between_multiple_sources() -> None:
+ result = asyncio.run(
+ _registry().execute(
+ "pdf",
+ source_index={
+ "at-pdf-1": "First PDF",
+ "at-pdf-2": "Second PDF",
+ },
+ )
+ )
+
+ assert result.success is False
+ assert "source_id is required when multiple sources are available" in result.content
+
+
+def test_pdf_alias_is_augmented_as_read_source() -> None:
+ source_index = {"at-pdf-1": "Algebra worksheet contents"}
+
+ def augment(
+ tool_name: str,
+ args: dict[str, object],
+ _context: UnifiedContext,
+ ) -> dict[str, object]:
+ augmented = dict(args)
+ if tool_name == "read_source":
+ augmented["source_index"] = source_index
+ return augmented
+
+ prepared, _ = _prepare_tool_args(
+ [{"id": "call-1", "name": "pdf", "arguments": "{}"}],
+ UnifiedContext(),
+ augment,
+ registry=_registry(),
+ )
+
+ assert prepared == [("call-1", "pdf", {"source_index": source_index})]
+
+
+def test_alias_defaults_survive_canonical_argument_augmentation() -> None:
+ def augment(
+ tool_name: str,
+ args: dict[str, object],
+ _context: UnifiedContext,
+ ) -> dict[str, object]:
+ augmented = dict(args)
+ if tool_name == "rag":
+ augmented.setdefault("mode", "hybrid")
+ return augmented
+
+ prepared, _ = _prepare_tool_args(
+ [{"id": "call-1", "name": "rag_naive", "arguments": "{}"}],
+ UnifiedContext(),
+ augment,
+ registry=_registry(),
+ )
+
+ assert prepared == [("call-1", "rag_naive", {"mode": "naive"})]