fix(agent): preserve state for required Codex compaction (#5883)
* fix(agent): preserve state for required Codex compaction * fix(codex): keep pending tool exchanges after compaction * refactor(agent): simplify compaction context forwarding and strengthen tests
This commit is contained in:
1 parent
155a6ada02
commit
c75192975c
5 files changed
+440
-24
No files matched your search
@@ -22,6 +22,7 @@ from loguru import logger
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
|
||||
from nanobot.providers.base import (
|
||||
CONTEXT_SAFETY_BUFFER,
|
||||
LLMResponse,
|
||||
LLMUsage,
|
||||
ProviderCallContext,
|
||||
@@ -63,7 +64,6 @@ ProviderCompactionConsolidator = Callable[
|
||||
Awaitable[str | None],
|
||||
]
|
||||
|
||||
CONTEXT_SAFETY_BUFFER = 1024
|
||||
# read_file has its own bound; exempt it to avoid persist->read->persist loops.
|
||||
TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS = frozenset({"read_file"})
|
||||
BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
|
||||
@@ -650,16 +650,6 @@ class ContextGovernor:
|
||||
tool_definitions=tool_definitions,
|
||||
request_context_tokens=request_context_tokens,
|
||||
)
|
||||
if pressure is not None:
|
||||
prepared = await self._compact_request_history(
|
||||
state,
|
||||
state.compaction,
|
||||
messages,
|
||||
pressure,
|
||||
tool_definitions=tool_definitions,
|
||||
)
|
||||
model_messages = prepared
|
||||
supplemental_messages = None
|
||||
provider_context = (
|
||||
state.conversation.prepare_request(
|
||||
transcript,
|
||||
@@ -672,6 +662,32 @@ class ContextGovernor:
|
||||
context_window_tokens=state.config.context_window_tokens,
|
||||
)
|
||||
)
|
||||
if pressure is not None:
|
||||
input_budget = self.input_budget(state.config)
|
||||
if (
|
||||
input_budget > 0
|
||||
and provider_context is not None
|
||||
and provider_context.conversation_state is not None
|
||||
and state.config.provider.supports_pre_request_compaction(state.config.model) is True
|
||||
):
|
||||
# Keep the resumable state until its owner has compacted it. Inline
|
||||
# server compaction alone cannot make an oversized request safe.
|
||||
provider_context = replace(provider_context, compaction_input_budget=input_budget)
|
||||
logger.info(
|
||||
"Request requires provider pre-request compaction for {}: tokens={} budget={} via {}",
|
||||
state.config.session_key or "default", pressure[0], input_budget, pressure[1],
|
||||
)
|
||||
else:
|
||||
prepared = await self._compact_request_history(
|
||||
state,
|
||||
state.compaction,
|
||||
messages,
|
||||
pressure,
|
||||
tool_definitions=tool_definitions,
|
||||
)
|
||||
provider_context = state.conversation.independent_request_context(
|
||||
context_window_tokens=state.config.context_window_tokens,
|
||||
)
|
||||
if state.events.publish is not None:
|
||||
provider_context = replace(
|
||||
provider_context or ProviderCallContext(), events=state.events,
|
||||
|
||||
@@ -36,6 +36,7 @@ STREAM_IDLE_TIMEOUT_ENV = "NANOBOT_STREAM_IDLE_TIMEOUT_S"
|
||||
DEFAULT_STREAM_IDLE_TIMEOUT_S = 90.0
|
||||
MAX_STREAM_IDLE_TIMEOUT_S = 3600.0
|
||||
RETRY_AFTER_BUFFER = 1
|
||||
CONTEXT_SAFETY_BUFFER = 1024
|
||||
|
||||
RetryEventCallback = Callable[[str], Awaitable[None]]
|
||||
LLMCallObserver = Callable[["LLMCallRecord"], None]
|
||||
@@ -273,6 +274,8 @@ class ProviderCallContext:
|
||||
# None opts out (auxiliary calls); an empty name denotes an unnamed preset.
|
||||
response_preset: str | None = None
|
||||
response_is_fallback: bool = False
|
||||
# A pre-request compactor must fit this budget before sending the pending input.
|
||||
compaction_input_budget: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -820,6 +823,10 @@ class LLMProvider(ABC):
|
||||
"""Whether requests may include provider-native context compaction."""
|
||||
return False
|
||||
|
||||
def supports_pre_request_compaction(self, model: str | None = None) -> bool:
|
||||
"""Whether the provider enforces compaction_input_budget before generation."""
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Sanitize message content: fix empty blocks, strip internal _meta fields.
|
||||
|
||||
@@ -188,6 +188,9 @@ class FallbackProvider(LLMProvider):
|
||||
def supports_native_compaction(self, model: str | None = None) -> bool:
|
||||
return self._primary.supports_native_compaction(model)
|
||||
|
||||
def supports_pre_request_compaction(self, model: str | None = None) -> bool:
|
||||
return self._primary.supports_pre_request_compaction(model)
|
||||
|
||||
def _primary_call_context(
|
||||
self,
|
||||
provider_context: ProviderCallContext,
|
||||
@@ -200,14 +203,7 @@ class FallbackProvider(LLMProvider):
|
||||
)
|
||||
if not self._primary.supports_native_compaction(model):
|
||||
context_window_tokens = None
|
||||
return ProviderCallContext(
|
||||
conversation_state=provider_context.conversation_state,
|
||||
context_window_tokens=context_window_tokens,
|
||||
session_id=provider_context.session_id,
|
||||
events=provider_context.events,
|
||||
response_preset=provider_context.response_preset,
|
||||
response_is_fallback=provider_context.response_is_fallback,
|
||||
)
|
||||
return replace(provider_context, context_window_tokens=context_window_tokens)
|
||||
|
||||
def _primary_available(self) -> bool:
|
||||
"""Return True if the primary provider is not currently tripped."""
|
||||
@@ -588,16 +584,24 @@ class FallbackProvider(LLMProvider):
|
||||
fallback_model,
|
||||
):
|
||||
state = None
|
||||
if provider_context.compaction_input_budget is not None and (
|
||||
state is None
|
||||
or not fallback_provider.supports_pre_request_compaction(fallback_model)
|
||||
):
|
||||
logger.warning(
|
||||
"Skipping fallback '{}': required pre-request compaction cannot resume",
|
||||
fallback_model,
|
||||
)
|
||||
continue
|
||||
context_window_tokens = (
|
||||
fallback.context_window_tokens
|
||||
if fallback_provider.supports_native_compaction(fallback_model)
|
||||
else None
|
||||
)
|
||||
fallback_kwargs["provider_context"] = ProviderCallContext(
|
||||
fallback_kwargs["provider_context"] = replace(
|
||||
provider_context,
|
||||
conversation_state=state,
|
||||
context_window_tokens=context_window_tokens,
|
||||
session_id=provider_context.session_id,
|
||||
events=provider_context.events,
|
||||
response_preset=(
|
||||
self._fallback_preset_names[idx] or ""
|
||||
if provider_context.response_preset is not None else None
|
||||
|
||||
@@ -19,6 +19,7 @@ from oauth_cli_kit.storage import FileTokenStorage
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.providers.base import (
|
||||
CONTEXT_SAFETY_BUFFER,
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
ProviderCallContext,
|
||||
@@ -46,6 +47,7 @@ from nanobot.providers.openai_responses import (
|
||||
responses_state_matches,
|
||||
)
|
||||
from nanobot.providers.registry import ProviderModelSpec, find_by_name
|
||||
from nanobot.utils.helpers import estimate_prompt_tokens
|
||||
|
||||
DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
|
||||
DEFAULT_OPENAI_CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models"
|
||||
@@ -145,6 +147,22 @@ class OpenAICodexProvider(LLMProvider):
|
||||
stage = "oauth_token"
|
||||
native_compaction_applied = False
|
||||
native_compaction_state: ProviderConversationState | None = None
|
||||
input_budget = (
|
||||
provider_context.compaction_input_budget if provider_context is not None else None
|
||||
)
|
||||
if input_budget is not None:
|
||||
if not replayed or not self.supports_pre_request_compaction(model):
|
||||
return LLMResponse(
|
||||
content="Required Codex pre-request compaction is unavailable; request not sent.",
|
||||
finish_reason="error", error_kind="context_window_exceeded",
|
||||
error_should_retry=False,
|
||||
preserve_provider_state_on_error=True,
|
||||
)
|
||||
if provider_context is not None and provider_context.context_window_tokens is not None:
|
||||
input_budget = min(
|
||||
input_budget,
|
||||
provider_context.context_window_tokens - max_tokens - CONTEXT_SAFETY_BUFFER,
|
||||
)
|
||||
try:
|
||||
token = await asyncio.to_thread(get_codex_token, proxy=self.proxy)
|
||||
headers = _build_headers(
|
||||
@@ -197,12 +215,18 @@ class OpenAICodexProvider(LLMProvider):
|
||||
self.supports_native_compaction(model)
|
||||
and replayed
|
||||
and sanitized_state is not None
|
||||
and compact_threshold is not None
|
||||
and responses_state_context_tokens(sanitized_state) >= compact_threshold
|
||||
and (
|
||||
input_budget is not None
|
||||
or (
|
||||
compact_threshold is not None
|
||||
and responses_state_context_tokens(sanitized_state) >= compact_threshold
|
||||
)
|
||||
)
|
||||
):
|
||||
stage = "codex_compaction"
|
||||
history_items = responses_state_items(sanitized_state) or []
|
||||
delta_items = input_items[len(history_items):]
|
||||
history_items, delta_items = _split_compaction_input(history_items, delta_items)
|
||||
compact_body = {
|
||||
**body,
|
||||
"input": [*history_items, {"type": "compaction_trigger"}],
|
||||
@@ -234,6 +258,11 @@ class OpenAICodexProvider(LLMProvider):
|
||||
except Exception as compact_error:
|
||||
if is_compaction_compatibility_error(compact_error):
|
||||
self._native_compaction_available = False
|
||||
if input_budget is not None:
|
||||
# Required compaction must not fall through to the
|
||||
# original oversized request. Preserve transport errors
|
||||
# so the normal retry policy can handle transient failures.
|
||||
raise
|
||||
logger.warning(
|
||||
"Codex native compaction unavailable; continuing without it "
|
||||
"(type={} status={} disabled={})",
|
||||
@@ -242,6 +271,20 @@ class OpenAICodexProvider(LLMProvider):
|
||||
not self._native_compaction_available,
|
||||
)
|
||||
|
||||
if input_budget is not None:
|
||||
estimated = estimate_prompt_tokens([{
|
||||
"role": "user", "content": json.dumps(body, ensure_ascii=False),
|
||||
}])
|
||||
if input_budget <= 0 or estimated > input_budget:
|
||||
return LLMResponse(
|
||||
content=(
|
||||
"Codex input still exceeds the local budget after native compaction "
|
||||
f"({estimated}/{input_budget} estimated tokens); request not sent."
|
||||
),
|
||||
finish_reason="error", error_kind="context_window_exceeded",
|
||||
error_should_retry=False,
|
||||
preserve_provider_state_on_error=True,
|
||||
)
|
||||
stage = "codex_request"
|
||||
result = await _send(body, emit_deltas=True)
|
||||
result.provider_compaction_applied = (
|
||||
@@ -253,6 +296,8 @@ class OpenAICodexProvider(LLMProvider):
|
||||
return result
|
||||
except Exception as e:
|
||||
response = _codex_error_response(e)
|
||||
if input_budget is not None and stage != "codex_request":
|
||||
response.preserve_provider_state_on_error = True
|
||||
exc_type = "CodexHTTPError" if isinstance(e, _CodexHTTPError) else type(e).__name__
|
||||
logger.warning(
|
||||
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
|
||||
@@ -362,6 +407,9 @@ class OpenAICodexProvider(LLMProvider):
|
||||
_ = model
|
||||
return self._native_compaction_available
|
||||
|
||||
def supports_pre_request_compaction(self, model: str | None = None) -> bool:
|
||||
return self.supports_native_compaction(model)
|
||||
|
||||
|
||||
def _strip_model_prefix(model: str) -> str:
|
||||
if model.startswith("openai-codex/") or model.startswith("openai_codex/"):
|
||||
@@ -393,6 +441,27 @@ def _without_response_item_ids(
|
||||
return body
|
||||
|
||||
|
||||
def _split_compaction_input(
|
||||
history_items: list[dict[str, Any]],
|
||||
delta_items: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""Keep pending outputs and their function calls after the compaction boundary."""
|
||||
pending_ids = {
|
||||
item["call_id"] for item in delta_items
|
||||
if item.get("type") == "function_call_output" and isinstance(item.get("call_id"), str)
|
||||
}
|
||||
history: list[dict[str, Any]] = []
|
||||
pending_calls: list[dict[str, Any]] = []
|
||||
for item in history_items:
|
||||
if item.get("type") == "function_call" and item.get("call_id") in pending_ids:
|
||||
pending_calls.append(item)
|
||||
else:
|
||||
history.append(item)
|
||||
# Compaction rejects unanswered calls; the following generation request
|
||||
# needs each original call before its still-unsubmitted output.
|
||||
return history, [*pending_calls, *delta_items]
|
||||
|
||||
|
||||
def _retained_compaction_messages(
|
||||
input_items: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
|
||||
Reference in new issue
Block a user