forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB0877e45Ahmet Kaan Gümüş2 months ago172 commits

dispatch.py155 lines, 8.2 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, BridgeFrameError, BridgeRequest,
27 BridgeResponse)
28
29# `rag.index` is served end to end: the payload is parsed, every attachment is
30# read as bytes over its own blob stream, the note is chunked, embedded and
31# written into the school's note index (`service::notes_index`), and the answer
32# object goes back for the backend to store as the note's `rag_output`.
33class Dispatcher:
34 """`Request` çerçevesi → servis metodu → `Response` çerçevesi."""
35
36 def __init__(self, service, *, capabilities=None, indexer=None):
37 self.service = service
38 #: `rag.index`'in gövdesi (not → parça → gömme → not indeksi). Enjekte
39 #: edilebilir: taşıma testleri ağ/örnek istemeyen bir sahte verir;
40 #: üretimde `service::notes_index.index_course_note` koşar.
41 self.indexer = indexer
42 #: Blob okuyucusu — TAŞIMA takar (`transport.BridgeTransport.register`).
43 #: Yoksa ekler okunamaz ve notun kendi metni yine indekslenir.
44 self.blob_reader = None
45 self.capabilities = tuple(capabilities or (
46 AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY))
47
48 # -- tel biçimi düzeyi ------------------------------------------------
49 def handle(self, frame: dict) -> dict | None:
50 """Bir `Request` çerçevesini karşılar. Bozuk çerçevede None (akış
51 DÜŞER): ekolayacak bir okul/id yoktur, uydurmak protokolü bozar."""
52 try:
53 req = BridgeRequest.from_wire(frame)
54 except BridgeFrameError as e:
55 print(f"[kopru][HATA] {e}", flush=True)
56 return None
57 return self.dispatch(req).to_wire()
58
59 # -- yetenek düzeyi ---------------------------------------------------
60 def dispatch(self, req: BridgeRequest) -> BridgeResponse:
61 from ..guard.tenant import TenantError, normalize_school
62 try:
63 okul = normalize_school(req.school)
64 except TenantError as e:
65 return BridgeResponse.err(req, "invalid_school", str(e))
66 if okul is None:
67 # Buraya normalde düşülmez: `from_wire` okulsuz çerçeveyi reddeder.
68 return BridgeResponse.err(req, "malformed",
69 "`school` ZORUNLU (varsayılan/fallback yok)")
70
71 if req.capability == AI_RAG_INDEX_CAPABILITY:
72 return self._rag_index(req, okul)
73 if req.capability == AI_RAG_CHAT_CAPABILITY:
74 return BridgeResponse.ok(req, self._rag_chat(req, okul))
75 if req.capability == AI_CHAT_CAPABILITY:
76 return BridgeResponse.ok(req, self._chat(req, okul))
77 return BridgeResponse.err(
78 req, "unsupported_capability",
79 f"bu servis `{req.capability}` sunmuyor (yetenekler: "
80 f"{', '.join(self.capabilities)})")
81
82 # -- gövde eşlemeleri (tel biçimi → servis sözlüğü) --------------------
83 def _rag_index(self, req: BridgeRequest, okul: str) -> BridgeResponse:
84 """`rag.index` → not + ekler → not indeksi → backend'in sakladığı gövde.
85
86 Redler TİPLİ ve küçük tutulur: backend bir hatada eski `rag_output`
87 satırını korur, yani "sessiz tamam" en kötü sonuçtur. Tek bir ekin
88 okunamaması ise red DEĞİLDİR — notun kendi metni indekslenir ve cevap
89 hangi ekin okunamadığını söyler (bkz. `service/notes_index.py`)."""
90 from .contract import RagIndexPayload
91 try:
92 payload = RagIndexPayload.from_wire(req.payload)
93 except (KeyError, TypeError) as exc:
94 return BridgeResponse.err(req, "malformed",
95 f"rag.index gövdesi eksik/yanlış: {exc}")
96 indexer = self.indexer
97 if indexer is None:
98 from ..service.notes_index import index_course_note as indexer
99 try:
100 cevap = indexer(payload, school=okul, blob_reader=self.blob_reader)
101 except Exception as exc: # noqa: BLE001
102 import traceback
103 traceback.print_exc()
104 return BridgeResponse.err(req, "internal",
105 f"rag.index çalıştırılamadı: "
106 f"{type(exc).__name__}: {exc}")
107 if not isinstance(cevap, dict):
108 return BridgeResponse.err(req, "internal",
109 "rag.index bir nesne döndürmedi")
110 return BridgeResponse.ok(req, cevap)
111
112 def _govde(self, req: BridgeRequest, okul: str) -> dict:
113 """Servis isteğinin ortak alanları: sorgu + ROL + okul.
114
115 Rol backend'de türetilir (`asker_role`); burada ADI eşlenir
116 (`role.role`) — bkz. API-CONTRACT §0.2(a). Rol yoksa servis zaten
117 fail-closed reddeder (`role_required`)."""
118 from .contract import ChatRequestPayload, RagChatRequestPayload
119 if req.capability == AI_RAG_CHAT_CAPABILITY:
120 p = RagChatRequestPayload.from_wire(req.payload)
121 return {"query": p.message, "user": p.asker or None,
122 "role": {"role": p.asker_role} if p.asker_role else None,
123 "scope": [s.to_wire() for s in p.scope],
124 "history": [t.to_wire() for t in p.history],
125 "school": okul, "deadline_ms": req.deadline_ms}
126 p = ChatRequestPayload.from_wire(req.payload)
127 return {"query": p.message,
128 "role": {"role": p.asker_role} if p.asker_role else None,
129 "history": [t.to_wire() for t in p.history],
130 "school": okul, "deadline_ms": req.deadline_ms}
131
132 def _rag_chat(self, req: BridgeRequest, okul: str) -> dict:
133 """`rag.chat` → servis `chat()` → backend'in `RagChatReplyPayload`i."""
134 from .contract import RagCitation, RagChatReplyPayload
135 cevap = self.service.chat(self._govde(req, okul))
136 return RagChatReplyPayload(
137 text=str(cevap.get("text") or ""),
138 abstained=bool(cevap.get("abstained", False)),
139 reason=str(cevap.get("reason") or ""),
140 citations=[RagCitation(n=int(c.get("n") or 0),
141 doc_id=str(c.get("doc_id") or ""),
142 pages=list(c.get("pages") or []),
143 span_ids=list(c.get("span_ids") or []),
144 ders=c.get("ders"))
145 for c in (cevap.get("citations") or [])],
146 ).to_wire()
147
148 def _chat(self, req: BridgeRequest, okul: str) -> dict:
149 """`chat.reply` → servis `chat()` → backend'in `ChatReplyPayload`i.
150
151 `chat.reply` YALNIZ metin taşır (atıf `rag.chat`e aittir); bu yüzden
152 cevap TEK alana indirgenir — fazladan alan göndermek sözleşmeyi
153 genişletmek olurdu."""
154 cevap = self.service.chat(self._govde(req, okul))
155 return {"text": str(cevap.get("text") or "")}