from __future__ import annotations
from typing import Any
class AiMemoryError(Exception):
def __init__(
self,
message: str,
*,
status_code: int | None = None,
payload: Any = None,
) -> None:
super().__init__(message)
self.status_code = status_code
self.payload = payload
class TransportError(AiMemoryError):
class ValidationError(AiMemoryError):
class AuthError(AiMemoryError):
class ForbiddenError(AiMemoryError):
class NotFoundError(AiMemoryError):
class ConflictError(AiMemoryError):
class RateLimitError(AiMemoryError):
class ServerError(AiMemoryError):
def raise_for_status(status: int, payload: Any) -> None:
if status < 400:
return
message = _extract_message(payload) or f"HTTP {status}"
cls: type[AiMemoryError]
if status == 400:
cls = ValidationError
elif status == 401:
cls = AuthError
elif status == 403:
cls = ForbiddenError
elif status == 404:
cls = NotFoundError
elif status == 409:
cls = ConflictError
elif status == 429:
cls = RateLimitError
elif 500 <= status < 600:
cls = ServerError
else:
cls = AiMemoryError
raise cls(message, status_code=status, payload=payload)
def _extract_message(payload: Any) -> str | None:
if isinstance(payload, dict):
for key in ("error", "message", "reason", "detail"):
v = payload.get(key)
if isinstance(v, str) and v:
return v
return None