diff --git a/src/llm/links.py b/src/llm/links.py index 9a25d2b..8d089fc 100644 --- a/src/llm/links.py +++ b/src/llm/links.py @@ -20,6 +20,10 @@ _COMMENT = "https://www.regulations.gov/comment/{cid}" _DOWNLOAD = "https://downloads.regulations.gov/{cid}/{name}" _TITLE_MAX = 60 _SNIPPET_CHARS = 500 +#: What the model reads per source. The 500-char snippet is for the UI; +#: rule paragraphs often put the number past it (the CY2027 CF sentence +#: starts at char 518), so the prompt gets the chunk itself, capped. +PROMPT_TEXT_CHARS = 1600 def _short(title: str) -> str: @@ -157,6 +161,7 @@ def as_source(md: dict[str, str], text: str, score: float) -> dict: "docket": md.get("docket", ""), "comment_id": md.get("comment_id", ""), "snippet": snippet, + "text": text.strip()[:PROMPT_TEXT_CHARS], "score": round(score, 4), "item_key": md.get("item_key", ""), "p_id": md.get("p_id", "") if kind == "rule" else "", diff --git a/src/llm/rag.py b/src/llm/rag.py index 1653221..ca3479c 100644 --- a/src/llm/rag.py +++ b/src/llm/rag.py @@ -30,7 +30,7 @@ import threading import time from dataclasses import replace from datetime import date -from typing import Iterator, Sequence +from typing import Callable, Iterator, Sequence import httpx @@ -59,6 +59,8 @@ log = logging.getLogger(__name__) _TIMEOUT = httpx.Timeout(300.0, connect=5.0) _COLLECTIONS = {"comment": "comments", "rule": "rules", "corpus": "corpus"} _OVERFETCH = 3 +#: Cap on the following paragraph a rule hit carries into the prompt. +_NEXT_PARAGRAPH_CHARS = 1200 #: History/timeline-shaped questions — "history of CCM", "what replaced #: G2058", "when was 99490 created" — trigger era-balanced retrieval @@ -351,9 +353,16 @@ def retrieve( now: date | None = None, mode: str = "auto", exclude_phrases: Sequence[str] = (), + next_paragraph: Callable[[str, int], str] | None = None, ) -> list[dict]: """Top sources for ``question`` across all collections. + ``next_paragraph(item_key, p_id)`` returns a rule paragraph's text + (``""`` when absent). When given, each retrieved rule paragraph's + prompt ``text`` gains the paragraph after it: FR lead-ins ("As + required by section 1848(d)(1)(A)...") put the figures in the next + paragraph, which is often not retrieved on its own. + ``since`` (ISO date) hard-filters to material dated on/after it. ``exclude_phrases`` (lower-case) drops any hit whose full chunk text contains one of them before ranking — a detected family's acronym @@ -387,7 +396,50 @@ def retrieve( now=now or date.today(), top_n=cfg.top_n, ) - return [_source(h) for h in ranked] + sources = [_source(h) for h in ranked] + if next_paragraph is not None: + for h, src in zip(ranked, sources, strict=True): + md = h.metadata + if md.get("kind") != "rule" or not md.get("item_key"): + continue + last = md.get("p_id_last") or md.get("p_id") or "" + if not last.isdigit(): + continue + nxt = next_paragraph(md["item_key"], int(last) + 1).strip() + if nxt: + src["text"] = f"{src['text']}\n{nxt[:_NEXT_PARAGRAPH_CHARS]}" + return sources + + +def pg_next_paragraph( + cfg: LlmConfig, +) -> Callable[[str, int], str]: # pragma: no cover — needs a live DB + """A ``next_paragraph`` for :func:`retrieve` reading the ``rules`` + collection; any failure yields ``""`` so retrieval never breaks.""" + import sqlalchemy as sa + + from llm.index import _engine + + sql = sa.text( + "SELECT e.document FROM langchain_pg_embedding e " + "JOIN langchain_pg_collection c ON c.uuid = e.collection_id " + "WHERE c.name = 'rules' AND e.cmetadata->>'item_key' = :k " + "AND e.cmetadata->>'p_id' = :p LIMIT 1" + ) + engine = None + + def fetch(item_key: str, p_id: int) -> str: + nonlocal engine + try: + engine = engine or _engine(cfg) + with engine.connect() as con: + row = con.execute(sql, {"k": item_key, "p": str(p_id)}).fetchone() + return row[0] if row else "" + except Exception: # noqa: BLE001 + log.debug("next paragraph lookup failed for %s p-%s", item_key, p_id) + return "" + + return fetch #: Ruling B11 drop-order floors — how many of each source block survive @@ -494,7 +546,7 @@ def _user_message( if s.get("cited_by") else "" ) - + f") {s['snippet']}" + + f") {s.get('text') or s['snippet']}" for s in sources ) else: @@ -779,6 +831,7 @@ def _stream_answer( since=since, mode=mode, exclude_phrases=conflict_phrases, + next_paragraph=pg_next_paragraph(cfg), ) n_retrieved = len(sources) n_cited = n_lineage_sources = n_manual = 0 diff --git a/tests/llm/test_links.py b/tests/llm/test_links.py index 0fe89c8..8b5f514 100644 --- a/tests/llm/test_links.py +++ b/tests/llm/test_links.py @@ -166,6 +166,7 @@ class TestAsSource: "docket", "comment_id", "snippet", + "text", "score", "item_key", "p_id", @@ -259,3 +260,17 @@ class TestRuleKindAndManual: 0.5, ) assert s2["label"] == "Chapter 18 (2024)" + + +class TestAsSourceText: + def test_prompt_text_keeps_the_chunk_past_the_ui_snippet(self): + # The CY2027 CF sentence starts at char 518 of its paragraph; the + # model only ever saw the 500-char UI snippet. + from llm.links import as_source + + body = ( + "x" * 517 + " We estimate the CY 2027 PFS qualifying APM CF to be 32.9548." + ) + s = as_source({"kind": "comment", "comment_id": "C-1"}, body, 0.5) + assert len(s["snippet"]) <= 500 and "32.9548" not in s["snippet"] + assert "32.9548" in s["text"] diff --git a/tests/llm/test_rag.py b/tests/llm/test_rag.py index 791be10..37a4b03 100644 --- a/tests/llm/test_rag.py +++ b/tests/llm/test_rag.py @@ -4,7 +4,7 @@ import json import logging from dataclasses import replace from datetime import date -from unittest.mock import MagicMock, patch +from unittest.mock import ANY, MagicMock, patch import pytest from langchain_core.documents import Document @@ -846,7 +846,13 @@ class TestStreamAnswer: # no codes in the question — pgvector is never asked for cited rules mock_engine.assert_not_called() mock_retrieve.assert_called_once_with( - "q", cfg=CFG, pool=pool, since="", mode="auto", exclude_phrases=() + "q", + cfg=CFG, + pool=pool, + since="", + mode="auto", + exclude_phrases=(), + next_paragraph=ANY, ) assert events[0] == {"type": "token", "text": "Doc"} assert events[1] == {"type": "token", "text": "tors"} @@ -1702,3 +1708,59 @@ class TestStreamAnswerPromptOverflow: list(stream_answer("q", cfg=CFG, pool=self._pool())) assert client.stream.call_count == 1 mock_overflow.assert_not_called() + + +class TestRuleContinuation: + def _rule_hit(self, p_id: str, text: str): + return ( + _doc( + text, + kind="rule", + item_key="JC", + html_url="https://fr.test/doc", + p_id=p_id, + page="71653", + ordinal="2", + fr_volume="91", + date="2026-11-09", + title="CY2027 PFS final", + ), + 0.1, + ) + + @patch("llm.rag.PoolEmbeddings") + @patch("llm.index.vectorstore") + def test_rule_hit_carries_its_next_paragraph(self, mock_vs, MockEmb): + MockEmb.return_value.embed_query.return_value = [0.1] * 3 + mock_vs.side_effect = _stores( + {"rules": [self._rule_hit("6658", "There are two separate CFs.")]} + ) + asked = [] + + def nxt(item_key, p_id): + asked.append((item_key, p_id)) + return "We estimate the CY 2027 PFS qualifying APM CF to be 32.9548." + + out = retrieve("cf", cfg=CFG, pool=MagicMock(), now=NOW, next_paragraph=nxt) + assert asked == [("JC", 6659)] + assert "32.9548" in out[0]["text"] and "32.9548" not in out[0]["snippet"] + + @patch("llm.rag.PoolEmbeddings") + @patch("llm.index.vectorstore") + def test_no_fetcher_no_lookup(self, mock_vs, MockEmb): + MockEmb.return_value.embed_query.return_value = [0.1] * 3 + mock_vs.side_effect = _stores({"rules": [self._rule_hit("6658", "Two CFs.")]}) + out = retrieve("cf", cfg=CFG, pool=MagicMock(), now=NOW) + assert out[0]["text"] == "Two CFs." + + def test_prompt_uses_the_full_text(self): + src = { + "label": "91 FR 71653 ¶2", + "kind": "rule", + "rule_kind": "final", + "date": "2026-11-09", + "snippet": "Two CFs.", + "text": "Two CFs.\nWe estimate the CY 2027 PFS qualifying APM CF to be 32.9548.", + } + msg = rag._user_message("q", [src], [], [], [], [], None, None, None, None) + assert "32.9548" in msg