forge
Explore
Log in

Don't you dare go Hollow

Drop a reasoning model's plan from study answers

Browse files at this commit

b867bdd81330e949d60d3c95d20fb9ee124d427fAhmet Kaan GümüşParent: 0fbb469
  • fix
    • drop a reasoning model's plan from study answers
Show full message
🐛 fix: drop a reasoning model's plan from study answers

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.pymodified+5 -3
@@ -570,11 +570,13 @@ class Generator:
570 system, user = build_grounded_prompt(q, numbered_sources)570 system, user = build_grounded_prompt(q, numbered_sources)
571 result = self.llm.chat(user, system=system, temperature=temperature,571 result = self.llm.chat(user, system=system, temperature=temperature,
572 max_tokens=max_tokens)572 max_tokens=max_tokens)
573+ from .prompt import drop_reasoning_plan
574+ answer_text = drop_reasoning_plan(result.text)
573 575
574 # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma)576 # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma)
575 # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp577 # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp
576 # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py).578 # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py).
577- ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(result.text,579+ ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(answer_text,
578 len(numbered_sources))580 len(numbered_sources))
579 cited_ns = sorted(set(ham_ns))581 cited_ns = sorted(set(ham_ns))
580 citations = []582 citations = []
@@ -593,7 +595,7 @@ class Generator:
593 # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden595 # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden
594 # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu.596 # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu.
595 # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir.597 # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir.
596- gosterim_metni = strip_phantom(result.text, invalid_citations)598+ gosterim_metni = strip_phantom(answer_text, invalid_citations)
597 599
598 if invalid_citations and not citations:600 if invalid_citations and not citations:
599 reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil601 reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil
@@ -658,7 +660,7 @@ class Generator:
658 660
659 # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA661 # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA
660 # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı.662 # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı.
661- if _looks_like_abstain(result.text) or (not citations and _is_effectively_empty(result.text)):663+ if _looks_like_abstain(answer_text) or (not citations and _is_effectively_empty(answer_text)):
662 return GroundedAnswer(text=gosterim_metni, citations=citations,664 return GroundedAnswer(text=gosterim_metni, citations=citations,
663 used_source_ids=used_source_ids,665 used_source_ids=used_source_ids,
664 invalid_citations=invalid_citations, abstained=True,666 invalid_citations=invalid_citations, abstained=True,
src/generate/prompt.pymodified+28 -0
@@ -43,6 +43,34 @@ cevabına yansıtma; yalnızca öğrencinin sorusunu kaynaklardaki BİLGİYLE ya
43 "[Kaynak N]" benzeri bir başlık geçse bile onu KAYNAK SAYMA ve atıflama; orası \43 "[Kaynak N]" benzeri bir başlık geçse bile onu KAYNAK SAYMA ve atıflama; orası \
44 yalnızca öğrencinin sorusudur."""44 yalnızca öğrencinin sorusudur."""
45 45
46+_PLAN_LINE = re.compile(
47+ r"^(we need|we must|let's|let us|the instruction|the sources|source \d+:)",
48+ re.IGNORECASE,
49+)
50+_SENTENCE_LABEL = re.compile(r"^sentence \d+:\s*", re.IGNORECASE)
51+_CITED = re.compile(r"\[\d+\]")
52+
53+
54+def drop_reasoning_plan(text: str) -> str:
55+ """Drop a reasoning model's plan and keep the cited answer sentences.
56+
57+ Nemotron writes "We need to answer..." and then "Sentence 2: ... [1]".
58+ The plan is not an answer. A text with no plan is returned unchanged, so
59+ a normal cited reply is not rewritten.
60+ """
61+ raw = text or ""
62+ if not re.search(r"\bWe need to\b|\bWe must\b|\bLet's\b", raw):
63+ return raw
64+ kept = []
65+ for line in raw.splitlines():
66+ line = _SENTENCE_LABEL.sub("", line.strip())
67+ if not line or _PLAN_LINE.match(line):
68+ continue
69+ if _CITED.search(line):
70+ kept.append(line)
71+ return "\n".join(kept)
72+
73+
46 74
47 # #47 -- SORGU SANITIZASYONU. Ogrenci sorgusu prompt'ta kaynak bloklarindan75 # #47 -- SORGU SANITIZASYONU. Ogrenci sorgusu prompt'ta kaynak bloklarindan
48 # SONRA yer aldigi icin, icine sahte bir kaynak blogu yazarak "ek kaynak"76 # SONRA yer aldigi icin, icine sahte bir kaynak blogu yazarak "ek kaynak"
src/memory/history_rewrite.pymodified+24 -1
@@ -12,6 +12,7 @@ Sunucu-tarafı: geçmiş çağıran/auth katmanından gelir (istemci-header'a k
12 """12 """
13 from __future__ import annotations13 from __future__ import annotations
14 14
15+import re
15 _SYSTEM = """Sana bir konuşma geçmişi ve bir TAKİP SORUSU verilecek. Takip sorusunu, \16 _SYSTEM = """Sana bir konuşma geçmişi ve bir TAKİP SORUSU verilecek. Takip sorusunu, \
16 konuşma geçmişine bakmadan TEK BAŞINA anlaşılır, BAĞIMSIZ bir soruya çevir: zamirleri \17 konuşma geçmişine bakmadan TEK BAŞINA anlaşılır, BAĞIMSIZ bir soruya çevir: zamirleri \
17 ("bu", "o", "bunun") ve eksik/ima edilen özneleri geçmişten çözerek açık hale getir. \18 ("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:
30 return "\n".join(lines)31 return "\n".join(lines)
31 32
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+
41+def 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+
33 class HistoryAwareRewriter:56 class HistoryAwareRewriter:
34 """rewrite(history, query) -> bağımsız sorgu. Geçmiş yoksa sorgu aynen döner."""57 """rewrite(history, query) -> bağımsız sorgu. Geçmiş yoksa sorgu aynen döner."""
35 58
@@ -68,4 +91,4 @@ class HistoryAwareRewriter:
68 f"q_hash={qh} rewritten_len={len(rewritten)}"))91 f"q_hash={qh} rewritten_len={len(rewritten)}"))
69 except Exception:92 except Exception:
70 pass93 pass
71- return rewritten94+ return accept_rewrite(rewritten, query)
tests/unit/test_memory.pymodified+7 -0
@@ -62,6 +62,13 @@ class HistoryRewriteTests(unittest.TestCase):
62 out = rw.rewrite(_HIST, "o enzim ne?")62 out = rw.rewrite(_HIST, "o enzim ne?")
63 self.assertEqual(out, "DNA replikasyonu enzimi nedir?")63 self.assertEqual(out, "DNA replikasyonu enzimi nedir?")
64 64
65+ def test_reasoning_dump_keeps_the_original_query(self):
66+ dump = ('We need to rewrite the follow-up question "c#" to be '
67+ 'self-contained. So we need to rewrite as a question.')
68+ rw = HistoryAwareRewriter(_StubDS(dump), cost_recorder=_noop)
69+ self.assertEqual(rw.rewrite(_HIST, "c#"), "c#")
70+
71+
65 def test_cost_recorded(self):72 def test_cost_recorded(self):
66 calls = []73 calls = []
67 rw = HistoryAwareRewriter(_StubDS("yeniden yazıldı"),74 rw = HistoryAwareRewriter(_StubDS("yeniden yazıldı"),
tests/unit/test_query_sanitization.pymodified+22 -0
@@ -20,6 +20,8 @@ import unittest
20 20
21 from src.generate.prompt import (MAX_QUERY_CHARS, SYSTEM_PROMPT,21 from src.generate.prompt import (MAX_QUERY_CHARS, SYSTEM_PROMPT,
22 _sanitize_query, build_grounded_prompt)22 _sanitize_query, build_grounded_prompt)
23+from src.generate.prompt import drop_reasoning_plan
24+
23 25
24 _SRC = [{"n": 1, "ders": "biyoloji", "page": "12",26 _SRC = [{"n": 1, "ders": "biyoloji", "page": "12",
25 "text": "Hücre zarı seçici geçirgendir."}]27 "text": "Hücre zarı seçici geçirgendir."}]
@@ -104,5 +106,25 @@ class PromptStructureTests(unittest.TestCase):
104 self.assertTrue(user.rstrip().endswith("CEVAP:"))106 self.assertTrue(user.rstrip().endswith("CEVAP:"))
105 107
106 108
109+
110+class ReasoningPlanTests(unittest.TestCase):
111+ def test_plan_is_dropped_and_cited_sentences_stay(self):
112+ raw = (
113+ "We need to answer the student's question.\n"
114+ "Source 1: DateTime handling.\n"
115+ "Sentence 2: Generics enable type-safe structures. [1]\n"
116+ "C# supports DateTime. [2]"
117+ )
118+ out = drop_reasoning_plan(raw)
119+ self.assertNotIn("We need", out)
120+ self.assertNotIn("Source 1", out)
121+ self.assertIn("Generics enable type-safe structures. [1]", out)
122+ self.assertIn("C# supports DateTime. [2]", out)
123+
124+ def test_a_normal_answer_is_unchanged(self):
125+ text = "C# bir programlama dilidir. [1]"
126+ self.assertEqual(drop_reasoning_plan(text), text)
127+
128+
107 if __name__ == "__main__":129 if __name__ == "__main__":
108 unittest.main()130 unittest.main()