fix(middlewares): keep queued hints when an empty model response is retried (#8424)

* fix(middlewares): keep queued hints when an empty model response is retried

LoopDetection, TokenBudget, ToolProgress and Todo take their queued hint out
of the run's queue in wrap_model_call and put it back only when the call
raises. A completed call with no content returns normally;
LLMErrorHandlingMiddleware, which sits outside them, then turns it into
EmptyModelResponseError and retries by running the inner wraps again. The
queue was already empty, so the retry went out without the hint. Loop and
TokenBudget had already marked the run as warned, so that run never saw the
warning.

Each wrap now puts its hints back on an empty stop response too, using the
same check LLMErrorHandlingMiddleware retries on
(model_response.is_empty_stop_response). Test fakes that returned a MagicMock
or a string as the model's answer now return an AIMessage, since the check
reads anything else as no answer, as LLMErrorHandlingMiddleware does.

* docs(middlewares): note that a model retry runs the inner wraps again

LLM error handling retries both a call that raised and an empty stop response by calling the inner wraps again, so a wrap that takes a queued hint for one call must put it back in both cases.
This commit is contained in:
Hyeonsang Cho 2026-11-21 11:31:13 +09:00 committed by GitHub
parent 6addd93d32
commit 8a6eb9c898
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 163 additions and 70 deletions

View File

@ -33,6 +33,10 @@ make test-blocking-io
sees the result that error handling produced.
- **Progress tracking fences late results and hint retries by graph entry**, also
within one run.
- **A model retry runs the inner wraps again.** LLM error handling retries a call
that raised and a call that returned an empty stop response
(`model_response.is_empty_stop_response`). A wrap that takes a queued hint for
one call puts it back in both cases, or the retry goes out without it.
## Rules for a middleware that changes messages

View File

@ -24,7 +24,7 @@ from langchain.agents.middleware.types import (
from langchain_core.messages import AIMessage
from langgraph.errors import GraphBubbleUp
from deerflow.agents.middlewares.model_response import append_visible_text, finish_reason, has_tool_call_intent, has_visible_content, last_ai_message
from deerflow.agents.middlewares.model_response import append_visible_text, is_empty_stop_response, last_ai_message
from deerflow.config.app_config import AppConfig
from deerflow.models.request_admission import AdmissionError
from deerflow.models.response_errors import EmptyModelResponseError
@ -45,14 +45,8 @@ class _CircuitAdmission:
def _raise_for_empty_response(response: ModelCallResult) -> None:
"""在响应写入图状态前把零内容 stop 转换为可重试错误。"""
message = last_ai_message(response)
if message is None:
raise EmptyModelResponseError()
if has_visible_content(message) or has_tool_call_intent(message):
return
reason = finish_reason(message)
if reason in (None, "", "stop", "end_turn"):
raise EmptyModelResponseError(response_message=message)
if is_empty_stop_response(response):
raise EmptyModelResponseError(response_message=last_ai_message(response))
def _consume_empty_response_retry(request: ModelRequest) -> bool:

View File

@ -90,6 +90,7 @@ from deerflow.agents.middlewares.audit_context import (
LOOP_DETECTION_RECORDER_CONTEXT_KEY,
resolve_audit_recorder,
)
from deerflow.agents.middlewares.model_response import is_empty_stop_response
from deerflow.agents.middlewares.tool_call_args import pair_tool_call_results
from deerflow.agents.middlewares.tool_call_metadata import clone_ai_message_with_tool_calls
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY
@ -984,11 +985,12 @@ class LoopDetectionMiddleware(AgentMiddleware[AgentState]):
return warnings
def _restore_pending_warnings(self, runtime: Runtime, warnings: list[str]) -> None:
"""Requeue warnings taken for a model call that raised.
"""Requeue warnings taken for a model call that raised or came back empty.
LLMErrorHandlingMiddleware sits outside this middleware and retries a
failed call by running this wrap again, so the retry must still find
the warning. It would not be queued again: it is already marked warned.
failed call, or an empty stop response, by running this wrap again, so
the retry must still find the warning. It would not be queued again: it
is already marked warned.
"""
if not warnings:
return
@ -1027,10 +1029,13 @@ class LoopDetectionMiddleware(AgentMiddleware[AgentState]):
) -> ModelCallResult:
warnings = self._drain_pending_warnings(request.runtime)
try:
return handler(self._inject_warnings(request, warnings))
response = handler(self._inject_warnings(request, warnings))
except Exception:
self._restore_pending_warnings(request.runtime, warnings)
raise
if is_empty_stop_response(response):
self._restore_pending_warnings(request.runtime, warnings)
return response
@override
async def awrap_model_call(
@ -1040,10 +1045,13 @@ class LoopDetectionMiddleware(AgentMiddleware[AgentState]):
) -> ModelCallResult:
warnings = self._drain_pending_warnings(request.runtime)
try:
return await handler(self._inject_warnings(request, warnings))
response = await handler(self._inject_warnings(request, warnings))
except Exception:
self._restore_pending_warnings(request.runtime, warnings)
raise
if is_empty_stop_response(response):
self._restore_pending_warnings(request.runtime, warnings)
return response
def reset(self, thread_id: str | None = None) -> None:
"""Clear tracking state. If thread_id given, clear only that thread."""

View File

@ -56,6 +56,22 @@ def append_visible_text(message: AIMessage, text: str) -> Any:
return text
def is_empty_stop_response(response: Any) -> bool:
"""Return whether a model call completed without any content.
``LLMErrorHandlingMiddleware`` turns such a response into
``EmptyModelResponseError`` and retries the call by running the inner
model wrappers again. A wrapper that took queued hints out for this call
puts them back on this response, as it does when the call raises.
"""
message = last_ai_message(response)
if message is None:
return True
if has_visible_content(message) or has_tool_call_intent(message):
return False
return finish_reason(message) in (None, "", "stop", "end_turn")
def finish_reason(message: AIMessage) -> str | None:
"""Read and normalize common provider termination-reason fields."""
for metadata in (message.response_metadata or {}, message.additional_kwargs or {}):

View File

@ -36,6 +36,7 @@ from pydantic import BaseModel
from typing_extensions import TypedDict
from deerflow.agents.middlewares.model_length_finish_reason_middleware import MODEL_LENGTH_CAPPED_STOP_REASON, MODEL_LENGTH_TERMINATION_MARKER
from deerflow.agents.middlewares.model_response import is_empty_stop_response
from deerflow.agents.middlewares.safety_finish_reason_middleware import SAFETY_CAPPED_STOP_REASON, SAFETY_TERMINATION_MARKER
from deerflow.agents.thread_state import ThreadState
@ -370,11 +371,11 @@ class TodoMiddleware(TodoListMiddleware):
return reminders
def _restore_completion_reminders(self, runtime: Runtime, reminders: list[str]) -> None:
"""Requeue reminders taken for a model call that raised.
"""Requeue reminders taken for a model call that raised or came back empty.
LLMErrorHandlingMiddleware sits outside this middleware and retries a
failed call by running this wrap again, so the retry must still find
the reminder. The count is not bumped again: it was spent when the
failed call, or an empty stop response, by running this wrap again, so
the retry must still find the reminder. The count is not bumped again: it was spent when the
reminder was queued. A run whose reminder state was dropped meanwhile
stays dropped.
"""
@ -519,10 +520,13 @@ class TodoMiddleware(TodoListMiddleware):
# carries the injected system prompt.
reminders = self._drain_completion_reminders(request.runtime)
try:
return super().wrap_model_call(request, lambda req: handler(self._inject_completion_reminders(req, reminders)))
response = super().wrap_model_call(request, lambda req: handler(self._inject_completion_reminders(req, reminders)))
except Exception:
self._restore_completion_reminders(request.runtime, reminders)
raise
if is_empty_stop_response(response):
self._restore_completion_reminders(request.runtime, reminders)
return response
@override
async def awrap_model_call(
@ -541,10 +545,13 @@ class TodoMiddleware(TodoListMiddleware):
return await handler(self._inject_completion_reminders(req, reminders))
try:
return await super().awrap_model_call(request, augmented_handler)
response = await super().awrap_model_call(request, augmented_handler)
except Exception:
self._restore_completion_reminders(request.runtime, reminders)
raise
if is_empty_stop_response(response):
self._restore_completion_reminders(request.runtime, reminders)
return response
@override
def after_agent(self, state: ThreadState, runtime: Runtime) -> dict[str, Any] | None:

View File

@ -57,7 +57,7 @@ from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langgraph.runtime import Runtime
from deerflow.agents.middlewares._bounded_dict import BoundedDict
from deerflow.agents.middlewares.model_response import last_ai_message
from deerflow.agents.middlewares.model_response import is_empty_stop_response, last_ai_message
from deerflow.agents.middlewares.tool_call_metadata import clone_ai_message_with_tool_calls
from deerflow.config.token_budget_config import TokenBudgetConfig
@ -409,11 +409,12 @@ class TokenBudgetMiddleware(AgentMiddleware[AgentState]):
return warnings or []
def _restore_pending_warnings(self, runtime: Runtime, warnings: list[str]) -> None:
"""Requeue warnings taken for a model call that raised.
"""Requeue warnings taken for a model call that raised or came back empty.
LLMErrorHandlingMiddleware sits outside this middleware and retries a
failed call by running this wrap again, so the retry must still find
the warning. It is not queued twice: ``_warned`` is already set.
failed call, or an empty stop response, by running this wrap again, so
the retry must still find the warning. It is not queued twice:
``_warned`` is already set.
"""
if not warnings:
return
@ -504,12 +505,14 @@ class TokenBudgetMiddleware(AgentMiddleware[AgentState]):
try:
response = handler(self._inject_warnings(request, warnings))
self._record_pending_model_call(request.runtime, response)
return response
except BaseException as exc:
self._discard_pending_model_call(request.runtime)
if isinstance(exc, Exception):
self._restore_pending_warnings(request.runtime, warnings)
raise
if is_empty_stop_response(response):
self._restore_pending_warnings(request.runtime, warnings)
return response
@override
async def awrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]]) -> ModelCallResult:
@ -517,9 +520,11 @@ class TokenBudgetMiddleware(AgentMiddleware[AgentState]):
try:
response = await handler(self._inject_warnings(request, warnings))
self._record_pending_model_call(request.runtime, response)
return response
except BaseException as exc:
self._discard_pending_model_call(request.runtime)
if isinstance(exc, Exception):
self._restore_pending_warnings(request.runtime, warnings)
raise
if is_empty_stop_response(response):
self._restore_pending_warnings(request.runtime, warnings)
return response

View File

@ -71,6 +71,7 @@ from deerflow.agents.middlewares.audit_context import (
TOOL_PROGRESS_RECORDER_CONTEXT_KEY,
resolve_audit_recorder,
)
from deerflow.agents.middlewares.model_response import is_empty_stop_response
from deerflow.agents.middlewares.tool_result_meta import (
PROGRESS_GUARD_ERROR_TYPE,
TOOL_META_KEY,
@ -598,11 +599,11 @@ class ToolProgressMiddleware(AgentMiddleware[AgentState]):
return self._pending.pop(key, [])
def _restore_pending(self, runtime: Runtime, hints: list[str], *, entry_epoch: object | None = None) -> None:
"""Requeue hints taken for a model call that raised.
"""Requeue hints taken for a model call that raised or came back empty.
LLMErrorHandlingMiddleware sits outside this middleware and retries a
failed call by running this wrap again, so the retry must still find
the hints.
failed call, or an empty stop response, by running this wrap again, so
the retry must still find the hints.
"""
if not hints:
return
@ -770,10 +771,13 @@ class ToolProgressMiddleware(AgentMiddleware[AgentState]):
entry_epoch = self._entry_epoch(request.runtime)
hints = self._drain_pending(request.runtime)
try:
return handler(self._inject_hints(request, hints))
response = handler(self._inject_hints(request, hints))
except Exception:
self._restore_pending(request.runtime, hints, entry_epoch=entry_epoch)
raise
if is_empty_stop_response(response):
self._restore_pending(request.runtime, hints, entry_epoch=entry_epoch)
return response
@override
async def awrap_model_call(
@ -784,10 +788,13 @@ class ToolProgressMiddleware(AgentMiddleware[AgentState]):
entry_epoch = self._entry_epoch(request.runtime)
hints = self._drain_pending(request.runtime)
try:
return await handler(self._inject_hints(request, hints))
response = await handler(self._inject_hints(request, hints))
except Exception:
self._restore_pending(request.runtime, hints, entry_epoch=entry_epoch)
raise
if is_empty_stop_response(response):
self._restore_pending(request.runtime, hints, entry_epoch=entry_epoch)
return response
# ------------------------------------------------------------------
# before_agent: clean up stale pending hints from previous runs

View File

@ -1,5 +1,6 @@
"""Tests for LoopDetectionMiddleware."""
import asyncio
import copy
from collections import OrderedDict
from pathlib import Path
@ -11,6 +12,7 @@ import pytest
from langchain.agents import create_agent
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import Runnable
from langchain_core.tools import tool as as_tool
from pydantic import PrivateAttr
@ -63,7 +65,7 @@ def _capture_handler():
def handler(req):
captured.append(req)
return MagicMock()
return AIMessage(content="answer")
return captured, handler
@ -1323,8 +1325,10 @@ class TestLoopDetectionAgentGraphIntegration:
_scope_key("cached-thread", "run-2"),
}
def test_loop_warning_survives_a_retried_model_call_in_real_agent_graph(self):
"""LLMErrorHandlingMiddleware retries a failed call by running the inner wraps again; the retry must still carry the warning."""
@pytest.mark.parametrize("invoke_async", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
def test_loop_warning_survives_a_retried_model_call_in_real_agent_graph(self, failure, invoke_async):
"""LLMErrorHandlingMiddleware retries a failed call or an empty stop response by running the inner wraps again; the retry must still carry the warning."""
from deerflow.agents.middlewares.llm_error_handling_middleware import LLMErrorHandlingMiddleware
from deerflow.config.app_config import AppConfig, LlmCallConfig
from deerflow.config.sandbox_config import SandboxConfig
@ -1342,6 +1346,8 @@ class TestLoopDetectionAgentGraphIntegration:
if not self._failed and any(isinstance(message, HumanMessage) and message.name == "loop_warning" for message in messages):
self._failed = True
self._seen_messages.append(list(messages))
if failure == "empty-response":
return ChatResult(generations=[ChatGeneration(message=AIMessage(content="", response_metadata={"finish_reason": "stop"}))])
raise ProviderUnavailable()
return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
@ -1369,11 +1375,9 @@ class TestLoopDetectionAgentGraphIntegration:
middleware=[LLMErrorHandlingMiddleware(app_config=app_config), LoopDetectionMiddleware(warn_threshold=3, hard_limit=10)],
)
result = graph.invoke(
{"messages": [("user", "inspect the directory")]},
context={"thread_id": "retry-thread", "run_id": "retry-run"},
config={"recursion_limit": 20},
)
invoke_args = ({"messages": [("user", "inspect the directory")]},)
invoke_kwargs = {"context": {"thread_id": "retry-thread", "run_id": "retry-run"}, "config": {"recursion_limit": 20}}
result = asyncio.run(graph.ainvoke(*invoke_args, **invoke_kwargs)) if invoke_async else graph.invoke(*invoke_args, **invoke_kwargs)
# Three tool-calling requests, then the failed attempt and its retry.
assert len(model.seen_messages) == 5

View File

@ -14,6 +14,7 @@ from langchain.agents.middleware.types import ModelRequest
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.checkpoint.memory import InMemorySaver
from pydantic import PrivateAttr
@ -687,12 +688,13 @@ class TestWrapModelCall:
request = _make_model_request(state["messages"], runtime=runtime)
seen: list[ModelRequest] = []
answer = AIMessage(content="response")
def handler(model_request: ModelRequest):
seen.append(model_request)
return "response"
return answer
assert mw.wrap_model_call(request, handler) == "response"
assert mw.wrap_model_call(request, handler) is answer
assert len(seen) == 1
sent = seen[0]
assert sent.system_message is not None
@ -704,12 +706,13 @@ class TestWrapModelCall:
# Second call: the reminder was drained, so only the system prompt is
# injected and the original messages pass through untouched.
seen.clear()
assert mw.wrap_model_call(request, handler) == "response"
assert mw.wrap_model_call(request, handler) is answer
assert len(seen) == 1
assert seen[0].messages == state["messages"]
def test_pending_reminder_survives_a_failed_model_call(self):
"""A call that raises is retried by LLMErrorHandlingMiddleware through this wrap; the reminder must still be sent."""
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
def test_pending_reminder_survives_a_failed_model_call(self, failure):
"""A call that raises or returns an empty stop response is retried by LLMErrorHandlingMiddleware through this wrap; the reminder must still be sent."""
mw = TodoMiddleware()
runtime = _make_runtime()
state = {"messages": [_ai_no_tool_calls()], "todos": _incomplete_todos()}
@ -717,16 +720,22 @@ class TestWrapModelCall:
request = _make_model_request(state["messages"], runtime=runtime)
sent: list[list[Any]] = []
answer = AIMessage(content="response")
def flaky_handler(model_request: ModelRequest):
sent.append(model_request.messages)
if len(sent) == 1:
if failure == "empty-response":
return AIMessage(content="", response_metadata={"finish_reason": "stop"})
raise RuntimeError("503 Service Unavailable")
return "response"
return answer
with pytest.raises(RuntimeError):
if failure == "empty-response":
mw.wrap_model_call(request, flaky_handler)
assert mw.wrap_model_call(request, flaky_handler) == "response"
else:
with pytest.raises(RuntimeError):
mw.wrap_model_call(request, flaky_handler)
assert mw.wrap_model_call(request, flaky_handler) is answer
assert [len(_todo_completion_reminders(messages)) for messages in sent] == [1, 1]
# Restoring is not a new reminder: the retry must not spend the cap.
@ -1013,8 +1022,10 @@ class TestTodoMiddlewareAgentGraphIntegration:
assert mw._pending_completion_reminders == {}
assert mw._completion_reminder_counts == {}
def test_completion_reminder_survives_a_retried_model_call_in_real_agent_graph(self):
"""LLMErrorHandlingMiddleware retries a failed call by running the inner wraps again; the retry must still carry the reminder."""
@pytest.mark.parametrize("invoke_async", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
def test_completion_reminder_survives_a_retried_model_call_in_real_agent_graph(self, failure, invoke_async):
"""LLMErrorHandlingMiddleware retries a failed call or an empty stop response by running the inner wraps again; the retry must still carry the reminder."""
from deerflow.agents.middlewares.llm_error_handling_middleware import LLMErrorHandlingMiddleware
from deerflow.config.app_config import AppConfig, LlmCallConfig
from deerflow.config.sandbox_config import SandboxConfig
@ -1032,6 +1043,8 @@ class TestTodoMiddlewareAgentGraphIntegration:
if not self._failed and _todo_completion_reminders(messages):
self._failed = True
self._seen_messages.append(list(messages))
if failure == "empty-response":
return ChatResult(generations=[ChatGeneration(message=AIMessage(content="", response_metadata={"finish_reason": "stop"}))])
raise ProviderUnavailable()
return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
@ -1063,10 +1076,9 @@ class TestTodoMiddlewareAgentGraphIntegration:
state_schema=ThreadState,
)
result = graph.invoke(
{"messages": [("user", "finish all todos")]},
context={"thread_id": "retry-thread", "run_id": "retry-run"},
)
invoke_args = ({"messages": [("user", "finish all todos")]},)
invoke_kwargs = {"context": {"thread_id": "retry-thread", "run_id": "retry-run"}}
result = asyncio.run(graph.ainvoke(*invoke_args, **invoke_kwargs)) if invoke_async else graph.invoke(*invoke_args, **invoke_kwargs)
# write_todos, the premature exit, the failed attempt and its retry, then
# the second reminder: the retry did not spend the two-reminder cap.

View File

@ -1,3 +1,4 @@
import asyncio
from types import SimpleNamespace
from unittest.mock import MagicMock
@ -186,8 +187,10 @@ class TestTokenBudgetWarning:
assert sent[2].name == "budget_warning"
assert "TOKEN BUDGET WARNING" in sent[2].content
def test_warning_survives_a_failed_model_call(self):
"""A call that raises is retried by LLMErrorHandlingMiddleware through this wrap; the warning must still be sent."""
@pytest.mark.parametrize("invoke_async", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
def test_warning_survives_a_failed_model_call(self, failure, invoke_async):
"""A call that raises or returns an empty stop response is retried by LLMErrorHandlingMiddleware through this wrap; the warning must still be sent."""
config = TokenBudgetConfig(max_tokens=100000, warn_threshold=0.8, enabled=True)
mw = TokenBudgetMiddleware.from_config(config)
runtime = _make_runtime()
@ -199,14 +202,30 @@ class TestTokenBudgetWarning:
def flaky_handler(req):
sent.append(req.messages)
if len(sent) == 1:
if failure == "empty-response":
return AIMessage(content="", response_metadata={"finish_reason": "stop"})
raise RuntimeError("503 Service Unavailable")
return MagicMock()
return AIMessage(content="answer")
with pytest.raises(RuntimeError):
mw.wrap_model_call(request, flaky_handler)
mw.wrap_model_call(request, flaky_handler)
def call():
if not invoke_async:
return mw.wrap_model_call(request, flaky_handler)
assert [any(getattr(message, "name", None) == "budget_warning" for message in messages) for messages in sent] == [True, True]
async def async_handler(req):
return flaky_handler(req)
return asyncio.run(mw.awrap_model_call(request, async_handler))
if failure == "empty-response":
call()
else:
with pytest.raises(RuntimeError):
call()
call()
call()
# The answered call spends the warning; a later call goes out without it.
assert [any(getattr(message, "name", None) == "budget_warning" for message in messages) for messages in sent] == [True, True, False]
def test_warn_only_once_per_run(self):
config = TokenBudgetConfig(max_tokens=100000, warn_threshold=0.8, enabled=True)

View File

@ -9,7 +9,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langgraph.types import Command
from deerflow.agents.middlewares.tool_progress_middleware import (
@ -1362,7 +1362,9 @@ async def test_awrap_tool_call_malformed_meta_passthrough():
assert mw._phase_states.get("t1", {}).get("web_search") is None
def test_hint_survives_a_failed_sync_model_call():
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
def test_hint_survives_a_failed_sync_model_call(failure):
"""A call that raises or returns an empty stop response is retried by LLMErrorHandlingMiddleware through this wrap; the hint must still be sent."""
mw = _make_mw(stagnation_threshold=2, warn_escalation_count=5)
rt = _make_runtime()
req = _make_tool_request(runtime=rt)
@ -1376,19 +1378,27 @@ def test_hint_survives_a_failed_sync_model_call():
def flaky_handler(r):
sent.append(r.messages)
if len(sent) == 1:
if failure == "empty-response":
return AIMessage(content="", response_metadata={"finish_reason": "stop"})
raise RuntimeError("503 Service Unavailable")
return MagicMock()
return AIMessage(content="answer")
with pytest.raises(RuntimeError):
if failure == "empty-response":
mw.wrap_model_call(model_req, flaky_handler)
else:
with pytest.raises(RuntimeError):
mw.wrap_model_call(model_req, flaky_handler)
mw.wrap_model_call(model_req, flaky_handler)
mw.wrap_model_call(model_req, flaky_handler)
assert [any(isinstance(m, HumanMessage) and "PROGRESS HINT" in m.content for m in messages) for messages in sent] == [True, True]
# The answered call spends the hint; a later call goes out without it.
assert [any(isinstance(m, HumanMessage) and "PROGRESS HINT" in m.content for m in messages) for messages in sent] == [True, True, False]
@pytest.mark.anyio
async def test_hint_survives_a_failed_model_call():
"""A call that raises is retried by LLMErrorHandlingMiddleware through this wrap; the hint must still be sent."""
@pytest.mark.parametrize("failure", ["provider-error", "empty-response"])
async def test_hint_survives_a_failed_model_call(failure):
"""A call that raises or returns an empty stop response is retried by LLMErrorHandlingMiddleware through this wrap; the hint must still be sent."""
mw = _make_mw(stagnation_threshold=2, warn_escalation_count=5)
rt = _make_runtime()
req = _make_tool_request(runtime=rt)
@ -1402,14 +1412,21 @@ async def test_hint_survives_a_failed_model_call():
async def flaky_handler(r):
sent.append(r.messages)
if len(sent) == 1:
if failure == "empty-response":
return AIMessage(content="", response_metadata={"finish_reason": "stop"})
raise RuntimeError("503 Service Unavailable")
return MagicMock()
return AIMessage(content="answer")
with pytest.raises(RuntimeError):
if failure == "empty-response":
await mw.awrap_model_call(model_req, flaky_handler)
else:
with pytest.raises(RuntimeError):
await mw.awrap_model_call(model_req, flaky_handler)
await mw.awrap_model_call(model_req, flaky_handler)
await mw.awrap_model_call(model_req, flaky_handler)
assert [any(isinstance(m, HumanMessage) and "PROGRESS HINT" in m.content for m in messages) for messages in sent] == [True, True]
# The answered call spends the hint; a later call goes out without it.
assert [any(isinstance(m, HumanMessage) and "PROGRESS HINT" in m.content for m in messages) for messages in sent] == [True, True, False]
@pytest.mark.anyio
@ -1891,7 +1908,7 @@ def test_tool_progress_and_loop_detection_coexist_without_interfering():
def capture_handler(r):
captured.extend(r.messages)
return MagicMock()
return AIMessage(content="answer")
tp_mw.wrap_model_call(model_req, capture_handler)
injected = [m for m in captured if isinstance(m, HumanMessage)]