| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- # -*- coding: utf-8 -*-
- """
- Intent Decorator.
- Dekorator zum Markieren von Plugin-Methoden als Intent-Handler.
- """
- from functools import wraps
- from typing import Any, Callable, TypeVar, get_type_hints
- from trixy_core.nlp.intent_registry import IntentSlot
- # Type variable für generische Funktionssignaturen
- F = TypeVar("F", bound=Callable[..., Any])
- # Attributname für Intent-Metadaten
- INTENT_METADATA_ATTR = "_trixy_intent_metadata"
- def intent(
- name: str,
- *,
- slots: dict[str, type | IntentSlot] | None = None,
- examples: list[str] | None = None,
- description: str = "",
- priority: int = 0,
- ) -> Callable[[F], F]:
- """
- Dekorator zum Markieren einer Methode als Intent-Handler.
- Der PluginManager entdeckt diese Methoden automatisch und
- registriert sie in der IntentRegistry.
- Args:
- name: Eindeutiger Intent-Name
- slots: Slot-Definitionen (dict mit Name -> Typ oder IntentSlot)
- examples: Beispiel-Phrasen für den Intent
- description: Beschreibung des Intents
- priority: Priorität (höher = wird bevorzugt)
- Returns:
- Dekorierte Funktion
- Beispiel:
- class SmartHomePlugin(TrixyPlugin):
- @intent(
- "turn_on_device",
- slots={"device": str, "room": str},
- examples=["Licht an", "Lampe einschalten", "schalte das Licht an"],
- description="Schaltet ein Gerät ein"
- )
- async def handle_turn_on(self, data: IntentReceivedData) -> IntentResult:
- device = data.slots.get("device")
- room = data.slots.get("room", data.room_id)
- # Gerät einschalten...
- return IntentResult(
- success=True,
- response_text=f"{device} in {room} wurde eingeschaltet."
- )
- """
- def decorator(func: F) -> F:
- # Slots normalisieren
- normalized_slots: dict[str, IntentSlot] = {}
- if slots:
- for slot_name, slot_value in slots.items():
- if isinstance(slot_value, IntentSlot):
- normalized_slots[slot_name] = slot_value
- elif isinstance(slot_value, type):
- normalized_slots[slot_name] = IntentSlot(
- name=slot_name,
- slot_type=slot_value,
- )
- else:
- # Fallback: str als Typ
- normalized_slots[slot_name] = IntentSlot(
- name=slot_name,
- slot_type=str,
- )
- # Metadaten an Funktion anhängen
- metadata = {
- "name": name,
- "slots": normalized_slots,
- "examples": examples or [],
- "description": description,
- "priority": priority,
- }
- setattr(func, INTENT_METADATA_ATTR, metadata)
- @wraps(func)
- async def wrapper(*args: Any, **kwargs: Any) -> Any:
- return await func(*args, **kwargs)
- # Metadaten auch auf Wrapper übertragen
- setattr(wrapper, INTENT_METADATA_ATTR, metadata)
- return wrapper # type: ignore
- return decorator
- def get_intent_metadata(func: Callable[..., Any]) -> dict[str, Any] | None:
- """
- Gibt die Intent-Metadaten einer Funktion zurück.
- Args:
- func: Funktion zum Prüfen
- Returns:
- Metadaten-Dictionary oder None
- """
- return getattr(func, INTENT_METADATA_ATTR, None)
- def is_intent_handler(func: Callable[..., Any]) -> bool:
- """
- Prüft ob eine Funktion ein Intent-Handler ist.
- Args:
- func: Funktion zum Prüfen
- Returns:
- True wenn Intent-Handler
- """
- return hasattr(func, INTENT_METADATA_ATTR)
- def discover_intent_handlers(obj: object) -> list[tuple[str, Callable[..., Any], dict[str, Any]]]:
- """
- Entdeckt alle Intent-Handler in einem Objekt.
- Durchsucht alle Methoden des Objekts nach @intent Dekoratoren.
- Args:
- obj: Objekt zum Durchsuchen (z.B. Plugin-Instanz)
- Returns:
- Liste von (intent_name, handler_func, metadata) Tupeln
- """
- handlers = []
- for attr_name in dir(obj):
- if attr_name.startswith("_"):
- continue
- try:
- attr = getattr(obj, attr_name)
- except Exception:
- continue
- if not callable(attr):
- continue
- metadata = get_intent_metadata(attr)
- if metadata is not None:
- handlers.append((metadata["name"], attr, metadata))
- return handlers
|