forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBdaf5582Kadir Yönak3 months ago37 commits

decision.py227 lines, 8.0 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. Kapsam genişletme intent'leri (catalog.RULE_ONLY_INTENTS)
31# benzerlik (TF-IDF) havuzuna ALINMAZ; bu sayede ortak kelimeleri (bugün/menü/
32# program...) IDF'i kirletmez ve OOS ayrımı bozulmadan eşik 0.18'de kalır.
33DEFAULT_THRESHOLD: Final[float] = 0.18
34DEFAULT_TIE_MARGIN: Final[float] = 0.05
35DEFAULT_TOP_K: Final[int] = 3
36# Rol-farkında yönlendirme marjı: seçilen (kapalı) intent ile erişilebilir,
37# karışabilir bir aday arasındaki en yüksek skor farkı. Confusable-pair şartı
38# zaten çok kısıtlayıcı olduğundan cömert tutulabilir.
39DEFAULT_ROLE_REDIRECT_MARGIN: Final[float] = 0.15
40
41# auth_action değerleri
42LOGIN_REQUIRED: Final[str] = "login_required"
43ROLE_INSUFFICIENT: Final[str] = "role_insufficient"
44
45
46@dataclass(frozen=True)
47class Decision:
48 """Karar katmanının çıktısı (loglanabilir)."""
49
50 intent: str | None
51 fallback: bool
52 source: str # "rule" | "similarity" | "fallback"
53 confidence: float
54 top_k: tuple[ScoredIntent, ...] = ()
55 margin: float | None = None
56 tie_break: str | None = None
57 # "src_intent->dst_intent" — top1 oturuma kapalıyken erişilebilir,
58 # karışabilir bir adaya yönlendirildiyse (rol-farkında tie-break).
59 role_redirect: str | None = None
60 auth_action: str | None = None # None | LOGIN_REQUIRED | ROLE_INSUFFICIENT
61 required_role: str | None = None
62 role: str = "ziyaretci"
63 view_id: str | None = None
64 outcome: str | None = None
65 scope: str | None = None
66 reason_code: str | None = None
67 role_space_version: str | None = None
68 role_space_hash: str | None = None
69
70
71def _apply_role_gating(
72 decision: Decision, role: str, authenticated: bool
73) -> Decision:
74 """Seçilen intent için oturum/rol yeterliliğini değerlendirir."""
75
76 if decision.fallback or decision.intent is None:
77 return decision
78
79 effective_role = role if authenticated else "ziyaretci"
80 space = get_role_space(effective_role)
81 view = space.view_for(decision.intent)
82 if view is None:
83 return decision
84 action: str | None = None
85 if view.outcome is AccessOutcome.DENY:
86 action = LOGIN_REQUIRED if not authenticated else ROLE_INSUFFICIENT
87 return replace(
88 decision,
89 auth_action=action,
90 required_role=view.required_role,
91 role=effective_role,
92 view_id=view.view_id,
93 outcome=view.outcome.value,
94 scope=view.scope.value if view.scope else None,
95 reason_code=view.reason_code.value,
96 role_space_version=space.version,
97 role_space_hash=space.content_hash,
98 )
99
100
101def _accessible(intent: str, role: str, authenticated: bool) -> bool:
102 """Oturum bu intent'i (auth + min_role) gerçekten yapabilir mi?"""
103
104 effective_role = role if authenticated else "ziyaretci"
105 view = get_role_space(effective_role).view_for(intent)
106 return view is not None and view.outcome is AccessOutcome.ALLOW
107
108
109def _is_confusable_pair(intent_a: str, intent_b: str) -> bool:
110 """İki intent must_not_match ile (herhangi yönde) karışabilir işaretli mi?"""
111
112 info_a = get_intent(intent_a)
113 info_b = get_intent(intent_b)
114 a_targets = set(info_a.get("must_not_match", [])) if info_a else set()
115 b_targets = set(info_b.get("must_not_match", [])) if info_b else set()
116 return intent_b in a_targets or intent_a in b_targets
117
118
119def decide_core(
120 rule_match: "rules.RuleMatch | None",
121 ranked: list[ScoredIntent] | None,
122 role: str,
123 authenticated: bool,
124 *,
125 in_domain: bool = True,
126 threshold: float = DEFAULT_THRESHOLD,
127 tie_margin: float = DEFAULT_TIE_MARGIN,
128 top_k: int = DEFAULT_TOP_K,
129 role_redirect_margin: float = DEFAULT_ROLE_REDIRECT_MARGIN,
130) -> Decision:
131 """Önceden hesaplanmış kural/benzerlik sonuçlarından nihai kararı üretir.
132
133 Karar mantığının tek yetkili yeri; hem `decide` hem de loglama boru hattı
134 (per-stage zamanlama için) bunu kullanır.
135
136 in_domain=False ise (alan kapısı) benzerlik skoru yüksek olsa bile FALLBACK'e
137 düşülür — kural katmanı bu kapıdan muaftır (yüksek kesinlik).
138 """
139
140 if rule_match is not None:
141 decision = Decision(
142 intent=rule_match.intent,
143 fallback=False,
144 source="rule",
145 confidence=1.0,
146 )
147 return _apply_role_gating(decision, role, authenticated)
148
149 if not ranked:
150 return Decision(intent=None, fallback=True, source="fallback", confidence=0.0)
151
152 top1 = ranked[0]
153 if (not in_domain) or top1.score < threshold:
154 return Decision(
155 intent=None,
156 fallback=True,
157 source="fallback",
158 confidence=top1.score,
159 top_k=tuple(ranked[:top_k]),
160 )
161
162 margin: float | None = None
163 tie_break: str | None = None
164 if len(ranked) >= 2:
165 margin = top1.score - ranked[1].score
166 if margin < tie_margin and _is_confusable_pair(top1.intent, ranked[1].intent):
167 tie_break = f"{top1.intent}~{ranked[1].intent}"
168
169 # V2 closed-space invariant: candidates were produced inside one concrete
170 # role-space. Never redirect to another candidate based on a global role
171 # hierarchy; the chosen view carries its own allow/deny policy.
172 chosen = top1
173 role_redirect: str | None = None
174
175 decision = Decision(
176 intent=chosen.intent,
177 fallback=False,
178 source="similarity",
179 confidence=chosen.score,
180 top_k=tuple(ranked[:top_k]),
181 margin=margin,
182 tie_break=tie_break,
183 role_redirect=role_redirect,
184 )
185 return _apply_role_gating(decision, role, authenticated)
186
187
188def decide(
189 query: str,
190 role: str = "ziyaretci",
191 authenticated: bool = False,
192 *,
193 matcher: SimilarityMatcher | None = None,
194 threshold: float = DEFAULT_THRESHOLD,
195 tie_margin: float = DEFAULT_TIE_MARGIN,
196 top_k: int = DEFAULT_TOP_K,
197) -> Decision:
198 """Bir sorgu için nihai kararı üretir."""
199
200 effective_role = role if authenticated else "ziyaretci"
201 space = get_role_space(effective_role)
202 matcher = matcher or space.similarity_matcher
203 rule_match = space.rule_matcher.match(query)
204 ranked = None if rule_match is not None else matcher.rank(query)
205 if ranked is not None:
206 # Legacy injected matchers remain supported, but their candidates are
207 # projected into this role's local view set and tagged accordingly.
208 ranked = [
209 ScoredIntent(item.intent, item.score, space.space_id)
210 for item in ranked
211 if item.intent in space.views
212 ]
213 in_domain = (
214 True
215 if rule_match is not None
216 else is_in_domain(query, set(space.domain_vocab))
217 )
218 return decide_core(
219 rule_match,
220 ranked,
221 role,
222 authenticated,
223 in_domain=in_domain,
224 threshold=threshold,
225 tie_margin=tie_margin,
226 top_k=top_k,
227 )