decorators.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. """
  3. Intent Decorator.
  4. Dekorator zum Markieren von Plugin-Methoden als Intent-Handler.
  5. """
  6. from functools import wraps
  7. from typing import Any, Callable, TypeVar, get_type_hints
  8. from trixy_core.nlp.intent_registry import IntentSlot
  9. # Type variable für generische Funktionssignaturen
  10. F = TypeVar("F", bound=Callable[..., Any])
  11. # Attributname für Intent-Metadaten
  12. INTENT_METADATA_ATTR = "_trixy_intent_metadata"
  13. def intent(
  14. name: str,
  15. *,
  16. slots: dict[str, type | IntentSlot] | None = None,
  17. examples: list[str] | None = None,
  18. description: str = "",
  19. priority: int = 0,
  20. ) -> Callable[[F], F]:
  21. """
  22. Dekorator zum Markieren einer Methode als Intent-Handler.
  23. Der PluginManager entdeckt diese Methoden automatisch und
  24. registriert sie in der IntentRegistry.
  25. Args:
  26. name: Eindeutiger Intent-Name
  27. slots: Slot-Definitionen (dict mit Name -> Typ oder IntentSlot)
  28. examples: Beispiel-Phrasen für den Intent
  29. description: Beschreibung des Intents
  30. priority: Priorität (höher = wird bevorzugt)
  31. Returns:
  32. Dekorierte Funktion
  33. Beispiel:
  34. class SmartHomePlugin(TrixyPlugin):
  35. @intent(
  36. "turn_on_device",
  37. slots={"device": str, "room": str},
  38. examples=["Licht an", "Lampe einschalten", "schalte das Licht an"],
  39. description="Schaltet ein Gerät ein"
  40. )
  41. async def handle_turn_on(self, data: IntentReceivedData) -> IntentResult:
  42. device = data.slots.get("device")
  43. room = data.slots.get("room", data.room_id)
  44. # Gerät einschalten...
  45. return IntentResult(
  46. success=True,
  47. response_text=f"{device} in {room} wurde eingeschaltet."
  48. )
  49. """
  50. def decorator(func: F) -> F:
  51. # Slots normalisieren
  52. normalized_slots: dict[str, IntentSlot] = {}
  53. if slots:
  54. for slot_name, slot_value in slots.items():
  55. if isinstance(slot_value, IntentSlot):
  56. normalized_slots[slot_name] = slot_value
  57. elif isinstance(slot_value, type):
  58. normalized_slots[slot_name] = IntentSlot(
  59. name=slot_name,
  60. slot_type=slot_value,
  61. )
  62. else:
  63. # Fallback: str als Typ
  64. normalized_slots[slot_name] = IntentSlot(
  65. name=slot_name,
  66. slot_type=str,
  67. )
  68. # Metadaten an Funktion anhängen
  69. metadata = {
  70. "name": name,
  71. "slots": normalized_slots,
  72. "examples": examples or [],
  73. "description": description,
  74. "priority": priority,
  75. }
  76. setattr(func, INTENT_METADATA_ATTR, metadata)
  77. @wraps(func)
  78. async def wrapper(*args: Any, **kwargs: Any) -> Any:
  79. return await func(*args, **kwargs)
  80. # Metadaten auch auf Wrapper übertragen
  81. setattr(wrapper, INTENT_METADATA_ATTR, metadata)
  82. return wrapper # type: ignore
  83. return decorator
  84. def get_intent_metadata(func: Callable[..., Any]) -> dict[str, Any] | None:
  85. """
  86. Gibt die Intent-Metadaten einer Funktion zurück.
  87. Args:
  88. func: Funktion zum Prüfen
  89. Returns:
  90. Metadaten-Dictionary oder None
  91. """
  92. return getattr(func, INTENT_METADATA_ATTR, None)
  93. def is_intent_handler(func: Callable[..., Any]) -> bool:
  94. """
  95. Prüft ob eine Funktion ein Intent-Handler ist.
  96. Args:
  97. func: Funktion zum Prüfen
  98. Returns:
  99. True wenn Intent-Handler
  100. """
  101. return hasattr(func, INTENT_METADATA_ATTR)
  102. def discover_intent_handlers(obj: object) -> list[tuple[str, Callable[..., Any], dict[str, Any]]]:
  103. """
  104. Entdeckt alle Intent-Handler in einem Objekt.
  105. Durchsucht alle Methoden des Objekts nach @intent Dekoratoren.
  106. Args:
  107. obj: Objekt zum Durchsuchen (z.B. Plugin-Instanz)
  108. Returns:
  109. Liste von (intent_name, handler_func, metadata) Tupeln
  110. """
  111. handlers = []
  112. for attr_name in dir(obj):
  113. if attr_name.startswith("_"):
  114. continue
  115. try:
  116. attr = getattr(obj, attr_name)
  117. except Exception:
  118. continue
  119. if not callable(attr):
  120. continue
  121. metadata = get_intent_metadata(attr)
  122. if metadata is not None:
  123. handlers.append((metadata["name"], attr, metadata))
  124. return handlers