forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiB3c4e59dKadir Yönak3 months ago15 commits

decision.py226 lines, 7.9 KiBHistoryRawDownload
1"""Karar katmanı: kural + benzerlik katmanlarını nihai bir karara bağlar.
2
3Akış:
4 1) Kural katmanı bir intent döndürürse onu kullan (yüksek kesinlik).
5 2) Aksi hâlde benzerlik katmanının en iyi skoru:
6 - eşiğin (threshold) altındaysa -> FALLBACK (kapsam dışı / emin değil).
7 - eşiğin üstündeyse -> o intent; en yakın iki skor birbirine çok yakın ve
8 çift `must_not_match`'te işaretliyse tie-break olarak KAYDEDİLİR.
9 3) Rol gating: seçilen intent oturum/rol gerektiriyor ve kullanıcı yetersizse
10 auth_action belirlenir (intent yine döner; ne gösterileceğine cevap katmanı karar verir).
11
12Eşik/margin parametreleri Aşama 11'de benchmark üzerinde ayarlanacaktır; buradaki
13varsayılanlar makul bir başlangıçtır.
14"""
15
16from __future__ import annotations
17
18from dataclasses import dataclass, replace
19from typing import Final
20
21from . import rules
22from .access import AccessOutcome
23from .catalog import get_intent
24from .domain import is_in_domain
25from .role_spaces import get_role_space
26from .similarity import ScoredIntent, SimilarityMatcher, get_default_matcher
27
28
29# Varsayılan parametreler (Aşama 11'de benchmark taramasıyla seçildi).
30# 0.18 + domain-gate: coverage %100, acc-on-covered ~%80, OOS recall ~%78,
31# false-fallback 0. (Domain-gate olmadan OOS recall yalnızca ~%44'tü.)
32DEFAULT_THRESHOLD: Final[float] = 0.18
33DEFAULT_TIE_MARGIN: Final[float] = 0.05
34DEFAULT_TOP_K: Final[int] = 3
35# Rol-farkında yönlendirme marjı: seçilen (kapalı) intent ile erişilebilir,
36# karışabilir bir aday arasındaki en yüksek skor farkı. Confusable-pair şartı
37# zaten çok kısıtlayıcı olduğundan cömert tutulabilir.
38DEFAULT_ROLE_REDIRECT_MARGIN: Final[float] = 0.15
39
40# auth_action değerleri
41LOGIN_REQUIRED: Final[str] = "login_required"
42ROLE_INSUFFICIENT: Final[str] = "role_insufficient"
43
44
45@dataclass(frozen=True)
46class Decision:
47 """Karar katmanının çıktısı (loglanabilir)."""
48
49 intent: str | None
50 fallback: bool
51 source: str # "rule" | "similarity" | "fallback"
52 confidence: float
53 top_k: tuple[ScoredIntent, ...] = ()
54 margin: float | None = None
55 tie_break: str | None = None
56 # "src_intent->dst_intent" — top1 oturuma kapalıyken erişilebilir,
57 # karışabilir bir adaya yönlendirildiyse (rol-farkında tie-break).
58 role_redirect: str | None = None
59 auth_action: str | None = None # None | LOGIN_REQUIRED | ROLE_INSUFFICIENT
60 required_role: str | None = None
61 role: str = "ziyaretci"
62 view_id: str | None = None
63 outcome: str | None = None
64 scope: str | None = None
65 reason_code: str | None = None
66 role_space_version: str | None = None
67 role_space_hash: str | None = None
68
69
70def _apply_role_gating(
71 decision: Decision, role: str, authenticated: bool
72) -> Decision:
73 """Seçilen intent için oturum/rol yeterliliğini değerlendirir."""
74
75 if decision.fallback or decision.intent is None:
76 return decision
77
78 effective_role = role if authenticated else "ziyaretci"
79 space = get_role_space(effective_role)
80 view = space.view_for(decision.intent)
81 if view is None:
82 return decision
83 action: str | None = None
84 if view.outcome is AccessOutcome.DENY:
85 action = LOGIN_REQUIRED if not authenticated else ROLE_INSUFFICIENT
86 return replace(
87 decision,
88 auth_action=action,
89 required_role=view.required_role,
90 role=effective_role,
91 view_id=view.view_id,
92 outcome=view.outcome.value,
93 scope=view.scope.value if view.scope else None,
94 reason_code=view.reason_code.value,
95 role_space_version=space.version,
96 role_space_hash=space.content_hash,
97 )
98
99
100def _accessible(intent: str, role: str, authenticated: bool) -> bool:
101 """Oturum bu intent'i (auth + min_role) gerçekten yapabilir mi?"""
102
103 effective_role = role if authenticated else "ziyaretci"
104 view = get_role_space(effective_role).view_for(intent)
105 return view is not None and view.outcome is AccessOutcome.ALLOW
106
107
108def _is_confusable_pair(intent_a: str, intent_b: str) -> bool:
109 """İki intent must_not_match ile (herhangi yönde) karışabilir işaretli mi?"""
110
111 info_a = get_intent(intent_a)
112 info_b = get_intent(intent_b)
113 a_targets = set(info_a.get("must_not_match", [])) if info_a else set()
114 b_targets = set(info_b.get("must_not_match", [])) if info_b else set()
115 return intent_b in a_targets or intent_a in b_targets
116
117
118def decide_core(
119 rule_match: "rules.RuleMatch | None",
120 ranked: list[ScoredIntent] | None,
121 role: str,
122 authenticated: bool,
123 *,
124 in_domain: bool = True,
125 threshold: float = DEFAULT_THRESHOLD,
126 tie_margin: float = DEFAULT_TIE_MARGIN,
127 top_k: int = DEFAULT_TOP_K,
128 role_redirect_margin: float = DEFAULT_ROLE_REDIRECT_MARGIN,
129) -> Decision:
130 """Önceden hesaplanmış kural/benzerlik sonuçlarından nihai kararı üretir.
131
132 Karar mantığının tek yetkili yeri; hem `decide` hem de loglama boru hattı
133 (per-stage zamanlama için) bunu kullanır.
134
135 in_domain=False ise (alan kapısı) benzerlik skoru yüksek olsa bile FALLBACK'e
136 düşülür — kural katmanı bu kapıdan muaftır (yüksek kesinlik).
137 """
138
139 if rule_match is not None:
140 decision = Decision(
141 intent=rule_match.intent,
142 fallback=False,
143 source="rule",
144 confidence=1.0,
145 )
146 return _apply_role_gating(decision, role, authenticated)
147
148 if not ranked:
149 return Decision(intent=None, fallback=True, source="fallback", confidence=0.0)
150
151 top1 = ranked[0]
152 if (not in_domain) or top1.score < threshold:
153 return Decision(
154 intent=None,
155 fallback=True,
156 source="fallback",
157 confidence=top1.score,
158 top_k=tuple(ranked[:top_k]),
159 )
160
161 margin: float | None = None
162 tie_break: str | None = None
163 if len(ranked) >= 2:
164 margin = top1.score - ranked[1].score
165 if margin < tie_margin and _is_confusable_pair(top1.intent, ranked[1].intent):
166 tie_break = f"{top1.intent}~{ranked[1].intent}"
167
168 # V2 closed-space invariant: candidates were produced inside one concrete
169 # role-space. Never redirect to another candidate based on a global role
170 # hierarchy; the chosen view carries its own allow/deny policy.
171 chosen = top1
172 role_redirect: str | None = None
173
174 decision = Decision(
175 intent=chosen.intent,
176 fallback=False,
177 source="similarity",
178 confidence=chosen.score,
179 top_k=tuple(ranked[:top_k]),
180 margin=margin,
181 tie_break=tie_break,
182 role_redirect=role_redirect,
183 )
184 return _apply_role_gating(decision, role, authenticated)
185
186
187def decide(
188 query: str,
189 role: str = "ziyaretci",
190 authenticated: bool = False,
191 *,
192 matcher: SimilarityMatcher | None = None,
193 threshold: float = DEFAULT_THRESHOLD,
194 tie_margin: float = DEFAULT_TIE_MARGIN,
195 top_k: int = DEFAULT_TOP_K,
196) -> Decision:
197 """Bir sorgu için nihai kararı üretir."""
198
199 effective_role = role if authenticated else "ziyaretci"
200 space = get_role_space(effective_role)
201 matcher = matcher or space.similarity_matcher
202 rule_match = space.rule_matcher.match(query)
203 ranked = None if rule_match is not None else matcher.rank(query)
204 if ranked is not None:
205 # Legacy injected matchers remain supported, but their candidates are
206 # projected into this role's local view set and tagged accordingly.
207 ranked = [
208 ScoredIntent(item.intent, item.score, space.space_id)
209 for item in ranked
210 if item.intent in space.views
211 ]
212 in_domain = (
213 True
214 if rule_match is not None
215 else is_in_domain(query, set(space.domain_vocab))
216 )
217 return decide_core(
218 rule_match,
219 ranked,
220 role,
221 authenticated,
222 in_domain=in_domain,
223 threshold=threshold,
224 tie_margin=tie_margin,
225 top_k=top_k,
226 )