fix(agent): serialize session inbox processing
This commit is contained in:
1 parent
56f7afcfe4
commit
4e2173c9eb
7 files changed
+486
-359
No files matched your search
+43
-63
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from copy import deepcopy
|
||||
@@ -60,7 +59,7 @@ from nanobot.utils.runtime import (
|
||||
|
||||
ContinuationCallback = Callable[[], str | None]
|
||||
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
InjectionCallback = Callable[..., Awaitable[Iterable[Any] | None]]
|
||||
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
|
||||
|
||||
_DEFAULT_ERROR_MESSAGE = "Sorry, I encountered an error calling the AI model."
|
||||
_ARREARAGE_ERROR_MESSAGE = (
|
||||
@@ -70,8 +69,6 @@ _ARREARAGE_ERROR_MESSAGE = (
|
||||
_PERSISTED_MODEL_ERROR_PLACEHOLDER = "[Assistant reply unavailable due to model error.]"
|
||||
_MAX_EMPTY_RETRIES = 2
|
||||
_MAX_LENGTH_RECOVERIES = 3
|
||||
_MAX_INJECTIONS_PER_TURN = 3
|
||||
_MAX_INJECTION_CYCLES = 5
|
||||
|
||||
|
||||
def _restore_outer_whitespace(content: str, original: str | None) -> str:
|
||||
@@ -164,19 +161,11 @@ class AgentRunner:
|
||||
iteration: int | None = None,
|
||||
allow_continuation: bool = False,
|
||||
wait_at_terminal: bool = False,
|
||||
drain_callback: bool = True,
|
||||
) -> tuple[bool, int]:
|
||||
"""Drain pending injections. Returns (should_continue, updated_cycles).
|
||||
|
||||
If injections are found and we haven't exceeded _MAX_INJECTION_CYCLES,
|
||||
append them to *messages* (and emit a checkpoint if *assistant_message*
|
||||
and *iteration* are both provided) and return (True, cycles+1) so the
|
||||
caller continues the iteration loop. Otherwise return (False, cycles).
|
||||
"""
|
||||
injections: list[dict[str, Any]] = []
|
||||
real_injection = False
|
||||
if injection_cycles < _MAX_INJECTION_CYCLES:
|
||||
injections = await self._drain_injections(spec)
|
||||
real_injection = bool(injections)
|
||||
"""Append one pending-input snapshot and return whether execution continues."""
|
||||
injections = await self._drain_injections(spec) if drain_callback else []
|
||||
real_injection = bool(injections)
|
||||
if not injections and allow_continuation and assistant_message is not None:
|
||||
continuation = self._build_continuation_message(spec)
|
||||
if continuation is not None:
|
||||
@@ -184,7 +173,7 @@ class AgentRunner:
|
||||
if (
|
||||
not injections
|
||||
and wait_at_terminal
|
||||
and injection_cycles < _MAX_INJECTION_CYCLES
|
||||
and drain_callback
|
||||
):
|
||||
injections = await self._drain_injections(spec, terminal=True)
|
||||
real_injection = bool(injections)
|
||||
@@ -214,8 +203,8 @@ class AgentRunner:
|
||||
self._append_injected_messages(messages, injections)
|
||||
if real_injection:
|
||||
logger.info(
|
||||
"Injected {} follow-up message(s) {} ({}/{})",
|
||||
len(injections), phase, injection_cycles, _MAX_INJECTION_CYCLES,
|
||||
"Injected {} follow-up message(s) {} (snapshot {})",
|
||||
len(injections), phase, injection_cycles,
|
||||
)
|
||||
else:
|
||||
logger.info("Injected caller-requested continuation {}", phase)
|
||||
@@ -241,13 +230,7 @@ class AgentRunner:
|
||||
*,
|
||||
terminal: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Drain pending user messages via the injection callback.
|
||||
|
||||
Returns normalized user messages (capped by
|
||||
``_MAX_INJECTIONS_PER_TURN``), or an empty list when there is
|
||||
nothing to inject. Messages beyond the cap are logged so they
|
||||
are not silently lost.
|
||||
"""
|
||||
"""Drain one pending-input snapshot via the injection callback."""
|
||||
callback = (
|
||||
spec.terminal_injection_callback
|
||||
if terminal
|
||||
@@ -256,18 +239,7 @@ class AgentRunner:
|
||||
if callback is None:
|
||||
return []
|
||||
try:
|
||||
signature = inspect.signature(callback)
|
||||
accepts_limit = (
|
||||
"limit" in signature.parameters
|
||||
or any(
|
||||
parameter.kind is inspect.Parameter.VAR_KEYWORD
|
||||
for parameter in signature.parameters.values()
|
||||
)
|
||||
)
|
||||
if accepts_limit:
|
||||
items = await callback(limit=_MAX_INJECTIONS_PER_TURN)
|
||||
else:
|
||||
items = await callback()
|
||||
items = await callback()
|
||||
except Exception:
|
||||
logger.exception("injection_callback failed")
|
||||
return []
|
||||
@@ -286,13 +258,6 @@ class AgentRunner:
|
||||
content = getattr(item, "content") if hasattr(item, "content") else str(item)
|
||||
if self._has_injection_content(content):
|
||||
injected_messages.append({"role": "user", "content": content})
|
||||
if len(injected_messages) > _MAX_INJECTIONS_PER_TURN:
|
||||
dropped = len(injected_messages) - _MAX_INJECTIONS_PER_TURN
|
||||
logger.warning(
|
||||
"Injection callback returned {} messages, capping to {} ({} dropped)",
|
||||
len(injected_messages), _MAX_INJECTIONS_PER_TURN, dropped,
|
||||
)
|
||||
injected_messages = injected_messages[:_MAX_INJECTIONS_PER_TURN]
|
||||
return injected_messages
|
||||
|
||||
@staticmethod
|
||||
@@ -433,6 +398,18 @@ class AgentRunner:
|
||||
)
|
||||
|
||||
for iteration in range(spec.max_iterations):
|
||||
# The session inbox cuts a finite snapshot before every model call.
|
||||
# This includes follow-ups that arrived before the first request and
|
||||
# messages received while the previous request or tools were running.
|
||||
drained_before_request, injection_cycles = await self._try_drain_injections(
|
||||
spec,
|
||||
messages,
|
||||
None,
|
||||
injection_cycles,
|
||||
phase="before model call",
|
||||
)
|
||||
if drained_before_request:
|
||||
had_injections = True
|
||||
context = AgentHookContext(
|
||||
iteration=iteration,
|
||||
messages=messages,
|
||||
@@ -568,13 +545,6 @@ class AgentRunner:
|
||||
)
|
||||
empty_content_retries = 0
|
||||
length_recovery_parts.clear()
|
||||
# Checkpoint 1: drain injections after tools, before next LLM call
|
||||
_drained, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after tool execution",
|
||||
)
|
||||
if _drained:
|
||||
had_injections = True
|
||||
await hook.after_iteration(context)
|
||||
continue
|
||||
|
||||
@@ -687,6 +657,10 @@ class AgentRunner:
|
||||
# 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.
|
||||
can_make_followup_request = (
|
||||
iteration + 1 < spec.max_iterations
|
||||
or spec.finalize_on_max_iterations
|
||||
)
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, assistant_message, injection_cycles,
|
||||
conversation_state=conversation_state,
|
||||
@@ -700,6 +674,7 @@ class AgentRunner:
|
||||
and response.finish_reason
|
||||
not in {"error", "length", "refusal", "content_filter"}
|
||||
),
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -727,6 +702,7 @@ class AgentRunner:
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after LLM error",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -746,6 +722,7 @@ class AgentRunner:
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after empty response",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -789,19 +766,22 @@ class AgentRunner:
|
||||
break
|
||||
else:
|
||||
stop_reason = "max_iterations"
|
||||
# Drain any remaining injections so they are appended to the
|
||||
# conversation history instead of being re-published as
|
||||
# independent inbound messages by _dispatch's finally block.
|
||||
# We include them before the no-tools finalization pass so the
|
||||
# final response can account for every known follow-up.
|
||||
drained_after_max_iterations, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after max_iterations",
|
||||
)
|
||||
if drained_after_max_iterations:
|
||||
had_injections = True
|
||||
terminal_content = None
|
||||
if spec.finalize_on_max_iterations:
|
||||
# The no-tools finalization is a real model boundary, so include
|
||||
# exactly the inputs waiting before that request. Without this
|
||||
# request, leave them in the session inbox for its worker.
|
||||
drained_after_max_iterations, injection_cycles = (
|
||||
await self._try_drain_injections(
|
||||
spec,
|
||||
messages,
|
||||
None,
|
||||
injection_cycles,
|
||||
phase="before max-iterations finalization",
|
||||
)
|
||||
)
|
||||
if drained_after_max_iterations:
|
||||
had_injections = True
|
||||
terminal_content, usage = await self._try_finalize_after_max_iterations(
|
||||
spec,
|
||||
hook,
|
||||
|
||||
Reference in new issue
Block a user