mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:19:26 +08:00
fix(tools): tell the model why a tool failed, not that it failed
Stop the Ollama a vector KB embeds against, ask a question, and the model is told "An unknown error occurred while executing rag." The adapter had already written the answer — `Cannot connect to Ollama at http://localhost:11434. Make sure Ollama is running. Start it with: ollama serve` — and the dispatcher was holding it (#1356). `unknown_error_message_factory` took the tool name and nothing else, so no caller could have done better. Four capabilities each wrote their own message from that one argument and three of them called the result unknown; the fourth, pageindex, restated the dispatcher's own default minus the cause. The name was the bug: it presumed a cause the runtime always had. It is now `ToolErrorMessageFactory`, `(tool, cause) -> str`, and the key plus the English wording live once in `tool_error_message_factory`, which each capability wraps around its own `_t`. Capabilities keep their translations and can no longer keep the cause out of them. pageindex passes nothing and takes the default. A bundle predating the new `notices.tool_error` key falls back to English rather than to silence about what went wrong, which is the reason the fallback carries the cause too. This is the same shape as read_skill answering "skill not found" when the skill resolved and only the file was missing (#1347): a failure the caller cannot see has no way out, and the model spends its rounds inventing one. The regression test is the reporter's turn — a `rag` call raising the real adapter error — and asserts the endpoint and the remediation reach the role=tool message.
This commit is contained in:
@@ -127,7 +127,7 @@ notices:
|
||||
tool_result_snipped: "[earlier tool result snipped to stay within context window; call the same tool again if the content is still needed]"
|
||||
ask_user_resolved_directive: "[ask_user resolved. Continue the user's original request using these answers. Do not stop with an acknowledgement.]"
|
||||
too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one round, so the list was truncated."
|
||||
tool_unknown_error: "An unknown error occurred while executing {tool}."
|
||||
tool_error: "{tool} failed: {error}"
|
||||
tool_not_available: "This tool is not available in this conversation. Only the tools listed in the prompt can be called."
|
||||
start_retrieval: "Starting retrieval"
|
||||
empty_tool_result: "The tool completed without returning text output."
|
||||
|
||||
@@ -91,7 +91,7 @@ notices:
|
||||
tool_result_snipped: "[较早的工具结果已裁剪以保持在上下文窗口内;如果仍需要该内容,请再次调用同一工具]"
|
||||
ask_user_resolved_directive: "[ask_user 已解决。请使用这些回答继续处理用户的原始请求。不要只回复确认。]"
|
||||
too_many_tool_calls: "模型请求了 {requested} 个工具,单轮最多并行执行 {limit} 个,已截断。"
|
||||
tool_unknown_error: "执行工具 {tool} 时发生未知错误。"
|
||||
tool_error: "{tool} 执行失败:{error}"
|
||||
tool_not_available: "该工具在本次对话中不可用,只能调用提示中列出的工具。"
|
||||
start_retrieval: "开始检索"
|
||||
empty_tool_result: "工具执行完成,但没有返回文本内容。"
|
||||
|
||||
@@ -68,7 +68,10 @@ from deeptutor.runtime.agentic import (
|
||||
can_use_native_tool_calling,
|
||||
dispatch_tool_calls,
|
||||
)
|
||||
from deeptutor.runtime.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
|
||||
from deeptutor.runtime.agentic.tool_dispatch import (
|
||||
MAX_PARALLEL_TOOL_CALLS,
|
||||
tool_error_message_factory,
|
||||
)
|
||||
from deeptutor.runtime.providers import ToolScope
|
||||
from deeptutor.runtime.providers.view import ProviderToolView, build_tool_view
|
||||
from deeptutor.runtime.registry.deferred_tools import DeferredToolLoader
|
||||
@@ -1054,11 +1057,7 @@ class AgenticLoopPipeline:
|
||||
"notices.start_retrieval", default="Starting retrieval"
|
||||
),
|
||||
retrieve_label=self._t("labels.retrieve", default="Retrieve"),
|
||||
unknown_error_message_factory=lambda tn: self._t(
|
||||
"notices.tool_unknown_error",
|
||||
tool=tn,
|
||||
default=f"An unknown error occurred while executing {tn}.",
|
||||
),
|
||||
tool_error_message_factory=tool_error_message_factory(self._t),
|
||||
)
|
||||
|
||||
async def _dispatch_tool_calls(
|
||||
@@ -1097,11 +1096,7 @@ class AgenticLoopPipeline:
|
||||
"notices.start_retrieval", default="Starting retrieval"
|
||||
),
|
||||
too_many_tool_calls_message=too_many,
|
||||
unknown_error_message_factory=lambda tn: self._t(
|
||||
"notices.tool_unknown_error",
|
||||
tool=tn,
|
||||
default=f"An unknown error occurred while executing {tn}.",
|
||||
),
|
||||
tool_error_message_factory=tool_error_message_factory(self._t),
|
||||
trace_id_prefix=f"{self.event_source}-loop",
|
||||
)
|
||||
|
||||
|
||||
@@ -70,7 +70,10 @@ from deeptutor.runtime.agentic import (
|
||||
)
|
||||
from deeptutor.runtime.agentic.labels import find_inline_labels
|
||||
from deeptutor.runtime.agentic.messages import assistant_message
|
||||
from deeptutor.runtime.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
|
||||
from deeptutor.runtime.agentic.tool_dispatch import (
|
||||
MAX_PARALLEL_TOOL_CALLS,
|
||||
tool_error_message_factory,
|
||||
)
|
||||
from deeptutor.runtime.agentic.usage import record_streamed_usage
|
||||
from deeptutor.runtime.registry.tool_registry import get_tool_registry
|
||||
from deeptutor.runtime.stream_bus import StreamBus
|
||||
@@ -1997,11 +2000,7 @@ class _BaseLoopHost:
|
||||
"notices.start_retrieval", default="Starting retrieval"
|
||||
),
|
||||
too_many_tool_calls_message=too_many,
|
||||
unknown_error_message_factory=lambda tn: self._pipeline._t(
|
||||
"notices.tool_unknown_error",
|
||||
tool=tn,
|
||||
default=f"Error executing {tn}.",
|
||||
),
|
||||
tool_error_message_factory=tool_error_message_factory(self._pipeline._t),
|
||||
trace_id_prefix=self._trace_id_prefix,
|
||||
)
|
||||
pageindex_sources = [
|
||||
|
||||
@@ -322,7 +322,7 @@ notices:
|
||||
start_retrieval: "Starting retrieval"
|
||||
empty_tool_result: "The tool completed without returning text output."
|
||||
too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one iteration, so the list was truncated."
|
||||
tool_unknown_error: "An unknown error occurred while executing {tool}."
|
||||
tool_error: "{tool} failed: {error}"
|
||||
protocol_retry: "The model violated the action-label protocol; retrying this iteration."
|
||||
max_iterations_reached: "Reached the iteration ceiling. Producing the best output I can with what I have."
|
||||
context_window_guard: "Trimmed older tool results to keep within the model's context window."
|
||||
|
||||
@@ -303,7 +303,7 @@ notices:
|
||||
start_retrieval: "开始检索"
|
||||
empty_tool_result: "工具完成但未返回文本输出。"
|
||||
too_many_tool_calls: "模型请求了 {requested} 个工具。一次最多并行 {limit} 个,已截断。"
|
||||
tool_unknown_error: "执行 {tool} 时出现未知错误。"
|
||||
tool_error: "{tool} 执行失败:{error}"
|
||||
protocol_retry: "模型违反了动作标签协议;本轮重试。"
|
||||
max_iterations_reached: "已达迭代上限。基于当前已有内容产出输出。"
|
||||
context_window_guard: "为了保持在模型上下文窗口内,裁剪了较早的工具结果。"
|
||||
|
||||
@@ -83,6 +83,7 @@ from deeptutor.runtime.agentic import (
|
||||
from deeptutor.runtime.agentic.messages import assistant_message
|
||||
from deeptutor.runtime.agentic.tool_dispatch import (
|
||||
MAX_PARALLEL_TOOL_CALLS,
|
||||
tool_error_message_factory,
|
||||
)
|
||||
from deeptutor.runtime.registry.tool_registry import get_tool_registry
|
||||
from deeptutor.runtime.stream_bus import StreamBus
|
||||
@@ -2576,11 +2577,7 @@ class _BlockLoopHost:
|
||||
"notices.start_retrieval", default="Starting retrieval"
|
||||
),
|
||||
too_many_tool_calls_message=too_many,
|
||||
unknown_error_message_factory=lambda tn: self._pipeline._t(
|
||||
"notices.tool_unknown_error",
|
||||
tool=tn,
|
||||
default=f"Error executing {tn}.",
|
||||
),
|
||||
tool_error_message_factory=tool_error_message_factory(self._pipeline._t),
|
||||
trace_id_prefix=f"research-{self._block.block_id}-iter",
|
||||
)
|
||||
pageindex_sources = [
|
||||
@@ -2964,11 +2961,7 @@ class _RephraseLoopHost:
|
||||
"notices.start_retrieval", default="Starting retrieval"
|
||||
),
|
||||
too_many_tool_calls_message=too_many,
|
||||
unknown_error_message_factory=lambda tn: self._pipeline._t(
|
||||
"notices.tool_unknown_error",
|
||||
tool=tn,
|
||||
default=f"Error executing {tn}.",
|
||||
),
|
||||
tool_error_message_factory=tool_error_message_factory(self._pipeline._t),
|
||||
trace_id_prefix="research-rephrase-iter",
|
||||
)
|
||||
if rejected:
|
||||
|
||||
@@ -44,7 +44,7 @@ notices:
|
||||
protocol_retry: "The model violated the action-label protocol; retrying."
|
||||
empty_tool_result: "Tool returned no result."
|
||||
start_retrieval: "Starting retrieval"
|
||||
tool_unknown_error: "Error executing {tool}."
|
||||
tool_error: "{tool} failed: {error}"
|
||||
too_many_tool_calls: "Requested {requested} tool calls; capped at {limit}."
|
||||
max_iterations_reached: "Reached the iteration ceiling for this block; forcing FINISH."
|
||||
partial_results: "{failed} of {total} research subtopics could not be completed; the report is based on the remaining evidence."
|
||||
|
||||
@@ -36,7 +36,7 @@ notices:
|
||||
protocol_retry: "模型未遵循标签协议,正在重试。"
|
||||
empty_tool_result: "工具未返回任何结果。"
|
||||
start_retrieval: "开始检索"
|
||||
tool_unknown_error: "执行 {tool} 时出错。"
|
||||
tool_error: "{tool} 执行失败:{error}"
|
||||
too_many_tool_calls: "本轮请求 {requested} 次工具调用,已截断到上限 {limit}。"
|
||||
max_iterations_reached: "当前研究块已达到迭代上限,强制 FINISH。"
|
||||
partial_results: "{total} 个研究子主题中有 {failed} 个未能完成;报告基于其余已收集的证据生成。"
|
||||
|
||||
@@ -10,7 +10,7 @@ Lifted from chat's pipeline. Capability-agnostic: the caller supplies:
|
||||
its running/terminal state and its intermediate progress into its own
|
||||
sub-trace regardless of flavor.
|
||||
* labels for the trace UI rows (``tool_call``, ``retrieve``) plus the
|
||||
capability-specific copy for empty results / over-quota / unknown errors.
|
||||
capability-specific copy for empty results / over-quota / tool failures.
|
||||
|
||||
The dispatcher executes all tool calls in parallel, emits one sub-trace per
|
||||
tool call, and returns a :class:`DispatchOutcome` carrying the role=tool
|
||||
@@ -60,7 +60,38 @@ KwargAugmenter = Callable[[str, dict[str, Any], UnifiedContext], dict[str, Any]]
|
||||
# which tools rebind is a capability's knowledge, not the dispatcher's.
|
||||
RebindingTools = frozenset[str]
|
||||
RetrieveMetaFactory = Callable[[dict[str, Any], str, dict[str, Any]], dict[str, Any] | None]
|
||||
UnknownErrorMessageFactory = Callable[[str], str]
|
||||
# What a raising tool reports back to the model: the tool that failed *and*
|
||||
# why. The cause is a parameter rather than something the caller may look up,
|
||||
# because it is the half that kept going missing — the dispatcher holds the
|
||||
# exception, every capability wrote its own message from the tool name alone,
|
||||
# and three of the four called the result "unknown". A stopped Ollama says
|
||||
# where it was listening and how to start it (#1356); the model was told "an
|
||||
# unknown error occurred while executing rag" and went looking for one.
|
||||
ToolErrorMessageFactory = Callable[[str, str], str]
|
||||
#: Prompt-bundle key for that message. One key, one wording, five call sites.
|
||||
TOOL_ERROR_NOTICE_KEY = "notices.tool_error"
|
||||
|
||||
|
||||
def tool_error_message_factory(
|
||||
translate: Callable[..., str],
|
||||
) -> ToolErrorMessageFactory:
|
||||
"""A capability's localized failed-tool notice, from its own bundle.
|
||||
|
||||
``translate`` is the capability's ``_t``. The key and the English wording
|
||||
live here so the capabilities cannot drift apart again, and the fallback
|
||||
still names the cause — a bundle that predates this key degrades to
|
||||
English, never to silence about what went wrong.
|
||||
"""
|
||||
|
||||
def _message(tool_name: str, error: str) -> str:
|
||||
return translate(
|
||||
TOOL_ERROR_NOTICE_KEY,
|
||||
tool=tool_name,
|
||||
error=error,
|
||||
default=f"{tool_name} failed: {error}",
|
||||
)
|
||||
|
||||
return _message
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -103,7 +134,7 @@ async def dispatch_tool_calls(
|
||||
empty_tool_result_message: str = "",
|
||||
start_retrieval_message: str = "Starting retrieval",
|
||||
too_many_tool_calls_message: str | None = None,
|
||||
unknown_error_message_factory: UnknownErrorMessageFactory | None = None,
|
||||
tool_error_message_factory: ToolErrorMessageFactory | None = None,
|
||||
trace_id_prefix: str = "iter",
|
||||
) -> DispatchOutcome:
|
||||
"""Execute tool calls in parallel and assemble a :class:`DispatchOutcome`."""
|
||||
@@ -207,7 +238,7 @@ async def dispatch_tool_calls(
|
||||
),
|
||||
empty_tool_result_message=empty_tool_result_message,
|
||||
start_retrieval_message=start_retrieval_message,
|
||||
unknown_error_message_factory=unknown_error_message_factory,
|
||||
tool_error_message_factory=tool_error_message_factory,
|
||||
retrieve_label=retrieve_label,
|
||||
)
|
||||
|
||||
@@ -551,7 +582,7 @@ async def execute_tool_call(
|
||||
empty_tool_result_message: str = "",
|
||||
start_retrieval_message: str = "Starting retrieval",
|
||||
retrieve_label: str = "Retrieve",
|
||||
unknown_error_message_factory: UnknownErrorMessageFactory | None = None,
|
||||
tool_error_message_factory: ToolErrorMessageFactory | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Run one tool, streaming its state (and any intermediate progress) into
|
||||
the tool's own sub-trace.
|
||||
@@ -678,13 +709,14 @@ async def execute_tool_call(
|
||||
error=str(exc),
|
||||
),
|
||||
)
|
||||
unknown_msg = (
|
||||
unknown_error_message_factory(tool_name)
|
||||
if unknown_error_message_factory is not None
|
||||
else f"Error executing {tool_name}: {exc}"
|
||||
cause = str(exc) or exc.__class__.__name__
|
||||
failure_msg = (
|
||||
tool_error_message_factory(tool_name, cause)
|
||||
if tool_error_message_factory is not None
|
||||
else f"Error executing {tool_name}: {cause}"
|
||||
)
|
||||
return {
|
||||
"result_text": unknown_msg,
|
||||
"result_text": failure_msg,
|
||||
"success": False,
|
||||
"sources": [],
|
||||
"metadata": {"error": str(exc)},
|
||||
|
||||
@@ -100,7 +100,6 @@ class _ReadingHost:
|
||||
empty_tool_result_message="PageIndex returned no content.",
|
||||
start_retrieval_message="Reading PageIndex documents",
|
||||
too_many_tool_calls_message="Too many tool calls in one round.",
|
||||
unknown_error_message_factory=lambda name: f"Error executing {name}.",
|
||||
trace_id_prefix=f"{self.source}-pageindex",
|
||||
)
|
||||
|
||||
|
||||
109
tests/core/agentic/test_tool_failure_reaches_the_model.py
Normal file
109
tests/core/agentic/test_tool_failure_reaches_the_model.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""A raising tool must tell the model *why*, not just that it failed.
|
||||
|
||||
#1356: a learner stops their local Ollama and asks a question against a vector
|
||||
KB. The embedding adapter raises a fully-formed diagnosis — the address it
|
||||
tried and the command that starts the server — the dispatcher catches it, and
|
||||
then the chat capability's ``unknown_error_message_factory`` rebuilt the
|
||||
message from the tool name alone: "An unknown error occurred while executing
|
||||
rag." The model, told only that something unknown happened, cannot tell the
|
||||
learner to start Ollama; it retries, works around, or apologises.
|
||||
|
||||
The factory could not do better, because the cause was never passed to it.
|
||||
That is what these tests pin: the contract carries the cause, and each
|
||||
capability's own bundle spends it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
from deeptutor.core.tool_protocol import ToolResult
|
||||
from deeptutor.runtime.agentic.tool_dispatch import (
|
||||
dispatch_tool_calls,
|
||||
tool_error_message_factory,
|
||||
)
|
||||
from deeptutor.runtime.stream_bus import StreamBus
|
||||
|
||||
# What ``deeptutor/services/embedding/adapters/ollama.py`` actually raises.
|
||||
OLLAMA_DOWN = ConnectionError(
|
||||
"Cannot connect to Ollama at http://localhost:11434. "
|
||||
"Make sure Ollama is running. Start it with: ollama serve"
|
||||
)
|
||||
|
||||
|
||||
class _UnreachableEmbedding:
|
||||
async def execute(self, name: str, **kwargs: Any) -> ToolResult:
|
||||
raise OLLAMA_DOWN
|
||||
|
||||
|
||||
async def _rag_failure_text(**dispatch_kwargs: Any) -> str:
|
||||
"""The ``role=tool`` content a failed ``rag`` call puts in front of the model."""
|
||||
bus = StreamBus()
|
||||
outcome = await dispatch_tool_calls(
|
||||
tool_calls=[
|
||||
{
|
||||
"id": "c1",
|
||||
"name": "rag",
|
||||
"arguments": json.dumps({"query": "q", "kb_name": "kb"}),
|
||||
}
|
||||
],
|
||||
context=UnifiedContext(session_id="s1", user_message="hi"),
|
||||
stream=bus,
|
||||
source="chat",
|
||||
stage="responding",
|
||||
iteration_index=0,
|
||||
registry=_UnreachableEmbedding(),
|
||||
**dispatch_kwargs,
|
||||
)
|
||||
await bus.close()
|
||||
return str(outcome.tool_messages[0]["content"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stopped_embedding_server_tells_the_model_where_and_how() -> None:
|
||||
"""The reporter's turn: the remediation survives all the way to the model."""
|
||||
content = await _rag_failure_text(
|
||||
tool_error_message_factory=tool_error_message_factory(
|
||||
# A capability whose bundle carries the key, as all three now do.
|
||||
lambda _key, tool="", error="", default="": f"{tool} failed: {error}"
|
||||
)
|
||||
)
|
||||
assert "http://localhost:11434" in content
|
||||
assert "ollama serve" in content
|
||||
assert "unknown" not in content.lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_capability_that_passes_no_factory_still_names_the_cause() -> None:
|
||||
"""The dispatcher's own default is the floor, not a bare tool name.
|
||||
|
||||
``pageindex`` used to override this with a message that dropped the cause;
|
||||
it now passes nothing, so this is the message it gets.
|
||||
"""
|
||||
content = await _rag_failure_text()
|
||||
assert "ollama serve" in content
|
||||
|
||||
|
||||
def test_a_bundle_without_the_key_falls_back_to_english_with_the_cause() -> None:
|
||||
"""An older or user-edited prompt bundle loses the wording, never the cause."""
|
||||
|
||||
def _stale_bundle(_key: str, default: str = "", **kwargs: Any) -> str:
|
||||
return default.format(**kwargs)
|
||||
|
||||
message = tool_error_message_factory(_stale_bundle)("rag", str(OLLAMA_DOWN))
|
||||
assert message == f"rag failed: {OLLAMA_DOWN}"
|
||||
|
||||
|
||||
def test_a_translated_bundle_spends_the_cause_it_is_given() -> None:
|
||||
"""zh keeps its own phrasing and still shows the endpoint and the fix."""
|
||||
|
||||
def _zh_bundle(_key: str, default: str = "", **kwargs: Any) -> str:
|
||||
return "{tool} 执行失败:{error}".format(**kwargs)
|
||||
|
||||
message = tool_error_message_factory(_zh_bundle)("rag", str(OLLAMA_DOWN))
|
||||
assert message.startswith("rag 执行失败:")
|
||||
assert "ollama serve" in message
|
||||
Reference in New Issue
Block a user