2023-09-26 09:03:22 +00:00
|
|
|
from abc import ABC, abstractmethod
|
2024-04-15 13:27:28 +00:00
|
|
|
from application.usage import gen_token_usage, stream_token_usage
|
2023-09-26 09:03:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BaseLLM(ABC):
|
|
|
|
def __init__(self):
|
2024-04-15 09:33:00 +00:00
|
|
|
self.token_usage = {"prompt_tokens": 0, "generated_tokens": 0}
|
2023-09-26 09:03:22 +00:00
|
|
|
|
2024-04-15 13:27:28 +00:00
|
|
|
def _apply_decorator(self, method, decorator, *args, **kwargs):
|
|
|
|
return decorator(method, *args, **kwargs)
|
|
|
|
|
2023-09-26 09:03:22 +00:00
|
|
|
@abstractmethod
|
2024-04-15 13:27:28 +00:00
|
|
|
def _raw_gen(self, model, messages, stream, *args, **kwargs):
|
2023-09-26 09:03:22 +00:00
|
|
|
pass
|
|
|
|
|
2024-04-15 13:27:28 +00:00
|
|
|
def gen(self, model, messages, stream=False, *args, **kwargs):
|
|
|
|
return self._apply_decorator(self._raw_gen, gen_token_usage)(
|
|
|
|
self, model=model, messages=messages, stream=stream, *args, **kwargs
|
|
|
|
)
|
|
|
|
|
2023-09-26 09:03:22 +00:00
|
|
|
@abstractmethod
|
2024-04-15 13:27:28 +00:00
|
|
|
def _raw_gen_stream(self, model, messages, stream, *args, **kwargs):
|
2023-09-26 09:03:22 +00:00
|
|
|
pass
|
2024-04-15 13:27:28 +00:00
|
|
|
|
|
|
|
def gen_stream(self, model, messages, stream=True, *args, **kwargs):
|
|
|
|
return self._apply_decorator(self._raw_gen_stream, stream_token_usage)(
|
|
|
|
self, model=model, messages=messages, stream=stream, *args, **kwargs
|
|
|
|
)
|