File size: 6,357 Bytes
b5698d6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
## built-in libraries
import typing
## third-party libraries
from openai import AsyncOpenAI
## custom modules
from modules.common.exceptions import InvalidAPIKeyException
from custom_classes.messages import SystemTranslationMessage, Message
class OpenAIService:
## async client session
client = AsyncOpenAI(max_retries=0, api_key="DummyKey")
model:str
system_message:typing.Optional[typing.Union[SystemTranslationMessage, str]] = None
temperature:float
top_p:float
n:int
stream:bool
stop:typing.List[str] | None
logit_bias:typing.Dict[str, float] | None
max_tokens:int | None
presence_penalty:float
frequency_penalty:float
decorator_to_use:typing.Union[typing.Callable, None] = None
##-------------------start-of-set_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
def set_api_key(api_key:str) -> None:
"""
Sets the API key for the OpenAI client.
Parameters:
api_key (string) : The API key to set.
"""
OpenAIService.client.api_key = api_key
##-------------------start-of-set_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
def set_decorator(decorator:typing.Callable) -> None:
"""
Sets the decorator to use for the OpenAI service. Should be a callable that returns a decorator.
Parameters:
decorator (callable) : The decorator to use.
"""
OpenAIService.decorator_to_use = decorator
##-------------------start-of-trans()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
async def translate_message(translation_instructions:Message, translation_prompt:Message) -> str:
"""
Translates a system and user message.
Parameters:
translation_instructions (object - SystemTranslationMessage | ModelTranslationMessage) : The system message also known as the instructions.
translation_prompt (object - ModelTranslationMessage) : The user message also known as the prompt.
Returns:
output (string) a string that gpt gives to us also known as the translation.
"""
if(OpenAIService.decorator_to_use == None):
return await OpenAIService._translate_message(translation_instructions, translation_prompt)
decorated_function = OpenAIService.decorator_to_use(OpenAIService._translate_message)
return await decorated_function(translation_instructions, translation_prompt)
##-------------------start-of-_translate_message()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## backoff wrapper for retrying on errors, As of OpenAI > 1.0.0, it comes with a built in backoff system, but I've grown accustomed to this one so I'm keeping it.
@staticmethod
async def _translate_message(translation_instructions:Message, translation_prompt:Message) -> str:
"""
Translates a system and user message.
Parameters:
translation_instructions (object - SystemTranslationMessage | ModelTranslationMessage) : The system message also known as the instructions.
translation_prompt (object - ModelTranslationMessage) : The user message also known as the prompt.
Returns:
output (string) a string that gpt gives to us also known as the translation.
"""
if(OpenAIService.client.api_key == "DummyKey"):
raise InvalidAPIKeyException("OpenAI")
## logit bias is currently excluded due to a lack of need, and the fact that i am lazy
response = await OpenAIService.client.chat.completions.create(
model=OpenAIService.model,
messages=[
translation_instructions.to_dict(),
translation_prompt.to_dict()
], # type: ignore
temperature = OpenAIService.temperature,
top_p = OpenAIService.top_p,
n = OpenAIService.n,
stream = OpenAIService.stream,
stop = OpenAIService.stop,
presence_penalty = OpenAIService.presence_penalty,
frequency_penalty = OpenAIService.frequency_penalty,
max_tokens = OpenAIService.max_tokens
)
## if anyone knows how to type hint this please let me know
output = response.choices[0].message.content
return output
##-------------------start-of-test_api_key_validity()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
async def test_api_key_validity() -> typing.Tuple[bool, typing.Union[Exception, None]]:
"""
Tests the validity of the API key.
Returns:
validity (bool) : True if the API key is valid, False if it is not.
e (Exception) : The exception that was raised, if any.
"""
validity = False
try:
await OpenAIService.client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role":"user","content":"This is a test."}],
max_tokens=1
)
validity = True
return validity, None
except Exception as e:
return validity, e
##-------------------start-of-get_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
def get_decorator() -> typing.Union[typing.Callable, None]:
"""
Returns the decorator to use for the OpenAI service.
Returns:
decorator (callable) : The decorator to use.
"""
return OpenAIService.decorator_to_use |