fix(agent): preserve streamed replies after model failures (#6494)
* fix(agent): preserve streamed replies after model failures * test(webui): settle lazy imports and async settings saves * test(agent): synchronize estimation checks at the operation boundary * docs(webui): explain retained replies after stream failures
This commit is contained in:
1 parent
b6536bfc5e
commit
219c8bb2bc
31 files changed
+462
-27
No files matched your search
@@ -26,6 +26,8 @@ class AgentHookContext:
|
||||
tool_results: list[Any] = field(default_factory=list)
|
||||
tool_events: list[dict[str, str]] = field(default_factory=list)
|
||||
streamed_content: bool = False
|
||||
# Raw segments observed this round, retained only if its terminal response fails.
|
||||
streamed_content_parts: list[str] = field(default_factory=list, repr=False)
|
||||
streamed_reasoning: bool = False
|
||||
stream_continues_current_message: bool = False
|
||||
final_content: str | None = None
|
||||
|
||||
@@ -726,6 +726,23 @@ class AgentRunner:
|
||||
response,
|
||||
)
|
||||
|
||||
if response.finish_reason == "error":
|
||||
interrupted_parts = [
|
||||
content
|
||||
for part in context.streamed_content_parts
|
||||
if (content := extract_reasoning(None, None, part)[1])
|
||||
]
|
||||
interrupted_content = hook.finalize_content(
|
||||
context, "\n\n".join(interrupted_parts),
|
||||
)
|
||||
if not is_blank_text(interrupted_content):
|
||||
# This is unsynchronized output, not a completed response or
|
||||
# provider-owned projection. Keep it in the next native delta.
|
||||
messages.append({
|
||||
**build_assistant_message(interrupted_content),
|
||||
"_interrupted": True,
|
||||
})
|
||||
|
||||
# Check for mid-turn injections BEFORE signaling stream end.
|
||||
# If injections are found we keep the stream alive (resuming=True)
|
||||
# so streaming channels don't prematurely finalize the card.
|
||||
@@ -934,6 +951,13 @@ class AgentRunner:
|
||||
first_output_at: float | None = None
|
||||
generation_started_at: float | None = None
|
||||
generation_elapsed_s = 0.0
|
||||
stream_buf = ""
|
||||
|
||||
def _end_stream_segment() -> None:
|
||||
nonlocal stream_buf
|
||||
if stream_buf:
|
||||
context.streamed_content_parts.append(stream_buf)
|
||||
stream_buf = ""
|
||||
|
||||
def _generation_delta(delta: str) -> None:
|
||||
nonlocal first_output_at, generation_started_at
|
||||
@@ -981,6 +1005,8 @@ class AgentRunner:
|
||||
if event.get("kind") != "hosted_tool":
|
||||
return
|
||||
await _close_native_reasoning()
|
||||
if event.get("phase") == "start":
|
||||
_end_stream_segment()
|
||||
await hook.on_provider_tool_event(context, event)
|
||||
call_id = event.get("call_id")
|
||||
if not call_id:
|
||||
@@ -995,6 +1021,8 @@ class AgentRunner:
|
||||
thinking_buf = ""
|
||||
|
||||
async def _stream(delta: str) -> None:
|
||||
nonlocal stream_buf
|
||||
stream_buf += delta
|
||||
_generation_delta(delta)
|
||||
if delta:
|
||||
context.streamed_content = True
|
||||
@@ -1018,6 +1046,7 @@ class AgentRunner:
|
||||
async def _stream_recover() -> None:
|
||||
_pause_generation()
|
||||
await _close_native_reasoning()
|
||||
_end_stream_segment()
|
||||
await hook.on_stream_end(context, resuming=True)
|
||||
|
||||
kwargs.update(
|
||||
@@ -1039,6 +1068,7 @@ class AgentRunner:
|
||||
raise
|
||||
_pause_generation()
|
||||
await _close_native_reasoning()
|
||||
_end_stream_segment()
|
||||
if first_output_at is not None:
|
||||
response.ttft_ms = max(0, round((first_output_at - request_started_at) * 1000))
|
||||
if generation_elapsed_s > 0:
|
||||
|
||||
@@ -70,6 +70,7 @@ class RecoveryStateEvent(AgentEvent):
|
||||
attempts: int = 0
|
||||
can_continue: bool | None = None
|
||||
failure_error_kind: str | None = None
|
||||
reply_preserved: bool | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -1120,7 +1120,7 @@ class LLMProvider(ABC):
|
||||
),
|
||||
timeout=resolve_stream_idle_timeout_s(),
|
||||
)
|
||||
if on_content_delta and response.content:
|
||||
if on_content_delta and response.content and response.finish_reason != "error":
|
||||
await on_content_delta(response.content)
|
||||
return response
|
||||
|
||||
|
||||
@@ -452,4 +452,6 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str
|
||||
"authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown",
|
||||
}:
|
||||
payload["failure_error_kind"] = failure_error_kind
|
||||
if state.get("reply_preserved") is True:
|
||||
payload["reply_preserved"] = True
|
||||
return payload
|
||||
@@ -73,6 +73,7 @@ class RecoveryStateWirePayload(_ChatWirePayload):
|
||||
reason: NotRequired[str]
|
||||
can_continue: NotRequired[bool]
|
||||
failure_error_kind: NotRequired[str]
|
||||
reply_preserved: NotRequired[bool]
|
||||
|
||||
|
||||
class RetryStatusWirePayload(_ChatWirePayload):
|
||||
@@ -139,6 +140,8 @@ def encode_recovery_state(
|
||||
payload["can_continue"] = event.can_continue
|
||||
if event.failure_error_kind is not None:
|
||||
payload["failure_error_kind"] = event.failure_error_kind
|
||||
if event.reply_preserved is not None:
|
||||
payload["reply_preserved"] = event.reply_preserved
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
@@ -187,6 +187,8 @@ class RecoveryCoordinator:
|
||||
can_continue=any(message.get("role") == "user" for message in session.messages),
|
||||
)
|
||||
waiting["failure_error_kind"] = failure_error_kind or "unknown"
|
||||
if session.messages and session.messages[-1].get("_interrupted") is True:
|
||||
waiting["reply_preserved"] = True
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(route[1], waiting)
|
||||
return
|
||||
@@ -449,6 +451,7 @@ class RecoveryCoordinator:
|
||||
attempts=cast(int, state.get("attempts", 0)),
|
||||
can_continue=cast(bool | None, state.get("can_continue")),
|
||||
failure_error_kind=cast(str | None, state.get("failure_error_kind")),
|
||||
reply_preserved=cast(bool | None, state.get("reply_preserved")),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user