fix(ui): surface model retry status (NAN-34) (#5504)

This commit is contained in:
chengyongru authored and GitHub committed 2026-09-07 15:12:39 +08:00
1 parent 0b1fa0c3e4
commit b581a496a6
52 files changed
+1697 -55

No files matched your search

+6
View File
@@ -155,6 +155,7 @@ class TurnContext:
final_content: str | None = None
all_messages: list[dict[str, Any]] = field(default_factory=list)
stop_reason: str = ""
failure_error_kind: str | None = None
streamed_content: bool = False
input_persisted_early: bool = False
@@ -2012,6 +2013,7 @@ class AgentLoop:
ctx.summary_checkpoint = result.summary_checkpoint
ctx.provider_compaction_applied = result.provider_compaction_applied
ctx.stop_reason = result.stop_reason
ctx.failure_error_kind = result.failure_error_kind
if (
ctx.kind is TurnKind.USER
and (ctx.delivery.route.channel, ctx.delivery.route.chat_id) in message_sends
@@ -2073,6 +2075,10 @@ class AgentLoop:
)
async def _prepare_outbound(self, ctx: TurnContext) -> None:
ctx.delivery.record_stop_reason(
ctx.stop_reason,
failure_error_kind=ctx.failure_error_kind,
)
if ctx.suppress_response:
ctx.outbound = None
return
+4
View File
@@ -130,6 +130,7 @@ class AgentRunResult:
round_usages: list[LLMUsage] = field(default_factory=list)
stop_reason: str = "completed"
error: str | None = None
failure_error_kind: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list)
had_injections: bool = False
# Terminal tail to emit when the preceding final-content prefix was already streamed.
@@ -396,6 +397,7 @@ class AgentRunner:
usage: LLMUsage | None = None
round_usages: list[LLMUsage] = []
error: str | None = None
failure_error_kind: str | None = None
stop_reason = "completed"
tool_events: list[dict[str, str]] = []
external_lookup_counts: dict[str, int] = {}
@@ -730,6 +732,7 @@ class AgentRunner:
had_injections = True
length_recovery_parts.clear()
continue
failure_error_kind = LLMProvider.public_error_kind(response)
break
if is_blank_text(clean):
final_content = EMPTY_FINAL_RESPONSE_MESSAGE
@@ -827,6 +830,7 @@ class AgentRunner:
round_usages=round_usages,
stop_reason=stop_reason,
error=error,
failure_error_kind=failure_error_kind,
tool_events=tool_events,
had_injections=had_injections,
pending_stream_content=pending_stream_content,
+39 -1
View File
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import (
RetryStatusEvent,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
@@ -61,6 +62,14 @@ def _bind_events(
return EventSink(publish, accepts)
def _turn_outcome(stop_reason: object) -> tuple[str, str | None]:
if stop_reason == "error":
return "failed", "model"
if stop_reason == "tool_error":
return "failed", "tool"
return "completed", None
class TurnDeliveryFactory:
"""Route turn delivery and session-level notifications."""
@@ -182,6 +191,9 @@ class TurnDelivery:
_stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False)
_routed_events: EventSink = field(init=False)
_stop_reason: str | None = field(init=False, default=None)
_failure_error_kind: str | None = field(init=False, default=None)
_retry_status: RetryStatusEvent | None = field(init=False, default=None)
def __post_init__(self) -> None:
self._routed_events = _bind_events(self.bus, self.route)
@@ -244,6 +256,15 @@ class TurnDelivery:
def record_usage(self, round_usages: list[LLMUsage]) -> None:
self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages)
def record_stop_reason(
self,
stop_reason: str,
*,
failure_error_kind: str | None = None,
) -> None:
self._stop_reason = stop_reason
self._failure_error_kind = failure_error_kind
def background_response(
self,
content: str | None,
@@ -276,12 +297,16 @@ class TurnDelivery:
*,
publish_completion: bool,
) -> None:
stop_reason = self._stop_reason
if stop_reason is None and response is not None:
stop_reason = cast(str | None, response.metadata.get("_stop_reason"))
completed_channel = self.lifecycle_message.channel
completed_chat_id = self.lifecycle_message.chat_id
if response is not None:
await self.bus.publish_outbound(response)
completed_channel = response.channel
completed_chat_id = response.chat_id
if response.channel != "websocket" or stop_reason != "error":
await self.bus.publish_outbound(response)
elif self.lifecycle_message.channel == "cli":
await self.bus.publish_outbound(
OutboundMessage(
@@ -292,11 +317,20 @@ class TurnDelivery:
)
)
if publish_completion:
outcome, failure_kind = _turn_outcome(stop_reason)
await self.runtime_event_publisher.turn_completed(
channel=completed_channel,
chat_id=completed_chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=(self._failure_error_kind or (
self._retry_status.error_kind if failure_kind == "model" and self._retry_status else None
)),
failure_attempts=(
self._retry_status.attempt if failure_kind == "model" and self._retry_status else None
),
)
async def fail(self, *, publish_completion: bool) -> None:
@@ -314,6 +348,8 @@ class TurnDelivery:
chat_id=self.lifecycle_message.chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome="failed",
failure_kind="internal",
)
async def idle(self) -> None:
@@ -329,6 +365,8 @@ class TurnDelivery:
return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_event(self, event: AgentEvent) -> None:
if isinstance(event, RetryStatusEvent):
self._retry_status = event if event.state == "exhausted" else None
if isinstance(event, StreamDeltaEvent | StreamEndEvent):
if not self.streaming:
return
+5 -1
View File
@@ -5,6 +5,7 @@ from typing import Literal
from nanobot.bus.outbound_events import (
FileEditEvent,
ProgressEvent,
RetryStatusEvent,
StreamDeltaEvent,
StreamEndEvent,
)
@@ -20,6 +21,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
ContextCompactionEvent: "channel",
RetryWaitEvent: "lifecycle",
RecoveryStateEvent: "interactive",
RetryStatusEvent: "interactive",
}
@@ -33,5 +35,7 @@ def notification_is_deliverable(
if audience == "lifecycle":
return publish_lifecycle
if audience == "interactive":
return channel == "websocket"
return channel == "websocket" and (
event_type is not RetryStatusEvent or publish_lifecycle
)
return True
+6
View File
@@ -15,6 +15,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.events import AgentEvent
from nanobot.events import ContextCompactionEvent as ContextCompactionEvent
from nanobot.events import RecoveryStateEvent as RecoveryStateEvent
from nanobot.events import RetryStatusEvent as RetryStatusEvent
from nanobot.events import RetryWaitEvent as RetryWaitEvent
from nanobot.providers.base import LLMUsage
@@ -62,6 +63,11 @@ class TurnEndEvent(AgentEvent):
usage: LLMUsage | None = None
round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None
outcome: str = "completed"
failure_kind: str | None = None
failure_error_kind: str | None = None
failure_attempts: int | None = None
failure_message: str | None = None
@dataclass(frozen=True)
+12
View File
@@ -67,6 +67,10 @@ class TurnCompleted(AgentEvent):
usage: LLMUsage | None = None
# Logical model rounds in display order; recovery dispatches are aggregated.
round_usages: tuple[LLMUsage, ...] = ()
outcome: str = "completed"
failure_kind: str | None = None
failure_error_kind: str | None = None
failure_attempts: int | None = None
@dataclass(frozen=True)
@@ -259,6 +263,10 @@ class RuntimeEventPublisher:
chat_id: str,
session_key: str,
metadata: dict[str, Any] | None,
outcome: str = "completed",
failure_kind: str | None = None,
failure_error_kind: str | None = None,
failure_attempts: int | None = None,
) -> None:
await self.bus.publish(
TurnCompleted(
@@ -272,6 +280,10 @@ class RuntimeEventPublisher:
runtime=self._turn_runtime.pop(session_key, None),
usage=self._turn_usage.pop(session_key, None),
round_usages=self._turn_round_usages.pop(session_key, ()),
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
failure_attempts=failure_attempts,
)
)
@@ -29,6 +29,8 @@ from nanobot.bus.outbound_events import (
GoalStatusEvent,
ProgressEvent,
RecoveryStateEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent,
SessionUpdatedEvent,
TurnEndEvent,
@@ -2806,6 +2808,106 @@ async def test_send_turn_end_emits_turn_end_event() -> None:
]
@pytest.mark.asyncio
async def test_retry_status_is_transient_and_turn_scoped(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 120.0)
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={WEBUI_TURN_METADATA_KEY: "turn-1"},
event=RetryStatusEvent(
state="waiting",
attempt=2,
max_attempts=4,
error_kind="connection",
next_retry_at=123.5,
),
))
assert _sent_ws_payloads(mock_ws) == [{
"event": "retry_status",
"chat_id": "chat-1",
"turn_id": "turn-1",
"state": "waiting",
"attempt": 2,
"max_attempts": 4,
"error_kind": "connection",
"retry_after_s": 3.5,
}]
@pytest.mark.asyncio
async def test_legacy_retry_wait_is_not_sent_or_persisted() -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
channel._persist_turn_transcript_event = MagicMock(return_value=True)
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="Model request failed, retry in 2s (attempt 1).",
event=RetryWaitEvent(
content="Model request failed, retry in 2s (attempt 1).",
),
))
assert _sent_ws_payloads(mock_ws) == []
channel._persist_turn_transcript_event.assert_not_called()
@pytest.mark.asyncio
async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
event=TurnEndEvent(
outcome="failed",
failure_kind="model",
failure_error_kind="connection",
failure_attempts=4,
failure_message="Model provider request failed.",
),
))
assert _sent_ws_payloads(mock_ws)[0] == {
"event": "turn_end",
"chat_id": "chat-1",
"outcome": "failed",
"failure_kind": "model",
"failure_error_kind": "connection",
"failure_attempts": 4,
"failure_message": "Model provider request failed.",
}
@pytest.mark.asyncio
async def test_context_compaction_started_is_live_only() -> None:
bus = MagicMock()
+11
View File
@@ -24,6 +24,17 @@ class RetryWaitEvent(AgentEvent):
content: str = ""
@dataclass(frozen=True)
class RetryStatusEvent(AgentEvent):
"""Sanitized retry lifecycle for one model request chain."""
state: Literal["waiting", "recovered", "cleared", "exhausted"]
attempt: int
max_attempts: int | None
error_kind: str
next_retry_at: float | None = None
@dataclass(frozen=True)
class RecoveryStateEvent(AgentEvent):
status: str
+94 -9
View File
@@ -19,7 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
import json_repair
from loguru import logger
from nanobot.events import NO_EVENTS, EventSink, RetryWaitEvent
from nanobot.events import NO_EVENTS, EventSink, RetryStatusEvent, RetryWaitEvent
from nanobot.utils.helpers import sanitize_surrogates_deep
if TYPE_CHECKING:
@@ -33,6 +33,7 @@ RETRY_AFTER_BUFFER = 1
RetryEventCallback = Callable[[str], Awaitable[None]]
LLMCallObserver = Callable[["LLMCallRecord"], None]
ProviderCompactionScope = Literal["prior_context", "current_request"]
RetryStatusCallback = Callable[[RetryStatusEvent], Awaitable[None]]
def resolve_stream_idle_timeout_s(
@@ -1453,6 +1454,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse:
"""Call chat_stream() with retry on transient provider failures."""
if max_tokens is self._SENTINEL or max_tokens is None:
@@ -1489,8 +1491,8 @@ class LLMProvider(ABC):
kw["provider_context"] = provider_context
if on_stream_recover and getattr(self, "supports_stream_recover_callback", False):
kw["on_stream_recover"] = _recover_stream
on_retry_wait, on_retry_exhausted = self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted,
on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
)
return await self._run_chat_with_retry(
kw,
@@ -1499,6 +1501,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=lambda: not has_streamed_content,
on_stream_recover=_recover_stream if on_stream_recover else None,
)
@@ -1516,6 +1519,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse:
"""Call chat() with retry on transient provider failures.
@@ -1540,8 +1544,8 @@ class LLMProvider(ABC):
)
if provider_context is not None:
kw["provider_context"] = provider_context
on_retry_wait, on_retry_exhausted = self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted,
on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
)
return await self._run_chat_with_retry(
kw,
@@ -1550,14 +1554,16 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
)
@staticmethod
def _retry_notifications(
async def _retry_notifications(
context: ProviderCallContext | None,
on_wait: RetryEventCallback | None,
on_exhausted: RetryEventCallback | None,
) -> tuple[RetryEventCallback | None, RetryEventCallback | None]:
on_status: RetryStatusCallback | None,
) -> tuple[RetryEventCallback | None, RetryEventCallback | None, RetryStatusCallback | None]:
"""Adapt once at the retry-chain boundary, before candidate callbacks.
Explicit callbacks retain precedence. In particular a fallback candidate
@@ -1568,7 +1574,12 @@ class LLMProvider(ABC):
await context.events.emit(RetryWaitEvent(content))
on_wait = publish
return on_wait, on_exhausted or on_wait
if on_status is None and context is not None and context.events.accepts(RetryStatusEvent):
on_status = context.events.emit
# A turn may continue after an exhausted request; the new chain owns
# its own retry state, including when its first attempt is terminal.
await on_status(RetryStatusEvent("cleared", 1, None, "unknown"))
return on_wait, on_exhausted or on_wait, on_status
async def _run_chat_with_retry(
self,
@@ -1579,6 +1590,7 @@ class LLMProvider(ABC):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -1591,6 +1603,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=should_retry_guard,
on_stream_recover=on_stream_recover,
)
@@ -1676,8 +1689,12 @@ class LLMProvider(ABC):
*,
attempt: int,
persistent: bool,
on_retry_wait: Callable[[str], Awaitable[None]] | None = None,
error_kind: str,
max_attempts: int | None,
on_retry_wait: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> None:
next_retry_at = time.time() + max(0.0, delay)
remaining = max(0.0, delay)
while remaining > 0:
if on_retry_wait:
@@ -1686,10 +1703,34 @@ class LLMProvider(ABC):
f"Model request failed, {kind} in {max(1, int(round(remaining)))}s "
f"(attempt {attempt})."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="waiting",
attempt=attempt,
max_attempts=max_attempts,
error_kind=error_kind,
next_retry_at=next_retry_at,
)
)
chunk = min(remaining, self._RETRY_HEARTBEAT_CHUNK)
await asyncio.sleep(chunk)
remaining -= chunk
@classmethod
def public_error_kind(cls, response: LLMResponse) -> str:
"""Return a stable public category without exposing provider details."""
if cls.is_arrearage_response(response):
return "billing"
kind = (response.error_kind or "").strip().lower()
if kind in {"connection", "timeout"}:
return kind
if response.error_status_code == 429:
return "rate_limit"
if response.error_status_code is not None and response.error_status_code >= 500:
return "server"
return "unknown"
async def _run_with_retry(
self,
call: Callable[..., Awaitable[LLMResponse]],
@@ -1699,6 +1740,7 @@ class LLMProvider(ABC):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -1708,10 +1750,26 @@ class LLMProvider(ABC):
last_response: LLMResponse | None = None
last_error_key: str | None = None
identical_error_count = 0
async def _finish_retry_status(
state: Literal["recovered", "cleared"],
response: LLMResponse,
) -> None:
if attempt > 1 and on_retry_status:
await on_retry_status(
RetryStatusEvent(
state=state,
attempt=attempt,
max_attempts=None if persistent else len(delays) + 1,
error_kind=self.public_error_kind(response),
)
)
while True:
attempt += 1
response = await call(**kw)
if response.finish_reason != "error":
await _finish_retry_status("recovered", response)
return response
last_response = response
if should_retry_guard is not None and not should_retry_guard():
@@ -1737,6 +1795,7 @@ class LLMProvider(ABC):
logger.warning(
"LLM stream failed after content was emitted; skipping retry"
)
await _finish_retry_status("cleared", response)
return response
error_key = ((response.content or "").strip().lower() or None)
if error_key and error_key == last_error_key:
@@ -1779,7 +1838,12 @@ class LLMProvider(ABC):
# subsequent iterations do not repeat the error-retry cycle.
if result.finish_reason != "error":
self._strip_image_content_inplace(original_messages)
await _finish_retry_status(
"recovered" if result.finish_reason != "error" else "cleared",
result,
)
return result
await _finish_retry_status("cleared", response)
return response
if persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT:
@@ -1792,6 +1856,15 @@ class LLMProvider(ABC):
await on_retry_exhausted(
f"Persistent retry stopped after {identical_error_count} identical errors."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="exhausted",
attempt=attempt,
max_attempts=None,
error_kind=self.public_error_kind(response),
)
)
return response
if not persistent and attempt > len(delays):
@@ -1804,6 +1877,15 @@ class LLMProvider(ABC):
await on_retry_exhausted(
f"Model request failed after {attempt} attempts, giving up."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="exhausted",
attempt=attempt,
max_attempts=len(delays) + 1,
error_kind=self.public_error_kind(response),
)
)
break
retry_after = self._extract_retry_after_from_response(response)
@@ -1823,7 +1905,10 @@ class LLMProvider(ABC):
delay,
attempt=attempt,
persistent=persistent,
error_kind=self.public_error_kind(response),
max_attempts=None if persistent else len(delays) + 1,
on_retry_wait=on_retry_wait,
on_retry_status=on_retry_status,
)
return last_response if last_response is not None else await call(**kw) # pyright: ignore[reportUnnecessaryComparison]
+37 -8
View File
@@ -12,6 +12,7 @@ from typing import Any
from loguru import logger
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import (
GenerationSettings,
LLMCallObserver,
@@ -20,6 +21,7 @@ from nanobot.providers.base import (
ProviderCallContext,
ProviderConversationState,
RetryEventCallback,
RetryStatusCallback,
)
# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.
@@ -213,6 +215,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -229,6 +232,7 @@ class FallbackProvider(LLMProvider):
"retry_mode": retry_mode,
"on_retry_wait": on_retry_wait,
"on_retry_exhausted": on_retry_exhausted,
"on_retry_status": on_retry_status,
})
if stream:
return await self._primary.chat_stream_with_retry(**call_kwargs)
@@ -273,6 +277,7 @@ class FallbackProvider(LLMProvider):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
has_streamed=has_streamed,
on_stream_recover=recover_stream,
persistent_retry_guard=should_retry_guard,
@@ -328,6 +333,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None,
persistent_retry_guard: Callable[[], bool] | None,
@@ -336,22 +342,42 @@ class FallbackProvider(LLMProvider):
async def _call_chain(**chain_kwargs: Any) -> LLMResponse:
last_exhausted_message: str | None = None
last_exhausted_status: RetryStatusEvent | None = None
async def _capture_exhaustion(message: str) -> None:
nonlocal last_exhausted_message
last_exhausted_message = message
async def _capture_status(status: RetryStatusEvent) -> None:
nonlocal last_exhausted_status
if status.state == "exhausted":
last_exhausted_status = status
elif on_retry_status:
await on_retry_status(status)
async def _clear_status_for_fallback() -> None:
if last_exhausted_status is not None and on_retry_status is not None:
await on_retry_status(
replace(
last_exhausted_status,
state="cleared",
next_retry_at=None,
)
)
async def _call_candidate(
provider: LLMProvider,
candidate_kwargs: dict[str, Any],
) -> LLMResponse:
nonlocal last_exhausted_message
nonlocal last_exhausted_message, last_exhausted_status
last_exhausted_message = None
last_exhausted_status = None
return await call(provider, {
**candidate_kwargs,
"retry_mode": "standard",
"on_retry_wait": on_retry_wait,
"on_retry_exhausted": _capture_exhaustion,
"on_retry_status": _capture_status,
})
response = await self._try_with_fallback(
@@ -359,14 +385,13 @@ class FallbackProvider(LLMProvider):
chain_kwargs,
has_streamed=has_streamed,
on_stream_recover=on_stream_recover,
on_fallback_attempt=_clear_status_for_fallback,
)
if (
retry_mode != "persistent"
and response.finish_reason == "error"
and last_exhausted_message
and on_retry_exhausted
):
await on_retry_exhausted(last_exhausted_message)
if retry_mode != "persistent" and response.finish_reason == "error":
if last_exhausted_message and on_retry_exhausted:
await on_retry_exhausted(last_exhausted_message)
if last_exhausted_status and on_retry_status:
await on_retry_status(last_exhausted_status)
return response
if retry_mode != "persistent":
@@ -378,6 +403,7 @@ class FallbackProvider(LLMProvider):
retry_mode="persistent",
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=persistent_retry_guard,
on_stream_recover=on_stream_recover,
)
@@ -420,6 +446,7 @@ class FallbackProvider(LLMProvider):
kwargs: dict[str, Any],
has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
on_fallback_attempt: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
primary_model = kwargs.get("model") or self._primary.get_default_model()
primary_was_attempted = False
@@ -517,6 +544,8 @@ class FallbackProvider(LLMProvider):
"Fallback '{}' also failed, trying next fallback '{}'",
self._fallback_presets[idx - 1].model, fallback_model,
)
if on_fallback_attempt is not None:
await on_fallback_attempt()
try:
fallback_provider = self._provider_factory(fallback)
fallback_provider.set_llm_call_observer(self._llm_call_observer)
+20 -1
View File
@@ -558,7 +558,6 @@ class WebuiTurnCoordinator:
sessions: SessionManager
schedule_background: Callable[[Awaitable[None]], None]
recovery: RecoveryCoordinator | None = None
def subscribe(self) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events."""
unsubscribe = [
@@ -710,6 +709,10 @@ class WebuiTurnCoordinator:
context_window_tokens=(
event.runtime.context_window_tokens if event.runtime is not None else None
),
outcome=event.outcome,
failure_kind=event.failure_kind,
failure_error_kind=event.failure_error_kind,
failure_attempts=event.failure_attempts,
)
if self.recovery is not None:
await self.recovery.turn_completed(event.context.session_key)
@@ -753,6 +756,10 @@ class WebuiTurnCoordinator:
usage: LLMUsage | None = None,
round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
outcome: str = "completed",
failure_kind: str | None = None,
failure_error_kind: str | None = None,
failure_attempts: int | None = None,
) -> None:
if msg.channel != "websocket":
return
@@ -768,6 +775,18 @@ class WebuiTurnCoordinator:
usage=usage,
round_usages=round_usages,
context_window_tokens=context_window_tokens,
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
failure_attempts=failure_attempts,
failure_message=(
"Model provider request failed. Check the provider configuration or "
"service status, then try again."
if failure_kind == "model"
else "This turn failed and has ended."
if outcome == "failed"
else None
),
),
metadata=msg.metadata,
)
+6 -1
View File
@@ -12,6 +12,8 @@ from nanobot.bus.outbound_events import (
GoalStateSyncEvent,
GoalStatusEvent,
ProgressEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent,
SessionUpdatedEvent,
TurnEndEvent,
@@ -134,6 +136,8 @@ class WebUIOutboundProjector:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, RetryWaitEvent):
return
progress_event = event if isinstance(event, ProgressEvent) else None
if isinstance(event, RuntimeModelUpdatedEvent):
await self._transport.send_runtime_model_updated(
@@ -146,6 +150,7 @@ class WebUIOutboundProjector:
if not conns:
quiet_events = (
ProgressEvent,
RetryStatusEvent,
UserInputEvent,
TurnEndEvent,
SessionUpdatedEvent,
@@ -179,7 +184,7 @@ class WebUIOutboundProjector:
provenance=event.provenance,
)
return
notification = project_notification(msg.chat_id, event)
notification = project_notification(msg.chat_id, event, msg.metadata)
if notification is not None:
if conns or notification.deliver_offline:
kwargs: dict[str, Any] = (
+53 -2
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import time
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
@@ -9,6 +10,7 @@ from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
from nanobot.bus.outbound_events import (
ContextCompactionEvent,
RecoveryStateEvent,
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.events import AgentEvent
@@ -29,6 +31,15 @@ class RecoveryStateWirePayload(_ChatWirePayload):
can_continue: NotRequired[bool]
class RetryStatusWirePayload(_ChatWirePayload):
event: Literal["retry_status"]
state: str
attempt: int
max_attempts: NotRequired[int]
error_kind: str
retry_after_s: NotRequired[float]
class TurnEndWirePayload(_ChatWirePayload):
event: Literal["turn_end"]
latency_ms: NotRequired[int]
@@ -36,6 +47,11 @@ class TurnEndWirePayload(_ChatWirePayload):
usage: NotRequired[dict[str, int]]
round_usages: NotRequired[list[dict[str, int]]]
context_window_tokens: NotRequired[int]
outcome: NotRequired[str]
failure_kind: NotRequired[str]
failure_error_kind: NotRequired[str]
failure_attempts: NotRequired[int]
failure_message: NotRequired[str]
class ContextCompactionWirePayload(_ChatWirePayload):
@@ -45,7 +61,7 @@ class ContextCompactionWirePayload(_ChatWirePayload):
WebUIWirePayload: TypeAlias = (
ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
)
WebUIWirePersistence: TypeAlias = Literal[
"transient",
@@ -97,7 +113,9 @@ class NotificationProjection:
attach_turn_metadata: bool = False
def project_notification(chat_id: str, event: AgentEvent | None) -> NotificationProjection | None:
def project_notification(
chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None,
) -> NotificationProjection | None:
"""Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ContextCompactionEvent):
return NotificationProjection(
@@ -106,11 +124,34 @@ def project_notification(chat_id: str, event: AgentEvent | None) -> Notification
deliver_offline=True,
attach_turn_metadata=True,
)
if isinstance(event, RetryStatusEvent):
return NotificationProjection(encode_retry_status(chat_id, event, metadata))
if isinstance(event, RecoveryStateEvent):
return NotificationProjection(encode_recovery_state(chat_id, event))
return None
def encode_retry_status(
chat_id: str,
event: RetryStatusEvent,
metadata: Mapping[str, object] | None = None,
) -> RetryStatusWirePayload:
"""Project one transient retry transition onto its stable wire shape."""
payload: RetryStatusWirePayload = {
"event": "retry_status",
"chat_id": chat_id,
"state": event.state,
"attempt": event.attempt,
"error_kind": event.error_kind,
}
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id:
payload["turn_id"] = turn_id
if event.max_attempts is not None:
payload["max_attempts"] = event.max_attempts
if event.next_retry_at is not None:
payload["retry_after_s"] = max(0.0, event.next_retry_at - time.time())
return payload
def encode_turn_end(
chat_id: str,
event: TurnEndEvent,
@@ -134,4 +175,14 @@ def encode_turn_end(
payload["round_usages"] = [item.to_turn_dict() for item in event.round_usages]
if event.context_window_tokens is not None:
payload["context_window_tokens"] = int(event.context_window_tokens)
if event.outcome != "completed":
payload["outcome"] = event.outcome
if event.failure_kind is not None:
payload["failure_kind"] = event.failure_kind
if event.failure_error_kind is not None:
payload["failure_error_kind"] = event.failure_error_kind
if event.failure_attempts is not None:
payload["failure_attempts"] = int(event.failure_attempts)
if event.failure_message is not None:
payload["failure_message"] = event.failure_message
return payload