Skip to content

Only retry transient OpenAI errors #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main_july_updates
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion promptify/models/nlp/text2text/base_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABCMeta, abstractmethod
from typing import List, Optional, Union, Dict
from typing import Dict, List, Optional, Union

import tenacity


Expand Down Expand Up @@ -396,6 +397,7 @@ def _retry_decorator(self):
multiplier=0.3, exp_base=3, max=self.api_wait
),
stop=tenacity.stop_after_attempt(self.api_retry),
reraise=True,
)

def execute_with_retry(self, *args, **kwargs):
Expand Down
33 changes: 31 additions & 2 deletions promptify/models/nlp/text2text/openai_complete.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from typing import Dict, List, Optional, Tuple, Union
import openai

import json
import openai
import tenacity
import tiktoken
from promptify.parser.parser import Parser

from promptify.models.nlp.text2text.base_model import Model
from promptify.parser.parser import Parser


class OpenAI(Model):
Expand Down Expand Up @@ -329,6 +332,32 @@ def model_output(self, response: Dict, max_completion_length: int) -> Dict:

return data

def _retry_decorator(self):
"""
Decorator function for retrying API requests if they fail.

Returns
-------
tenacity.Retrying
A decorator function for retrying API requests.

Notes
-----
This method is a decorator function for retrying API requests using tenacity.
"""

return tenacity.retry(
wait=tenacity.wait_random_exponential(
multiplier=0.3, exp_base=3, max=self.api_wait
),
stop=tenacity.stop_after_attempt(self.api_retry),
retry=tenacity.retry_if_exception_type(
(openai.error.APIError, openai.error.TryAgain, openai.error.Timeout,
openai.error.APIConnectionError, openai.error.RateLimitError,
openai.error.ServiceUnavailableError, )),
reraise=True,
)

def _store_session(self, session_identifier: str):
import json
import os
Expand Down