dsh-router-laya 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,324 @@
1
+ """Dependency-free language/script detection used to route between Laya checkpoints.
2
+
3
+ Routing only needs one decision: *is this English Latin text, or is it something the English
4
+ checkpoint cannot read?* Benchmarks on MASSIVE (14 languages) showed the English checkpoint
5
+ collapsing to near-random on non-Latin scripts (Hindi 0.100, Korean 0.103, Swahili 0.103,
6
+ Tamil 0.113 at 20 options, where random is 0.050), while holding up far better on Latin-script
7
+ languages (French 0.487, Spanish 0.480). So the signal that matters most is *script*, and the
8
+ secondary signal is whether Latin text is English.
9
+
10
+ Script detection is exact. The Latin-script language guess is a stopword/diacritic heuristic and
11
+ is explicitly best-effort: pass an explicit model or `lang=` when you already know the language.
12
+ """
13
+ import re
14
+ from typing import Dict, List, Optional, Union
15
+
16
+ # Unicode blocks that the English (ModernBERT-large, 50k English BPE) checkpoint cannot read.
17
+ _SCRIPT_RANGES = [
18
+ ("greek", ((0x0370, 0x03FF), (0x1F00, 0x1FFF))),
19
+ ("cyrillic", ((0x0400, 0x052F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F))),
20
+ ("armenian", ((0x0530, 0x058F),)),
21
+ ("hebrew", ((0x0590, 0x05FF),)),
22
+ ("arabic", ((0x0600, 0x06FF), (0x0750, 0x077F), (0x08A0, 0x08FF), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF))),
23
+ ("devanagari", ((0x0900, 0x097F), (0xA8E0, 0xA8FF))),
24
+ ("bengali", ((0x0980, 0x09FF),)),
25
+ ("gurmukhi", ((0x0A00, 0x0A7F),)),
26
+ ("gujarati", ((0x0A80, 0x0AFF),)),
27
+ ("oriya", ((0x0B00, 0x0B7F),)),
28
+ ("tamil", ((0x0B80, 0x0BFF),)),
29
+ ("telugu", ((0x0C00, 0x0C7F),)),
30
+ ("kannada", ((0x0C80, 0x0CFF),)),
31
+ ("malayalam", ((0x0D00, 0x0D7F),)),
32
+ ("sinhala", ((0x0D80, 0x0DFF),)),
33
+ ("thai", ((0x0E00, 0x0E7F),)),
34
+ ("lao", ((0x0E80, 0x0EFF),)),
35
+ ("tibetan", ((0x0F00, 0x0FFF),)),
36
+ ("myanmar", ((0x1000, 0x109F),)),
37
+ ("georgian", ((0x10A0, 0x10FF),)),
38
+ ("ethiopic", ((0x1200, 0x137F),)),
39
+ ("khmer", ((0x1780, 0x17FF),)),
40
+ ("hangul", ((0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF))),
41
+ ("kana", ((0x3040, 0x309F), (0x30A0, 0x30FF), (0x31F0, 0x31FF))),
42
+ ("han", ((0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF))),
43
+ ]
44
+
45
+ # Function words. Latin-script languages overlap heavily (de/la/le/un/e/que), so each hit is
46
+ # weighted and a margin is required before calling something non-English.
47
+ #
48
+ # The Romance lists (fr/es/pt/it) deliberately carry the *unaccented* function words as well as the
49
+ # accented ones. A state that lost its accents -- mail clients, ticket systems and any pipeline that
50
+ # normalises to ASCII strip them -- keeps no diacritic rate for the non-English signal to read, so
51
+ # `la`, `un`, `y`, `e`, `et`, `deux` and friends are the only evidence left. With a list of mostly
52
+ # accented words such a state produced one hit or none, fell under the two-hit margin below, and was
53
+ # handed to the English checkpoint as undecided-but-not-non-English text (see #172 and #54).
54
+ _STOP = {
55
+ "en": {"the", "and", "is", "are", "was", "were", "to", "of", "in", "for", "with", "that",
56
+ "this", "it", "you", "have", "has", "not", "but", "on", "at", "be", "as", "from",
57
+ "will", "can", "would", "there", "their", "what", "which", "please", "we", "i"},
58
+ "fr": {"le", "la", "les", "des", "une", "est", "pour", "dans", "que", "qui", "avec", "sur",
59
+ "pas", "plus", "nous", "vous", "être", "cette", "mais", "sont", "ont", "aux", "ce",
60
+ "et", "du", "au", "ou", "je", "tu", "il", "elle", "ils", "elles", "mon", "ton",
61
+ "ma", "ta", "sa", "mes", "tes", "ses", "ces", "deux", "trois", "très", "bien",
62
+ "tout", "tous", "toute", "fait", "veux", "veut", "peux", "peut", "dois", "doit",
63
+ "merci", "bonjour", "jour", "jours", "mois", "fois", "quand", "comment", "pourquoi",
64
+ "alors", "donc"},
65
+ "de": {"der", "die", "das", "und", "ist", "ein", "eine", "den", "dem", "nicht", "mit", "für",
66
+ "auf", "von", "zu", "sich", "auch", "werden", "wurde", "haben", "sind", "oder", "aber"},
67
+ "es": {"el", "los", "las", "que", "por", "con", "para", "una", "es", "se", "del", "como",
68
+ "pero", "son", "está", "este", "esta", "todo", "más", "muy", "hay", "sus",
69
+ # `de`/`en` are Spanish too, but they are common English tokens as well (`de facto`,
70
+ # `en-US`, `en route`, `Rio de Janeiro`), and a state of those alone already carries
71
+ # no English function word for the margin below to weigh them against, so they stay out.
72
+ "la", "un", "y", "al", "lo", "le", "les", "su", "mi", "tu", "nos",
73
+ "ni", "dos", "tres", "fue", "fueron", "ser", "tiene", "tienen", "tengo", "puede",
74
+ "pueden", "quiero", "necesito", "hemos", "han", "sobre", "entre", "cuando", "donde",
75
+ "porque", "aunque", "también", "ya", "eso", "esto", "esa", "ese", "nada", "algo",
76
+ "aquí", "hoy", "gracias"},
77
+ "pt": {"os", "as", "que", "em", "um", "uma", "para", "com", "não", "é", "se", "do", "da",
78
+ "dos", "das", "mas", "são", "está", "este", "esta", "muito", "pelo", "pela",
79
+ # `no` is Portuguese too, and among the most frequent words it has; it is also one of the
80
+ # most frequent English words, so it stays out and short Portuguese states that lean on it
81
+ # alone are left to the diacritic rate, as before.
82
+ "o", "e", "na", "nas", "nos", "ao", "aos", "por", "foi", "era", "ser", "sou",
83
+ "tem", "tenho", "pode", "podem", "quero", "preciso", "eu", "meu", "minha", "seu",
84
+ "sua", "isso", "isto", "aqui", "ali", "como", "quando", "onde", "porque", "mais",
85
+ "já", "ainda", "agora", "hoje", "ontem", "dois", "três", "tudo", "nada", "obrigado",
86
+ "olá",
87
+ # Brazilian support text: `você` and the unaccented `nao`/`voce`/`sao`/`ja` that a stripped
88
+ # state keeps (#172), and the chat abbreviations `vc`/`pra`. Without them "Voce pode me
89
+ # mandar a nota fiscal?" matched one word and went to the English checkpoint, which on
90
+ # `pt` reports 0.97 mean confidence at 0.47 accuracy. `ate`, `bom`, `sim` and `cade` stay
91
+ # out: each is an English token too (ate, BOM, SIM, Cade).
92
+ "você", "vocês", "voce", "voces", "vc", "vcs", "nao", "sao", "ja", "até", "tá", "pra",
93
+ "gostaria", "obrigada", "também", "tambem", "estou", "estamos", "meus", "minhas",
94
+ "nosso", "nossa", "consigo", "cadê", "boa", "tarde", "noite",
95
+ # the words a ticket keeps once the jargon is English ("Deu erro 500 no endpoint de login
96
+ # depois do update"): time and person words plus the past tenses a bug report is told in
97
+ "depois", "antes", "então", "entao", "ninguém", "ninguem", "alguém", "alguem", "nenhum",
98
+ "nenhuma", "estava", "ficou", "fiz", "deu"},
99
+ "it": {"il", "lo", "gli", "che", "di", "per", "con", "non", "è", "si", "del", "della", "sono",
100
+ "questo", "questa", "anche", "come", "più", "sono", "nella", "alla",
101
+ "la", "le", "un", "uno", "una", "e", "ed", "o", "da", "su", "tra", "fra", "mi",
102
+ "ci", "ne", "ho", "hai", "ha", "abbiamo", "avete", "hanno", "era", "stato", "stata",
103
+ "devo", "deve", "devono", "voglio", "vorrei", "mio", "mia", "tuo", "sua", "quando",
104
+ "dove", "perche", "molto", "poco", "sempre", "mai", "già", "ancora", "adesso", "oggi",
105
+ "ieri", "grazie", "ciao", "scusa",
106
+ # the articulated prepositions: Italian-only words, which is what lets a state made of
107
+ # shared articles (`la fattura`) still name the language rather than stay undecided
108
+ "nel", "nell", "negli", "sul", "sulla", "sulle", "dal", "dalla", "dallo", "dagli", "dei",
109
+ "delle", "dello", "degli", "agli", "alle", "col"},
110
+ "nl": {"het", "een", "van", "is", "op", "te", "dat", "niet", "met", "voor", "zijn", "aan",
111
+ "door", "maar", "ook", "worden", "deze", "naar", "wordt"},
112
+ # Romanian words that its Romance neighbours do not share, so adding `ro` cannot steal a
113
+ # French/Spanish/Italian/Portuguese state: `la`, `o`, `un`, `de`, `pe`, `ca` are deliberately
114
+ # left out for that reason, and the diacritic signal below carries the rest.
115
+ "ro": {"și", "să", "este", "sunt", "care", "pentru", "din", "dar", "după", "până", "fără",
116
+ "ale", "lui", "în", "fost", "acum", "vreau", "trebuie", "foarte", "acest", "această",
117
+ "acesta", "aceasta", "mi", "ți", "vă", "nu"},
118
+ }
119
+ # Letters that ordinary English does not use. This is the signal that catches a Latin-script
120
+ # language we hold no stopwords for at all (Romanian, Polish, Czech, Turkish, Baltic, ...),
121
+ # which is the difference between routing it to the multilingual checkpoint and silently
122
+ # handing it to the English one.
123
+ _NON_EN_DIACRITICS = set(
124
+ "àâäãáåçéèêëíìîïñóòôöõøúùûüýÿßæœ" # Western European
125
+ "ăâîșțşţ" # Romanian
126
+ "ąćęłńśźż" # Polish
127
+ "čďěňřšťůž" # Czech / Slovak
128
+ "őű" # Hungarian
129
+ "ğı" # Turkish (text is lowercased before matching)
130
+ "āēģīķļņūž" # Baltic
131
+ "đ" # Serbo-Croatian / Vietnamese
132
+ )
133
+ # Words that more than one list claims. `la`, `un`, `e`, `que`, `una` and friends are function words
134
+ # of several of these languages at once, so matching one says "not English" without saying *which*
135
+ # language: a shared word may not name a winner by itself (Romanian text was reported as French that
136
+ # way), though it still counts toward the total of a language that also matched a word of its own.
137
+ _SHARED_WORDS = {w for w in {word for words in _STOP.values() for word in words}
138
+ if sum(w in words for words in _STOP.values()) > 1}
139
+
140
+ _WORD = re.compile(r"[^\W\d_]+", re.UNICODE)
141
+ # A token whose dot or @ joins word characters is an identifier, not prose: `github.com`,
142
+ # `user@acme.com`, `v1.2.3`, `U.S.A.`. `_WORD` splits them into pieces that collide with real
143
+ # function words -- `com` is Portuguese for "with", `o` is its article, `e` is Italian "e" -- so a
144
+ # state that was mostly links scored a language it does not contain, and two domains were enough to
145
+ # cross the margin below. A sentence-final period (`arrivato.`) keeps its word: the pattern needs
146
+ # word characters on both sides of the dot.
147
+ _IDENTIFIER = re.compile(r"[\w-]*(?:[.@][\w-]+)+", re.UNICODE)
148
+
149
+
150
+ def _iter_text(state: Union[str, dict, list, None], _depth: int = 0) -> List[str]:
151
+ """Collect the string leaves of a state (str / dict / list), so detection sees real content."""
152
+ if _depth > 6 or state is None:
153
+ return []
154
+ if isinstance(state, str):
155
+ return [state]
156
+ if isinstance(state, dict):
157
+ out = []
158
+ for v in state.values():
159
+ out.extend(_iter_text(v, _depth + 1))
160
+ return out
161
+ if isinstance(state, (list, tuple)):
162
+ out = []
163
+ for v in state:
164
+ out.extend(_iter_text(v, _depth + 1))
165
+ return out
166
+ return []
167
+
168
+
169
+ def state_text(state: Union[str, dict, list, None], max_chars: int = 4000) -> str:
170
+ """Flatten a state into the text used for detection (keys are ignored: they are usually English)."""
171
+ return " ".join(_iter_text(state))[:max_chars]
172
+
173
+
174
+ def detect_script(text: str) -> str:
175
+ """Dominant script of `text`: 'latin', 'han', 'devanagari', ... or 'unknown' if there are no letters."""
176
+ counts: Dict[str, int] = {}
177
+ latin = 0
178
+ for ch in text:
179
+ if not ch.isalpha():
180
+ continue
181
+ cp = ord(ch)
182
+ if cp < 0x0250 or 0x1E00 <= cp <= 0x1EFF or 0xFF21 <= cp <= 0xFF3A or 0xFF41 <= cp <= 0xFF5A:
183
+ latin += 1 # Latin, Latin Ext-Additional, fullwidth
184
+ continue
185
+ for name, ranges in _SCRIPT_RANGES:
186
+ if any(lo <= cp <= hi for lo, hi in ranges):
187
+ counts[name] = counts.get(name, 0) + 1
188
+ break
189
+ else:
190
+ # An alphabetic character no range claims used to be counted nowhere, so text
191
+ # written only in an unlisted script produced a total of 0 and was reported as
192
+ # "unknown" -- and `analyse` treats "unknown" as English, sending it to the
193
+ # checkpoint that has no tokens for it. 68% of Unicode's alphabetic codepoints
194
+ # are outside _SCRIPT_RANGES (the CJK extensions, kana supplements, bopomofo,
195
+ # halfwidth katakana, and dozens of smaller scripts), so enumerating them all is
196
+ # not maintainable. Counting the remainder under "other" keeps them visible and
197
+ # non-Latin, which is the safe direction: an unreadable script must not be
198
+ # handed to the English checkpoint.
199
+ counts["other"] = counts.get("other", 0) + 1
200
+ counts["latin"] = latin
201
+ total = sum(counts.values())
202
+ if total == 0:
203
+ return "unknown"
204
+ return max(counts.items(), key=lambda kv: kv[1])[0]
205
+
206
+
207
+ def script_profile(text: str) -> Dict[str, float]:
208
+ """Fraction of alphabetic characters belonging to each detected script."""
209
+ counts: Dict[str, int] = {"latin": 0}
210
+ for ch in text:
211
+ if not ch.isalpha():
212
+ continue
213
+ cp = ord(ch)
214
+ if cp < 0x0250 or 0x1E00 <= cp <= 0x1EFF or 0xFF21 <= cp <= 0xFF3A or 0xFF41 <= cp <= 0xFF5A:
215
+ counts["latin"] += 1
216
+ continue
217
+ for name, ranges in _SCRIPT_RANGES:
218
+ if any(lo <= cp <= hi for lo, hi in ranges):
219
+ counts[name] = counts.get(name, 0) + 1
220
+ break
221
+ else:
222
+ counts["other"] = counts.get("other", 0) + 1
223
+ total = sum(counts.values())
224
+ if not total:
225
+ return {}
226
+ return {k: v / total for k, v in counts.items() if v}
227
+
228
+
229
+ # A diacritic rate above this is taken as evidence the text is not English, even when no
230
+ # stopword list matches it.
231
+ NON_EN_DIACRITIC_RATE = 0.02
232
+
233
+
234
+ def latin_profile(text: str) -> Dict[str, object]:
235
+ """Evidence behind the Latin-script language guess.
236
+
237
+ Returns `language` (may be None when undecided), `english_hits`, `diacritic_rate` and
238
+ `looks_non_english`. `analyse` needs the evidence and not just the verdict, because
239
+ "undecided" and "English" are different answers and only one of them is safe to send to the
240
+ English checkpoint.
241
+
242
+ A non-English language is only named when it matched at least one word that no other list
243
+ claims: shared function words alone (`la`, `e`, `o`) identify no particular language.
244
+ """
245
+ words = [w.lower() for w in _WORD.findall(_IDENTIFIER.sub(" ", text))]
246
+ lowered = text.lower()
247
+ diac = sum(1 for ch in lowered if ch in _NON_EN_DIACRITICS)
248
+ diac_rate = diac / max(1, len(lowered))
249
+ non_english = diac_rate >= NON_EN_DIACRITIC_RATE
250
+ if len(words) < 4:
251
+ return {"language": None, "english_hits": 0, "diacritic_rate": diac_rate,
252
+ "looks_non_english": non_english}
253
+
254
+ scores = {lg: sum(1 for w in words if w in sw) for lg, sw in _STOP.items()}
255
+ en = scores.get("en", 0)
256
+ # Only a language that matched at least one word no other list claims may be named. Without
257
+ # that condition the top score can be pure overlap -- `la` and `e` in Romanian text made
258
+ # Italian the winner -- which is a guess dressed as a detection. Such a language is dropped
259
+ # from the running rather than merely losing the tie, so a lesser score with real evidence
260
+ # still gets named, and the text stays undecided when no list has any.
261
+ evidenced = {lg: s for lg, s in scores.items()
262
+ if lg != "en" and any(w not in _SHARED_WORDS for w in set(words) & _STOP[lg])}
263
+ best_lg, best = max(evidenced.items(), key=lambda kv: kv[1], default=(None, 0))
264
+
265
+ lang = None
266
+ if best_lg and best >= max(2, en + 2):
267
+ # a non-English language needs a clear margin over English function words
268
+ lang = best_lg
269
+ elif best_lg and non_english and best >= max(2, en):
270
+ # Needs two hits here too. One shared function word ("para" in Turkish text) named Spanish
271
+ # on the strength of the diacritics alone, which is a guess dressed as a detection.
272
+ lang = best_lg
273
+ elif en and not non_english:
274
+ lang = "en"
275
+ return {"language": lang, "english_hits": en, "diacritic_rate": diac_rate,
276
+ "looks_non_english": non_english}
277
+
278
+
279
+ def guess_latin_language(text: str) -> Optional[str]:
280
+ """Best-effort language code for Latin-script text, or None when undecided.
281
+
282
+ Scores function-word hits per language and requires the winner to beat English by a margin and
283
+ to have matched at least one word of its own, so ordinary English is never misrouted and a
284
+ word of several languages at once names none of them. Short inputs usually return None on
285
+ purpose.
286
+ """
287
+ return latin_profile(text)["language"]
288
+
289
+
290
+ def analyse(state: Union[str, dict, list, None]) -> Dict[str, object]:
291
+ """Full detection result for a state.
292
+
293
+ Returns `script`, `script_profile`, `language` (best effort, may be None),
294
+ `is_english` and `non_latin_fraction`.
295
+ """
296
+ text = state_text(state)
297
+ prof = script_profile(text)
298
+ script = detect_script(text)
299
+ non_latin = round(1.0 - prof.get("latin", 0.0), 4) if prof else 0.0
300
+ if script == "unknown":
301
+ return {"script": "unknown", "script_profile": prof, "language": None,
302
+ "is_english": True, "language_undecided": True, "diacritic_rate": 0.0,
303
+ "non_latin_fraction": 0.0}
304
+ if script != "latin":
305
+ return {"script": script, "script_profile": prof, "language": None,
306
+ "is_english": False, "language_undecided": True, "diacritic_rate": 0.0,
307
+ "non_latin_fraction": non_latin}
308
+ prof_lat = latin_profile(text)
309
+ lang = prof_lat["language"]
310
+ # Undecided is not English. Treating it as English sent every Latin-script language we hold no
311
+ # stopwords for to the checkpoint that cannot read it, silently. When nothing identifies the
312
+ # language, non-English letters are enough to prefer the multilingual checkpoint; text with no
313
+ # such letters (including short English) still goes to the English one.
314
+ undecided = lang is None
315
+ english = lang == "en" or (undecided and not prof_lat["looks_non_english"])
316
+ return {"script": "latin", "script_profile": prof, "language": lang,
317
+ "is_english": english, "language_undecided": undecided,
318
+ "diacritic_rate": round(float(prof_lat["diacritic_rate"]), 4),
319
+ "non_latin_fraction": non_latin}
320
+
321
+
322
+ def is_english(state: Union[str, dict, list, None]) -> bool:
323
+ """True when the English checkpoint can be expected to read this state."""
324
+ return bool(analyse(state)["is_english"])
@@ -0,0 +1,187 @@
1
+ """Ready-to-use question presets for common production decision workflows."""
2
+ from typing import Dict, Optional
3
+
4
+
5
+ def triage_questions() -> Dict:
6
+ """Preset questions for customer support ticket triage."""
7
+ return {
8
+ "intent": {
9
+ "type": "choice",
10
+ "instructions": "What does the customer want in `message`?",
11
+ "criteria": {
12
+ "refund": "money returned or a duplicate charge reversed",
13
+ "technical_help": "a bug, outage or integration problem",
14
+ "billing_question": "a question about an invoice, plan or payment method",
15
+ "information": "general information, pricing or how-to",
16
+ "cancellation": "wants to cancel or downgrade",
17
+ "other": "none of the other options fits",
18
+ },
19
+ },
20
+ "is_urgent": {
21
+ "type": "noul",
22
+ "instructions": "Does `message` communicate time pressure or a deadline?",
23
+ },
24
+ "frustration": {
25
+ "type": "score",
26
+ "instructions": "How frustrated does the customer sound in `message`?",
27
+ "criteria": [
28
+ "calm and neutral",
29
+ "concerned but civil",
30
+ "clearly annoyed",
31
+ "very angry or using strong language",
32
+ ],
33
+ },
34
+ "refund_requested": {
35
+ "type": "noul",
36
+ "instructions": "Does the customer ask for money back?",
37
+ },
38
+ "churn_risk": {
39
+ "type": "noul",
40
+ "instructions": "Does `message` suggest the customer may leave for a competitor or cancel?",
41
+ },
42
+ }
43
+
44
+
45
+ def email_questions(categories: Optional[Dict[str, str]] = None) -> Dict:
46
+ """Preset questions for inbound email triage and threat filtering."""
47
+ categories = categories or {
48
+ "billing": "invoices, payments, refunds",
49
+ "technical": "bugs, outages, integrations",
50
+ "sales": "pricing, demos, new purchases",
51
+ "security": "phishing, scams, account compromise",
52
+ "hr": "hiring, leave, payroll",
53
+ "other": "none of the above",
54
+ }
55
+ return {
56
+ "category": {
57
+ "type": "choice",
58
+ "instructions": "Which team should handle the email in `body`?",
59
+ "criteria": categories,
60
+ },
61
+ "is_spam": {
62
+ "type": "noul",
63
+ "instructions": "Is this email unsolicited spam or bulk marketing?",
64
+ },
65
+ "is_phishing": {
66
+ "type": "noul",
67
+ "instructions": "Is this email a phishing or scam attempt to steal money, credentials, or personal data?",
68
+ "criteria": {"true": "phishing, scam, or fraud", "false": "a legitimate email"},
69
+ },
70
+ "urgency": {
71
+ "type": "score",
72
+ "instructions": "How urgent is the request in `body`?",
73
+ "criteria": ["no time pressure", "needs attention soon", "blocking issue or hard deadline"],
74
+ },
75
+ "needs_reply": {
76
+ "type": "noul",
77
+ "instructions": "Does the sender expect a reply?",
78
+ },
79
+ }
80
+
81
+
82
+ def guard_questions() -> Dict:
83
+ """Preset questions for real-time LLM input guardrails."""
84
+ return {
85
+ "jailbreak": {
86
+ "type": "noul",
87
+ "instructions": "Does `prompt` try to make an AI assistant ignore its rules, policies or system instructions?",
88
+ },
89
+ "prompt_injection": {
90
+ "type": "noul",
91
+ "instructions": "Does `prompt` contain instructions aimed at the AI system rather than a genuine user request?",
92
+ },
93
+ "sensitive_data": {
94
+ "type": "noul",
95
+ "instructions": "Does `prompt` contain credentials, personal data or other sensitive information?",
96
+ },
97
+ "harm_severity": {
98
+ "type": "score",
99
+ "instructions": "How much harm would complying with `prompt` cause?",
100
+ "criteria": [
101
+ "none: ordinary request",
102
+ "minor: mildly inappropriate",
103
+ "serious: unsafe advice or abuse",
104
+ "severe: dangerous or illegal",
105
+ ],
106
+ },
107
+ "topic": {
108
+ "type": "choice",
109
+ "instructions": "What is `prompt` about?",
110
+ "criteria": {
111
+ "product_support": None,
112
+ "coding": None,
113
+ "general_knowledge": None,
114
+ "personal_advice": None,
115
+ "security_testing": None,
116
+ "other": None,
117
+ },
118
+ },
119
+ }
120
+
121
+
122
+ def moderation_questions() -> Dict:
123
+ """Preset questions for content safety and moderation."""
124
+ return {
125
+ "toxic": {
126
+ "type": "noul",
127
+ "instructions": "Is `post` toxic: rude, disrespectful or likely to make someone leave the discussion?",
128
+ },
129
+ "harassment": {
130
+ "type": "noul",
131
+ "instructions": "Does `post` target or harass a specific person?",
132
+ },
133
+ "threat": {
134
+ "type": "noul",
135
+ "instructions": "Does `post` threaten violence, harm or intimidation?",
136
+ },
137
+ "spam": {
138
+ "type": "noul",
139
+ "instructions": "Is `post` spam or advertising?",
140
+ },
141
+ "severity": {
142
+ "type": "score",
143
+ "instructions": "How severe is any rule-breaking in `post`?",
144
+ "criteria": [
145
+ "no rule-breaking: ordinary on-topic post",
146
+ "mild: rude tone or off-topic, no target",
147
+ "clear violation: insults, harassment or spam aimed at someone",
148
+ "severe: threats, hate speech or calls for violence",
149
+ ],
150
+ },
151
+ }
152
+
153
+
154
+ def router_questions() -> Dict:
155
+ """Preset questions for intelligent model routing."""
156
+ return {
157
+ "difficulty": {
158
+ "type": "score",
159
+ "instructions": "How hard is `request` for a language model?",
160
+ "criteria": [
161
+ "trivial: a lookup or one-liner",
162
+ "easy: short answer, no reasoning",
163
+ "moderate: several steps",
164
+ "hard: long multi-step reasoning or specialist knowledge",
165
+ ],
166
+ },
167
+ "domain": {
168
+ "type": "choice",
169
+ "instructions": "What domain does `request` belong to?",
170
+ "criteria": {
171
+ "code": "software engineering, programming, refactoring, architecture, debugging",
172
+ "math_or_logic": "mathematics, logic puzzles, proofs, complex calculation",
173
+ "writing": "creative writing, essays, emails, blog posts, copywriting",
174
+ "factual_lookup": "facts, definitions, trivia, history",
175
+ "data_analysis": "statistics, SQL, data manipulation, metrics",
176
+ "chitchat": "casual conversation, greetings, small talk",
177
+ },
178
+ },
179
+ "needs_tools": {
180
+ "type": "noul",
181
+ "instructions": "Does answering `request` require external tools, search or private data?",
182
+ },
183
+ "is_sensitive": {
184
+ "type": "noul",
185
+ "instructions": "Does `request` involve money, legal, medical or safety consequences?",
186
+ },
187
+ }
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "laya"
7
+ version = "0.3.7"
8
+ description = "Fast, non-autoregressive System 1 decision engine with calibrated probabilities"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "Convai Innovations" }
14
+ ]
15
+ keywords = ["decision-model", "rlcd", "calibration", "system-one", "routing", "guardrails", "moderation", "triage"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ ]
28
+ dependencies = [
29
+ "torch>=2.0.0",
30
+ "transformers>=4.45.0",
31
+ "safetensors>=0.4.0",
32
+ "huggingface_hub>=0.20.0",
33
+ "numpy>=1.20.0",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://huggingface.co/convaiinnovations/laya"
38
+ Demo = "https://huggingface.co/spaces/convaiinnovations/laya-demo"