DocsGPT/application/llm/base.py

29 lines
1019 B
Python
Raw Normal View History

2023-09-26 09:03:22 +00:00
from abc import ABC, abstractmethod
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
def _apply_decorator(self, method, decorator, *args, **kwargs):
return decorator(method, *args, **kwargs)
2023-09-26 09:03:22 +00:00
@abstractmethod
def _raw_gen(self, model, messages, stream, *args, **kwargs):
2023-09-26 09:03:22 +00:00
pass
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
def _raw_gen_stream(self, model, messages, stream, *args, **kwargs):
2023-09-26 09:03:22 +00:00
pass
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
)