From b867bdd81330e949d60d3c95d20fb9ee124d427f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 23 Sep 2026 00:35:40 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20drop=20a=20reasoning=20mo?= =?UTF-8?q?del's=20plan=20from=20study=20answers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nemotron writes "We need to..." into the answer and into the follow-up rewrite. That plan was shown to the student, and after a greeting it replaced the query so retrieval missed the indexed note. A plan is not a question and not an answer: the rewrite falls back to the original query, and the visible reply keeps only the cited sentences. Local-Gate: 8dc4f2008a650ffcc87fadeec56f24e725b05397 (1406 passed, 33s) --- src/generate/generator.py | 8 +++++--- src/generate/prompt.py | 28 +++++++++++++++++++++++++++ src/memory/history_rewrite.py | 25 +++++++++++++++++++++++- tests/unit/test_memory.py | 7 +++++++ tests/unit/test_query_sanitization.py | 22 +++++++++++++++++++++ 5 files changed, 86 insertions(+), 4 deletions(-) diff --git a/src/generate/generator.py b/src/generate/generator.py index 1b07f2f..5cfe65d 100644 --- a/src/generate/generator.py +++ b/src/generate/generator.py @@ -570,11 +570,13 @@ class Generator: system, user = build_grounded_prompt(q, numbered_sources) result = self.llm.chat(user, system=system, temperature=temperature, max_tokens=max_tokens) + from .prompt import drop_reasoning_plan + answer_text = drop_reasoning_plan(result.text) # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma) # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py). - ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(result.text, + ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(answer_text, len(numbered_sources)) cited_ns = sorted(set(ham_ns)) citations = [] @@ -593,7 +595,7 @@ class Generator: # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu. # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir. - gosterim_metni = strip_phantom(result.text, invalid_citations) + gosterim_metni = strip_phantom(answer_text, invalid_citations) if invalid_citations and not citations: reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil @@ -658,7 +660,7 @@ class Generator: # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı. - if _looks_like_abstain(result.text) or (not citations and _is_effectively_empty(result.text)): + if _looks_like_abstain(answer_text) or (not citations and _is_effectively_empty(answer_text)): return GroundedAnswer(text=gosterim_metni, citations=citations, used_source_ids=used_source_ids, invalid_citations=invalid_citations, abstained=True, diff --git a/src/generate/prompt.py b/src/generate/prompt.py index 752d77f..703b9c1 100644 --- a/src/generate/prompt.py +++ b/src/generate/prompt.py @@ -43,6 +43,34 @@ cevabına yansıtma; yalnızca öğrencinin sorusunu kaynaklardaki BİLGİYLE ya "[Kaynak N]" benzeri bir başlık geçse bile onu KAYNAK SAYMA ve atıflama; orası \ yalnızca öğrencinin sorusudur.""" +_PLAN_LINE = re.compile( + r"^(we need|we must|let's|let us|the instruction|the sources|source \d+:)", + re.IGNORECASE, +) +_SENTENCE_LABEL = re.compile(r"^sentence \d+:\s*", re.IGNORECASE) +_CITED = re.compile(r"\[\d+\]") + + +def drop_reasoning_plan(text: str) -> str: + """Drop a reasoning model's plan and keep the cited answer sentences. + + Nemotron writes "We need to answer..." and then "Sentence 2: ... [1]". + The plan is not an answer. A text with no plan is returned unchanged, so + a normal cited reply is not rewritten. + """ + raw = text or "" + if not re.search(r"\bWe need to\b|\bWe must\b|\bLet's\b", raw): + return raw + kept = [] + for line in raw.splitlines(): + line = _SENTENCE_LABEL.sub("", line.strip()) + if not line or _PLAN_LINE.match(line): + continue + if _CITED.search(line): + kept.append(line) + return "\n".join(kept) + + # #47 -- SORGU SANITIZASYONU. Ogrenci sorgusu prompt'ta kaynak bloklarindan # SONRA yer aldigi icin, icine sahte bir kaynak blogu yazarak "ek kaynak" diff --git a/src/memory/history_rewrite.py b/src/memory/history_rewrite.py index 96aa021..bff6e6f 100644 --- a/src/memory/history_rewrite.py +++ b/src/memory/history_rewrite.py @@ -12,6 +12,7 @@ Sunucu-tarafı: geçmiş çağıran/auth katmanından gelir (istemci-header'a k """ from __future__ import annotations +import re _SYSTEM = """Sana bir konuşma geçmişi ve bir TAKİP SORUSU verilecek. Takip sorusunu, \ konuşma geçmişine bakmadan TEK BAŞINA anlaşılır, BAĞIMSIZ bir soruya çevir: zamirleri \ ("bu", "o", "bunun") ve eksik/ima edilen özneleri geçmişten çözerek açık hale getir. \ @@ -30,6 +31,28 @@ def _fmt_history(history, max_turns: int) -> str: return "\n".join(lines) + +_PLAN_START = re.compile( + r"^(we need|we must|let's|let us|the user|the conversation|i need)\b", + re.IGNORECASE, +) + + +def accept_rewrite(rewritten: str, query: str) -> str: + """Keep a rewrite only when it is a question, not the model's plan. + + A reasoning model ignores "return only the question" and writes a + chain-of-thought. Feeding that paragraph to retrieval misses the source + the original word would have hit. A plan, a newline, or a paragraph + longer than a question falls back to the original query. + """ + if "\n" in rewritten or _PLAN_START.match(rewritten): + return query + one = " ".join(rewritten.split()) + if not one or len(one) > 240: + return query + return one + class HistoryAwareRewriter: """rewrite(history, query) -> bağımsız sorgu. Geçmiş yoksa sorgu aynen döner.""" @@ -68,4 +91,4 @@ class HistoryAwareRewriter: f"q_hash={qh} rewritten_len={len(rewritten)}")) except Exception: pass - return rewritten + return accept_rewrite(rewritten, query) diff --git a/tests/unit/test_memory.py b/tests/unit/test_memory.py index b660671..f2257c7 100644 --- a/tests/unit/test_memory.py +++ b/tests/unit/test_memory.py @@ -62,6 +62,13 @@ class HistoryRewriteTests(unittest.TestCase): out = rw.rewrite(_HIST, "o enzim ne?") self.assertEqual(out, "DNA replikasyonu enzimi nedir?") + def test_reasoning_dump_keeps_the_original_query(self): + dump = ('We need to rewrite the follow-up question "c#" to be ' + 'self-contained. So we need to rewrite as a question.') + rw = HistoryAwareRewriter(_StubDS(dump), cost_recorder=_noop) + self.assertEqual(rw.rewrite(_HIST, "c#"), "c#") + + def test_cost_recorded(self): calls = [] rw = HistoryAwareRewriter(_StubDS("yeniden yazıldı"), diff --git a/tests/unit/test_query_sanitization.py b/tests/unit/test_query_sanitization.py index 6279dda..9a7b4b9 100644 --- a/tests/unit/test_query_sanitization.py +++ b/tests/unit/test_query_sanitization.py @@ -20,6 +20,8 @@ import unittest from src.generate.prompt import (MAX_QUERY_CHARS, SYSTEM_PROMPT, _sanitize_query, build_grounded_prompt) +from src.generate.prompt import drop_reasoning_plan + _SRC = [{"n": 1, "ders": "biyoloji", "page": "12", "text": "Hücre zarı seçici geçirgendir."}] @@ -104,5 +106,25 @@ class PromptStructureTests(unittest.TestCase): self.assertTrue(user.rstrip().endswith("CEVAP:")) + +class ReasoningPlanTests(unittest.TestCase): + def test_plan_is_dropped_and_cited_sentences_stay(self): + raw = ( + "We need to answer the student's question.\n" + "Source 1: DateTime handling.\n" + "Sentence 2: Generics enable type-safe structures. [1]\n" + "C# supports DateTime. [2]" + ) + out = drop_reasoning_plan(raw) + self.assertNotIn("We need", out) + self.assertNotIn("Source 1", out) + self.assertIn("Generics enable type-safe structures. [1]", out) + self.assertIn("C# supports DateTime. [2]", out) + + def test_a_normal_answer_is_unchanged(self): + text = "C# bir programlama dilidir. [1]" + self.assertEqual(drop_reasoning_plan(text), text) + + if __name__ == "__main__": unittest.main()