diff --git a/deepinfra/clients/deepinfra.py b/deepinfra/clients/deepinfra.py index ce5a7ee..0ca7667 100644 --- a/deepinfra/clients/deepinfra.py +++ b/deepinfra/clients/deepinfra.py @@ -1,7 +1,7 @@ -import json import time import requests +from deepinfra.exceptions import MaxRetriesExceededError from deepinfra.constants import ( MAX_RETRIES, USER_AGENT, @@ -19,6 +19,10 @@ def __init__(self, url, auth_token): self.url = url self.auth_token = auth_token + def backoff_delay(self, attempt): + delay = self.initial_backoff if attempt == 1 else self.subsequent_backoff + time.sleep(delay) + def post(self, data, config=None): """ Performs a POST request. @@ -36,9 +40,18 @@ def post(self, data, config=None): "User-Agent": USER_AGENT, "Authorization": f"Bearer {self.auth_token}", } - try: - response = requests.post(self.url, data=data, headers=headers) - response.raise_for_status() - return response - except requests.RequestException as error: - raise error + for attempt in range(self.max_retries + 1): + try: + response = requests.post(self.url, data=data, headers=headers) + response.raise_for_status() + return response + except requests.RequestException as error: + if attempt < self.max_retries: + print( + f"Request failed, retrying... Attempt {attempt + 1}/{self.max_retries}" + ) + self.backoff_delay(attempt + 1) + else: + raise error + + raise MaxRetriesExceededError() \ No newline at end of file diff --git a/deepinfra/constants/client.py b/deepinfra/constants/client.py index 6d9cc07..2d57565 100644 --- a/deepinfra/constants/client.py +++ b/deepinfra/constants/client.py @@ -2,7 +2,7 @@ This module contains the constants used by the DeepInfra API client. """ -MAX_RETRIES = 0 +MAX_RETRIES = 5 INITIAL_BACKOFF = 5000 SUBSEQUENT_BACKOFF = 2000 USER_AGENT = "DeepInfra Python API Client" diff --git a/deepinfra/exceptions/__init__.py b/deepinfra/exceptions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/deepinfra/exceptions/max_retries_exceeded.py b/deepinfra/exceptions/max_retries_exceeded.py new file mode 100644 index 0000000..ce51107 --- /dev/null +++ b/deepinfra/exceptions/max_retries_exceeded.py @@ -0,0 +1,12 @@ +""" +This error is raised when the maximum number of retries is exceeded by DeepInfraClient. +""" + + +class MaxRetriesExceededError(Exception): + """ + This error is raised when the maximum number of retries is exceeded by DeepInfraClient. + """ + + def __init__(self, message="Maximum retries exceeded"): + super().__init__(message) \ No newline at end of file