CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(providers): self-describing errors with provider/model/cause context (#101)
Chris8781d45ffff1
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.pyindex 0a279c2..eaf16f0 100644--- a/cubepi/providers/anthropic.py+++ b/cubepi/providers/anthropic.py@@ -206,15 +206,18 @@ class AnthropicProvider(BaseProvider):except BaseException as e:exc = e+ err_text = self._error_message(e, model)error_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(e),+ error_message=err_text,usage=Usage(),timestamp=time.time(),+ provider_id=model.provider,+ model_id=model.id,)await self._emit(- ms, StreamEvent(type="error", error_message=str(e)), model+ ms, StreamEvent(type="error", error_message=err_text), model)ms.set_result(error_msg)if not isinstance(e, Exception):diff --git a/cubepi/providers/base.py b/cubepi/providers/base.pyindex 72d70aa..96e1564 100644--- a/cubepi/providers/base.py+++ b/cubepi/providers/base.py@@ -175,6 +175,37 @@ class StreamEvent(BaseModel):error_message: str | None = None+def format_provider_error(+ exc: BaseException,+ model: "Model",+ base_url: str | None = None,+) -> str:+ """Build a self-describing error string for a failed provider call.++ SDK exceptions like openai's ``APIConnectionError`` stringify to bare+ ``"Connection error."`` and drop the transport failure into ``__cause__``+ / ``__context__``. Without provider/model/cause context, a logged or+ persisted error tells you nothing about *which* model failed or *why*.+ """+ target = f"{model.provider}/{model.id}"+ if base_url:+ target = f"{target} @ {base_url}"++ chain: list[str] = [f"{type(exc).__name__}: {exc}"]+ seen: set[int] = {id(exc)}+ cur: BaseException | None = exc+ while cur is not None:+ nxt = cur.__cause__ or cur.__context__+ if nxt is None or id(nxt) in seen:+ break+ seen.add(id(nxt))+ chain.append(f"{type(nxt).__name__}: {nxt}")+ cur = nxt++ detail = " <- ".join(chain)+ return f"[{target}] {detail}"++class MessageStream:def __init__(self) -> None:self._queue: asyncio.Queue[StreamEvent | None] = asyncio.Queue()@@ -583,6 +614,14 @@ class BaseProvider:) -> MessageStream:raise NotImplementedError+ def _error_message(self, exc: BaseException, model: Model) -> str:+ """Format a failed-call error with provider/model/base_url + cause."""+ base_url: str | None = None+ client = getattr(self, "_client", None)+ if client is not None:+ base_url = str(getattr(client, "base_url", "") or "") or None+ return format_provider_error(exc, model, base_url)+def subscribe_request(self, cb: OnRequestCallback) -> Callable[[], None]:"""Register a persistent observer for request payloads.diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.pyindex 785c387..48b22d0 100644--- a/cubepi/providers/openai.py+++ b/cubepi/providers/openai.py@@ -461,15 +461,18 @@ class OpenAIProvider(BaseProvider):except BaseException as e:exc = e+ err_text = self._error_message(e, model)error_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(e),+ error_message=err_text,usage=Usage(),timestamp=time.time(),+ provider_id=model.provider,+ model_id=model.id,)await self._emit(- ms, StreamEvent(type="error", error_message=str(e)), model+ ms, StreamEvent(type="error", error_message=err_text), model)ms.set_result(error_msg)if not isinstance(e, Exception):diff --git a/cubepi/providers/openai_responses.py b/cubepi/providers/openai_responses.pyindex cf1f8ab..a17445a 100644--- a/cubepi/providers/openai_responses.py+++ b/cubepi/providers/openai_responses.py@@ -518,15 +518,18 @@ class OpenAIResponsesProvider(BaseProvider):except BaseException as e:exc = e+ err_text = self._error_message(e, model)error_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(e),+ error_message=err_text,usage=Usage(),timestamp=time.time(),+ provider_id=model.provider,+ model_id=model.id,)await self._emit(- ms, StreamEvent(type="error", error_message=str(e)), model+ ms, StreamEvent(type="error", error_message=err_text), model)ms.set_result(error_msg)if not isinstance(e, Exception):diff --git a/tests/providers/test_anthropic.py b/tests/providers/test_anthropic.pyindex a7028e7..496f958 100644--- a/tests/providers/test_anthropic.py+++ b/tests/providers/test_anthropic.py@@ -824,6 +824,26 @@ class TestAnthropicStreamError:event_types = [e.type for e in stream_events]assert "error" in event_types+ @pytest.mark.asyncio+ async def test_error_result_carries_provider_and_model(self):+ provider = _make_provider("none")+ mock_client = MagicMock()+ mock_client.messages = MagicMock()+ mock_client.messages.stream = MagicMock(side_effect=RuntimeError("API down"))+ provider._client = mock_client++ model = _anthropic_model()+ ms = await provider.stream(+ model, [UserMessage(content=[TextContent(text="hi")])]+ )+ async for _ in ms:+ pass+ result = await ms.result()++ assert result.provider_id == "anthropic"+ assert result.model_id == model.id+ assert f"anthropic/{model.id}" in (result.error_message or "")+@pytest.mark.asyncioasync def test_base_exception_reraises(self):"""When the SDK raises BaseException (not Exception), it should be re-raised on the task."""diff --git a/tests/providers/test_base.py b/tests/providers/test_base.pyindex 34ec2c2..a2cca19 100644--- a/tests/providers/test_base.py+++ b/tests/providers/test_base.py@@ -16,9 +16,56 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ format_provider_error,)+class TestFormatProviderError:+ @staticmethod+ def _model() -> Model:+ return Model(id="gpt-4o", provider="openai")++ def test_includes_provider_model_and_exception(self):+ msg = format_provider_error(RuntimeError("boom"), self._model())+ assert "openai/gpt-4o" in msg+ assert "RuntimeError" in msg+ assert "boom" in msg++ def test_includes_base_url_when_given(self):+ msg = format_provider_error(+ RuntimeError("boom"),+ self._model(),+ base_url="https://api.deepseek.com/anthropic",+ )+ assert "https://api.deepseek.com/anthropic" in msg++ def test_surfaces_underlying_cause_chain(self):+ # Mirrors openai's APIConnectionError("Connection error.") wrapping the+ # real transport failure in __cause__ — the part users actually need.+ try:+ try:+ raise OSError("Cannot connect to proxy 192.168.1.111:7892")+ except OSError as root:+ raise RuntimeError("Connection error.") from root+ except RuntimeError as exc:+ msg = format_provider_error(exc, self._model())+ assert "Connection error." in msg+ assert "Cannot connect to proxy 192.168.1.111:7892" in msg+ assert "OSError" in msg++ def test_surfaces_implicit_context_cause(self):+ # Exceptions raised during handling without `from` keep the original in+ # __context__; that must still be surfaced.+ try:+ try:+ raise OSError("network down")+ except OSError:+ raise RuntimeError("wrapper")+ except RuntimeError as exc:+ msg = format_provider_error(exc, self._model())+ assert "network down" in msg++class TestMessageTypes:def test_text_content_defaults(self):tc = TextContent()diff --git a/tests/providers/test_openai.py b/tests/providers/test_openai.pyindex 64f5e2b..6e69863 100644--- a/tests/providers/test_openai.py+++ b/tests/providers/test_openai.py@@ -570,6 +570,65 @@ class TestOpenAIStreamError:types = [e.type for e in events]assert "error" in types+ @pytest.mark.asyncio+ async def test_error_result_carries_provider_and_model(self):+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()+ mock_client.chat.completions.create = AsyncMock(+ side_effect=RuntimeError("API down")+ )++ provider = OpenAIProvider(api_key="test-key")+ provider._client = mock_client++ ms = await provider.stream(+ _model(),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ error_events = [e async for e in ms if e.type == "error"]+ result = await ms.result()++ assert result.provider_id == "openai"+ assert result.model_id == "gpt-4o"+ assert "openai/gpt-4o" in (result.error_message or "")+ assert error_events and "openai/gpt-4o" in (+ error_events[0].error_message or ""+ )++ @pytest.mark.asyncio+ async def test_error_message_surfaces_underlying_cause(self):+ try:+ raise OSError("Cannot connect to proxy 192.168.1.111:7892")+ except OSError as root:+ api_err = RuntimeError("Connection error.")+ api_err.__cause__ = root++ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()+ mock_client.chat.completions.create = AsyncMock(side_effect=api_err)++ provider = OpenAIProvider(api_key="test-key")+ provider._client = mock_client++ ms = await provider.stream(+ _model(),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ async for _ in ms:+ pass+ result = await ms.result()++ assert "Connection error." in (result.error_message or "")+ assert "Cannot connect to proxy 192.168.1.111:7892" in (+ result.error_message or ""+ )+@pytest.mark.asyncioasync def test_base_exception_reraised(self):"""BaseException subclass (non-Exception) should set error result and re-raise."""