forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

config.py339 lines, 14.3 KiBHistoryRawDownload
1"""Segmentasyon alt sisteminin yapilandirma katmani.
2
3Desen `service/src/config.py` ile ayni felsefede: ortamdan okuyan kucuk
4yardimcilar, tek bir dataclass, hatali yapilandirmada acik hata. Ancak o dosya
5ICE AKTARILMAZ — bu alt sistem bagimsiz durur.
6
7Sir hijyeni: API anahtari HICBIR ZAMAN loglanmaz; `summary()` yalnizca
8"tanimli / TANIMSIZ" yazar.
9"""
10
11from __future__ import annotations
12
13import os
14import sys
15from dataclasses import dataclass, field
16from pathlib import Path
17
18# --- gunlukleme ------------------------------------------------------------
19# Windows konsolu ASCII disini bozabiliyor; bu yuzden log satirlari ASCII-Turkce.
20
21_LEVELS = {"debug": 10, "info": 20, "warn": 30, "error": 40}
22_active = _LEVELS["info"]
23
24
25#: KALDIRILAN LLM adlari. Dolu bulunurlarsa yapilandirma reddedilir: yarim
26#: kalan bir adi sessizce yok saymak, operatorun kendi ayar dosyasinin artik
27#: okunmadigini fark etmemesi demek olurdu.
28ESKI_LLM_ADLARI: tuple[str, ...] = (
29 "DEEPSEEK_API_KEY",
30 "SEGMENT_API_KEY",
31 "SEGMENT_BASE_URL",
32 "SEGMENT_MODEL_FLASH",
33 "SEGMENT_MODEL_PRO",
34 "SEGMENT_MODEL_REASONER",
35 "SEGMENT_MODEL_ROLE",
36)
37
38
39class SegmentConfigError(Exception):
40 """Yapilandirma hatasi."""
41
42
43def set_log_level(name: str) -> None:
44 lvl = _LEVELS.get(name.strip().lower())
45 if lvl is None:
46 raise SegmentConfigError(f"LOG_LEVEL gecersiz: {name!r}")
47 global _active
48 _active = lvl
49
50
51def log(level: str, message: str) -> None:
52 """Gunluk satiri — DAIMA stderr'e.
53
54 stdout yalnizca makine tarafindan okunacak JSON'u tasir; gunluk satirlari
55 oraya karisirsa `python -m src.segment.cli run ... > rapor.json` ciktisi
56 ayristirilamaz hale gelir (olculdu: `work/stab.json` bozuldu).
57 """
58 if _LEVELS.get(level, 20) >= _active:
59 print(f"[segment] {message}", file=sys.stderr, flush=True)
60
61
62def _env(name: str) -> str | None:
63 val = os.environ.get(name)
64 return val.strip() if val and val.strip() else None
65
66
67def _env_float(name: str, default: float) -> float:
68 raw = _env(name)
69 if raw is None:
70 return default
71 try:
72 return float(raw)
73 except ValueError as exc: # noqa: PERF203
74 raise SegmentConfigError(f"{name} sayi olmali: {raw!r}") from exc
75
76
77def _env_int(name: str, default: int) -> int:
78 raw = _env(name)
79 if raw is None:
80 return default
81 try:
82 return int(raw)
83 except ValueError as exc:
84 raise SegmentConfigError(f"{name} tamsayi olmali: {raw!r}") from exc
85
86
87# Model rolleri. Gorev tanimi "pro / flash / reasoner" adlarini yapilandirmadan
88# ister; API model id'leri ortamdan degistirilebilir.
89#
90# UCTAN OLCULDU (2026-09-14, GET https://api.deepseek.com/models): katalogda
91# TAM OLARAK IKI model var -> `deepseek-flash` ve `deepseek-v4-pro`.
92# `deepseek-chat`, `deepseek-reasoner`, `deepseek-v4-flash` ADLARI ARTIK YOK.
93#
94# `reasoner` rolu bu yuzden AYRI BIR MODEL DEGILDIR: ayni `deepseek-v4-pro`
95# modelinin akil yurutme KIPIDIR (`thinking={"type":"enabled"}`). Ayrimi
96# `THINKING_BY_ROLE` tasir.
97DEFAULT_MODEL_IDS = {
98 "flash": "deepseek-flash",
99 "pro": "deepseek-v4-pro",
100 "reasoner": "deepseek-v4-pro",
101}
102
103#: Rol basina varsayilan akil yurutme kipi (`SEGMENT_THINKING` bunu ezer).
104#: UCTAN OLCULDU: `deepseek-v4-pro` akil yurutmeyi VARSAYILAN olarak yapar;
105#: "disabled" denmedikce dusunce uretir ve dusunce token'lari CIKTI olarak
106#: faturalanir (pahali taraf). Bu yuzden `pro` rolu acikca "disabled" alir,
107#: `reasoner` rolu acikca "enabled".
108THINKING_BY_ROLE: dict[str, str | None] = {
109 "flash": None, # uca gonderilmez (modelin kendi varsayilani)
110 "pro": "disabled", # maliyet kontrolu: dusunce kapali
111 "reasoner": "enabled", # "pro max thinking" istegi bu rol
112}
113
114#: Uctan dogrulanmis gecerli degerler.
115THINKING_VALUES = ("enabled", "disabled")
116REASONING_EFFORTS = ("minimal", "low", "medium", "high")
117
118
119@dataclass
120class SegmentConfig:
121 """Segmentasyon kosusunun tum ayarlari."""
122
123 # --- saglayici ---------------------------------------------------------
124 base_url: str = "https://api.deepseek.com"
125 api_key: str | None = None
126 model_ids: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_MODEL_IDS))
127 #: Taban cizgi ve varyantlarin varsayilan model rolu.
128 model_role: str = "flash"
129 timeout_s: float = 120.0
130 #: Akil yurutme kipi. None = rol varsayilani (`THINKING_BY_ROLE`),
131 #: "" (bos) = uca HIC gonderme, "enabled"/"disabled" = acikca gonder.
132 #: Govdeye METIN degil NESNE olarak konur: {"type": "enabled"}.
133 #: UCTAN OLCULDU: metin gonderilirse 400 "invalid type: string, expected
134 #: struct ThinkingOptions".
135 thinking: str | None = None
136 #: `minimal|low|medium|high`; None = uca gonderme.
137 reasoning_effort: str | None = None
138
139 # --- maliyet / hiz -----------------------------------------------------
140 #: USD tavani. Asilirsa kosu `BudgetExceeded` ile DURUR (gorev sartı).
141 budget_usd: float = 5.0
142 #: Dakikada azami istek (hiz siniri). `provider.RateLimiter` ile UYGULANIR;
143 #: is parcaciklari arasinda paylasilir, es zamanlilik onu EZMEZ.
144 rpm: int = 60
145 #: Es zamanli istek siniri. IKI yerde birden baglayicidir:
146 #: * `labelers.BaseLabeler.run()` madde havuzunun isci sayisi,
147 #: * `provider.BaseProvider._sem` semaforu (bagimsiz guvenlik kemeri).
148 concurrency: int = 4
149 #: Ustel geri cekilmeli yeniden deneme sayisi.
150 max_retry: int = 4
151 retry_base_s: float = 0.5
152
153 # --- onbellek ----------------------------------------------------------
154 cache_dir: Path = Path("work/segment_cache")
155 cache_enabled: bool = True
156
157 # --- Asama 0: kararlilik kapisi ---------------------------------------
158 #: Bulgu 6: "alpha < 0,70 ise istemi revize et". Kapi kodda uygulanir.
159 alpha_gate: float = 0.70
160 #: Bulgu 6: "PSS >= 0,80 saglam kabul edilir" — bilgi amacli ikinci esik.
161 alpha_solid: float = 0.80
162 #: Bulgu 11: 300-500 soruluk alt kume (KANITLANMIS DEGIL, pratik tahmin).
163 stability_n: int = 300
164 #: Bulgu 6'da intra-PSS 30 tekrarla olculuyor; maliyet nedeniyle varsayilan
165 #: dusuk tutuldu, gercek kosuda 10+ onerilir.
166 intra_replicates: int = 5
167 #: Inter-PSS icin anlamca esdegerli istem varyanti sayisi.
168 inter_variants: int = 3
169
170 # --- Asama 2: esit token butcesi --------------------------------------
171 #: Bulgu 7/9: cok ajanli varyantlar ESIT butcede karsilastirilir. Her cok
172 #: ajanli varyant tam olarak bu kadar LLM cagrisi yapar.
173 equal_budget_calls: int = 4
174 #: Butce esitligi toleransi (token orani |1 - r| <= tol).
175 budget_tolerance: float = 0.15
176
177 # --- Asama 3: karar kurali --------------------------------------------
178 #: Cok ajanli varyantin taban cizgiyi gecmesi icin gereken asgari F1 farki.
179 min_effect: float = 0.03
180 #: McNemar testi anlamlilik esigi.
181 alpha_significance: float = 0.05
182 #: Bulgu 10: ajanlar arasi uyum bu esigin ustunde ama dogruluk taban
183 #: cizginin altindaysa "uzlasma yanilsamasi" bayragi kalkar.
184 consensus_illusion_agreement: float = 0.80
185
186 # --- veri --------------------------------------------------------------
187 items_path: Path = Path("work/items_enriched.json")
188 manifest_path: Path = Path("seed/_seed_manifest.json")
189 answers_path: Path = Path("seed/11_exam_answer.surql")
190 out_dir: Path = Path("work/segment_out")
191
192 #: Belirlenimcilik tohumu (MockProvider + orneklem + permutasyon).
193 seed: int = 20260913
194 #: Ornekleme/etiketleme sicakligi. MockProvider bunu "kararsizlik" olarak
195 #: kullanir; gercek saglayicida API'ye gider.
196 temperature: float = 0.2
197
198 @classmethod
199 def from_env(cls, root: Path | None = None) -> "SegmentConfig":
200 """Ortam degiskenlerinden yapilandirma uretir.
201
202 `root` verilirse tum goreli yollar onun altinda cozulur (depo koku).
203 """
204 cfg = cls()
205 # --- LLM adlari: TEMIZ KESIM (2026-09-17) --------------------------
206 # Eski adlar KALDIRILDI: anahtar `LLM_API_KEY`, adres `LLM_BASE_URL`,
207 # modeller `LLM_MODEL_FLASH/PRO/REASONER`, rol `LLM_MODEL_ROLE`.
208 # Bir "eski ad da calissin" dali birakmak "hangi ad kazandi" sorusunu
209 # kodun icine tasirdi; onun yerine eski ad gorulunce yapilandirma
210 # ACIKCA REDDEDILIR -- sessizce calisan bir kurulum, adi degismemis
211 # bir operatoru fark ettirmez.
212 eski = [ad for ad in ESKI_LLM_ADLARI if (os.environ.get(ad) or "").strip()]
213 if eski:
214 raise SegmentConfigError(
215 "su adlar artik DESTEKLENMIYOR: %s. Yeni adlar: LLM_API_KEY, "
216 "LLM_BASE_URL, LLM_MODEL_FLASH / LLM_MODEL_PRO / "
217 "LLM_MODEL_REASONER, LLM_MODEL_ROLE."
218 % ", ".join(eski))
219 # Varsayilan adres DeepSeek'tir ama bu bir ZORUNLULUK degildir:
220 # OpenAI uyumlu her ag gecidi LLM_BASE_URL ile bu hatayi kosturur.
221 cfg.base_url = (_env("LLM_BASE_URL") or cfg.base_url).rstrip("/")
222 # Anahtar yoksa anahtar YOKTUR -- sessiz bir varsayilan yoktur.
223 cfg.api_key = _env("LLM_API_KEY")
224 for role in ("flash", "pro", "reasoner"):
225 override = _env(f"LLM_MODEL_{role.upper()}")
226 if override:
227 cfg.model_ids[role] = override
228 role = _env("LLM_MODEL_ROLE")
229 if role:
230 if role not in cfg.model_ids:
231 raise SegmentConfigError(
232 f"LLM_MODEL_ROLE gecersiz: {role!r} "
233 f"(beklenen: {', '.join(sorted(cfg.model_ids))})")
234 cfg.model_role = role
235
236 # Akil yurutme: BOS STRING ile "hic gonderme" ayrimi korunur, bu yuzden
237 # `_env` degil dogrudan `os.environ` okunur.
238 if "SEGMENT_THINKING" in os.environ:
239 cfg.thinking = os.environ["SEGMENT_THINKING"].strip().lower()
240 if "SEGMENT_REASONING_EFFORT" in os.environ:
241 raw = os.environ["SEGMENT_REASONING_EFFORT"].strip().lower()
242 cfg.reasoning_effort = raw or None
243
244 cfg.budget_usd = _env_float("SEGMENT_BUDGET_USD", cfg.budget_usd)
245 cfg.rpm = _env_int("SEGMENT_RPM", cfg.rpm)
246 cfg.concurrency = _env_int("SEGMENT_CONCURRENCY", cfg.concurrency)
247 cfg.max_retry = _env_int("SEGMENT_MAX_RETRY", cfg.max_retry)
248 cfg.timeout_s = _env_float("SEGMENT_TIMEOUT_S", cfg.timeout_s)
249
250 cfg.alpha_gate = _env_float("SEGMENT_ALPHA_GATE", cfg.alpha_gate)
251 cfg.stability_n = _env_int("SEGMENT_STABILITY_N", cfg.stability_n)
252 cfg.intra_replicates = _env_int("SEGMENT_INTRA_REPLICATES",
253 cfg.intra_replicates)
254 cfg.inter_variants = _env_int("SEGMENT_INTER_VARIANTS", cfg.inter_variants)
255 cfg.equal_budget_calls = _env_int("SEGMENT_EQUAL_BUDGET_CALLS",
256 cfg.equal_budget_calls)
257 cfg.min_effect = _env_float("SEGMENT_MIN_EFFECT", cfg.min_effect)
258 cfg.seed = _env_int("SEGMENT_SEED", cfg.seed)
259 cfg.temperature = _env_float("SEGMENT_TEMPERATURE", cfg.temperature)
260 cfg.cache_enabled = (_env("SEGMENT_CACHE") or "1") not in ("0", "off", "no")
261
262 cache = _env("SEGMENT_CACHE_DIR")
263 if cache:
264 cfg.cache_dir = Path(cache)
265 items = _env("SEGMENT_ITEMS")
266 if items:
267 cfg.items_path = Path(items)
268 out = _env("SEGMENT_OUT_DIR")
269 if out:
270 cfg.out_dir = Path(out)
271
272 if root is not None:
273 cfg.resolve_under(root)
274 cfg.validate()
275 return cfg
276
277 def resolve_under(self, root: Path) -> None:
278 """Goreli yollari depo koku altinda coz."""
279 root = Path(root)
280 for name in ("cache_dir", "items_path", "manifest_path", "answers_path",
281 "out_dir"):
282 p = Path(getattr(self, name))
283 if not p.is_absolute():
284 setattr(self, name, root / p)
285
286 def validate(self) -> None:
287 if self.budget_usd <= 0:
288 raise SegmentConfigError("SEGMENT_BUDGET_USD pozitif olmali.")
289 if not 0.0 <= self.alpha_gate <= 1.0:
290 raise SegmentConfigError("SEGMENT_ALPHA_GATE [0,1] araliginda olmali.")
291 if self.intra_replicates < 2:
292 raise SegmentConfigError(
293 "intra-PSS icin en az 2 tekrar gerekir (alpha tanimsiz olur).")
294 if self.equal_budget_calls < 2:
295 raise SegmentConfigError("equal_budget_calls en az 2 olmali.")
296 if self.concurrency < 1:
297 raise SegmentConfigError("concurrency en az 1 olmali.")
298 # RPM sessizce kirpilmasin: `RateLimiter` 1'in altini 1'e cekerdi,
299 # yani hatali ayar fark edilmeden kosuyu dakikada 1 istege dusururdu.
300 if self.rpm < 1:
301 raise SegmentConfigError("SEGMENT_RPM en az 1 olmali.")
302 if self.thinking not in (None, "") and self.thinking not in THINKING_VALUES:
303 raise SegmentConfigError(
304 f"SEGMENT_THINKING gecersiz: {self.thinking!r} "
305 f"(beklenen: {', '.join(THINKING_VALUES)} ya da bos)")
306 if self.reasoning_effort is not None and \
307 self.reasoning_effort not in REASONING_EFFORTS:
308 raise SegmentConfigError(
309 f"SEGMENT_REASONING_EFFORT gecersiz: {self.reasoning_effort!r} "
310 f"(beklenen: {', '.join(REASONING_EFFORTS)})")
311
312 def model_id(self, role: str | None = None) -> str:
313 role = role or self.model_role
314 try:
315 return self.model_ids[role]
316 except KeyError as exc:
317 raise SegmentConfigError(f"Bilinmeyen model rolu: {role!r}") from exc
318
319 def thinking_for(self, role: str | None = None) -> str | None:
320 """Bu rol icin uca gonderilecek akil yurutme kipi.
321
322 Oncelik: acik `SEGMENT_THINKING` > rol varsayilani. `""` (bos) verilirse
323 uca HIC gonderilmez ve modelin kendi varsayilani gecerli olur.
324 """
325 if self.thinking is not None:
326 return self.thinking or None
327 return THINKING_BY_ROLE.get(role or self.model_role)
328
329 def summary(self) -> str:
330 key = "tanimli" if self.api_key else "TANIMSIZ"
331 think = self.thinking_for() or "(uca gonderilmiyor)"
332 effort = self.reasoning_effort or "(uca gonderilmiyor)"
333 return (
334 f"base_url={self.base_url} api_key={key} rol={self.model_role} "
335 f"model={self.model_id()} thinking={think} reasoning_effort={effort} "
336 f"butce={self.budget_usd:.2f} USD "
337 f"alpha_kapi={self.alpha_gate} esit_butce_cagri={self.equal_budget_calls} "
338 f"onbellek={'acik' if self.cache_enabled else 'kapali'}"
339 )