๐Ÿ“ฆ langgenius / dify-plugin-sdks

๐Ÿ“„ moderation_model.py ยท 55 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55from abc import abstractmethod

from pydantic import ConfigDict

from dify_plugin.entities.model import ModelType
from dify_plugin.interfaces.model.ai_model import AIModel


class ModerationModel(AIModel):
    """
    Model class for moderation model.
    """

    model_type: ModelType = ModelType.MODERATION

    # pydantic configs
    model_config = ConfigDict(protected_namespaces=())

    ############################################################
    #        Methods that can be implemented by plugin         #
    ############################################################

    @abstractmethod
    def _invoke(self, model: str, credentials: dict, text: str, user: str | None = None) -> bool:
        """
        Invoke large language model

        :param model: model name
        :param credentials: model credentials
        :param text: text to moderate
        :param user: unique user id
        :return: false if text is safe, true otherwise
        """
        raise NotImplementedError

    ############################################################
    #                 For executor use only                    #
    ############################################################

    def invoke(self, model: str, credentials: dict, text: str, user: str | None = None) -> bool:
        """
        Invoke moderation model

        :param model: model name
        :param credentials: model credentials
        :param text: text to moderate
        :param user: unique user id
        :return: false if text is safe, true otherwise
        """
        with self.timing_context():
            try:
                return self._invoke(model, credentials, text, user)
            except Exception as e:
                raise self._transform_invoke_error(e) from e