File size: 7,351 Bytes
dc67045
 
 
 
f0ef107
119cf80
f0ef107
 
dc67045
119cf80
f0ef107
 
 
 
 
119cf80
f0ef107
dc67045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0ef107
 
8077280
 
 
 
 
 
 
119cf80
8077280
 
 
f0ef107
 
 
 
 
 
 
 
 
dc67045
 
 
f0ef107
 
 
 
 
 
 
119cf80
 
f0ef107
 
8077280
 
 
 
 
 
 
 
119cf80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8077280
dc67045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119cf80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0ef107
8077280
 
dc67045
 
 
 
9c98929
 
 
 
 
 
 
 
 
 
 
 
8077280
 
 
 
 
119cf80
9c98929
8077280
 
 
119cf80
 
 
 
 
 
 
f0ef107
dc67045
 
 
f0ef107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8077280
 
 
 
f0ef107
 
 
 
 
 
 
 
8077280
 
 
f0ef107
a4c6e98
 
 
 
 
 
 
f0ef107
 
 
 
a4c6e98
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from enum import StrEnum
from typing import Literal, Set
from uuid import UUID

import nh3
from pydantic import BaseModel, Field, field_validator, model_validator

from constants import (
    CHAMP_RAG_ENABLED,
    MARVIN_CONNECT_ENABLED,
    MAX_COMMENT_LENGTH,
    MAX_FILE_NAME_LENGTH,
    MAX_ID_LENGTH,
    MAX_MESSAGE_LENGTH,
    MAX_RESPONSE_LENGTH,
    SITE_LOCALES,
)


class AgeGroup(StrEnum):
    AGE_0_17 = "0-17"
    AGE_18_24 = "18-24"
    AGE_25_34 = "25-34"
    AGE_35_44 = "35-44"
    AGE_45_54 = "45-54"
    AGE_55_64 = "55-64"
    AGE_65_PLUS = "65+"


class Gender(StrEnum):
    MALE = "male"
    FEMALE = "female"
    NON_BINARY = "non-binary"
    OTHER = "other"
    PREFER_NOT = "prefer-not"


class Role(StrEnum):
    PATIENT = "patient"
    CLINICIAN = "clinician"
    COMPUTER_SCIENTIST = "computer-scientist"
    RESEARCHER = "researcher"
    OTHER = "other"


ModelType = Literal[
    "champ",
    "openai",
    "google-conservative",
    "google-creative",
    "fake",
    "skills_wiki",
    "marvin_connect",
]


class IdentifierBase(BaseModel):
    # Participant ID could be in ProfileBase instead. It doesn't really matter.
    participant_id: str = Field(
        pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )


class ProfileBase(BaseModel):
    consent: bool
    age_group: AgeGroup
    gender: Gender
    roles: Set[Role] = Field(min_length=1, max_length=5)


class ChatRequest(IdentifierBase, ProfileBase):
    conversation_id: str = Field(
        pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )
    lang: Literal["en", "fr"]
    # The language to answer in, or "auto" for the user's own; None uses lang; decision 0019.
    reply_lang: Literal["auto", "en", "fr", "de", "es", "ja"] | None = None
    human_message: str = Field(min_length=1, max_length=MAX_MESSAGE_LENGTH)

    @field_validator("human_message")
    def sanitize_human_message(cls, human_message: str):
        """Remove HTML tags to prevent XSS"""
        return nh3.clean(human_message)


