anthropic_wrapper.py 1.1 KB

123456789101112131415161718192021222324252627
  1. import logging
  2. from functools import wraps
  3. import anthropic
  4. from core.llm.error import LLMAPIConnectionError, LLMAPIUnavailableError, LLMRateLimitError, LLMAuthorizationError, \
  5. LLMBadRequestError
  6. def handle_anthropic_exceptions(func):
  7. @wraps(func)
  8. def wrapper(*args, **kwargs):
  9. try:
  10. return func(*args, **kwargs)
  11. except anthropic.APIConnectionError as e:
  12. logging.exception("Failed to connect to Anthropic API.")
  13. raise LLMAPIConnectionError(f"Anthropic: The server could not be reached, cause: {e.__cause__}")
  14. except anthropic.RateLimitError:
  15. raise LLMRateLimitError("Anthropic: A 429 status code was received; we should back off a bit.")
  16. except anthropic.AuthenticationError as e:
  17. raise LLMAuthorizationError(f"Anthropic: {e.message}")
  18. except anthropic.BadRequestError as e:
  19. raise LLMBadRequestError(f"Anthropic: {e.message}")
  20. except anthropic.APIStatusError as e:
  21. raise LLMAPIUnavailableError(f"Anthropic: code: {e.status_code}, cause: {e.message}")
  22. return wrapper