Re-ask the LLM once when post-hoc model_abstained fires
Browse files at this commit970bd8287799dae6072db60934c0a8ba436e5f28Parent: 5af65fc- fix
- re-ask the LLM once when post-hoc model_abstained fires
2 changed files +244 -136
- src/generate/generator.py +154 -134
- tests/unit/test_generate.py +90 -2
src/generate/generator.pymodified+154 -134
| @@ -568,141 +568,161 @@ class Generator: | |||
| 568 | "doc_id": getattr(ctx, "doc_id", "")} | 568 | "doc_id": getattr(ctx, "doc_id", "")} |
| 569 | 569 | ||
| 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 | + # One bounded re-ask when the post-hoc detector says model_abstained. |
| 572 | - max_tokens=max_tokens) | 572 | + # Prompt and params stay the same; the sampler is what varies. A second |
| 573 | - from .prompt import drop_reasoning_plan | 573 | + # abstain is returned exactly as before. insufficient_data never reaches |
| 574 | - answer_text = drop_reasoning_plan(result.text) | 574 | + # this loop. ungrounded_no_citations is not retried. |
| 575 | - | 575 | + for attempt in range(2): |
| 576 | - # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma) | 576 | + result = self.llm.chat(user, system=system, temperature=temperature, |
| 577 | - # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp | 577 | + max_tokens=max_tokens) |
| 578 | - # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py). | 578 | + from .prompt import drop_reasoning_plan |
| 579 | - ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(answer_text, | 579 | + answer_text = drop_reasoning_plan(result.text) |
| 580 | - len(numbered_sources)) | 580 | + |
| 581 | - cited_ns = sorted(set(ham_ns)) | 581 | + # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma) |
| 582 | - citations = [] | 582 | + # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp |
| 583 | - used_source_ids = [] | 583 | + # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py). |
| 584 | - invalid_citations = sorted(set(hayalet_ns)) | 584 | + ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(answer_text, |
| 585 | - for n in cited_ns: | 585 | + len(numbered_sources)) |
| 586 | - src = source_lookup.get(n) | 586 | + cited_ns = sorted(set(ham_ns)) |
| 587 | - if src is None: # aralık denetimi sonrası olmamalı | 587 | + citations = [] |
| 588 | - invalid_citations.append(n) | 588 | + used_source_ids = [] |
| 589 | - continue | 589 | + invalid_citations = sorted(set(hayalet_ns)) |
| 590 | - citations.append({"n": n, "chunk_id": src["chunk_id"], | 590 | + for n in cited_ns: |
| 591 | - "span_ids": src["span_ids"], "pages": src["pages"], | 591 | + src = source_lookup.get(n) |
| 592 | - "ders": self.ders, "doc_id": src["doc_id"]}) | 592 | + if src is None: # aralık denetimi sonrası olmamalı |
| 593 | - used_source_ids.append(src["chunk_id"]) | 593 | + invalid_citations.append(n) |
| 594 | - invalid_citations = sorted(set(invalid_citations)) | 594 | + continue |
| 595 | - # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden | 595 | + citations.append({"n": n, "chunk_id": src["chunk_id"], |
| 596 | - # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu. | 596 | + "span_ids": src["span_ids"], "pages": src["pages"], |
| 597 | - # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir. | 597 | + "ders": self.ders, "doc_id": src["doc_id"]}) |
| 598 | - gosterim_metni = strip_phantom(answer_text, invalid_citations) | 598 | + used_source_ids.append(src["chunk_id"]) |
| 599 | - | 599 | + invalid_citations = sorted(set(invalid_citations)) |
| 600 | - if invalid_citations and not citations: | 600 | + # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden |
| 601 | - reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil | 601 | + # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu. |
| 602 | - elif invalid_citations: | 602 | + # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir. |
| 603 | - reason = "phantom_citation" # bazıları geçerli, bazıları hayalet | 603 | + gosterim_metni = strip_phantom(answer_text, invalid_citations) |
| 604 | - else: | 604 | + |
| 605 | - reason = "" | 605 | + if invalid_citations and not citations: |
| 606 | - | 606 | + reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil |
| 607 | - usd = pricing_cost_usd(result.model, result.usage) | 607 | + elif invalid_citations: |
| 608 | - # LLM GERÇEKTEN çağrıldı → maliyet gerçek; aşağıdaki post-hoc abstain kontrolü | 608 | + reason = "phantom_citation" # bazıları geçerli, bazıları hayalet |
| 609 | - # yalnız `abstained` bayrağını/`reason`'ı düzeltir, cost_usd'yi SIFIRLAMAZ. | 609 | + else: |
| 610 | - self._record(module=self.module, model=result.model, usage=result.usage, items=1, | 610 | + reason = "" |
| 611 | - config={"top_n": top_n, "candidate_n": candidate_n}, | 611 | + |
| 612 | - note=f"grounded-answer: {len(citations)}/{len(contexts)} kaynak atıflandı") | 612 | + usd = pricing_cost_usd(result.model, result.usage) |
| 613 | - | 613 | + # LLM GERÇEKTEN çağrıldı → maliyet gerçek; aşağıdaki post-hoc abstain kontrolü |
| 614 | - # GUARDRAIL (Faz 1.7b) — üretimden SONRA: girdi guard'ı geçse bile | 614 | + # yalnız `abstained` bayrağını/`reason`'ı düzeltir, cost_usd'yi SIFIRLAMAZ. |
| 615 | - # LLM'in ÜRETTİĞİ metin zararlı olabilir (ince ikinci savunma katmanı, | 615 | + self._record(module=self.module, model=result.model, usage=result.usage, items=1, |
| 616 | - # bkz. src/guard/output_guard.py). LLM GERÇEKTEN çağrıldığı için | 616 | + config={"top_n": top_n, "candidate_n": candidate_n}, |
| 617 | - # usage/cost_usd GERÇEK kalır (sıfırlanmaz) — yalnız kullanıcıya | 617 | + note=f"grounded-answer: {len(citations)}/{len(contexts)} kaynak atıflandı") |
| 618 | - # gösterilecek metin + atıflar red mesajıyla değiştirilir. | 618 | + |
| 619 | - output_verdict = check_output(result.text) | 619 | + # GUARDRAIL (Faz 1.7b) — üretimden SONRA: girdi guard'ı geçse bile |
| 620 | - if output_verdict.action == "refuse": | 620 | + # LLM'in ÜRETTİĞİ metin zararlı olabilir (ince ikinci savunma katmanı, |
| 621 | - return GroundedAnswer(text=output_verdict.message, citations=[], | 621 | + # bkz. src/guard/output_guard.py). LLM GERÇEKTEN çağrıldığı için |
| 622 | - used_source_ids=[], invalid_citations=[], | 622 | + # usage/cost_usd GERÇEK kalır (sıfırlanmaz) — yalnız kullanıcıya |
| 623 | - abstained=True, reason="guard_output", | 623 | + # gösterilecek metin + atıflar red mesajıyla değiştirilir. |
| 624 | - usage=result.usage, cost_usd=usd, | 624 | + output_verdict = check_output(result.text) |
| 625 | - latency_s=result.latency_s) | 625 | + if output_verdict.action == "refuse": |
| 626 | - | 626 | + return GroundedAnswer(text=output_verdict.message, citations=[], |
| 627 | - # #56: ATIF BÜTÜNLÜĞÜ. Ölçüm HER ZAMAN yapılır; politika env'den gelir. | 627 | + used_source_ids=[], invalid_citations=[], |
| 628 | - kapsama = citation_coverage(gosterim_metni) | 628 | + abstained=True, reason="guard_output", |
| 629 | - n_sent = kapsama["n_sentences"] | 629 | + usage=result.usage, cost_usd=usd, |
| 630 | - n_cited = kapsama["n_cited_sentences"] | 630 | + latency_s=result.latency_s) |
| 631 | - dropped: list = [] | 631 | + |
| 632 | - if citations and SENTENCE_POLICY in ("trim", "abstain") and n_sent > n_cited: | 632 | + # #56: ATIF BÜTÜNLÜĞÜ. Ölçüm HER ZAMAN yapılır; politika env'den gelir. |
| 633 | - if SENTENCE_POLICY == "abstain": | ||
| 634 | - _tr("decision", stage="generate", abstained=True, | ||
| 635 | - reason="ungrounded_sentences", n_sentences=n_sent, | ||
| 636 | - n_cited_sentences=n_cited) | ||
| 637 | - return GroundedAnswer( | ||
| 638 | - text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], | ||
| 639 | - invalid_citations=invalid_citations, abstained=True, | ||
| 640 | - reason="ungrounded_sentences", usage=result.usage, cost_usd=usd, | ||
| 641 | - latency_s=result.latency_s, n_sentences=n_sent, | ||
| 642 | - n_cited_sentences=n_cited, | ||
| 643 | - dropped_sentences=kapsama["uncited_sentences"]) | ||
| 644 | - kirpilmis, dropped = drop_uncited(gosterim_metni) | ||
| 645 | - if not kirpilmis.strip(): | ||
| 646 | - # Kırpma her şeyi götürdüyse sunulacak bir cevap kalmadı. | ||
| 647 | - return GroundedAnswer( | ||
| 648 | - text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], | ||
| 649 | - invalid_citations=invalid_citations, abstained=True, | ||
| 650 | - reason="ungrounded_sentences", usage=result.usage, cost_usd=usd, | ||
| 651 | - latency_s=result.latency_s, n_sentences=n_sent, | ||
| 652 | - n_cited_sentences=n_cited, dropped_sentences=dropped) | ||
| 653 | - gosterim_metni = kirpilmis | ||
| 654 | - # kırpma sonrası atıf listesini metinde GERÇEKTEN kalanlarla daralt | ||
| 655 | - kalan_ns = set(parse_citation_ns(gosterim_metni, len(numbered_sources))) | ||
| 656 | - citations = [c for c in citations if c["n"] in kalan_ns] | ||
| 657 | - used_source_ids = [c["chunk_id"] for c in citations] | ||
| 658 | kapsama = citation_coverage(gosterim_metni) | 633 | kapsama = citation_coverage(gosterim_metni) |
| 659 | - n_sent, n_cited = kapsama["n_sentences"], kapsama["n_cited_sentences"] | 634 | + n_sent = kapsama["n_sentences"] |
| 660 | - | 635 | + n_cited = kapsama["n_cited_sentences"] |
| 661 | - # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA | 636 | + dropped: list = [] |
| 662 | - # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı. | 637 | + if citations and SENTENCE_POLICY in ("trim", "abstain") and n_sent > n_cited: |
| 663 | - if _looks_like_abstain(answer_text) or (not citations and _is_effectively_empty(answer_text)): | 638 | + if SENTENCE_POLICY == "abstain": |
| 664 | - return GroundedAnswer(text=gosterim_metni, citations=citations, | 639 | + _tr("decision", stage="generate", abstained=True, |
| 665 | - used_source_ids=used_source_ids, | 640 | + reason="ungrounded_sentences", n_sentences=n_sent, |
| 666 | - invalid_citations=invalid_citations, abstained=True, | 641 | + n_cited_sentences=n_cited) |
| 667 | - reason="model_abstained", usage=result.usage, | 642 | + return GroundedAnswer( |
| 668 | - cost_usd=usd, latency_s=result.latency_s, | 643 | + text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], |
| 669 | - n_sentences=n_sent, n_cited_sentences=n_cited, | 644 | + invalid_citations=invalid_citations, abstained=True, |
| 670 | - dropped_sentences=dropped) | 645 | + reason="ungrounded_sentences", usage=result.usage, cost_usd=usd, |
| 671 | - | 646 | + latency_s=result.latency_s, n_sentences=n_sent, |
| 672 | - # TEMELLENDİRME BÜTÜNLÜĞÜ (audit EXP-007 #C1): metin DOLU ama GEÇERLİ ATIF YOK | 647 | + n_cited_sentences=n_cited, |
| 673 | - # (model [N] hiç emitmedi YA DA hepsi hayalet) → kaynağa bağlanamamış = | 648 | + dropped_sentences=kapsama["uncited_sentences"]) |
| 674 | - # temellendirilmemiş. Grounded RAG'de böyle bir cevabı kullanıcıya SUNMA; | 649 | + kirpilmis, dropped = drop_uncited(gosterim_metni) |
| 675 | - # çekimser kal (kaynak-yok cümlesiyle). LLM çağrıldı → cost gerçek; CACHE'LENMEZ. | 650 | + if not kirpilmis.strip(): |
| 676 | - # Eskiden atıfsız-ama-dolu cevap "güvenli" sanılıp sunuluyordu. | 651 | + # Kırpma her şeyi götürdüyse sunulacak bir cevap kalmadı. |
| 677 | - if not citations: | 652 | + return GroundedAnswer( |
| 678 | - r = "all_citations_phantom" if invalid_citations else "ungrounded_no_citations" | 653 | + text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], |
| 679 | - return GroundedAnswer(text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], | 654 | + invalid_citations=invalid_citations, abstained=True, |
| 680 | - invalid_citations=invalid_citations, abstained=True, | 655 | + reason="ungrounded_sentences", usage=result.usage, cost_usd=usd, |
| 681 | - reason=r, usage=result.usage, cost_usd=usd, | 656 | + latency_s=result.latency_s, n_sentences=n_sent, |
| 682 | - latency_s=result.latency_s) | 657 | + n_cited_sentences=n_cited, dropped_sentences=dropped) |
| 683 | - | 658 | + gosterim_metni = kirpilmis |
| 684 | - final_answer = GroundedAnswer(text=gosterim_metni, citations=citations, | 659 | + # kırpma sonrası atıf listesini metinde GERÇEKTEN kalanlarla daralt |
| 660 | + kalan_ns = set(parse_citation_ns(gosterim_metni, len(numbered_sources))) | ||
| 661 | + citations = [c for c in citations if c["n"] in kalan_ns] | ||
| 662 | + used_source_ids = [c["chunk_id"] for c in citations] | ||
| 663 | + kapsama = citation_coverage(gosterim_metni) | ||
| 664 | + n_sent, n_cited = kapsama["n_sentences"], kapsama["n_cited_sentences"] | ||
| 665 | + | ||
| 666 | + # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA | ||
| 667 | + # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı. | ||
| 668 | + looks_abstain = _looks_like_abstain(answer_text) | ||
| 669 | + empty_no_cite = not citations and _is_effectively_empty(answer_text) | ||
| 670 | + if looks_abstain or empty_no_cite: | ||
| 671 | + fired = "looks_like_abstain" if looks_abstain else "empty_no_citations" | ||
| 672 | + if attempt == 0: | ||
| 673 | + print( | ||
| 674 | + f"[generate] model_abstained ({fired}); re-asking the LLM once", | ||
| 675 | + flush=True, | ||
| 676 | + ) | ||
| 677 | + _tr("decision", stage="abstain_reask", reason="model_abstained", | ||
| 678 | + fired=fired) | ||
| 679 | + continue | ||
| 680 | + print( | ||
| 681 | + f"[generate] re-ask also model_abstained ({fired}); returning abstain", | ||
| 682 | + flush=True, | ||
| 683 | + ) | ||
| 684 | + return GroundedAnswer(text=gosterim_metni, citations=citations, | ||
| 685 | used_source_ids=used_source_ids, | 685 | used_source_ids=used_source_ids, |
| 686 | - invalid_citations=invalid_citations, abstained=False, | 686 | + invalid_citations=invalid_citations, abstained=True, |
| 687 | - reason=reason, usage=result.usage, cost_usd=usd, | 687 | + reason="model_abstained", usage=result.usage, |
| 688 | - latency_s=result.latency_s, | 688 | + cost_usd=usd, latency_s=result.latency_s, |
| 689 | n_sentences=n_sent, n_cited_sentences=n_cited, | 689 | n_sentences=n_sent, n_cited_sentences=n_cited, |
| 690 | dropped_sentences=dropped) | 690 | dropped_sentences=dropped) |
| 691 | - _tr("decision", stage="generate", abstained=False, reason=reason or "answer", | 691 | + |
| 692 | - n_citations=len(citations), n_phantom=len(invalid_citations), | 692 | + # TEMELLENDİRME BÜTÜNLÜĞÜ (audit EXP-007 #C1): metin DOLU ama GEÇERLİ ATIF YOK |
| 693 | - # #56: kapi A-03 bu ikisinden hesaplanir | 693 | + # (model [N] hiç emitmedi YA DA hepsi hayalet) → kaynağa bağlanamamış = |
| 694 | - n_sentences=n_sent, n_cited_sentences=n_cited, | 694 | + # temellendirilmemiş. Grounded RAG'de böyle bir cevabı kullanıcıya SUNMA; |
| 695 | - # #57 telemetrisi: `[0,1]` gibi belirsiz gruplar atıf sayılmadı. | 695 | + # çekimser kal (kaynak-yok cümlesiyle). LLM çağrıldı → cost gerçek; CACHE'LENMEZ. |
| 696 | - # Sıklığı bilinmeden kuralın doğru eşikte olduğu iddia EDİLEMEZ. | 696 | + # Eskiden atıfsız-ama-dolu cevap "güvenli" sanılıp sunuluyordu. |
| 697 | - n_belirsiz_grup=len(belirsiz_gruplar), | 697 | + if not citations: |
| 698 | - cost_usd=round(usd, 6)) | 698 | + r = "all_citations_phantom" if invalid_citations else "ungrounded_no_citations" |
| 699 | - | 699 | + return GroundedAnswer(text=ABSTAIN_SENTENCE, citations=[], used_source_ids=[], |
| 700 | - # Yalnız GERÇEK (abstained olmayan) cevaplar cache'e yazılır. FAIL-CLOSED | 700 | + invalid_citations=invalid_citations, abstained=True, |
| 701 | - # abstain zaten LLM'i hiç çağırmadı (cache'lemenin maliyet kazancı yok); | 701 | + reason=r, usage=result.usage, cost_usd=usd, |
| 702 | - # model_abstained/guard_output ise LLM ÇAĞRILDI ama sonuç kullanıcıya | 702 | + latency_s=result.latency_s) |
| 703 | - # ret/çekimser olarak gösterildi — bunları cache'lemek "bu soru bir daha | 703 | + |
| 704 | - # asla cevaplanamaz" diye DONDURUR (retrieval/index/eşik ileride değişebilir) | 704 | + final_answer = GroundedAnswer(text=gosterim_metni, citations=citations, |
| 705 | - # -> BİLİNÇLİ OLARAK cache'lenmez (yalnız buradaki başarılı dönüş yazar). | 705 | + used_source_ids=used_source_ids, |
| 706 | - if self.response_cache is not None and cache_kwargs is not None: | 706 | + invalid_citations=invalid_citations, abstained=False, |
| 707 | - self.response_cache.set(final_answer, **cache_kwargs) | 707 | + reason=reason, usage=result.usage, cost_usd=usd, |
| 708 | - return final_answer | 708 | + latency_s=result.latency_s, |
| 709 | + n_sentences=n_sent, n_cited_sentences=n_cited, | ||
| 710 | + dropped_sentences=dropped) | ||
| 711 | + _tr("decision", stage="generate", abstained=False, reason=reason or "answer", | ||
| 712 | + n_citations=len(citations), n_phantom=len(invalid_citations), | ||
| 713 | + # #56: kapi A-03 bu ikisinden hesaplanir | ||
| 714 | + n_sentences=n_sent, n_cited_sentences=n_cited, | ||
| 715 | + # #57 telemetrisi: `[0,1]` gibi belirsiz gruplar atıf sayılmadı. | ||
| 716 | + # Sıklığı bilinmeden kuralın doğru eşikte olduğu iddia EDİLEMEZ. | ||
| 717 | + n_belirsiz_grup=len(belirsiz_gruplar), | ||
| 718 | + cost_usd=round(usd, 6)) | ||
| 719 | + | ||
| 720 | + # Yalnız GERÇEK (abstained olmayan) cevaplar cache'e yazılır. FAIL-CLOSED | ||
| 721 | + # abstain zaten LLM'i hiç çağırmadı (cache'lemenin maliyet kazancı yok); | ||
| 722 | + # model_abstained/guard_output ise LLM ÇAĞRILDI ama sonuç kullanıcıya | ||
| 723 | + # ret/çekimser olarak gösterildi — bunları cache'lemek "bu soru bir daha | ||
| 724 | + # asla cevaplanamaz" diye DONDURUR (retrieval/index/eşik ileride değişebilir) | ||
| 725 | + # -> BİLİNÇLİ OLARAK cache'lenmez (yalnız buradaki başarılı dönüş yazar). | ||
| 726 | + if self.response_cache is not None and cache_kwargs is not None: | ||
| 727 | + self.response_cache.set(final_answer, **cache_kwargs) | ||
| 728 | + return final_answer | ||
tests/unit/test_generate.pymodified+90 -2
| @@ -9,6 +9,8 @@ işaretleniyor. | |||
| 9 | from __future__ import annotations | 9 | from __future__ import annotations |
| 10 | 10 | ||
| 11 | import unittest | 11 | import unittest |
| 12 | +import io | ||
| 13 | +from contextlib import redirect_stdout | ||
| 12 | from dataclasses import dataclass, field | 14 | from dataclasses import dataclass, field |
| 13 | 15 | ||
| 14 | from src.cache import EmbeddingCache, ResponseCache, SQLiteCache | 16 | from src.cache import EmbeddingCache, ResponseCache, SQLiteCache |
| @@ -67,6 +69,28 @@ class _StubLLMClient: | |||
| 67 | output=5, reasoning=0), | 69 | output=5, reasoning=0), |
| 68 | model=self.model, latency_s=0.001) | 70 | model=self.model, latency_s=0.001) |
| 69 | 71 | ||
| 72 | +class _SequenceLLM: | ||
| 73 | + """chat() returns texts in order and records the grounded call.""" | ||
| 74 | + def __init__(self, texts, model="deepseek-chat"): | ||
| 75 | + self.texts = list(texts) | ||
| 76 | + self.model = model | ||
| 77 | + self.calls = 0 | ||
| 78 | + self.prompts = [] | ||
| 79 | + self.systems = [] | ||
| 80 | + self.temperatures = [] | ||
| 81 | + self.max_tokens = [] | ||
| 82 | + | ||
| 83 | + def chat(self, prompt, system=None, *, temperature=0.2, max_tokens=None, extra=None): | ||
| 84 | + self.calls += 1 | ||
| 85 | + self.prompts.append(prompt) | ||
| 86 | + self.systems.append(system) | ||
| 87 | + self.temperatures.append(temperature) | ||
| 88 | + self.max_tokens.append(max_tokens) | ||
| 89 | + text = self.texts[self.calls - 1] | ||
| 90 | + return ChatResult(text=text, usage=Usage(input_cache_hit=0, input_cache_miss=10, | ||
| 91 | + output=5, reasoning=0), | ||
| 92 | + model=self.model, latency_s=0.001) | ||
| 93 | + | ||
| 70 | 94 | ||
| 71 | def _noop_recorder(**kwargs): | 95 | def _noop_recorder(**kwargs): |
| 72 | """costlog.record yerine geçer — gerçek Obsidian deftere YAZMAZ (yalnız birim test).""" | 96 | """costlog.record yerine geçer — gerçek Obsidian deftere YAZMAZ (yalnız birim test).""" |
| @@ -301,7 +325,7 @@ class PostHocAbstainTests(unittest.TestCase): | |||
| 301 | 325 | ||
| 302 | self.assertTrue(result.abstained) | 326 | self.assertTrue(result.abstained) |
| 303 | self.assertEqual(result.reason, "model_abstained") | 327 | self.assertEqual(result.reason, "model_abstained") |
| 304 | - self.assertEqual(llm.calls, 1) # LLM GERÇEKTEN çağrıldı | 328 | + self.assertEqual(llm.calls, 2) # one re-ask, both abstain |
| 305 | self.assertIsNotNone(result.usage) | 329 | self.assertIsNotNone(result.usage) |
| 306 | self.assertGreater(result.cost_usd, 0.0) # maliyet SIFIRLANMADI | 330 | self.assertGreater(result.cost_usd, 0.0) # maliyet SIFIRLANMADI |
| 307 | 331 | ||
| @@ -332,6 +356,70 @@ class PostHocAbstainTests(unittest.TestCase): | |||
| 332 | self.assertEqual(result.reason, "") | 356 | self.assertEqual(result.reason, "") |
| 333 | 357 | ||
| 334 | 358 | ||
| 359 | +class ModelAbstainReaskTests(unittest.TestCase): | ||
| 360 | + """One bounded re-ask when the post-hoc detector says model_abstained.""" | ||
| 361 | + | ||
| 362 | + _PLAN = ( | ||
| 363 | + "We need to answer from the sources.\n" | ||
| 364 | + "The sources do not contain this fact." | ||
| 365 | + ) | ||
| 366 | + _CITED = "DNA cift sarmal yapidadir [1]." | ||
| 367 | + | ||
| 368 | + def test_plan_only_then_cited_answer_is_not_abstained(self): | ||
| 369 | + llm = _SequenceLLM([self._PLAN, self._CITED]) | ||
| 370 | + gen = _make_generator(llm, scores={"c1": 0.9, "c2": 0.85}) | ||
| 371 | + gen.response_cache = ResponseCache(SQLiteCache(":memory:")) | ||
| 372 | + gen.corpus_version = "v1" | ||
| 373 | + buf = io.StringIO() | ||
| 374 | + with redirect_stdout(buf): | ||
| 375 | + result = gen.answer("DNA nedir?") | ||
| 376 | + self.assertFalse(result.abstained) | ||
| 377 | + self.assertEqual(result.reason, "") | ||
| 378 | + self.assertIn("[1]", result.text) | ||
| 379 | + self.assertEqual(result.citations[0]["n"], 1) | ||
| 380 | + self.assertEqual(result.citations[0]["chunk_id"], "c1") | ||
| 381 | + self.assertEqual(llm.calls, 2) | ||
| 382 | + self.assertEqual(llm.prompts[0], llm.prompts[1]) | ||
| 383 | + self.assertEqual(llm.systems[0], llm.systems[1]) | ||
| 384 | + self.assertEqual(llm.temperatures, [0.2, 0.2]) | ||
| 385 | + self.assertEqual(llm.max_tokens, [700, 700]) | ||
| 386 | + log = buf.getvalue() | ||
| 387 | + self.assertIn("model_abstained (looks_like_abstain)", log) | ||
| 388 | + self.assertIn("re-asking the LLM once", log) | ||
| 389 | + self.assertNotIn("re-ask also", log) | ||
| 390 | + with redirect_stdout(io.StringIO()): | ||
| 391 | + again = gen.answer("DNA nedir?") | ||
| 392 | + self.assertTrue(again.cache_hit) | ||
| 393 | + self.assertEqual(again.text, result.text) | ||
| 394 | + self.assertEqual(llm.calls, 2) | ||
| 395 | + | ||
| 396 | + def test_two_abstains_return_model_abstained(self): | ||
| 397 | + llm = _SequenceLLM([ABSTAIN_SENTENCE, ABSTAIN_SENTENCE]) | ||
| 398 | + gen = _make_generator(llm, scores={"c1": 0.9, "c2": 0.85}) | ||
| 399 | + buf = io.StringIO() | ||
| 400 | + with redirect_stdout(buf): | ||
| 401 | + result = gen.answer("DNA nedir?") | ||
| 402 | + self.assertTrue(result.abstained) | ||
| 403 | + self.assertEqual(result.reason, "model_abstained") | ||
| 404 | + self.assertEqual(llm.calls, 2) | ||
| 405 | + self.assertGreater(result.cost_usd, 0.0) | ||
| 406 | + log = buf.getvalue() | ||
| 407 | + self.assertIn("re-asking the LLM once", log) | ||
| 408 | + self.assertIn("re-ask also model_abstained (looks_like_abstain)", log) | ||
| 409 | + | ||
| 410 | + def test_insufficient_data_does_not_call_llm(self): | ||
| 411 | + llm = _SequenceLLM([self._PLAN, self._CITED]) | ||
| 412 | + gen = _make_generator(llm, scores={"c1": 0.05, "c2": 0.01}) | ||
| 413 | + buf = io.StringIO() | ||
| 414 | + with redirect_stdout(buf): | ||
| 415 | + result = gen.answer("DNA nedir?") | ||
| 416 | + self.assertTrue(result.abstained) | ||
| 417 | + self.assertEqual(result.reason, "insufficient_data") | ||
| 418 | + self.assertEqual(llm.calls, 0) | ||
| 419 | + self.assertEqual(result.cost_usd, 0.0) | ||
| 420 | + self.assertEqual(buf.getvalue(), "") | ||
| 421 | + | ||
| 422 | + | ||
| 335 | class CommaAndAdjacentCitationRegexTests(unittest.TestCase): | 423 | class CommaAndAdjacentCitationRegexTests(unittest.TestCase): |
| 336 | """DOĞRULAYICI bulgusu #2: `[1, 2]`, `[1,2]`, `[1][2]`, `[1] [2]` hepsi | 424 | """DOĞRULAYICI bulgusu #2: `[1, 2]`, `[1,2]`, `[1][2]`, `[1] [2]` hepsi |
| 337 | yakalanmalı; hayalet atıf kuralı hâlâ çalışmalı.""" | 425 | yakalanmalı; hayalet atıf kuralı hâlâ çalışmalı.""" |
| @@ -994,7 +1082,7 @@ class ResponseCacheIntegrationTests(unittest.TestCase): | |||
| 994 | gen.answer("DNA nedir?") | 1082 | gen.answer("DNA nedir?") |
| 995 | gen.answer("DNA nedir?") | 1083 | gen.answer("DNA nedir?") |
| 996 | 1084 | ||
| 997 | - self.assertEqual(llm.calls, 2, "model_abstained sonucu cache'lenmediği için 2. çağrı da LLM'e gider") | 1085 | + self.assertEqual(llm.calls, 4, "model_abstained sonucu cache'lenmediği için her answer() bir re-ask daha yapar") |
| 998 | self.assertEqual(gen.cache_hits, 0) | 1086 | self.assertEqual(gen.cache_hits, 0) |
| 999 | 1087 | ||
| 1000 | def test_no_response_cache_behaves_exactly_as_before(self): | 1088 | def test_no_response_cache_behaves_exactly_as_before(self): |