class StartConversationRequest(BaseModel):
    model_type: ModelType
    # MARVIN-CONNECT's site; None starts it in the deployment's locale.
    site: str | None = None

    @model_validator(mode="after")
    def refuse_unknown_site(self) -> "StartConversationRequest":
        """Refuse a site outside LOCATIONS, or a site for a model type other than MARVIN-CONNECT.

        Raises:
            ValueError: When the site is unknown or the model type takes none; answered with a 422.

        Returns:
            StartConversationRequest: The request.
        """
        if self.site is not None and self.model_type != "marvin_connect":
            raise ValueError(f"the model type '{self.model_type}' takes no site")
        if self.site is not None and self.site not in SITE_LOCALES:
            raise ValueError(f"the site '{self.site}' is not a supported one")
        return self

    @field_validator("model_type")
    def refuse_rag_champ_when_off(cls, model_type: str) -> str:
        """Refuse the RAG model type (champ) unless CHAMP_RAG_ENABLED turned it on.

        Args:
            model_type (str): The model type asked for.

        Raises:
            ValueError: When it is the RAG model type and that is off; answered with a 422.

        Returns:
            str: The model type.
        """
        if model_type == "champ" and not CHAMP_RAG_ENABLED:
            raise ValueError(
                "the RAG model type 'champ' is turned off (CHAMP_RAG_ENABLED is not true)"
            )
        return model_type

    @field_validator("model_type")
    def refuse_marvin_connect_when_off(cls, model_type: str) -> str:
        """Refuse MARVIN-CONNECT unless MARVIN_CONNECT_ENABLED turned it on.

        Args:
            model_type (str): The model type asked for.

        Raises:
            ValueError: When it is MARVIN-CONNECT and that is off; answered with a 422.

        Returns:
            str: The model type.
        """
        if model_type == "marvin_connect" and not MARVIN_CONNECT_ENABLED:
            raise ValueError(
                "the model type 'marvin_connect' is turned off (MARVIN_CONNECT_ENABLED is not true)"
            )
        return model_type


class ClearConversationRequest(BaseModel):
    conversation_id: str = Field(
        pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )


class RestoredTurn(BaseModel):
    """A turn as the user saw it, with the figures its reply showed."""

    human_message: str
    reply: str
    reply_id: str
    gwp_kgcoeq: float
    water_L: float
    electricity_kWh: float
    n_tokens: int


class CurrentConversation(BaseModel):
    """A conversation to show again: its turns as the user saw them, and its files' names."""

    conversation_id: str
    model_type: str
    site: str | None
    turns: list[RestoredTurn]
    file_names: list[str]


class MarvinConnectSites(BaseModel):
    """The sites a MARVIN-CONNECT conversation can start in; default is None when the deployment names none."""

    sites: list[str]
    default: str | None


class FeedbackRequest(IdentifierBase, ProfileBase):
    conversation_id: str = Field(
        pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )
    message_index: int = Field(ge=0, le=10_000)
    rating: Literal["like", "dislike", "mixed"]
    comment: str = Field(min_length=0, max_length=MAX_COMMENT_LENGTH)
    reply_content: str = Field(min_length=1, max_length=MAX_RESPONSE_LENGTH)
    reply_id: UUID

    @field_validator("comment")
    def sanitize_comment(cls, comment: str):
        """Remove HTML tags to prevent XSS"""
        return nh3.clean(comment)

    @field_validator("reply_content")
    def sanitize_reply_content(cls, reply_content: str):
        """Remove HTML tags to prevent XSS"""
        return nh3.clean(reply_content)


class CommentRequest(IdentifierBase, ProfileBase):
    comment: str = Field(min_length=1, max_length=MAX_COMMENT_LENGTH)
    # The conversation on screen; None when the user hasn't sent a message yet.
    conversation_id: str | None = Field(
        default=None, pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )

    @field_validator("comment")
    def sanitize_comment(cls, comment: str):
        """Remove HTML tags to prevent XSS"""
        return nh3.clean(comment)


class DeleteFileRequest(IdentifierBase, ProfileBase):
    conversation_id: str = Field(
        pattern="^[a-zA-Z0-9_-]+$", min_length=1, max_length=MAX_ID_LENGTH
    )
    file_name: str = Field(
        # Matches is_valid_filename in helpers/file_helper.py: block only
        # control characters, path separators, and HTML/attribute-injection
        # characters — everything else a real filename can contain (commas,
        # apostrophes, colons, etc.) is allowed, so anything accepted on
        # upload can also be deleted. The "." / ".." exclusion lives in the
        # validator below — pydantic-core's regex engine has no look-ahead.
        pattern=r'^[^\x00-\x1f\\/<>"]+$',
        min_length=1,
        max_length=MAX_FILE_NAME_LENGTH,
    )

    @field_validator("file_name")
    def reject_dot_names(cls, file_name: str):
        if file_name in {".", ".."}:
            raise ValueError('file_name cannot be "." or ".."')
        return file_name