"""Registry management for Haive engines.This module provides a centralized registry for all engine instances in the Haive system.The registry allows engines to be registered, retrieved, and managed through a singletonpattern, ensuring consistent access across the application."""importloggingfromhaive.core.engine.base.baseimportEnginefromhaive.core.engine.base.typesimportEngineTypefromhaive.core.registry.baseimportAbstractRegistrylogger=logging.getLogger(__name__)
[docs]classEngineRegistry(AbstractRegistry[Engine]):"""Central registry for all engines in the Haive system. This class implements a singleton pattern to ensure a single point of access for all engine registrations and lookups. Engines are organized by their type and can be accessed by name or by their unique ID. Attributes: engines (Dict[EngineType, Dict[str, Engine]]): Nested dictionary storing engines by their type and name. engine_ids (Dict[str, Engine]): Dictionary mapping engine IDs to engine instances. """_instance=None
[docs]@classmethoddefget_instance(cls)->"EngineRegistry":"""Get the singleton instance of the engine registry. This method ensures that only one instance of the registry exists throughout the application lifecycle. Returns: EngineRegistry: The singleton instance of the registry. Examples: >>> registry = EngineRegistry.get_instance() >>> # All subsequent calls return the same instance >>> registry2 = EngineRegistry.get_instance() >>> registry is registry2 True """ifcls._instanceisNone:cls._instance=cls()returncls._instance
def__init__(self)->None:"""Initialize the registry with empty dictionaries. Creates an empty registry structure with dictionaries for each engine type and an empty ID mapping dictionary. """self.engines={engine_type:{}forengine_typeinEngineType}self.engine_ids={}# id -> engine mapping
[docs]defregister(self,item:Engine)->Engine:"""Register an engine in the registry. Adds the provided engine to the registry, indexed by both its type/name and its unique ID. Args: item (Engine): The engine instance to register. Returns: Engine: The registered engine instance (same as input). Examples: >>> from haive.core.engine.base.base import Engine >>> registry = EngineRegistry.get_instance() >>> engine = Engine(name="my_engine", engine_type=EngineType.LLM) >>> registry.register(engine) >>> registry.find("my_engine") is engine True """self.engines[item.engine_type][item.name]=itemself.engine_ids[item.id]=itemlogger.debug(f"Registered engine {item.name} (id: {item.id}) of type {item.engine_type}")returnitem
[docs]defget(self,item_type:EngineType,name:str)->Engine|None:"""Get an engine by its type and name. Retrieves an engine instance from the registry using its type and name. Args: item_type (EngineType): The type of engine to retrieve. name (str): The name of the engine to retrieve. Returns: Optional[Engine]: The requested engine instance, or None if not found. Examples: >>> registry = EngineRegistry.get_instance() >>> engine = registry.get(EngineType.LLM, "gpt-4") >>> if engine: ... print(f"Found engine: {engine.name}") ... else: ... print("Engine not found") """returnself.engines[item_type].get(name)
[docs]deffind_by_id(self,id:str)->Engine|None:"""Find an engine by its unique ID. Retrieves an engine instance from the registry using its unique ID. Args: id (str): The unique ID of the engine to find. Returns: Optional[Engine]: The requested engine instance, or None if not found. Examples: >>> registry = EngineRegistry.get_instance() >>> engine = registry.find_by_id("550e8400-e29b-41d4-a716-446655440000") >>> if engine: ... print(f"Found engine: {engine.name}") """returnself.engine_ids.get(id)
[docs]deffind(self,name_or_id:str)->Engine|None:"""Find an engine by name or ID across all engine types. Searches for an engine by first checking the ID registry (faster) and then searching through all engine types by name. Args: name_or_id (str): The name or ID of the engine to find. Returns: Optional[Engine]: The requested engine instance, or None if not found. Examples: >>> registry = EngineRegistry.get_instance() >>> # Can find by ID >>> engine1 = registry.find("550e8400-e29b-41d4-a716-446655440000") >>> # Or by name >>> engine2 = registry.find("gpt-4") """# Check ID first (faster lookup)ifengine:=self.engine_ids.get(name_or_id):returnengine# Search through all engine types by nameforengine_typeinEngineType:ifengine:=self.get(engine_type,name_or_id):returnenginereturnNone
[docs]deflist(self,item_type:EngineType)->list[str]:"""List all engines of a specific type. Returns a list of names of all engines registered for the given type. Args: item_type (EngineType): The type of engines to list. Returns: List[str]: A list of engine names of the specified type. Examples: >>> registry = EngineRegistry.get_instance() >>> llm_engines = registry.list(EngineType.LLM) >>> print(f"Available LLM engines: {', '.join(llm_engines)}") """returnlist(self.engines[item_type].keys())
[docs]defget_all(self,item_type:EngineType)->dict[str,Engine]:"""Get all engines of a specific type. Returns a dictionary mapping names to engines for the given type. Args: item_type (EngineType): The type of engines to retrieve. Returns: Dict[str, Engine]: A dictionary of engine names to engine instances. Examples: >>> registry = EngineRegistry.get_instance() >>> all_llms = registry.get_all(EngineType.LLM) >>> for name, engine in all_llms.items(): ... print(f"LLM: {name}, ID: {engine.id}") """returnself.engines[item_type]
[docs]defclear(self)->None:"""Clear the registry. Removes all engines from the registry, resetting it to an empty state. Useful for testing or when reloading configurations. Examples: >>> registry = EngineRegistry.get_instance() >>> # After operations that registered engines >>> registry.clear() >>> assert len(registry.list(EngineType.LLM)) == 0 """self.engines={engine_type:{}forengine_typeinEngineType}self.engine_ids={}