initial a2a-pack
This commit is contained in:
34
a2a_pack/cli/loader.py
Normal file
34
a2a_pack/cli/loader.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""Load an :class:`A2AAgent` subclass from a string entrypoint."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from ..agent import A2AAgent
|
||||
|
||||
|
||||
def load_agent_class(entrypoint: str, *, project_dir: Path | None = None) -> type[A2AAgent]:
|
||||
"""Resolve ``module:ClassName`` to an :class:`A2AAgent` subclass.
|
||||
|
||||
If ``project_dir`` is given, it is prepended to ``sys.path`` so a local
|
||||
``agent.py`` can be imported without packaging.
|
||||
"""
|
||||
if ":" not in entrypoint:
|
||||
raise ValueError(
|
||||
f"entrypoint must be 'module:ClassName' (got {entrypoint!r})"
|
||||
)
|
||||
module_name, class_name = entrypoint.split(":", 1)
|
||||
|
||||
if project_dir is not None:
|
||||
path = str(project_dir.resolve())
|
||||
if path not in sys.path:
|
||||
sys.path.insert(0, path)
|
||||
|
||||
module = importlib.import_module(module_name)
|
||||
obj = getattr(module, class_name, None)
|
||||
if obj is None:
|
||||
raise AttributeError(f"{module_name} has no attribute {class_name!r}")
|
||||
if not isinstance(obj, type) or not issubclass(obj, A2AAgent):
|
||||
raise TypeError(f"{entrypoint} is not an A2AAgent subclass")
|
||||
return obj
|
||||
Reference in New Issue
Block a user