Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(providers): address #212 review on skip, classify, sticky

P.N. Beta567ef58789fa
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 993f2a4..bc2d8c0 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -1101,12 +1101,19 @@ class Agent(Generic[TMessage]):
await self._process_event(AgentAbortedEvent(reason=reason))
async def _run_hitl_resume(self) -> None:
- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run
+ from cubepi.providers.fallback import (
+ begin_fallback_run,
+ end_fallback_run,
+ get_active_index,
+ set_active_index,
+ )
token = begin_fallback_run()
+ set_active_index(self._fallback_active_index)
try:
await self._run_hitl_resume_body()
finally:
+ self._fallback_active_index = get_active_index()
end_fallback_run(token)
async def _run_hitl_resume_body(self) -> None:
diff --git a/cubepi/errors.py b/cubepi/errors.py
index 9645f7f..e87be65 100644
--- a/cubepi/errors.py
+++ b/cubepi/errors.py
@@ -171,11 +171,20 @@ _RATE_LIMIT_PATTERNS = (
re.compile(r"too many requests", re.IGNORECASE),
)
+_MODEL_NOT_FOUND_CODES = frozenset(
+ {
+ "model_not_found",
+ "model_not_available",
+ "invalid_model",
+ }
+)
+
_MODEL_NOT_FOUND_PATTERNS = (
re.compile(r"model[_ ]not[_ ]found", re.IGNORECASE),
- re.compile(r"does not exist", re.IGNORECASE),
re.compile(r"unknown model", re.IGNORECASE),
re.compile(r"invalid model", re.IGNORECASE),
+ re.compile(r"model .+ does not exist", re.IGNORECASE),
+ re.compile(r"does not exist.+model", re.IGNORECASE),
)
_CONTENT_FILTER_PATTERNS = (
@@ -252,16 +261,10 @@ def _first_str(*values: object) -> str | None:
return None
-def extract_error_code(exc: BaseException) -> str | None:
- """Best-effort vendor ``error_code`` from an SDK exception.
-
- Priority (OpenAI / OpenAI-compatible first, then Anthropic ``type``):
-
- 1. ``error.code`` / nested ``error.error.code`` / ``body.error.code``
- 2. ``error.type`` (Anthropic) / ``type``
- 3. ``param`` only when it identifies the model
- 4. Never the full human message
- """
+def _vendor_error_parts(
+ exc: BaseException,
+) -> tuple[str | None, str | None, str | None]:
+ """Return ``(code, type, param)`` from a vendor SDK exception."""
body = getattr(exc, "body", None)
err = getattr(exc, "error", None)
@@ -300,34 +303,57 @@ def extract_error_code(exc: BaseException) -> str | None:
nested_map.get("param") if nested_map else None,
body_error.get("param") if body_error else None,
)
+ return (
+ code.lower() if code else None,
+ typ.lower() if typ else None,
+ param.lower() if param else None,
+ )
+
+
+def extract_error_code(exc: BaseException) -> str | None:
+ """Best-effort vendor ``error_code`` from an SDK exception.
+
+ Priority (OpenAI / OpenAI-compatible first, then Anthropic ``type``):
+
+ 1. ``error.code`` / nested ``error.error.code`` / ``body.error.code``
+ 2. ``error.type`` (Anthropic) / ``type``
+ 3. ``param`` only when it identifies the model
+ 4. Never the full human message
+ """
+ code, typ, param = _vendor_error_parts(exc)
if code:
- return code.lower()
- if typ and typ.lower() in _SPECIFIC_ERROR_CODES:
- return typ.lower()
- if typ in {"not_found_error", "not_found"}:
- return typ.lower()
+ return code
+ if typ and typ in _SPECIFIC_ERROR_CODES:
+ return typ
if param == "model" and typ:
- return typ.lower()
- if typ and typ.lower() not in {"invalid_request_error", "api_error", "error"}:
- return typ.lower()
+ return typ
+ if typ and typ not in {
+ "invalid_request_error",
+ "api_error",
+ "error",
+ "not_found_error",
+ "not_found",
+ }:
+ return typ
return None
def _looks_like_model_not_found(
- *, status: int | None, code: str | None, msg: str
+ *,
+ status: int | None,
+ code: str | None,
+ msg: str,
+ param: str | None = None,
) -> bool:
- if code in {
- "model_not_found",
- "model_not_available",
- "invalid_model",
- "not_found_error",
- "not_found",
- }:
+ if code in _MODEL_NOT_FOUND_CODES:
return True
- if status == 404 and any(pat.search(msg) for pat in _MODEL_NOT_FOUND_PATTERNS):
+ if param == "model":
return True
- if any(pat.search(msg) for pat in _MODEL_NOT_FOUND_PATTERNS):
+ modelish = any(pat.search(msg) for pat in _MODEL_NOT_FOUND_PATTERNS)
+ if code in {"not_found_error", "not_found"} and modelish:
+ return True
+ if status in {400, 404} and modelish:
return True
return False
@@ -571,7 +597,9 @@ def classify_and_raise(
status = _status_of(exc)
provider = model.provider_id
model_id = model.id
- error_code = extract_error_code(exc)
+ error_code, _err_type, err_param = _vendor_error_parts(exc)
+ if error_code is None:
+ error_code = extract_error_code(exc)
tokens_in = _estimate_input_tokens(messages)
cw_val = getattr(model, "context_window", None)
@@ -633,15 +661,6 @@ def classify_and_raise(
error_code=error_code,
) from exc
- if _looks_like_model_not_found(status=status, code=error_code, msg=msg):
- raise ModelNotFound(
- msg,
- provider=provider,
- model=model_id,
- status_code=status,
- error_code=error_code,
- ) from exc
-
if isinstance(exc, (TimeoutError, ConnectionError)):
raise ProviderUnavailable(
msg,
@@ -673,6 +692,17 @@ def classify_and_raise(
error_code=error_code,
) from exc
+ if _looks_like_model_not_found(
+ status=status, code=error_code, msg=msg, param=err_param
+ ):
+ raise ModelNotFound(
+ msg,
+ provider=provider,
+ model=model_id,
+ status_code=status,
+ error_code=error_code,
+ ) from exc
+
if status is not None and 400 <= status < 500:
raise ProviderBadRequest(
msg,
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index 2524f89..2f72696 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -287,6 +287,8 @@ class AnthropicProvider(BaseProvider):
error_code=ev.error_code,
status_code=ev.status_code,
retry_after=ev.retry_after,
+ tokens_in=ev.tokens_in,
+ context_window=ev.context_window,
usage=Usage(),
timestamp=time.time(),
provider_id=ev.provider_id or model.provider_id,
diff --git a/cubepi/providers/base.py b/cubepi/providers/base.py
index 892522e..232e35e 100644
--- a/cubepi/providers/base.py
+++ b/cubepi/providers/base.py
@@ -109,6 +109,8 @@ class AssistantMessage(BaseModel):
error_code: str | None = None
status_code: int | None = None
retry_after: float | None = None
+ tokens_in: int | None = None
+ context_window: int | None = None
usage: Usage | None = None
timestamp: float | None = None
provider_id: str = ""
diff --git a/cubepi/providers/fallback.py b/cubepi/providers/fallback.py
index df2b8b4..d0f56ea 100644
--- a/cubepi/providers/fallback.py
+++ b/cubepi/providers/fallback.py
@@ -94,6 +94,21 @@ def reset_active() -> None:
state.active_index = 0
+def get_active_index() -> int:
+ """Return the current sticky index, or 0 if no run is open."""
+
+ state = _run_state.get()
+ return 0 if state is None else state.active_index
+
+
+def set_active_index(index: int) -> None:
+ """Restore a previously snapshotted sticky index into the current run."""
+
+ state = _run_state.get()
+ if state is not None:
+ state.active_index = max(0, index)
+
+
def _current_state() -> _FallbackRunState | None:
return _run_state.get()
@@ -143,9 +158,24 @@ def _typed_from_message(msg: AssistantMessage, bound: BoundModel) -> ProviderErr
retry_after=msg.retry_after,
provider_id=msg.provider_id or bound.spec.provider_id,
model_id=msg.model_id or bound.spec.id,
+ tokens_in=msg.tokens_in,
+ context_window=msg.context_window,
)
+def _window_cannot_fit(bound: BoundModel, tokens_in: int | None) -> bool:
+ window = bound.spec.context_window or None
+ if tokens_in is None or not window:
+ return False
+ return int(window) < int(tokens_in)
+
+
+def _needed_tokens(err: BaseException | None) -> int | None:
+ if isinstance(err, ContextLengthExceeded):
+ return err.tokens_in
+ return None
+
+
@dataclass(frozen=True)
class FailoverAttempt:
model_id: str
@@ -297,9 +327,12 @@ class FallbackBoundModel:
(f.error for f in reversed(failures) if isinstance(f.error, ProviderError)),
None,
)
+ by_leg: dict[tuple[str, str], BaseException] = {}
+ for item in failures:
+ by_leg[(item.provider_id, item.model_id)] = item.error
exc = ProviderUnavailable(
f"all providers exhausted; last error: {last!r}",
- errors=[f.error for f in failures],
+ errors=list(by_leg.values()),
)
if last_typed is not None:
exc.__cause__ = last_typed
@@ -338,12 +371,25 @@ class FallbackBoundModel:
retry = tuple(self.retry_errors)
failures: list[FailoverAttempt] = []
start = self._start_index()
+ needed: int | None = None
for index in range(start, len(self.chain)):
bound = self.chain[index]
next_bound = self.chain[index + 1] if index + 1 < len(self.chain) else None
same_retries = 0
+ if _window_cannot_fit(bound, needed):
+ skip = ContextLengthExceeded(
+ "skipped: context_window cannot fit prior tokens_in",
+ provider=bound.spec.provider_id,
+ model=bound.spec.id,
+ tokens_in=needed,
+ context_window=bound.spec.context_window,
+ )
+ self._record(failures, bound, skip, 0.0, 0, "failover")
+ await self._notify_failover(bound, next_bound, skip, index + 1)
+ continue
+
while True:
t0 = time.monotonic()
err: BaseException | None = None
@@ -406,6 +452,7 @@ class FallbackBoundModel:
return outer
assert err is not None
+ needed = _needed_tokens(err) or needed
duration_ms = (time.monotonic() - t0) * 1000
hop = await self._decide(
bound=bound,
@@ -443,12 +490,25 @@ class FallbackBoundModel:
retry = tuple(self.retry_errors)
failures: list[FailoverAttempt] = []
start = self._start_index()
+ needed: int | None = None
for index in range(start, len(self.chain)):
bound = self.chain[index]
next_bound = self.chain[index + 1] if index + 1 < len(self.chain) else None
same_retries = 0
+ if _window_cannot_fit(bound, needed):
+ skip = ContextLengthExceeded(
+ "skipped: context_window cannot fit prior tokens_in",
+ provider=bound.spec.provider_id,
+ model=bound.spec.id,
+ tokens_in=needed,
+ context_window=bound.spec.context_window,
+ )
+ self._record(failures, bound, skip, 0.0, 0, "failover")
+ await self._notify_failover(bound, next_bound, skip, index + 1)
+ continue
+
while True:
t0 = time.monotonic()
err: BaseException | None = None
@@ -473,6 +533,7 @@ class FallbackBoundModel:
return result
assert err is not None
+ needed = _needed_tokens(err) or needed
duration_ms = (time.monotonic() - t0) * 1000
hop = await self._decide(
bound=bound,
diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.py
index 3bea7d9..aa39fc6 100644
--- a/cubepi/providers/openai.py
+++ b/cubepi/providers/openai.py
@@ -542,6 +542,8 @@ class OpenAIProvider(BaseProvider):
error_code=ev.error_code,
status_code=ev.status_code,
retry_after=ev.retry_after,
+ tokens_in=ev.tokens_in,
+ context_window=ev.context_window,
usage=Usage(),
timestamp=time.time(),
provider_id=ev.provider_id or model.provider_id,
diff --git a/cubepi/providers/openai_responses.py b/cubepi/providers/openai_responses.py
index 915e025..8e804bc 100644
--- a/cubepi/providers/openai_responses.py
+++ b/cubepi/providers/openai_responses.py
@@ -579,6 +579,8 @@ class OpenAIResponsesProvider(BaseProvider):
error_code=ev.error_code,
status_code=ev.status_code,
retry_after=ev.retry_after,
+ tokens_in=ev.tokens_in,
+ context_window=ev.context_window,
usage=Usage(),
timestamp=time.time(),
provider_id=ev.provider_id or model.provider_id,
diff --git a/tests/providers/test_fallback.py b/tests/providers/test_fallback.py
index 9ed4cd1..1b36926 100644
--- a/tests/providers/test_fallback.py
+++ b/tests/providers/test_fallback.py
@@ -715,6 +715,12 @@ async def test_context_length_skips_too_small_fallback() -> None:
await fbm.stream(_messages())
assert ei.value.errors
assert all(isinstance(e, ContextLengthExceeded) for e in ei.value.errors)
+ assert getattr(b.provider, "_error", None) is small_err
+ # 16k window cannot fit 200k — must not be invoked.
+ assert not hasattr(b.provider, "calls") or getattr(b.provider, "calls", 0) == 0
+ # _RaisingProvider has no counter; wrap via call_count if present
+ if hasattr(b.provider, "call_count"):
+ assert b.provider.call_count == 0 # type: ignore[attr-defined]
@pytest.mark.asyncio
@@ -790,8 +796,29 @@ async def test_sticky_after_successful_failover() -> None:
s2 = await fbm.stream(_messages())
r2 = await s2.result()
assert r2.provider_id == "fallback"
- # second call must not probe primary again
- assert primary.provider # constructed
+ finally:
+ end_fallback_run(token)
+
+
+async def test_sticky_second_call_skips_primary() -> None:
+ from cubepi.providers.fallback import begin_fallback_run, end_fallback_run
+
+ err = ProviderUnavailable("down", provider="primary", model="m")
+ primary_p = _CountingRaiseProvider(err, fail_times=99, provider_id="primary")
+ primary = BoundModel(provider=primary_p, spec=Model(id="m", provider_id="primary"))
+ fb = FauxProvider(provider_id="fallback")
+ fb.set_responses([faux_assistant_message("ok"), faux_assistant_message("ok2")])
+ fallback = fb.model("model-1")
+ fbm = FallbackBoundModel(
+ chain=(primary, fallback), max_retries_per_model=0, retry_backoff=0.0
+ )
+ token = begin_fallback_run()
+ try:
+ await (await fbm.stream(_messages())).result()
+ after_first = primary_p.calls
+ await (await fbm.stream(_messages())).result()
+ assert primary_p.calls == after_first
finally:
end_fallback_run(token)
@@ -822,6 +849,36 @@ async def test_new_run_resets_sticky_to_primary() -> None:
end_fallback_run(token)
+async def test_new_run_after_failover_probes_primary_again() -> None:
+ from cubepi.providers.fallback import begin_fallback_run, end_fallback_run
+
+ err = ProviderUnavailable("down", provider="primary", model="m")
+ primary_p = _CountingRaiseProvider(err, fail_times=99, provider_id="primary")
+ primary = BoundModel(provider=primary_p, spec=Model(id="m", provider_id="primary"))
+ fb = FauxProvider(provider_id="fallback")
+ fb.set_responses([faux_assistant_message("ok"), faux_assistant_message("ok2")])
+ fbm = FallbackBoundModel(
+ chain=(primary, fb.model("model-1")),
+ max_retries_per_model=0,
+ retry_backoff=0.0,
+ )
+ token = begin_fallback_run()
+ try:
+ r1 = await (await fbm.stream(_messages())).result()
+ assert r1.provider_id == "fallback"
+ finally:
+ end_fallback_run(token)
+ after_run1 = primary_p.calls
+ token = begin_fallback_run()
+ try:
+ r2 = await (await fbm.stream(_messages())).result()
+ assert r2.provider_id == "fallback"
+ assert primary_p.calls > after_run1
+ finally:
+ end_fallback_run(token)
+
+
@pytest.mark.asyncio
async def test_generate_exhaustion_preserves_errors() -> None:
e1 = RateLimited("a", provider="p", model="m1")
@@ -834,3 +891,17 @@ async def test_generate_exhaustion_preserves_errors() -> None:
await fbm.generate(_messages())
assert len(ei.value.errors) == 2
assert isinstance(ei.value.__cause__, RateLimited)
+
+
+async def test_exhaustion_errors_are_one_per_leg() -> None:
+ e1 = RateLimited("a", provider="p", model="m1")
+ e2 = RateLimited("b", provider="p", model="m2")
+ fbm = FallbackBoundModel(
+ chain=(_raising(e1, "m1"), _raising(e2, "m2")),
+ max_retries_per_model=3,
+ retry_backoff=0.0,
+ )
+ with pytest.raises(ProviderUnavailable) as ei:
+ await fbm.generate(_messages())
+ assert len(ei.value.errors) == 2
diff --git a/tests/test_errors.py b/tests/test_errors.py
index 2591f28..2a0c893 100644
--- a/tests/test_errors.py
+++ b/tests/test_errors.py
@@ -382,3 +382,15 @@ class TestErrorCodeExtraction:
exc = _FakeExc("content policy violation", status_code=400)
with pytest.raises(ContentFiltered):
classify_and_raise(exc, model=_model())
+
+ def test_503_does_not_exist_is_unavailable_not_model_not_found(self) -> None:
+ exc = _FakeExc("replica does not exist", status_code=503)
+ with pytest.raises(ProviderUnavailable):
+ classify_and_raise(exc, model=_model())
+
+ def test_generic_not_found_code_without_model_hint_is_bad_request(self) -> None:
+ exc = _FakeExc("missing resource", status_code=404)
+ exc.body = {"error": {"code": "not_found_error"}}
+ with pytest.raises(ProviderBadRequest) as ei:
+ classify_and_raise(exc, model=_model())
+ assert not isinstance(ei.value, ModelNotFound)
diff --git a/website/docs/recipes/multi-provider-failover.md b/website/docs/recipes/multi-provider-failover.md
index 3025740..68f1939 100644
--- a/website/docs/recipes/multi-provider-failover.md
+++ b/website/docs/recipes/multi-provider-failover.md
@@ -49,9 +49,11 @@ Policy in one turn:
misses model-specific 400s more often than a true schema bug that fails
every provider.
3. **Stick** to the first *successful* leg for later `stream` / `generate`
- calls in the same `Agent.prompt` / run. The next user turn resets to
- `chain[0]`. Subagents start their own run and do **not** inherit the
- parent's sticky index.
+ calls in the same `Agent.prompt`. HITL `respond()` continues that run and
+ keeps the sticky index. The next user `prompt` resets to `chain[0]`.
+ Subagents start their own run and do **not** inherit the parent's index.
+ Sticky requires `begin_fallback_run()` (Agent does this); standalone
+ `FallbackBoundModel` calls do not stick.
## Default trigger conditions
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md
index b409d58..47142e9 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md
@@ -45,9 +45,11 @@ await agent.prompt("Capital of Mongolia?")
2. **再 hop** 到下一条。residual `ProviderBadRequest` 和 `ModelNotFound`
立刻 hop(不同模型重试)——分类漏报「其实是这个模型/网关的问题」比
「全链都会炸的真 schema 错误」更常见。
-3. **粘住**本轮第一次**成功**的那条腿:同一 `Agent.prompt` / run 里后续
- `stream` / `generate` 直接打这条。下一次用户回合重置回 `chain[0]`。
- Subagent 自己开 run,**不继承**父级 sticky index。
+3. **粘住**本轮第一次**成功**的那条腿:同一 `Agent.prompt` 里后续
+ `stream` / `generate` 直接打这条。HITL `respond()` 继续该 run,保留
+ sticky。下一次用户 `prompt` 重置回 `chain[0]`。Subagent 自己开 run,
+ **不继承**父级 index。Sticky 依赖 `begin_fallback_run()`(Agent 会调);
+ 单独调用 `FallbackBoundModel` 不会粘。
## 默认触发条件