30 lines
947 B
Python
30 lines
947 B
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from app.schemas.intent import IntentDefinition
|
|
|
|
|
|
class IntentRegistry:
|
|
def __init__(self, intents: list[IntentDefinition]) -> None:
|
|
self._intents = {intent.intent_id: intent for intent in intents}
|
|
|
|
@classmethod
|
|
def from_json(cls, file_path: str) -> "IntentRegistry":
|
|
data = json.loads(Path(file_path).read_text(encoding="utf-8"))
|
|
intents = [IntentDefinition.model_validate(item) for item in data]
|
|
return cls(intents)
|
|
|
|
def get(self, intent_id: str) -> IntentDefinition:
|
|
return self._intents[intent_id]
|
|
|
|
def list(self) -> list[IntentDefinition]:
|
|
return list(self._intents.values())
|
|
|
|
def match(self, text: str) -> IntentDefinition | None:
|
|
for intent in self._intents.values():
|
|
if any(keyword in text for keyword in intent.keywords):
|
|
return intent
|
|
return None
|