diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..56c04ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +secret* +*.[Ss]ecrets.* +__pycache__ \ No newline at end of file diff --git a/Python/AetherAgentsServer/Application/Printer.py b/Python/AetherAgentsServer/Application/Printer.py new file mode 100644 index 0000000..4c15f65 --- /dev/null +++ b/Python/AetherAgentsServer/Application/Printer.py @@ -0,0 +1,72 @@ +from typing import Self, Any, Optional, Sequence +import datetime +from AetherAgentsServer.Utils.Common import Common + +class Printer: + + def print(self:Self, + _type:str, + message:str|Sequence[str], + inputs:Optional[dict[str, Any|None]|Sequence[Any|None]] = None, + i:int = 0 + ) -> None: + + date:datetime.datetime = datetime.datetime.now() + own:dict[str, Any] = { + "raw_type" : _type, + "type": self.print_types.get(_type), + "message": self.i18n.get(message, inputs), + **Common.get_dictionary(inputs), + **Common.get_action_data(i + 1) + } + + for key in ("year", "month", "day", "hour", "minute", "second"): + + k:str = "i" if key == "minute" else key[0] + + own[k] = own[key] = getattr(date, key) + own[k + k] = ("00" + str(own[key]))[-2:] + + own["yyyy"] = ("0000" + str(own["year"]))[-4:] + + for root_path in self.__root_projects_paths: + if own["file"].startswith(root_path): + own["file"] = own["file"][len(root_path):] + break + + if any(own["type"].startswith(end_type) for end_type in self.__end_print_types) and "end" in own: + own["message"] += own["end"] + + print(Common.string_variables(self.__print_format, own)) + + def exception(self:Self, + exception:Exception, + message:str|Sequence[str], + inputs:Optional[dict[str, Any|None]|Sequence[Any|None]] = None, + i:int = 0 + ) -> None: + + lines:list[str] = extract_traceback(exception.__traceback__).format() + matches:REMatch = RE.EXCEPTION.match(lines[-1]) + data:dict[str, Any|None] = { + **Common.get_dictionary(inputs), + "lines" : "", + "exception_message" : str(exception), + "method" : matches.group(3), + "line" : matches.group(2), + "file" : matches.group(1) + } + block:str + j:int + + for root_path in self.__root_projects_paths: + if data["file"] and data["file"].startswith(root_path): + data["file"] = data["file"][len(root_path):] + + for j, block in enumerate(trace_format_stack()[:-2] + lines): + if block: + data["lines"] += "\n " + str(j) + " - " + RE.NEW_LINE.split(block.strip())[0] + + data["end"] = Common.string_variables(self.__exception_format, data) + + message and self.print("exception", message, data, i + 2) \ No newline at end of file diff --git a/Python/AetherCommon/Utils/Check.py b/Python/AetherCommon/Utils/Check.py new file mode 100644 index 0000000..c7284df --- /dev/null +++ b/Python/AetherCommon/Utils/Check.py @@ -0,0 +1,8 @@ +from typing import Any +from AetherAgentsServer.Utils.RE import RE + +class Check: + + @staticmethod + def is_key(item:Any) -> bool: + return isinstance(item, str) and item != "" and bool(RE.KEY.match(item)) \ No newline at end of file diff --git a/Python/AetherCommon/Utils/Common.py b/Python/AetherCommon/Utils/Common.py new file mode 100644 index 0000000..7ca1319 --- /dev/null +++ b/Python/AetherCommon/Utils/Common.py @@ -0,0 +1,82 @@ +from typing import Self, Any, Sequence, Optional +from inspect import FrameInfo, stack +from AetherAgentsServer.Utils.Check import Check + +class Common: + + @classmethod + def get_keys(cls:type[Self], *items:Any) -> list[str]: + + keys:list[str] = [] + item:Any + + for item in items: + if isinstance(item, (list, set, tuple)): + + key:str + + for key in cls.get_keys(*item): + if key not in keys: + keys.append(key) + elif Check.is_key(item) and item not in keys: + keys.append(item) + + return keys + + @classmethod + def get_dictionaries(cls:type[Self], *items:Any) -> list[dict[str, Any|None]]: + + dictionaries:list[dict[str, Any|None]] = [] + item:Any + + for item in items: + if isinstance(item, (list, set, tuple)): + + dictionary:dict[str, Any|None] + + for dictionary in cls.get_dictionaries(*item): + dictionaries.append(dictionary) + elif isinstance(item, dict): + dictionaries.append(item) + + return dictionaries + + @classmethod + def get_value(cls:type[Self], keys:str|Sequence[str], inputs:Any, _default:Optional[Any] = None) -> Any|None: + if len(keys := Common.get_keys(keys)): + + subinputs:dict[str, Any|None] + + for subinputs in Common.get_dictionaries(inputs): + + key:str + + for key in keys: + if key in subinputs: + return subinputs[key] + return _default + + @staticmethod + def get_action_data(i:int = 0) -> dict[str, str|int]: + + stack:FrameInfo = stack()[i] + + return { + "file" : stack.filename, + "method" : stack.function, + "line" : stack.lineno + } + + @classmethod + def get_dictionary(cls:type[Self], *inputs:Any) -> dict[str, Any|None]: + + dictionary:dict[str, Any|None] = {} + subinputs:Any|None + + for subinputs in inputs: + if isinstance(subinputs, (list, tuple, set)): + dictionary.update(cls.get_dictionary(*subinputs)) + elif isinstance(subinputs, dict): + dictionary.update(subinputs) + + return dictionary \ No newline at end of file diff --git a/Python/AetherCommon/Utils/RE.py b/Python/AetherCommon/Utils/RE.py new file mode 100644 index 0000000..7888c27 --- /dev/null +++ b/Python/AetherCommon/Utils/RE.py @@ -0,0 +1,4 @@ +from re import Pattern, compile, IGNORECASE + +class RE: + KEY:Pattern = compile(r'^[a-z_][a-z0-9_]*$', IGNORECASE) \ No newline at end of file diff --git a/Python/AetherModelsServer/AIModels/Gemma4AIModel.py b/Python/AetherModelsServer/AIModels/Gemma4AIModel.py new file mode 100644 index 0000000..02eb0f6 --- /dev/null +++ b/Python/AetherModelsServer/AIModels/Gemma4AIModel.py @@ -0,0 +1,4 @@ +from AetherOrchestrator.Abstracts.AIModelAbstract import AIModelAbstract + +class Gemma4AIModel(AIModelAbstract): + pass \ No newline at end of file diff --git a/Python/AetherModelsServer/Abstracts/ControllerAbstract.py b/Python/AetherModelsServer/Abstracts/ControllerAbstract.py new file mode 100644 index 0000000..a8f358d --- /dev/null +++ b/Python/AetherModelsServer/Abstracts/ControllerAbstract.py @@ -0,0 +1,11 @@ +from abc import ABC +from typing import Self, Optional, Any +from AetherModelsServer.Interfaces.Application.AetherModelsServerInterface import AetherModelsServerInterface + +class ControllerAbstract(ABC): + + ams:AetherModelsServerInterface + key:str + + def __init__(self:Self, ams:AetherModelsServerInterface, key:str, inputs:Optional[Any] = None) -> None: + object.__setattr__(self, "key", key) \ No newline at end of file diff --git a/Python/AetherModelsServer/Abstracts/ServerAbstract.py b/Python/AetherModelsServer/Abstracts/ServerAbstract.py new file mode 100644 index 0000000..3c3c774 --- /dev/null +++ b/Python/AetherModelsServer/Abstracts/ServerAbstract.py @@ -0,0 +1,70 @@ +from abc import ABC, abstractmethod +from typing import Self, Any, Optional +import threading +import requests +from AetherCommon.Utils.Common import Common +from AetherModelsServer.Models.CapabilitiesModel import CapabilitiesModel + +class ServerAbstract(CapabilitiesModel, ABC): + + id:int|str + name:str + host:str + maximum_threads:int + api_key:str|None + + def __init__(self:Self, id:int|str, inputs:Optional[Any] = None) -> None: + + object.__setattr__(self, "id", id) + object.__setattr__(self, "name", str(Common.get_value("name", inputs, "unknown"))) + object.__setattr__(self, "host", str(Common.get_value("host", inputs, "")).rstrip("/")) + object.__setattr__(self, "maximum_threads", int(Common.get_value(["maximum_threads", "max_threads"], inputs, 1))) + object.__setattr__(self, "api_key", Common.get_value(["api_key", "token"], inputs, None)) + + # Recursos vivos del servidor (no son propiedades inmutables de configuración) + self.semaphore:threading.BoundedSemaphore = threading.BoundedSemaphore(value = self.maximum_threads) + self.session:requests.Session = requests.Session() + + # Inicialización de capacidades base + super().__init__(inputs) + + def __setattr__(self, name:str, value:Any) -> None: + # Permitimos asignar atributos internos de infraestructura si fuera necesario, + # pero protegemos la configuración base + if hasattr(self, name) and name in ("id", "host", "maximum_threads", "api_key"): + raise AttributeError(f"El atributo '{name}' en {self.__class__.__name__} es inmutable.") + super().__setattr__(name, value) + + def send_http_request(self:Self, endpoint:str, payload:dict[str, Any], timeout:float = 120.0) -> dict[str, Any]: + """Método común para despachar HTTP a cualquier intérprete.""" + + url:str = f"{self.host}/{endpoint.lstrip('/')}" + headers:dict[str, str] = {} + response:requests.Response + + if self.api_key is not None: + headers["Authorization"] = f"Bearer {self.api_key}" + + response = self.session.post(url, json = payload, headers = headers, timeout = timeout) + + response.raise_for_status() + + return response.json() + + @abstractmethod + def execute_inference( + self:Self, + model_name:str, + messages:list[dict[str, Any]], + temperature:float = 0.2, + json_schema:Optional[dict[str, Any]] = None + ) -> dict[str, Any]: + """ + Debe devolver obligatoriamente un formato estándar: + { + "raw_text" : str, + "prompt_tokens" : int, + "completion_tokens" : int + } + """ + pass \ No newline at end of file diff --git a/Python/AetherModelsServer/Application/AetherModelsServer.py b/Python/AetherModelsServer/Application/AetherModelsServer.py new file mode 100644 index 0000000..382d325 --- /dev/null +++ b/Python/AetherModelsServer/Application/AetherModelsServer.py @@ -0,0 +1,13 @@ +import logging +from typing import Any, Self +from AetherModelsServer.Managers.ServersManager import ServersManager +from AetherModelsServer.Managers.AIModelsManager import AIModelsManager +from AetherModelsServer.Managers.ControllersManager import ControllersManager + +logging.basicConfig(level=logging.INFO, format="[%(threadName)s] %(message)s") + +class AetherModelsServer: + def __init__(self:Self, inputs:dict[str, Any]): + self.servers:ServersManager = ServersManager(self, inputs) + self.ai_models:AIModelsManager = AIModelsManager(self, inputs) + self.controllers:ControllersManager = ControllersManager(self, inputs) \ No newline at end of file diff --git a/Python/AetherModelsServer/Controllers/ModelController.py b/Python/AetherModelsServer/Controllers/ModelController.py new file mode 100644 index 0000000..f9d78ce --- /dev/null +++ b/Python/AetherModelsServer/Controllers/ModelController.py @@ -0,0 +1,115 @@ +from typing import Self, Any, Optional +import time +from AetherModelsServer.Abstracts.ControllerAbstract import ControllerAbstract +from AetherModelsServer.Abstracts.ServerAbstract import ServerAbstract +from AetherModelsServer.Models.AIModel import AIModel +from AetherModelsServer.Models.CapabilitiesModel import CapabilitiesModel + +class ModelController(ControllerAbstract): + + def echo(self:Self, server_id:Optional[int|str] = None) -> dict[str, Any]: + """Comprueba conectividad y latencia contra uno o todos los servidores activos.""" + + results:dict[int|str, Any] = {} + targets:dict[int|str, ServerAbstract] = ( + {server_id : self.ams.servers.get(server_id)} + if server_id is not None else self.ams.servers.get_all() + ) + id:int|str + server:ServerAbstract + + for id, server in targets.items(): + + start_time:float = time.time() + + try: + response = server.session.get(server.host, timeout=3.0) + is_alive:bool = response.status_code < 500 + except Exception: + is_alive = False + + results[id] = { + "host" : server.host, + "alive" : is_alive, + "latency_seconds" : round(time.time() - start_time, 3) + } + + return {"status" : "SUCCESS", "echo" : results} + + def catalog(self:Self) -> dict[str, Any]: + """Devuelve el catálogo de modelos resolviendo la capacidad efectiva con su servidor.""" + + data:dict[int|str, Any] = {} + id:int|str + model:AIModel + + for id, model in self.ams.ai_models.get_all().items(): + + server:ServerAbstract = self.ams.servers.get(model.server_id) + effective_capabilities:CapabilitiesModel = server.intersect(model) + + data[id] = { + "name" : model.name, + "server_id" : model.server_id, + "server_host" : server.host, + "capabilities" : { + "text" : effective_capabilities.text, + "json" : effective_capabilities.json, + "code" : effective_capabilities.code, + "vision" : effective_capabilities.vision, + "audio" : effective_capabilities.audio, + "video" : effective_capabilities.video, + "tools" : effective_capabilities.tools, + "streaming" : effective_capabilities.streaming + } + } + + return {"status" : "SUCCESS", "models" : data} + + def state(self:Self, model_id:int|str) -> dict[str, Any]: + """Consulta si el servidor del modelo tiene slots libres de ejecución inmediata.""" + + model:AIModel = self.ams.ai_models.get(model_id) + server:ServerAbstract = self.ams.servers.get(model.server_id) + + server_available:bool = server.semaphore.acquire(blocking=False) + if server_available: + server.semaphore.release() + + return { + "status" : "SUCCESS", + "model_id" : model_id, + "server_id" : server.id, + "ready_for_immediate_query" : server_available, + "server_busy" : not server_available + } + + def query( + self:Self, + model_id:int|str, + messages:list[dict[str, Any]], + temperature:float = 0.2, + json_schema:Optional[dict[str, Any]] = None + ) -> dict[str, Any]: + """Ejecuta inferencia aplicando semáforo del servidor y validación de capacidades.""" + + model:AIModel = self.ams.ai_models.get(model_id) + server:ServerAbstract = self.ams.servers.get(model.server_id) + effective_capabilities:CapabilitiesModel = server.intersect(model) + + if json_schema is not None and effective_capabilities.json is False: + raise ValueError(f"El modelo '{model_id}' o el servidor '{server.id}' no admiten salida por JSON Schema.") + + with server.semaphore: + inference_data:dict[str, Any] = server.execute_inference( + model_name = model.name, + messages = messages, + temperature = temperature, + json_schema = json_schema + ) + + return { + "model_id" : model_id, + "server_id" : server.id, + "response" : inference_data + } \ No newline at end of file diff --git a/Python/AetherModelsServer/Interfaces/Abstracts/ControllerAbstractInterface.py b/Python/AetherModelsServer/Interfaces/Abstracts/ControllerAbstractInterface.py new file mode 100644 index 0000000..01d0445 --- /dev/null +++ b/Python/AetherModelsServer/Interfaces/Abstracts/ControllerAbstractInterface.py @@ -0,0 +1,11 @@ +from abc import ABC +from typing import Self, Optional, Any + +class ControllerAbstractInterface(ABC): + + ams:Any + key:str + + def __init__(self:Self, ams:Any, key:str, inputs:Optional[Any] = None) -> None: + object.__setattr__(self, "ams", ams) + object.__setattr__(self, "key", key) \ No newline at end of file diff --git a/Python/AetherModelsServer/Interfaces/Application/AetherModelsServerInterface.py b/Python/AetherModelsServer/Interfaces/Application/AetherModelsServerInterface.py new file mode 100644 index 0000000..605c6db --- /dev/null +++ b/Python/AetherModelsServer/Interfaces/Application/AetherModelsServerInterface.py @@ -0,0 +1,10 @@ +from typing import Any, Self +from AetherModelsServer.Interfaces.Managers.ServersManagerInterface import ServersManagerInterface +from AetherModelsServer.Interfaces.Managers.AIModelsManagerInterface import AIModelsManagerInterface +from AetherModelsServer.Interfaces.Managers.ControllersManagerInterface import ControllersManagerInterface + +class AetherModelsServerInterface: + def __init__(self:Self, inputs:dict[str, Any]): + self.servers:ServersManagerInterface = None + self.ai_models:AIModelsManagerInterface = None + self.controllers:ControllersManagerInterface = None \ No newline at end of file diff --git a/Python/AetherModelsServer/Interfaces/Managers/AIModelsManagerInterface.py b/Python/AetherModelsServer/Interfaces/Managers/AIModelsManagerInterface.py new file mode 100644 index 0000000..fdd6bd8 --- /dev/null +++ b/Python/AetherModelsServer/Interfaces/Managers/AIModelsManagerInterface.py @@ -0,0 +1,22 @@ +from typing import Self, Any, Optional +from AetherModelsServer.Models.AIModel import AIModel + +class AIModelsManagerInterface: + + def register(self:Self, model:AIModel) -> AIModel:pass + + def create(self:Self, id:int|str, inputs:Optional[Any] = None) -> AIModel:pass + + def get(self:Self, id:int|str) -> AIModel:pass + + def has(self:Self, id:int|str) -> bool:pass + + def get_all(self:Self) -> dict[int|str, AIModel]:pass + + def get_list(self:Self) -> list[AIModel]:pass + + def get_by_server(self:Self, server_id:int|str) -> list[AIModel]:pass + + def get_by_capability(self:Self, capability:str) -> list[AIModel]:pass + + def load(self:Self, inputs:Optional[Any]) -> None:pass \ No newline at end of file diff --git a/Python/AetherModelsServer/Interfaces/Managers/ControllersManagerInterface.py b/Python/AetherModelsServer/Interfaces/Managers/ControllersManagerInterface.py new file mode 100644 index 0000000..390cb16 --- /dev/null +++ b/Python/AetherModelsServer/Interfaces/Managers/ControllersManagerInterface.py @@ -0,0 +1,20 @@ +from typing import Self, Any, Optional, Type +from AetherModelsServer.Interfaces.Abstracts.ControllerAbstractInterface import ControllerAbstractInterface + +class ControllersManagerInterface: + + def register_type(self:Self, key:str, Class:Type[ControllerAbstractInterface]) -> None:pass + + def load_types(self:Self, inputs:Any) -> None:pass + + def register(self:Self, key:str, controller:ControllerAbstractInterface) -> ControllerAbstractInterface:pass + + def create(self:Self, key:str, inputs:Optional[Any] = None) -> ControllerAbstractInterface:pass + + def get(self:Self, key:str) -> ControllerAbstractInterface:pass + + def has(self:Self, key:str) -> bool:pass + + def get_all(self:Self) -> dict[str, ControllerAbstractInterface]:pass + + def load(self:Self, inputs:Optional[Any]) -> None:pass \ No newline at end of file diff --git a/Python/AetherModelsServer/Interfaces/Managers/ServersManagerInterface.py b/Python/AetherModelsServer/Interfaces/Managers/ServersManagerInterface.py new file mode 100644 index 0000000..a4364ee --- /dev/null +++ b/Python/AetherModelsServer/Interfaces/Managers/ServersManagerInterface.py @@ -0,0 +1,24 @@ +from typing import Self, Any, Optional, Type +from AetherModelsServer.Abstracts.ServerAbstract import ServerAbstract + +class ServersManagerInterface: + + def register_type(self:Self, key:str, Class:Type[ServerAbstract]) -> None:pass + + def load_types(self:Self, inputs:Any) -> None:pass + + def register(self:Self, server:ServerAbstract) -> ServerAbstract:pass + + def create(self:Self, id:int|str, inputs:Optional[Any] = None) -> ServerAbstract:pass + + def get(self:Self, id:int|str) -> ServerAbstract:pass + + def has(self:Self, id:int|str) -> bool:pass + + def get_all(self:Self) -> dict[int|str, ServerAbstract]:pass + + def get_list(self:Self) -> list[ServerAbstract]:pass + + def get_by_capability(self:Self, capability:str) -> list[ServerAbstract]:pass + + def load(self:Self, inputs:Optional[Any]) -> None:pass \ No newline at end of file diff --git a/Python/AetherModelsServer/Managers/AIModelsManager.py b/Python/AetherModelsServer/Managers/AIModelsManager.py new file mode 100644 index 0000000..e104534 --- /dev/null +++ b/Python/AetherModelsServer/Managers/AIModelsManager.py @@ -0,0 +1,96 @@ +from typing import Self, Any, Optional +from AetherCommon.Utils.Common import Common +from AetherModelsServer.Models.AIModel import AIModel +from AetherModelsServer.Interfaces.Application.AetherModelsServerInterface import AetherModelsServerInterface + +class AIModelsManager: + + ams:AetherModelsServerInterface + + def __init__(self:Self, ams:AetherModelsServerInterface, inputs:Optional[Any] = None) -> None: + + object.__setattr__(self, "ams", ams) + self.__models:dict[int|str, AIModel] = {} + + self.load(Common.get_value("ai_models", inputs)) + + def register(self:Self, model:AIModel) -> AIModel: + if not isinstance(model, AIModel): + raise TypeError(f"El objeto proporcionado debe ser una instancia de AIModel, recibido: {type(model).__name__}") + + self.__models[model.id] = model + + return model + + def create(self:Self, id:int|str, inputs:Optional[Any] = None) -> AIModel: + return self.register(AIModel(id, inputs)) + + def get(self:Self, id:int|str) -> AIModel: + if id not in self.__models: + raise KeyError(f"Modelo con identificador '{id}' no encontrado en el gestor.") + return self.__models[id] + + def has(self:Self, id:int|str) -> bool: + return id in self.__models + + def get_all(self:Self) -> dict[int|str, AIModel]: + return dict(self.__models) + + def get_list(self:Self) -> list[AIModel]: + return list(self.__models.values()) + + def get_by_server(self:Self, server_id:int|str) -> list[AIModel]: + """Devuelve todos los modelos asignados a un servidor específico.""" + + matching:list[AIModel] = [] + model:AIModel + + for model in self.__models.values(): + if model.server_id == server_id: + matching.append(model) + + return matching + + def get_by_capability(self:Self, capability:str) -> list[AIModel]: + """Filtra modelos que declaren activa una capacidad específica.""" + + matching:list[AIModel] = [] + model:AIModel + + for model in self.__models.values(): + if getattr(model, capability, False) is True: + matching.append(model) + + return matching + + def load(self:Self, inputs:Optional[Any]) -> None: + """Extrae y registra modelos admitiendo lista, diccionario o bloque 'models'.""" + if inputs is None: + return + + container:Any = Common.get_value(["models", "ai_models"], inputs, inputs) + + if isinstance(container, AIModel): + self.__models[container.id] = container + + elif isinstance(container, dict): + if "name" in container and ("id" in container or "identifier" in container): + self.create(Common.get_value(["id", "identifier"], container, 0), container) + else: + + id:int|str + configuration:Any + + for id, configuration in container.items(): + if isinstance(configuration, dict): + self.create(id, configuration) + + elif isinstance(container, (list, tuple, set)): + + item:Any + + for item in container: + if isinstance(item, dict): + id:int|str|None = Common.get_value(["id", "identifier"], item, None) + if id is not None: + self.create(id, item) \ No newline at end of file diff --git a/Python/AetherModelsServer/Managers/ControllersManager.py b/Python/AetherModelsServer/Managers/ControllersManager.py new file mode 100644 index 0000000..e691b86 --- /dev/null +++ b/Python/AetherModelsServer/Managers/ControllersManager.py @@ -0,0 +1,107 @@ +from typing import Self, Any, Optional, Type +from AetherCommon.Utils.Common import Common +from AetherModelsServer.Abstracts.ControllerAbstract import ControllerAbstract +from AetherModelsServer.Controllers.ModelController import ModelController +from AetherModelsServer.Interfaces.Application.AetherModelsServerInterface import AetherModelsServerInterface + +class ControllersManager: + + ams:AetherModelsServerInterface + + def __init__(self:Self, ams:AetherModelsServerInterface, inputs:Optional[Any] = None) -> None: + + object.__setattr__(self, "ams", ams) + self.__types:dict[str, type[ControllerAbstract]] = {} + self.__controllers:dict[str, ControllerAbstract] = {} + + self.load_types(Common.get_value("controller_types", inputs)) + self.load(Common.get_value("controllers", inputs)) + + def register_type(self:Self, key:str, Class:Type[ControllerAbstract]) -> None: + """Permite registrar nuevos tipos de servidor externamente.""" + if not issubclass(Class, ControllerAbstract): + raise TypeError(f"La clase debe heredar de ControllerAbstract.") + self.__types[key.lower()] = Class + + def load_types(self:Self, inputs:Any) -> None: + if isinstance(inputs, type) and issubclass(inputs, ControllerAbstract): + self.__types[inputs.key] = inputs + elif isinstance(inputs, (list, set, tuple)): + + subinputs:Any + + for subinputs in inputs: + self.load_types(subinputs) + elif isinstance(inputs, dict): + + key:str + Class:Type[ControllerAbstract] + + for key, Class in inputs.items(): + self.register_type(key, Class) + + def register(self:Self, key:str, controller:ControllerAbstract) -> ControllerAbstract: + if not isinstance(controller, ControllerAbstract): + raise TypeError(f"El objeto debe heredar de ControllerAbstract, recibido: {type(controller).__name__}") + + self.__controllers[key.lower()] = controller + + return controller + + def create(self:Self, key:str, inputs:Optional[Any] = None) -> ControllerAbstract: + + _type:str = str(Common.get_value(["type", "_type"], inputs)).lower() + + if _type not in self.__types: + raise ValueError(f"Tipo de controlador no soportado: '{_type}'. Disponibles: {list(self.__types.keys())}") + return self.register(self.__types[_type](self.ams, key, inputs)) + + def get(self:Self, key:str) -> ControllerAbstract: + clean_key:str = key.lower() + if clean_key not in self.__controllers: + raise KeyError(f"Controlador '{key}' no encontrado en el gestor.") + return self.__controllers[clean_key] + + def has(self:Self, key:str) -> bool: + return key.lower() in self.__controllers + + def get_all(self:Self) -> dict[str, ControllerAbstract]: + return dict(self.__controllers) + + @property + def model(self:Self) -> ModelController: + instance:ControllerAbstract = self.get("model") + return instance # type: ignore + + def load(self:Self, inputs:Optional[Any]) -> None: + if inputs is None: + return + + container:Any = Common.get_value("servers", inputs, inputs) + + if isinstance(container, ControllerAbstract): + self.__servers[container.id] = container + + elif isinstance(container, dict): + if "host" in container and ("id" in container or "identifier" in container): + self.create(Common.get_value(["id", "identifier"], container, 0), container) + else: + + key:str + configuration:Any + + for key, configuration in container.items(): + if isinstance(configuration, dict): + self.create(key, configuration) + + elif isinstance(container, (list, tuple, set)): + + item:Any + + for item in container: + if isinstance(item, dict): + + key:int|str|None = Common.get_value("key", item, None) + + if key is not None: + self.create(key, item) \ No newline at end of file diff --git a/Python/AetherModelsServer/Managers/ServersManager.py b/Python/AetherModelsServer/Managers/ServersManager.py new file mode 100644 index 0000000..3d5d4fa --- /dev/null +++ b/Python/AetherModelsServer/Managers/ServersManager.py @@ -0,0 +1,112 @@ +from typing import Self, Any, Optional, Type +from AetherCommon.Utils.Common import Common +from AetherModelsServer.Abstracts.ServerAbstract import ServerAbstract +from AetherModelsServer.Interfaces.Application.AetherModelsServerInterface import AetherModelsServerInterface + +class ServersManager: + + ams:AetherModelsServerInterface + + def __init__(self:Self, ams:AetherModelsServerInterface, inputs:Optional[Any] = None) -> None: + + object.__setattr__(self, "ams", ams) + self.__servers:dict[int|str, ServerAbstract] = {} + self.__types:dict[str, Type[ServerAbstract]] = {} + + self.load_types(Common.get_value("server_types", inputs)) + self.load(Common.get_value("servers", inputs)) + + def register_type(self:Self, key:str, Class:Type[ServerAbstract]) -> None: + """Permite registrar nuevos tipos de servidor externamente.""" + if not issubclass(Class, ServerAbstract): + raise TypeError(f"La clase debe heredar de ServerAbstract.") + self.__types[key.lower()] = Class + + def load_types(self:Self, inputs:Any) -> None: + if isinstance(inputs, type) and issubclass(inputs, ServerAbstract): + self.__types[inputs.name] = inputs + elif isinstance(inputs, (list, set, tuple)): + + subinputs:Any + + for subinputs in inputs: + self.load_types(subinputs) + elif isinstance(inputs, dict): + + key:str + Class:Type[ServerAbstract] + + for key, Class in inputs.items(): + self.register_type(key, Class) + + def register(self:Self, server:ServerAbstract) -> ServerAbstract: + if not isinstance(server, ServerAbstract): + raise TypeError(f"El objeto debe ser instancia de ServerAbstract, recibido: {type(server).__name__}") + + self.__servers[server.id] = server + + return server + + def create(self:Self, id:int|str, inputs:Optional[Any] = None) -> ServerAbstract: + + _type:str = str(Common.get_value(["type", "engine", "_type"], inputs, "ollama")).lower() + + if _type not in self.__types: + raise ValueError(f"Tipo de servidor no soportado: '{_type}'. Disponibles: {list(self.__types.keys())}") + return self.register(self.__types[_type](id, inputs)) + + def get(self:Self, id:int|str) -> ServerAbstract: + if id not in self.__servers: + raise KeyError(f"Servidor con identificador '{id}' no encontrado.") + return self.__servers[id] + + def has(self:Self, id:int|str) -> bool: + return id in self.__servers + + def get_all(self:Self) -> dict[int|str, ServerAbstract]: + return dict(self.__servers) + + def get_list(self:Self) -> list[ServerAbstract]: + return list(self.__servers.values()) + + def get_by_capability(self:Self, capability:str) -> list[ServerAbstract]: + + matching:list[ServerAbstract] = [] + server:ServerAbstract + + for server in self.__servers.values(): + if getattr(server, capability, False) is True: + matching.append(server) + + return matching + + def load(self:Self, inputs:Optional[Any]) -> None: + if inputs is None: + return + + container:Any = Common.get_value("servers", inputs, inputs) + + if isinstance(container, ServerAbstract): + self.__servers[container.id] = container + + elif isinstance(container, dict): + if "host" in container and ("id" in container or "identifier" in container): + self.create(Common.get_value(["id", "identifier"], container, 0), container) + else: + + id:int|str + configuration:Any + + for id, configuration in container.items(): + if isinstance(configuration, dict): + self.create(id, configuration) + + elif isinstance(container, (list, tuple, set)): + + item:Any + + for item in container: + if isinstance(item, dict): + extracted_id:int|str|None = Common.get_value(["id", "identifier"], item, None) + if extracted_id is not None: + self.create(extracted_id, item) \ No newline at end of file diff --git a/Python/AetherModelsServer/Models/AIModel.py b/Python/AetherModelsServer/Models/AIModel.py new file mode 100644 index 0000000..5672f50 --- /dev/null +++ b/Python/AetherModelsServer/Models/AIModel.py @@ -0,0 +1,24 @@ +from typing import Self, Any, Optional +from AetherCommon.Utils.Common import Common +from AetherModelsServer.Models.CapabilitiesModel import CapabilitiesModel + +class AIModel(CapabilitiesModel): + + id:int|str + name:str + server_id:int|str + maximum_threads:int + + def __init__(self:Self, id:int|str, inputs:Optional[Any] = None) -> None: + object.__setattr__(self, "id", id) + # Nombre del modelo en el backend (ej: "llama3:8b", "qwen2.5-coder:7b") + object.__setattr__(self, "name", str(Common.get_value(["name", "model_name", "model"], inputs, id))) + # Identificador del servidor que lo aloja + object.__setattr__(self, "server_id", Common.get_value(["server_id", "server"], inputs, "")) + # Hilos máximos permitidos específicamente para este modelo + object.__setattr__(self, "maximum_threads", int(Common.get_value(["maximum_threads", "max_threads"], inputs, 1))) + + super().__init__(inputs) + + def __setattr__(self, name:str, value:Any) -> None: + raise AttributeError(f"{self.__class__.__name__} es inmutable.") \ No newline at end of file diff --git a/Python/AetherModelsServer/Models/CapabilitiesModel.py b/Python/AetherModelsServer/Models/CapabilitiesModel.py new file mode 100644 index 0000000..8796de4 --- /dev/null +++ b/Python/AetherModelsServer/Models/CapabilitiesModel.py @@ -0,0 +1,33 @@ +from typing import Self, Any +from AetherCommon.Utils.Common import Common + +class CapabilitiesModel: + + text:bool + json:bool + code:bool + vision:bool + audio:bool + video:bool + tools:bool + streaming:bool + + def __init__(self:Self, inputs:Any|None) -> None: + + key:str + value:bool + + for (key, value) in ( + ("text", True), + ("json", False), + ("code", True), + ("vision", False), + ("audio", False), + ("video", False), + ("tools", False), + ("streaming", False) + ): + object.__setattr__(self, key, bool(Common.get_value(key, inputs, value))) + + def __setattr__(self, name: str, value: Any) -> None: + raise AttributeError(f"{self.__class__.__name__} es inmutable.") \ No newline at end of file diff --git a/Python/AetherModelsServer/Servers/OllamaServer.py b/Python/AetherModelsServer/Servers/OllamaServer.py new file mode 100644 index 0000000..594899a --- /dev/null +++ b/Python/AetherModelsServer/Servers/OllamaServer.py @@ -0,0 +1,36 @@ +from typing import Self, Any, Optional +from AetherModelsServer.Abstracts.ServerAbstract import ServerAbstract + +class OllamaServer(ServerAbstract): + + def execute_inference( + self:Self, + model_name:str, + messages:list[dict[str, Any]], + temperature:float = 0.2, + json_schema:Optional[dict[str, Any]] = None + ) -> dict[str, Any]: + + payload:dict[str, Any] = { + "model" : model_name, + "messages" : messages, + "stream" : False, + "options" : { + "temperature" : temperature + } + } + response_data:dict[str, Any] + + # Ollama compila el JSON Schema a nivel de gramática si se pasa un dict en 'format' + if json_schema is not None: + payload["format"] = json_schema + elif self.json is True: + payload["format"] = "json" + + response_data = self.send_http_request("api/chat", payload) + + return { + "raw_text" : response_data.get("message", {}).get("content", ""), + "prompt_tokens" : response_data.get("prompt_eval_count", 0), + "completion_tokens" : response_data.get("eval_count", 0) + } \ No newline at end of file diff --git a/Python/run.models.py b/Python/run.models.py new file mode 100644 index 0000000..604214d --- /dev/null +++ b/Python/run.models.py @@ -0,0 +1,22 @@ +from AetherModelsServer.Application.AetherModelsServer import AetherModelsServer +from AetherModelsServer.Servers.OllamaServer import OllamaServer + +ams:AetherModelsServer = AetherModelsServer({ + "server_types": { + "ollama": OllamaServer + }, + "servers": { + "local_ollama": { + "type": "ollama", + "host": "http://localhost:11434", + "maximum_threads": 2 + } + }, + "ai_models": { + "gemma": { + "name": "gemma2:2b", + "server_id": "local_ollama", + "json": True + } + } +}) \ No newline at end of file