forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiBaaf05cfKadir Yönak2 months ago112 commits

handler.py157 lines, 8.1 KiBHistoryRawDownload
1"""Faz — RAG servis isteği işleyici (#2, transport-BAĞIMSIZ). API-CONTRACT.md'deki
2/rag/chat + /rag/summarize + /rag/questions girdi/çıktı sözleşmesini uygular; JSON-
3uyumlu dict alır/döner. HTTP sunucusu VEYA backend QUIC köprüsü bunu sarar (D3
4kararı transport'ta; iş mantığı + rol-uygulaması + biçimleme burada — tek yer).
5
6GÜVENLİK (RES-002/003): `role` SUNUCU-TARAFI türetilmiş kabul edilir (transport/auth
7katmanı üretir; bu handler onu OLDUĞU GİBİ uygular, doğrulamaz). role verilmişse
8kasa izolasyonu Generator.answer(role_ctx=...) ile; özet kapsamı için de erişim
9yeniden doğrulanır (yanlış sınıf/ders → red)."""
10from __future__ import annotations
11
12from ..guard.roles import RoleContext, Role, can_access
13
14
15def _role_ctx(role: dict | None):
16 """API role sözlüğü → RoleContext. Tanınmayan/eksik rol → None.
17
18 DİKKAT (#43): `None` "rol yok" demektir, "her şeye erişebilir" DEMEZ.
19 Çağıranın bunu fail-CLOSED yorumlaması ZORUNLUDUR (bkz. `_scope_denied`).
20 EXP-010/SEC-02'de tam bu yorum hatası vardı: `if role_ctx is not None:`
21 koruması yüzünden rol çözülemeyince kontrol TAMAMEN atlanıyordu."""
22 if not role or not isinstance(role, dict):
23 return None
24 try:
25 r = Role(str(role.get("role", "")).strip().lower())
26 except ValueError:
27 return None
28 return RoleContext(role=r, sinif=role.get("sinif"),
29 ders_list=list(role.get("ders_list") or []))
30
31
32# #42/#43 — TEK YETKİ KAPISI (özet + soru yolları). Gerekçe EXP-010:
33# SEC-01 (KRİTİK): erişim kararı istemcinin gönderdiği `scope.sinif`/`scope.ders`
34# ile veriliyordu → saldırgan `can_access`'e hem özneyi hem NESNEYİ kendisi
35# bildiriyordu. Koşularak kanıtlandı: 9. sınıf matematik öğrencisi gerçek
36# rolüyle `scope={"sinif":"9","ders":"matematik"}` gönderip 12-biyoloji
37# içeriğini özetletti.
38# SEC-02 (KRİTİK): rol çözülemezse (`manager` enum'da yok, `"Öğrenci"`, boş)
39# kontrol tamamen atlanıyordu (fail-OPEN).
40# Çözüm: kapsamın sınıf/dersi YALNIZ sunucu gerçeğinden (`self.doc`) alınır;
41# istemcinin bildirdiği değer varsa DOĞRULAMA GİRDİSİ değil, sunucu gerçeğiyle
42# EŞLEŞME ŞARTI olarak kullanılır (uyuşmazsa red). Rol yoksa red.
43def _scope_denied(service, scope: dict, role: dict | None) -> str | None:
44 """Yetki reddi gerekçesi ya da None (erişim serbest).
45
46 Dönen değerler: "role_required" | "role_denied" | "scope_mismatch" | None
47 """
48 role_ctx = _role_ctx(role)
49 if role_ctx is None:
50 return "role_required" # fail-CLOSED (#43)
51 # SUNUCU GERÇEĞİ — istemci bunu değiştiremez (#42)
52 srv_sinif = getattr(service.doc, "sinif", None)
53 srv_ders = service.ders or getattr(service.doc, "ders", None)
54 # İstemci kapsam etiketi gönderdiyse sunucu gerçeğiyle EŞLEŞMELİ; yoksa red.
55 cli_sinif, cli_ders = scope.get("sinif"), scope.get("ders")
56 if cli_sinif is not None and str(cli_sinif) != str(srv_sinif):
57 return "scope_mismatch"
58 if cli_ders is not None and str(cli_ders) != str(srv_ders):
59 return "scope_mismatch"
60 if not can_access(role_ctx, sinif=srv_sinif, ders=srv_ders):
61 return "role_denied"
62 return None
63
64
65def _answer_to_dict(a) -> dict:
66 return {
67 "text": a.text,
68 "abstained": bool(a.abstained),
69 "reason": a.reason or "",
70 "citations": [{"n": c.get("n"), "chunk_id": c.get("chunk_id"),
71 "span_ids": c.get("span_ids", []), "pages": c.get("pages", []),
72 "ders": c.get("ders", "")} for c in a.citations],
73 "used_source_ids": list(a.used_source_ids),
74 # #62 (EXP-010/ACC-12): hayalet `[N]` numaralari payload'a HIC girmiyordu.
75 # Metinden kirpilsa bile backend'in "bu cevapta cozulemeyen atif vardi"
76 # bilgisine erisimi olmali (telemetri + kalite kapisi O-?/A-*).
77 "invalid_citations": list(getattr(a, "invalid_citations", []) or []),
78 "cost_usd": round(a.cost_usd, 6),
79 "cache_hit": bool(getattr(a, "cache_hit", False)),
80 }
81
82
83class RagService:
84 """Bir korpus için RAG servisi: chat (generator) + özet (doc+summarizer) +
85 benzer-soru (question_gen). Bileşenler enjekte edilir (index/model paylaşılır)."""
86
87 def __init__(self, generator, *, doc=None, summarizer=None, question_gen=None,
88 ders: str = ""):
89 self.generator = generator
90 self.doc = doc
91 self.summarizer = summarizer
92 self.question_gen = question_gen
93 self.ders = ders
94
95 # ------------------------------------------------------------------ /rag/chat
96 def chat(self, req: dict) -> dict:
97 query = (req.get("query") or "").strip()
98 if not query:
99 return {"text": "", "abstained": True, "reason": "empty_query",
100 "citations": [], "used_source_ids": [], "cost_usd": 0.0, "cache_hit": False}
101 role_ctx = _role_ctx(req.get("role"))
102 opts = req.get("options") or {}
103 a = self.generator.answer(
104 query, history=req.get("history"),
105 top_n=int(opts.get("top_n", 6)), candidate_n=int(opts.get("candidate_n", 40)),
106 role_ctx=role_ctx)
107 return _answer_to_dict(a)
108
109 # -------------------------------------------------------------- /rag/summarize
110 def summarize(self, req: dict) -> dict:
111 if self.doc is None or self.summarizer is None:
112 return {"text": "", "abstained": True, "reason": "summary_unavailable",
113 "citations": [], "scope_pages": [], "hierarchical": False, "cost_usd": 0.0}
114 scope = req.get("scope") or {}
115 pages = scope.get("pages")
116 span_ids = scope.get("span_ids")
117 if not pages and not span_ids:
118 return {"text": "", "abstained": True, "reason": "empty_scope",
119 "citations": [], "scope_pages": [], "hierarchical": False, "cost_usd": 0.0}
120 # ERİŞİM YENİDEN DOĞRULAMA (API-CONTRACT §4) — #42/#43: karar YALNIZ
121 # sunucu gerçeğinden; rol yoksa fail-closed.
122 denied = _scope_denied(self, scope, req.get("role"))
123 if denied:
124 return {"text": "", "abstained": True, "reason": denied,
125 "citations": [], "scope_pages": [], "hierarchical": False, "cost_usd": 0.0}
126 from ..summarize.scope import resolve_scope
127 units = resolve_scope(self.doc, pages=pages, span_ids=span_ids)
128 res = self.summarizer.summarize(units, scope_label=scope.get("scope_label", ""))
129 return {
130 "text": res.text, "abstained": bool(res.abstained), "reason": res.reason or "",
131 "citations": [{"n": c.get("n"), "span_ids": c.get("span_ids", []),
132 "pages": c.get("pages", [])} for c in res.citations],
133 "scope_pages": res.scope_pages, "hierarchical": bool(res.hierarchical),
134 "cost_usd": round(res.cost_usd, 6),
135 }
136
137 # -------------------------------------------------------------- /rag/questions
138 def generate_questions(self, req: dict) -> dict:
139 if self.doc is None or self.question_gen is None:
140 return {"items": [], "abstained": True, "reason": "questions_unavailable",
141 "span_ids": [], "pages": [], "cost_usd": 0.0}
142 scope = req.get("scope") or {}
143 pages, span_ids = scope.get("pages"), scope.get("span_ids")
144 denied = _scope_denied(self, scope, req.get("role"))
145 if denied:
146 return {"items": [], "abstained": True, "reason": denied,
147 "span_ids": [], "pages": [], "cost_usd": 0.0}
148 from ..summarize.scope import resolve_scope
149 units = resolve_scope(self.doc, pages=pages, span_ids=span_ids)
150 res = self.question_gen.generate(units, n=int(req.get("n", 5)),
151 difficulty=req.get("difficulty", "orta"),
152 seed_question=req.get("seed_question"))
153 return {
154 "items": [{"soru": q.soru, "cevap": q.cevap, "zorluk": q.zorluk} for q in res.items],
155 "abstained": bool(res.abstained), "reason": res.reason or "",
156 "span_ids": res.span_ids, "pages": res.pages, "cost_usd": round(res.cost_usd, 6),
157 }