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

history_rewrite.py94 lines, 4.5 KiBHistoryRawDownload
1"""Faz — history-aware query rewriting (çok-turlu RAG'in EN kritik hafıza parçası).
2
3Sorun: çok-turlu sohbette takip soruları zamir/eksilti içerir ("peki bunun nedeni
4ne?", "o enzim ne yapar?"). Ham takip sorusunu retrieval'a vermek YANLIŞ sonuç
5getirir (bağlam yok). Çözüm (RES-003 §3, Rewrite-Retrieve-Read): geçmiş + takip
6sorusu → DeepSeek ile BAĞIMSIZ (tek-başına-anlaşılır) sorguya çevir → retrieval +
7üretim bunu kullanır.
8
9Enjekte edilebilir (test'te stub). Geçmiş boşsa LLM ÇAĞRILMAZ (sorgu aynen döner).
10FAIL-SAFE: rewrite hatası → orijinal sorgu (çok-turlu bozulursa tek-turlu gibi çalışır).
11Sunucu-tarafı: geçmiş çağıran/auth katmanından gelir (istemci-header'a körü körüne güvenme).
12"""
13from __future__ import annotations
14
15import re
16_SYSTEM = """Sana bir konuşma geçmişi ve bir TAKİP SORUSU verilecek. Takip sorusunu, \
17konuşma geçmişine bakmadan TEK BAŞINA anlaşılır, BAĞIMSIZ bir soruya çevir: zamirleri \
18("bu", "o", "bunun") ve eksik/ima edilen özneleri geçmişten çözerek açık hale getir. \
19Sorunun ANLAMINI değiştirme, yeni bilgi ekleme. Soru zaten bağımsızsa aynen bırak. \
20YALNIZCA yeniden yazılmış soruyu döndür — açıklama, tırnak veya başka hiçbir şey yazma."""
21
22
23def _fmt_history(history, max_turns: int) -> str:
24 """Son `max_turns` turu 'Kullanıcı: ... / Asistan: ...' biçiminde diz."""
25 turns = history[-max_turns:] if max_turns else history
26 lines = []
27 for t in turns:
28 role = t.get("role", "")
29 who = "Kullanıcı" if role == "user" else ("Asistan" if role == "assistant" else role)
30 lines.append(f"{who}: {t.get('content', '')}")
31 return "\n".join(lines)
32
33
34
35_PLAN_START = re.compile(
36 r"^(we need|we must|let's|let us|the user|the conversation|i need)\b",
37 re.IGNORECASE,
38)
39
40
41def accept_rewrite(rewritten: str, query: str) -> str:
42 """Keep a rewrite only when it is a question, not the model's plan.
43
44 A reasoning model ignores "return only the question" and writes a
45 chain-of-thought. Feeding that paragraph to retrieval misses the source
46 the original word would have hit. A plan, a newline, or a paragraph
47 longer than a question falls back to the original query.
48 """
49 if "\n" in rewritten or _PLAN_START.match(rewritten):
50 return query
51 one = " ".join(rewritten.split())
52 if not one or len(one) > 240:
53 return query
54 return one
55
56class HistoryAwareRewriter:
57 """rewrite(history, query) -> bağımsız sorgu. Geçmiş yoksa sorgu aynen döner."""
58
59 def __init__(self, llm=None, *, module: str = "rewrite", cost_recorder=None,
60 max_turns: int = 6, max_tokens: int = 120):
61 from ..providers.llm import LLMClient
62 self.llm = llm if llm is not None else LLMClient()
63 self.module = module
64 self.max_turns = max_turns
65 self.max_tokens = max_tokens
66 from .. import costlog
67 self._record = cost_recorder if cost_recorder is not None else costlog.record
68
69 def rewrite(self, history, query: str) -> str:
70 if not history or not query or not query.strip():
71 return query # geçmiş yok → LLM çağrılmaz, sorgu aynen
72 try:
73 user = f"KONUŞMA GEÇMİŞİ:\n{_fmt_history(history, self.max_turns)}\n\nTAKİP SORUSU: {query}"
74 r = self.llm.chat(user, system=_SYSTEM, temperature=0.0,
75 max_tokens=self.max_tokens)
76 rewritten = (r.text or "").strip().strip('"').strip("'")
77 if not rewritten:
78 return query # boş çıktı → orijinali koru
79 except Exception:
80 return query # FAIL-SAFE: hata → orijinal sorgu (tek-turlu davran)
81 try:
82 # #49 (EXP-010/SEC-10) KVKK: burada ogrencinin YAZDIGI metnin ilk 30
83 # karakteri `runs.jsonl`a ve oradan `Maliyet.md` tablosuna DUZ METIN
84 # olarak geciyordu. Veri minimizasyonu geregi metin artik yazilmaz;
85 # teshis icin uzunluk + kisa hash yeter (ayni sorgu tekrar mi geldi
86 # sorusu hash ile hâlâ cevaplanabilir, icerik ifsa olmadan).
87 import hashlib
88 qh = hashlib.sha256((query or "").encode("utf-8")).hexdigest()[:8]
89 self._record(module=self.module, model=r.model, usage=r.usage, items=1,
90 note=(f"history-rewrite: q_len={len(query or '')} "
91 f"q_hash={qh} rewritten_len={len(rewritten)}"))
92 except Exception:
93 pass
94 return accept_rewrite(rewritten, query)