Files
cyclop/base_telegram_inference_bot.py
T

74 lines
2.3 KiB
Python
Raw Normal View History

2024-08-19 12:54:13 -05:00
import importlib
2024-08-19 11:34:31 -05:00
import os
import json
2024-08-19 12:54:13 -05:00
import inspect
2024-08-19 11:34:31 -05:00
from abc import ABC, abstractmethod
2024-08-19 12:54:13 -05:00
from tools.base_tool import BaseTool
2024-08-19 11:34:31 -05:00
class BaseTelegramInferenceBot(ABC):
def __init__(self):
self.conversation_history = {}
self.processing_status = {}
self.system_prompt = self.load_system_prompt()
2024-08-19 12:54:13 -05:00
self.tools, self.functions = self.load_functions()
2024-08-19 11:34:31 -05:00
@staticmethod
def load_system_prompt():
2024-08-20 16:48:06 -05:00
with open(os.environ.get("SYSTEM_PROMPT_PATH"), "r", encoding="utf-8") as file:
2024-08-19 11:34:31 -05:00
return file.read().strip()
@staticmethod
def load_functions():
2024-08-19 12:54:13 -05:00
tools = []
tools_dir = os.path.join(os.path.dirname(__file__), 'tools')
for filename in os.listdir(tools_dir):
if filename.endswith('.py') and filename != '__init__.py' and filename != 'base_tool.py':
module_name = f'tools.{filename[:-3]}'
module = importlib.import_module(module_name)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(obj, BaseTool) and obj != BaseTool:
tools.append(obj())
# Collect all function definitions
functions = []
for tool in tools:
functions.extend(tool.get_functions())
return tools, functions
2024-08-19 11:34:31 -05:00
@abstractmethod
def get_chat_response(self, messages):
pass
@abstractmethod
async def handle_message(self, user_id, user_message):
pass
def clear_conversation(self, user_id):
if user_id in self.conversation_history:
del self.conversation_history[user_id]
2024-08-19 13:38:39 -05:00
for tool in self.tools:
tool.clear()
2024-08-19 11:34:31 -05:00
2024-08-19 12:54:13 -05:00
def call_tool(self, function_call_name, function_call_arguments):
function_name = function_call_name
function_args = json.loads(function_call_arguments if function_call_arguments is not None else "{}")
2024-08-19 11:34:31 -05:00
for tool in self.tools:
if function_name in [f["name"] for f in tool.get_functions()]:
return tool.execute(function_name, **function_args)
@abstractmethod
async def start(self):
pass
@abstractmethod
async def clear(self, user_id):
pass
@abstractmethod
async def status(self):
pass
@abstractmethod
async def abort_processing(self, user_id):
pass