forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

dispatch.py224 lines, 12.0 KiBHistoryRawDownload
1"""hab/2 dağıtımı — çerçeveden servise, TAŞIMADAN bağımsız.
2
3Taşıma (QUIC akışları) BURADA DEĞİL. Bu modül bir `Request` çerçevesini alır,
4okulunu doğrular, yeteneğe göre servis metoduna yönlendirir ve okulu AYNEN geri
5yazan tek bir `Response` üretir. Böylece dağıtım ağ olmadan test edilir —
6`BridgeReader`'ın "çerçeveyi kur/çöz, taşımayı dışarıdan ver" ayrımıyla aynı
7gerekçe.
8
9OKUL (kiracılık) BU KATMANIN İŞİDİR:
10 * Çerçevede okul yoksa → `malformed`, akış DÜŞÜRÜLÜR (`handle` None döner):
11 geri yazılacak bir okul yoktur ve backend'in kendi kuralı da "no default,
12 no fallback" der.
13 * Okul biçimi geçersiz/ayrılmışsa → `invalid_school` tipli reddi (okulun
14 VARLIĞI backend'in kararıdır; servis okul listesi icat ETMEZ).
15 * Geçerliyse okul servis çağrısının gövdesine AYNEN konur; servis katmanı
16 (registry + store) okuma/yazmayı onunla kapsamlar (bkz. guard/tenant.py).
17 * Cevap okulu her durumda EKO eder (`BridgeResponse.school`).
18
19`deadline_ms` DÜRÜST SINIR: taşınır ve istek gövdesine konur, ama bu modül
20isteği KESEMEZ — boru hattı (retrieval + LLM) senkron çalışır. Son tarihi
21zorlamak taşımanın/servis katmanının işidir; sessizce "uyulmuş" sayılmaz.
22"""
23from __future__ import annotations
24
25from .contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY,
26 AI_RAG_INDEX_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY,
27 AI_RAG_SUMMARIZE_CAPABILITY, BridgeFrameError, BridgeRequest,
28 BridgeResponse)
29
30# `rag.index` is served end to end: the payload is parsed, every attachment is
31# read as bytes over its own blob stream, the note is chunked, embedded and
32# written into the school's note index (`service::notes_index`), and the answer
33# object goes back for the backend to store as the note's `rag_output`.
34class Dispatcher:
35 """`Request` çerçevesi → servis metodu → `Response` çerçevesi."""
36
37 def __init__(self, service, *, capabilities=None, indexer=None):
38 self.service = service
39 #: `rag.index`'in gövdesi (not → parça → gömme → not indeksi). Enjekte
40 #: edilebilir: taşıma testleri ağ/örnek istemeyen bir sahte verir;
41 #: üretimde `service::notes_index.index_course_note` koşar.
42 self.indexer = indexer
43 #: Blob okuyucusu — TAŞIMA takar (`transport.BridgeTransport.register`).
44 #: Yoksa ekler okunamaz ve notun kendi metni yine indekslenir.
45 self.blob_reader = None
46 self.capabilities = tuple(capabilities or (
47 AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY,
48 AI_RAG_SUMMARIZE_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY))
49
50 # -- tel biçimi düzeyi ------------------------------------------------
51 def handle(self, frame: dict) -> dict | None:
52 """Bir `Request` çerçevesini karşılar. Bozuk çerçevede None (akış
53 DÜŞER): ekolayacak bir okul/id yoktur, uydurmak protokolü bozar."""
54 try:
55 req = BridgeRequest.from_wire(frame)
56 except BridgeFrameError as e:
57 print(f"[kopru][HATA] {e}", flush=True)
58 return None
59 return self.dispatch(req).to_wire()
60
61 # -- yetenek düzeyi ---------------------------------------------------
62 def dispatch(self, req: BridgeRequest) -> BridgeResponse:
63 from ..guard.tenant import TenantError, normalize_school
64 try:
65 okul = normalize_school(req.school)
66 except TenantError as e:
67 return BridgeResponse.err(req, "invalid_school", str(e))
68 if okul is None:
69 # Buraya normalde düşülmez: `from_wire` okulsuz çerçeveyi reddeder.
70 return BridgeResponse.err(req, "malformed",
71 "`school` ZORUNLU (varsayılan/fallback yok)")
72
73 if req.capability == AI_RAG_INDEX_CAPABILITY:
74 return self._rag_index(req, okul)
75 if req.capability == AI_RAG_CHAT_CAPABILITY:
76 return BridgeResponse.ok(req, self._rag_chat(req, okul))
77 if req.capability == AI_RAG_SUMMARIZE_CAPABILITY:
78 return BridgeResponse.ok(req, self._rag_summarize(req, okul))
79 if req.capability == AI_RAG_QUESTIONS_CAPABILITY:
80 return BridgeResponse.ok(req, self._rag_questions(req, okul))
81 if req.capability == AI_CHAT_CAPABILITY:
82 return BridgeResponse.ok(req, self._chat(req, okul))
83 return BridgeResponse.err(
84 req, "unsupported_capability",
85 f"bu servis `{req.capability}` sunmuyor (yetenekler: "
86 f"{', '.join(self.capabilities)})")
87
88 # -- gövde eşlemeleri (tel biçimi → servis sözlüğü) --------------------
89 def _rag_index(self, req: BridgeRequest, okul: str) -> BridgeResponse:
90 """`rag.index` → not + ekler → not indeksi → backend'in sakladığı gövde.
91
92 Redler TİPLİ ve küçük tutulur: backend bir hatada eski `rag_output`
93 satırını korur, yani "sessiz tamam" en kötü sonuçtur. Tek bir ekin
94 okunamaması ise red DEĞİLDİR — notun kendi metni indekslenir ve cevap
95 hangi ekin okunamadığını söyler (bkz. `service/notes_index.py`)."""
96 from .contract import RagIndexPayload
97 try:
98 payload = RagIndexPayload.from_wire(req.payload)
99 except (KeyError, TypeError) as exc:
100 return BridgeResponse.err(req, "malformed",
101 f"rag.index gövdesi eksik/yanlış: {exc}")
102 indexer = self.indexer
103 if indexer is None:
104 from ..service.notes_index import index_course_note as indexer
105 try:
106 cevap = indexer(payload, school=okul, blob_reader=self.blob_reader)
107 except Exception as exc: # noqa: BLE001
108 import traceback
109 traceback.print_exc()
110 return BridgeResponse.err(req, "internal",
111 f"rag.index çalıştırılamadı: "
112 f"{type(exc).__name__}: {exc}")
113 if not isinstance(cevap, dict):
114 return BridgeResponse.err(req, "internal",
115 "rag.index bir nesne döndürmedi")
116 return BridgeResponse.ok(req, cevap)
117
118 def _govde(self, req: BridgeRequest, okul: str) -> dict:
119 """Servis isteğinin ortak alanları: sorgu + ROL + okul.
120
121 Rol backend'de türetilir (`asker_role`); burada ADI eşlenir
122 (`role.role`) — bkz. API-CONTRACT §0.2(a). Rol yoksa servis zaten
123 fail-closed reddeder (`role_required`)."""
124 from .contract import ChatRequestPayload, RagChatRequestPayload
125 if req.capability in (AI_RAG_SUMMARIZE_CAPABILITY,
126 AI_RAG_QUESTIONS_CAPABILITY):
127 return self._govde_kapsam(req, okul)
128 if req.capability == AI_RAG_CHAT_CAPABILITY:
129 p = RagChatRequestPayload.from_wire(req.payload)
130 return {"query": p.message, "user": p.asker or None,
131 "role": {"role": p.asker_role} if p.asker_role else None,
132 "scope": [s.to_wire() for s in p.scope],
133 "history": [t.to_wire() for t in p.history],
134 "school": okul, "deadline_ms": req.deadline_ms}
135 p = ChatRequestPayload.from_wire(req.payload)
136 return {"query": p.message,
137 "role": {"role": p.asker_role} if p.asker_role else None,
138 "history": [t.to_wire() for t in p.history],
139 "school": okul, "deadline_ms": req.deadline_ms}
140
141 def _rag_chat(self, req: BridgeRequest, okul: str) -> dict:
142 """`rag.chat` → servis `chat()` → backend'in `RagChatReplyPayload`i."""
143 from .contract import RagCitation, RagChatReplyPayload
144 cevap = self.service.chat(self._govde(req, okul))
145 return RagChatReplyPayload(
146 text=str(cevap.get("text") or ""),
147 abstained=bool(cevap.get("abstained", False)),
148 reason=str(cevap.get("reason") or ""),
149 citations=[RagCitation(n=int(c.get("n") or 0),
150 doc_id=str(c.get("doc_id") or ""),
151 pages=list(c.get("pages") or []),
152 span_ids=list(c.get("span_ids") or []),
153 ders=c.get("ders"))
154 for c in (cevap.get("citations") or [])],
155 ).to_wire()
156
157 def _govde_kapsam(self, req: BridgeRequest, okul: str) -> dict:
158 """`rag.summarize`/`rag.questions` servis isteği — `rag.chat`ten AYRI.
159
160 `scope_pairs`, backend'in çağıran için hesapladığı grant listesidir ve
161 özet/soru yetki kapısına aynen aktarılır. Alanın boş olması eski
162 backend'lerin gönderdiği gövdelerde legacy role kapsamına düşürür.
163 """
164 from .contract import (RagQuestionsRequestPayload,
165 RagSummarizeRequestPayload)
166 if req.capability == AI_RAG_QUESTIONS_CAPABILITY:
167 p = RagQuestionsRequestPayload.from_wire(req.payload)
168 ek = {"n": p.n, "difficulty": p.difficulty,
169 "seed_question": p.seed_question}
170 else:
171 p = RagSummarizeRequestPayload.from_wire(req.payload)
172 ek = {}
173 govde = {"scope": p.scope.to_wire(), "user": p.asker or None,
174 "role": ({"role": p.asker_role, "sinif": p.scope.sinif,
175 "ders_list": [p.scope.ders]} if p.asker_role else None),
176 "school": okul, "deadline_ms": req.deadline_ms, **ek}
177 # Preserve the old handler request shape for old backend frames that
178 # have no scope_pairs field; an explicit empty field still round-trips.
179 if "scope_pairs" in req.payload:
180 govde["scope_pairs"] = list(p.scope_pairs)
181 return govde
182
183 def _rag_summarize(self, req: BridgeRequest, okul: str) -> dict:
184 """`rag.summarize` → servis `summarize()` → backend'in `RagSummarizeReplyPayload`i."""
185 from .contract import RagSummarizeReplyPayload, RagSummaryCitation
186 cevap = self.service.summarize(self._govde(req, okul))
187 return RagSummarizeReplyPayload(
188 text=str(cevap.get("text") or ""),
189 abstained=bool(cevap.get("abstained", False)),
190 reason=str(cevap.get("reason") or ""),
191 citations=[RagSummaryCitation(n=int(c.get("n") or 0),
192 span_ids=list(c.get("span_ids") or []),
193 pages=list(c.get("pages") or []))
194 for c in (cevap.get("citations") or [])],
195 scope_pages=list(cevap.get("scope_pages") or []),
196 hierarchical=bool(cevap.get("hierarchical", False)),
197 ).to_wire()
198
199 def _rag_questions(self, req: BridgeRequest, okul: str) -> dict:
200 """`rag.questions` → servis `generate_questions()` → backend DTO'su.
201
202 Soru satırının anahtarları servisin kendi sözlüğüdür (`soru`/`cevap`/
203 `zorluk`) ve AYNEN taşınır; yeniden adlandırma backend'in işidir."""
204 from .contract import RagQuestion, RagQuestionsReplyPayload
205 cevap = self.service.generate_questions(self._govde(req, okul))
206 return RagQuestionsReplyPayload(
207 items=[RagQuestion(soru=str(i.get("soru") or ""),
208 cevap=str(i.get("cevap") or ""),
209 zorluk=str(i.get("zorluk") or ""))
210 for i in (cevap.get("items") or [])],
211 abstained=bool(cevap.get("abstained", False)),
212 reason=str(cevap.get("reason") or ""),
213 span_ids=list(cevap.get("span_ids") or []),
214 pages=list(cevap.get("pages") or []),
215 ).to_wire()
216
217 def _chat(self, req: BridgeRequest, okul: str) -> dict:
218 """`chat.reply` → servis `chat()` → backend'in `ChatReplyPayload`i.
219
220 `chat.reply` YALNIZ metin taşır (atıf `rag.chat`e aittir); bu yüzden
221 cevap TEK alana indirgenir — fazladan alan göndermek sözleşmeyi
222 genişletmek olurdu."""
223 cevap = self.service.chat(self._govde(req, okul))
224 return {"text": str(cevap.get("text") or "")}