Backup-bdg/OpenHands
0
1import importlib2from functools import lru_cache3from typing import TypeVar4 5T = TypeVar('T')6 7 8def import_from(qual_name: str):9 """Import a value from its fully qualified name.10 11 This function is a utility to dynamically import any Python value (class, function, variable)12 from its fully qualified name. For example, 'openhands.server.user_auth.UserAuth' would13 import the UserAuth class from the openhands.server.user_auth module.14 15 Args:16 qual_name: A fully qualified name in the format 'module.submodule.name'17 e.g. 'openhands.server.user_auth.UserAuth'18 19 Returns:20 The imported value (class, function, or variable)21 22 Example:23 >>> UserAuth = import_from('openhands.server.user_auth.UserAuth')24 >>> auth = UserAuth()25 """26 parts = qual_name.split('.')27 module_name = '.'.join(parts[:-1])28 module = importlib.import_module(module_name)29 result = getattr(module, parts[-1])30 return result31 32 33@lru_cache()34def get_impl(cls: type[T], impl_name: str | None) -> type[T]:35 """Import and validate a named implementation of a base class.36 37 This function is an extensibility mechanism in OpenHands that allows runtime substitution38 of implementations. It enables applications to customize behavior by providing their own39 implementations of OpenHands base classes.40 41 The function ensures type safety by validating that the imported class is either the same as42 or a subclass of the specified base class.43 44 Args:45 cls: The base class that defines the interface46 impl_name: Fully qualified name of the implementation class, or None to use the base class47 e.g. 'openhands.server.conversation_manager.StandaloneConversationManager'48 49 Returns:50 The implementation class, which is guaranteed to be a subclass of cls51 52 Example:53 >>> # Get default implementation54 >>> ConversationManager = get_impl(ConversationManager, None)55 >>> # Get custom implementation56 >>> CustomManager = get_impl(ConversationManager, 'myapp.CustomConversationManager')57 58 Common Use Cases:59 - Server components (ConversationManager, UserAuth, etc.)60 - Storage implementations (ConversationStore, SettingsStore, etc.)61 - Service integrations (GitHub, GitLab services)62 63 The implementation is cached to avoid repeated imports of the same class.64 """65 if impl_name is None:66 return cls67 impl_class = import_from(impl_name)68 assert cls == impl_class or issubclass(impl_class, cls)69 return impl_class70 