Skip to content

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

feat(errors): add typed ProviderError taxonomy + classify_and_raise

xf gongad411b64881c
diff --git a/cubepi/__init__.py b/cubepi/__init__.py
index 97b999c..3c00e3c 100644
--- a/cubepi/__init__.py
+++ b/cubepi/__init__.py
@@ -35,6 +35,14 @@ from cubepi.providers import (
UserMessage,
adjust_max_tokens_for_thinking,
)
+from cubepi.errors import (
+ ContextLengthExceeded,
+ ProviderAuthFailed,
+ ProviderBadRequest,
+ ProviderError,
+ ProviderUnavailable,
+ RateLimited,
+)
from cubepi.providers.capability import (
CapabilityDescriptor,
ReasoningLevelSpec,
@@ -50,11 +58,17 @@ __all__ = [
"AssistantMessage",
"BaseProvider",
"CapabilityDescriptor",
+ "ContextLengthExceeded",
"Message",
"MessageStream",
"Middleware",
"Model",
"Provider",
+ "ProviderAuthFailed",
+ "ProviderBadRequest",
+ "ProviderError",
+ "ProviderUnavailable",
+ "RateLimited",
"ReasoningLevelSpec",
"StreamEvent",
"StreamOptions",
diff --git a/cubepi/errors.py b/cubepi/errors.py
new file mode 100644
index 0000000..1991f26
--- /dev/null
+++ b/cubepi/errors.py
@@ -0,0 +1,278 @@
+"""Typed provider errors.
+
+cubepi providers catch raw SDK exceptions and re-raise as one of these
+subclasses, so downstream callers can ``except cubepi.errors.X`` instead
+of pattern-matching on SDK-specific strings or status codes.
+
+Adding a new subclass: add it at the bottom of the file (never reorder)
+and re-export from ``cubepi/__init__.py`` and ``__all__``.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from typing import NoReturn
+
+from cubepi.providers.base import Message, Model
+
+
+class ProviderError(Exception):
+ """Base class for typed cubepi provider errors.
+
+ Always carries provider / model context. ``raw_exception`` is the
+ original SDK exception (kept on ``__cause__`` via ``raise … from``).
+ """
+
+ def __init__(
+ self,
+ message: str | None = None,
+ *,
+ provider: str | None = None,
+ model: str | None = None,
+ status_code: int | None = None,
+ ) -> None:
+ self.provider = provider
+ self.model = model
+ self.status_code = status_code
+ super().__init__(message or self.__class__.__name__)
+
+
+class ContextLengthExceeded(ProviderError):
+ """The request exceeded the model's context window.
+
+ ``tokens_in`` is an estimate (chars/4) of the prompt size at the time
+ of the failure; ``context_window`` is the model's advertised window.
+ Both may be None if the provider couldn't measure them.
+ """
+
+ def __init__(
+ self,
+ message: str | None = None,
+ *,
+ provider: str | None = None,
+ model: str | None = None,
+ status_code: int | None = None,
+ tokens_in: int | None = None,
+ context_window: int | None = None,
+ ) -> None:
+ self.tokens_in = tokens_in
+ self.context_window = context_window
+ super().__init__(
+ message, provider=provider, model=model, status_code=status_code
+ )
+
+
+class RateLimited(ProviderError):
+ """Provider rate-limit / quota error.
+
+ ``retry_after`` is the recommended retry delay in seconds, parsed from
+ the SDK response when available.
+ """
+
+ def __init__(
+ self,
+ message: str | None = None,
+ *,
+ provider: str | None = None,
+ model: str | None = None,
+ status_code: int | None = None,
+ retry_after: float | None = None,
+ ) -> None:
+ self.retry_after = retry_after
+ super().__init__(
+ message, provider=provider, model=model, status_code=status_code
+ )
+
+
+class ProviderAuthFailed(ProviderError):
+ """API-key invalid, account suspended, or 401/403 with no quota wording."""
+
+
+class ProviderUnavailable(ProviderError):
+ """5xx, timeout, or connection failure."""
+
+
+class ProviderBadRequest(ProviderError):
+ """Other 4xx provider error (model_not_found, schema rejection, etc.)."""
+
+
+# ---------------------------------------------------------------------------
+# Heuristics: turn a raw SDK exception into one of the typed errors above.
+# ---------------------------------------------------------------------------
+
+_CONTEXT_LENGTH_PATTERNS = (
+ re.compile(r"maximum context length", re.IGNORECASE),
+ re.compile(r"context.{0,10}length.{0,20}exceed", re.IGNORECASE),
+ re.compile(r"too many tokens", re.IGNORECASE),
+ re.compile(r"prompt is too long", re.IGNORECASE),
+ re.compile(r"reduce.{0,10}messages", re.IGNORECASE),
+)
+
+_RATE_LIMIT_PATTERNS = (
+ re.compile(r"rate ?limit", re.IGNORECASE),
+ re.compile(r"quota (?:exceed|exhaust|limit|reach)", re.IGNORECASE),
+ re.compile(r"too many requests", re.IGNORECASE),
+)
+
+
+def _status_of(exc: BaseException) -> int | None:
+ """Best-effort status code extraction from an SDK exception."""
+
+ code = getattr(exc, "status_code", None)
+ if isinstance(code, int):
+ return code
+ resp = getattr(exc, "response", None)
+ if resp is not None:
+ rc = getattr(resp, "status_code", None)
+ if isinstance(rc, int):
+ return rc
+ return None
+
+
+def _estimate_input_tokens(messages: list[Message] | None) -> int | None:
+ """Rough chars/4 estimate over message text, used only for diagnostics.
+
+ Returns None when ``messages`` is empty or missing.
+ """
+
+ if not messages:
+ return None
+ total = 0
+ for msg in messages:
+ content = getattr(msg, "content", None)
+ if isinstance(content, list):
+ for block in content:
+ text = getattr(block, "text", None)
+ if isinstance(text, str):
+ total += len(text)
+ else:
+ text = getattr(block, "content", None)
+ if isinstance(text, str):
+ total += len(text)
+ elif isinstance(content, str):
+ total += len(content)
+ if total == 0:
+ return None
+ return max(1, math.ceil(total / 4))
+
+
+def _retry_after_from(exc: BaseException) -> float | None:
+ """Pull retry-after seconds from an SDK exception's response headers."""
+
+ resp = getattr(exc, "response", None)
+ headers = getattr(resp, "headers", None) if resp is not None else None
+ if not headers:
+ return None
+ val = headers.get("retry-after") or headers.get("Retry-After")
+ if val is None:
+ return None
+ try:
+ return float(val)
+ except (TypeError, ValueError):
+ return None
+
+
+def classify_and_raise(
+ exc: BaseException,
+ *,
+ model: Model,
+ messages: list[Message] | None = None,
+) -> NoReturn:
+ """Inspect a raw SDK exception and raise the typed cubepi error.
+
+ Heuristics (first match wins):
+ 1. Explicit context-length wording → ContextLengthExceeded.
+ 2. status==400 + estimated tokens_in within 5% of model.context_window
+ → ContextLengthExceeded (covers Volcano ARK's opaque
+ ``InvalidParameter`` 400).
+ 3. status==429 OR quota/rate-limit wording → RateLimited.
+ 4. status==401 / 403 → ProviderAuthFailed.
+ 5. TimeoutError / ConnectionError / 5xx → ProviderUnavailable.
+ 6. Any other 4xx → ProviderBadRequest.
+ 7. Else: re-raise the original (caller should let it propagate).
+
+ ``raise classify_and_raise(...) from exc`` is the idiomatic call site.
+ """
+
+ # Already typed — re-raise unchanged so callers that catch ProviderError
+ # don't get double-wrapped.
+ if isinstance(exc, ProviderError):
+ raise exc
+
+ msg = str(exc) or getattr(exc, "message", "")
+ status = _status_of(exc)
+ provider = model.provider
+ model_id = model.id
+
+ tokens_in = _estimate_input_tokens(messages)
+ context_window = model.context_window if model.context_window else None
+
+ for pat in _CONTEXT_LENGTH_PATTERNS:
+ if pat.search(msg):
+ raise ContextLengthExceeded(
+ msg,
+ provider=provider,
+ model=model_id,
+ status_code=status,
+ tokens_in=tokens_in,
+ context_window=context_window,
+ ) from exc
+
+ if (
+ status == 400
+ and tokens_in is not None
+ and context_window is not None
+ and tokens_in >= int(context_window * 0.95)
+ ):
+ raise ContextLengthExceeded(
+ msg,
+ provider=provider,
+ model=model_id,
+ status_code=status,
+ tokens_in=tokens_in,
+ context_window=context_window,
+ ) from exc
+
+ if status == 429 or any(pat.search(msg) for pat in _RATE_LIMIT_PATTERNS):
+ raise RateLimited(
+ msg,
+ provider=provider,
+ model=model_id,
+ status_code=status,
+ retry_after=_retry_after_from(exc),
+ ) from exc
+
+ if status in (401, 403):
+ raise ProviderAuthFailed(
+ msg, provider=provider, model=model_id, status_code=status
+ ) from exc
+
+ if isinstance(exc, (TimeoutError, ConnectionError)):
+ raise ProviderUnavailable(
+ msg, provider=provider, model=model_id, status_code=status
+ ) from exc
+
+ if status is not None and 500 <= status < 600:
+ raise ProviderUnavailable(
+ msg, provider=provider, model=model_id, status_code=status
+ ) from exc
+
+ if status is not None and 400 <= status < 500:
+ raise ProviderBadRequest(
+ msg, provider=provider, model=model_id, status_code=status
+ ) from exc
+
+ # Unknown → let original propagate. Callers might still need to handle it.
+ raise exc
+
+
+__all__ = [
+ "ProviderError",
+ "ContextLengthExceeded",
+ "RateLimited",
+ "ProviderAuthFailed",
+ "ProviderUnavailable",
+ "ProviderBadRequest",
+ "classify_and_raise",
+]
diff --git a/tests/test_errors.py b/tests/test_errors.py
new file mode 100644
index 0000000..05093cf
--- /dev/null
+++ b/tests/test_errors.py
@@ -0,0 +1,255 @@
+"""Tests for cubepi.errors — classifier heuristics and typed error taxonomy."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from cubepi.errors import (
+ ContextLengthExceeded,
+ ProviderAuthFailed,
+ ProviderBadRequest,
+ ProviderError,
+ ProviderUnavailable,
+ RateLimited,
+ classify_and_raise,
+)
+from cubepi.providers.base import Model, TextContent, UserMessage
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _model(
+ provider: str = "openai",
+ model_id: str = "gpt-4o",
+ context_window: int = 128_000,
+) -> Model:
+ return Model(id=model_id, provider=provider, context_window=context_window)
+
+
+def _messages(text: str = "hello") -> list:
+ return [UserMessage(content=[TextContent(text=text)])]
+
+
+class _FakeExc(Exception):
+ """Fake SDK exception with configurable status_code, message, and headers."""
+
+ def __init__(
+ self,
+ message: str = "",
+ *,
+ status_code: int | None = None,
+ headers: dict | None = None,
+ ) -> None:
+ super().__init__(message)
+ if status_code is not None:
+ self.status_code = status_code
+ if headers is not None:
+ self.response = SimpleNamespace(
+ status_code=status_code,
+ headers=headers,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Classifier tests
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyContextLengthExceeded:
+ def test_explicit_context_length_message(self) -> None:
+ exc = _FakeExc("This model's maximum context length is 4096 tokens.")
+ with pytest.raises(ContextLengthExceeded) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.__cause__ is exc
+
+ def test_exceed_pattern(self) -> None:
+ exc = _FakeExc("context length exceeded: reduce your input")
+ with pytest.raises(ContextLengthExceeded):
+ classify_and_raise(exc, model=_model())
+
+ def test_too_many_tokens_pattern(self) -> None:
+ exc = _FakeExc("too many tokens in input")
+ with pytest.raises(ContextLengthExceeded):
+ classify_and_raise(exc, model=_model())
+
+ def test_prompt_is_too_long_pattern(self) -> None:
+ exc = _FakeExc("prompt is too long")
+ with pytest.raises(ContextLengthExceeded):
+ classify_and_raise(exc, model=_model())
+
+ def test_reduce_messages_pattern(self) -> None:
+ exc = _FakeExc("Please reduce the messages sent in your request.")
+ with pytest.raises(ContextLengthExceeded):
+ classify_and_raise(exc, model=_model())
+
+ def test_carries_provider_and_model_fields(self) -> None:
+ exc = _FakeExc("maximum context length exceeded", status_code=400)
+ with pytest.raises(ContextLengthExceeded) as ei:
+ classify_and_raise(exc, model=_model(provider="openai", model_id="gpt-4o"))
+ err = ei.value
+ assert err.provider == "openai"
+ assert err.model == "gpt-4o"
+ assert err.status_code == 400
+
+ def test_volcano_invalid_parameter_400_with_oversize_tokens(self) -> None:
+ """Volcano ARK sends opaque 400 InvalidParameter when over-context."""
+ # Build a message whose chars/4 estimate is >= 95% of context_window (100k).
+ # context_window=100_000; 95% threshold = 95_000 tokens = 380_000 chars.
+ big_text = "x" * 400_000
+ msgs = [UserMessage(content=[TextContent(text=big_text)])]
+ exc = _FakeExc("InvalidParameter", status_code=400)
+ with pytest.raises(ContextLengthExceeded) as ei:
+ classify_and_raise(exc, model=_model(context_window=100_000), messages=msgs)
+ assert ei.value.tokens_in is not None
+ assert ei.value.context_window == 100_000
+
+ def test_400_below_95_percent_threshold_not_context_length(self) -> None:
+ """400 with small messages should NOT be classified as ContextLengthExceeded."""
+ msgs = _messages("short prompt")
+ exc = _FakeExc("InvalidParameter", status_code=400)
+ with pytest.raises(ProviderBadRequest):
+ classify_and_raise(exc, model=_model(context_window=100_000), messages=msgs)
+
+
+class TestClassifyRateLimited:
+ def test_429_raises_rate_limited(self) -> None:
+ exc = _FakeExc("Too Many Requests", status_code=429)
+ with pytest.raises(RateLimited) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.status_code == 429
+
+ def test_retry_after_parsed_from_headers(self) -> None:
+ exc = _FakeExc(
+ "rate limit exceeded",
+ status_code=429,
+ headers={"retry-after": "42"},
+ )
+ with pytest.raises(RateLimited) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.retry_after == 42.0
+
+ def test_quota_wording_triggers_rate_limited(self) -> None:
+ # Pattern: "quota (?:exceed|exhaust|limit|reach)" — matches "quota exceeded"
+ exc = _FakeExc("quota exceeded for your account", status_code=200)
+ with pytest.raises(RateLimited):
+ classify_and_raise(exc, model=_model())
+
+ def test_403_with_quota_wording_raises_rate_limited(self) -> None:
+ """Anthropic-style 403 with 'quota limit' text → RateLimited, not AuthFailed."""
+ exc = _FakeExc(
+ "Your account has reached its quota limit. Please upgrade.",
+ status_code=403,
+ )
+ with pytest.raises(RateLimited):
+ classify_and_raise(exc, model=_model())
+
+
+class TestClassifyProviderAuthFailed:
+ def test_401_raises_provider_auth_failed(self) -> None:
+ exc = _FakeExc("Unauthorized", status_code=401)
+ with pytest.raises(ProviderAuthFailed) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.status_code == 401
+
+ def test_403_without_quota_wording_raises_provider_auth_failed(self) -> None:
+ exc = _FakeExc("Forbidden", status_code=403)
+ with pytest.raises(ProviderAuthFailed):
+ classify_and_raise(exc, model=_model())
+
+ def test_carries_provider_context(self) -> None:
+ exc = _FakeExc("Invalid API key", status_code=401)
+ with pytest.raises(ProviderAuthFailed) as ei:
+ classify_and_raise(
+ exc, model=_model(provider="anthropic", model_id="claude-3-5-sonnet")
+ )
+ assert ei.value.provider == "anthropic"
+
+
+class TestClassifyProviderUnavailable:
+ def test_5xx_raises_provider_unavailable(self) -> None:
+ exc = _FakeExc("Internal Server Error", status_code=500)
+ with pytest.raises(ProviderUnavailable) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.status_code == 500
+
+ def test_503_raises_provider_unavailable(self) -> None:
+ exc = _FakeExc("Service Unavailable", status_code=503)
+ with pytest.raises(ProviderUnavailable):
+ classify_and_raise(exc, model=_model())
+
+ def test_timeout_error_raises_provider_unavailable(self) -> None:
+ exc = TimeoutError("request timed out")
+ with pytest.raises(ProviderUnavailable):
+ classify_and_raise(exc, model=_model())
+
+ def test_connection_error_raises_provider_unavailable(self) -> None:
+ exc = ConnectionError("failed to connect")
+ with pytest.raises(ProviderUnavailable):
+ classify_and_raise(exc, model=_model())
+
+
+class TestClassifyProviderBadRequest:
+ def test_generic_400_raises_provider_bad_request(self) -> None:
+ exc = _FakeExc("Bad Request", status_code=400)
+ with pytest.raises(ProviderBadRequest) as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value.status_code == 400
+
+ def test_404_raises_provider_bad_request(self) -> None:
+ exc = _FakeExc("model not found", status_code=404)
+ with pytest.raises(ProviderBadRequest):
+ classify_and_raise(exc, model=_model())
+
+
+class TestClassifyUnknown:
+ def test_unknown_exception_re_raised_as_is(self) -> None:
+ """A plain RuntimeError with no status code propagates unchanged."""
+ exc = RuntimeError("boom")
+ with pytest.raises(RuntimeError, match="boom") as ei:
+ classify_and_raise(exc, model=_model())
+ assert ei.value is exc
+
+ def test_already_typed_error_re_raised_unchanged(self) -> None:
+ """A ProviderError passed in is re-raised without double-wrapping."""
+ original = ContextLengthExceeded(
+ "already typed", provider="openai", model="gpt-4o"
+ )
+ with pytest.raises(ContextLengthExceeded) as ei:
+ classify_and_raise(original, model=_model())
+ assert ei.value is original
+
+
+class TestProviderErrorInheritance:
+ def test_all_subclasses_are_provider_error(self) -> None:
+ for cls in (
+ ContextLengthExceeded,
+ RateLimited,
+ ProviderAuthFailed,
+ ProviderUnavailable,
+ ProviderBadRequest,
+ ):
+ err = cls("msg", provider="p", model="m")
+ assert isinstance(err, ProviderError)
+ assert isinstance(err, Exception)
+
+ def test_context_length_carries_token_fields(self) -> None:
+ err = ContextLengthExceeded(
+ "too long",
+ provider="openai",
+ model="gpt-4o",
+ tokens_in=5000,
+ context_window=4096,
+ )
+ assert err.tokens_in == 5000
+ assert err.context_window == 4096
+
+ def test_rate_limited_carries_retry_after(self) -> None:
+ err = RateLimited(
+ "slow down", provider="openai", model="gpt-4o", retry_after=30.0
+ )
+ assert err.retry_after == 30.0