From 8dc05fa4246a830ddc99571797cec5540de470ee Mon Sep 17 00:00:00 2001 From: Derek Roberts Date: Tue, 1 Dec 2026 19:30:35 -0700 Subject: [PATCH 1/3] fix(retrieval,llm): fold BM25 derivational stems and strip reference noise in condense_query --- .github/scripts/eval_test_space.py | 18 +++++++ app/indexing.py | 17 ++++++- app/services/llm.py | 42 ++++++++++++++++- .../integration/suitability_prompts.json | 32 +++++++++++++ app/tests/test_condense_query.py | 45 ++++++++++++++++++ app/tests/test_index.py | 47 +++++++++++++++++++ .../deploy_integrity/test_suitability_gate.py | 46 ++++++++++++++++++ 7 files changed, 243 insertions(+), 4 deletions(-) diff --git a/.github/scripts/eval_test_space.py b/.github/scripts/eval_test_space.py index 3aee439a..d4342178 100644 --- a/.github/scripts/eval_test_space.py +++ b/.github/scripts/eval_test_space.py @@ -666,6 +666,14 @@ def build_synthetic_passing_responses() -> dict[str, str]: "\n\n### 📄 Reference Documents\n" "- [BC Bargaining Unit Health and Dental Benefits](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md)" ), + "s09_chiropractic_benefits_limit": ( + "Chiropractic treatments performed by a chiropractor registered with the College of Chiropractors of " + "British Columbia are covered up to $500/year/person, subject to reasonable and customary limits; " + "X-rays taken by a chiropractor are not eligible for reimbursement " + "[BC Bargaining Unit Health and Dental Benefits - What's covered by your extended health plan]." + "\n\n### 📄 Reference Documents\n" + "- [BC Bargaining Unit Health and Dental Benefits](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md)" + ), } @@ -740,6 +748,16 @@ def build_break_it_cases() -> list[BreakItCase]: ), expected_failure_code="forbidden_fact_present", ), + BreakItCase( + name="chiropractic_wrong_2000_cap_missing_500", + prompt_id="s09_chiropractic_benefits_limit", + response=( + "Chiropractic services are covered under the extended health plan: Reimbursed at 80% for the " + "first $2,000 paid in a calendar year per person and then 100% for the balance of the year " + "[BC Bargaining Unit Health and Dental Benefits, Extended health benefits at a glance]." + ), + expected_failure_code="missing_factual_anchor", + ), ] diff --git a/app/indexing.py b/app/indexing.py index 6e8e5dd6..5d3745bd 100644 --- a/app/indexing.py +++ b/app/indexing.py @@ -578,6 +578,18 @@ def _tokenize_bm25(text: str) -> list[str]: return _BM25_TOKEN_RE.findall(text.lower()) +def _normalize_bm25_token(token: str) -> str: + """Fold common derivational suffixes for BM25 matching without collapsing plurals.""" + if len(token) <= 5 or not token.isalpha(): + return token + for suffix in ("ists", "ical", "ors", "ist", "ic", "or", "y"): + if token.endswith(suffix) and len(token) - len(suffix) >= 5: + return token[: -len(suffix)] + if token.endswith("ure") and len(token) >= 7: + return token[:-1] + return token + + class _BM25Index: """Minimal in-memory Okapi BM25 index over chunk texts.""" @@ -595,7 +607,7 @@ def __init__(self, texts: list[str], k1: float = _BM25_K1, b: float = _BM25_B) - total_len = 0 for doc_idx, text in enumerate(texts): - tokens = _tokenize_bm25(text) + tokens = [_normalize_bm25_token(tok) for tok in _tokenize_bm25(text)] self.doc_lens.append(len(tokens)) total_len += len(tokens) counts: dict[str, int] = {} @@ -617,7 +629,8 @@ def search(self, query: str, top_k: int) -> list[int]: if not raw_tokens: return [] filtered_tokens = [tok for tok in raw_tokens if tok not in _BM25_STOPWORDS] - query_tokens = filtered_tokens if filtered_tokens else raw_tokens + selected_tokens = filtered_tokens if filtered_tokens else raw_tokens + query_tokens = [_normalize_bm25_token(tok) for tok in selected_tokens] scores: dict[int, float] = {} k1 = self.k1 diff --git a/app/services/llm.py b/app/services/llm.py index 81a5265b..210ce4b3 100644 --- a/app/services/llm.py +++ b/app/services/llm.py @@ -2431,6 +2431,14 @@ async def clear_active_status_steps() -> None: logger.error(f"[chat] Failed to remove step: {e}") cl.user_session.set("steps_to_remove", []) +_CONDENSE_REFERENCE_SECTION_RE = re.compile( + r"\n*###\s*(?:📄\s*)?Reference Documents[\s\S]*$", + re.IGNORECASE, +) +_CONDENSE_INLINE_CITATION_RE = re.compile(r"\s*\[[^\]\n]{4,160}\](?!\()") +_CONDENSE_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]+\)") + + def _format_history(history: list[dict]) -> str: """Format conversation history list into a standardized string for LLM prompts.""" history_text = "" @@ -2442,13 +2450,43 @@ def _format_history(history: list[dict]) -> str: history_text += f"{role}: {content}\n" return history_text + +def _format_history_for_condense(history: list[dict]) -> str: + """Format recent turns for query condensation, stripping citations and Reference Documents.""" + lines: list[str] = [] + for turn in history[-5:]: + raw_role = (turn["role"] if isinstance(turn, dict) else turn.role).strip() + role = raw_role.capitalize() + content = turn["content"] if isinstance(turn, dict) else turn.content + if isinstance(content, list): + content = "".join([p.get("text", "") if isinstance(p, dict) else str(p) for p in content]) + content_str = str(content or "") + if raw_role.lower() == "assistant": + cleaned = _CONDENSE_REFERENCE_SECTION_RE.sub("", content_str) + cleaned = _CONDENSE_INLINE_CITATION_RE.sub("", cleaned) + cleaned = _CONDENSE_MARKDOWN_LINK_RE.sub(r"\1", cleaned) + cleaned = " ".join(cleaned.split()) + if len(cleaned) > 300: + cleaned = cleaned[:300] + "..." + content_str = cleaned + lines.append(f"{role}: {content_str}") + return "\n".join(lines) + ("\n" if lines else "") + + async def condense_query(message: str, history: list[dict]) -> str: """Turn the conversation history and new message into a standalone search query.""" if not history: return message - history_text = _format_history(history) - prompt = f"CONVERSATION HISTORY:\n{history_text}\nUSER MESSAGE: {message}\n\nTask: Condense into a standalone search query." + history_text = _format_history_for_condense(history) + prompt = ( + f"CONVERSATION HISTORY:\n{history_text}\n" + f"USER MESSAGE: {message}\n\n" + "Task: Rewrite the USER MESSAGE as a concise standalone search query. " + "Keep only the user's current topic and necessary context from prior turns. " + "Do not copy document titles, reference document lists, or unrelated details from prior answers. " + "Return only the search query." + ) try: resp_text = await unified_chat_create( model=CONDENSE_MODEL, diff --git a/app/tests/integration/suitability_prompts.json b/app/tests/integration/suitability_prompts.json index b0ae2893..e01b7c97 100644 --- a/app/tests/integration/suitability_prompts.json +++ b/app/tests/integration/suitability_prompts.json @@ -259,6 +259,38 @@ "Orthodontic services", "$3,500" ] + }, + { + "id": "s09_chiropractic_benefits_limit", + "category": "resources", + "expected_type": "positive", + "query": "What are my chiropractic benefits?", + "expected_sources": [ + "BC Bargaining Unit Health and Dental Benefits" + ], + "acceptable_citation_aliases": [ + "BC Bargaining Unit Health and Dental Benefits", + "Extended health and dental plans for bargaining unit employees" + ], + "required_section_patterns": [ + "\\bchiropract(?:ic|or)\\b" + ], + "required_fact_patterns": [ + "(?:\\$500(?:\\.00)?(?!\\d)(?:(?!\\$2,?000|[.!?\\n]).){0,50}(?:/\\s*year|\\bper\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|(?:\\bannual(?:\\s+(?:limit|maximum|cap))?\\b|\\bper\\s+(?:calendar\\s+)?year\\b)(?:(?!\\$2,?000|[.!?\\n]).){0,50}\\$500(?:\\.00)?(?!\\d))" + ], + "forbidden_patterns": [ + "/public/docs/forms/Grievance_-_", + "Grievance\\s*-\\s*(?:0\\s*-\\s*Instructions|A\\s*-\\s*Grievor\\s*Case|B\\s*-\\s*Notify\\s*Designates|C\\s*-\\s*Steward\\s*Case)", + "\\bFiling\\s+a\\s+Grievance\\b", + "\\b(?:file|submit|pursue|start|initiate)\\s+(?:a\\s+)?grievance\\b", + "\\bgrounds\\s+for\\s+a\\s+grievance\\b", + "\\bchiropract(?:ic|or)s?(?:(?![.!?\\n]).){0,80}(?:\\b(?:cap|limit|maximum|max)\\b(?:(?![.!?\\n]).){0,30}\\$2,?000(?:\\.00)?(?!\\d)|\\$2,?000(?:\\.00)?(?!\\d)(?:(?![.!?\\n]).){0,20}(?:/\\s*year|\\bper\\s+(?:calendar\\s+)?year\\b|\\bannual|\\bcap\\b|\\blimit\\b|\\bmaximum\\b))" + ], + "oracle_terms": [ + "Chiropractor", + "Chiropractic treatments", + "$500/year/person" + ] } ] } diff --git a/app/tests/test_condense_query.py b/app/tests/test_condense_query.py index 30fb46ec..1abd6c0c 100644 --- a/app/tests/test_condense_query.py +++ b/app/tests/test_condense_query.py @@ -69,3 +69,48 @@ async def test_condense_query_handles_api_failure_gracefully(): condensed = await app.condense_query(message, history) assert condensed == message + + +@pytest.mark.asyncio +async def test_condense_query_strips_citations_and_reference_documents(): + """Assistant citations and Reference Documents footers must not leak into condensation history.""" + history = [ + {"role": "user", "content": "What are my dental benefits?"}, + { + "role": "assistant", + "content": ( + "Basic services are 100% [BC Bargaining Unit Health and Dental Benefits, DENTAL BENEFITS AT A GLANCE]. " + "Submit via [My Canada Life at Work](https://my.canadalife.com/sign-in). " + + ("Details about annual claims. " * 20) + + "\n\n### 📄 Reference Documents\n" + "- [BC Bargaining Unit Health and Dental Benefits](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md)\n" + "- [BC Bargaining Unit Benefits Overview](/public/docs/BC_Bargaining_Unit_Benefits_Overview.md)\n" + "- [BC Bargaining Unit Benefits Glossary](/public/docs/BC_Bargaining_Unit_Benefits_Glossary.md)" + ), + }, + ] + message = "What about chiropractic?" + + mock_client = MagicMock() + mock_completion = MagicMock() + mock_completion.choices = [MagicMock(message=MagicMock(content="What are my chiropractic benefits?"))] + mock_client.chat.completions.create = AsyncMock(return_value=mock_completion) + + with patch("main.get_llm_client", return_value=mock_client): + with patch("main.get_embed_model"): + condensed = await app.condense_query(message, history) + + assert condensed == "What are my chiropractic benefits?" + args, kwargs = mock_client.chat.completions.create.call_args + prompt = kwargs["messages"][0]["content"] + assert "User: What are my dental benefits?" in prompt + assert "Reference Documents" not in prompt + assert "DENTAL BENEFITS AT A GLANCE" not in prompt + assert "/public/docs/" not in prompt + assert "https://my.canadalife.com/sign-in" not in prompt + assert "My Canada Life at Work" in prompt + assert "Do not copy document titles" in prompt + assistant_line = next(line for line in prompt.splitlines() if line.startswith("Assistant: ")) + assert assistant_line.endswith("...") + assert len(assistant_line) <= len("Assistant: ") + 303 + diff --git a/app/tests/test_index.py b/app/tests/test_index.py index 186e6a76..786f5796 100644 --- a/app/tests/test_index.py +++ b/app/tests/test_index.py @@ -382,3 +382,50 @@ def test_search_index_distant_tier1_does_not_beat_rank1_tier3(monkeypatch): results = indexing.search_index(index, chunks, "xyzzy", top_k=5) assert results[0] == chunks[0] + +def test_normalize_bm25_token_folds_derivational_suffixes_safely(): + """Derivational suffix normalization matches practitioner/discipline variants without breaking plurals.""" + assert ( + indexing._normalize_bm25_token("chiropractic") + == indexing._normalize_bm25_token("chiropractor") + == indexing._normalize_bm25_token("chiropractors") + ) + assert ( + indexing._normalize_bm25_token("naturopath") + == indexing._normalize_bm25_token("naturopathic") + == indexing._normalize_bm25_token("naturopathy") + ) + assert ( + indexing._normalize_bm25_token("physiotherapy") + == indexing._normalize_bm25_token("physiotherapist") + == indexing._normalize_bm25_token("physiotherapists") + ) + assert ( + indexing._normalize_bm25_token("podiatry") + == indexing._normalize_bm25_token("podiatrist") + == indexing._normalize_bm25_token("podiatrists") + ) + assert ( + indexing._normalize_bm25_token("acupuncture") + == indexing._normalize_bm25_token("acupuncturist") + ) + # Plurals and short legal tokens remain distinct + assert indexing._normalize_bm25_token("disabilities") == "disabilities" + assert indexing._normalize_bm25_token("benefits") == "benefits" + assert indexing._normalize_bm25_token("s") == "s" + assert indexing._normalize_bm25_token("21") == "21" + assert indexing._normalize_bm25_token("10.8") == "10.8" + + +def test_bm25_search_matches_chiropractic_to_chiropractor_row(): + """Searching 'chiropractic' must surface the 'Chiropractor: $500/year/person' chunk in BM25.""" + texts = [ + "extended health plan reimbursed at 80% for the first $2,000 paid in a calendar year", + "paramedical services chiropractor coverage is $500/year/person", + "dental plan basic services 100% and major services 65%", + ] + bm25 = indexing._BM25Index(texts) + hits = bm25.search("What are the BC Bargaining Unit Benefits for chiropractic?", top_k=3) + assert hits[0] == 1 + + diff --git a/tests/deploy_integrity/test_suitability_gate.py b/tests/deploy_integrity/test_suitability_gate.py index 6616895f..d9b8ed4d 100644 --- a/tests/deploy_integrity/test_suitability_gate.py +++ b/tests/deploy_integrity/test_suitability_gate.py @@ -192,6 +192,25 @@ def test_s08_live_gold_response_and_link_preservation(): assert cents_res.passed, cents_res.failures +def test_s09_chiropractic_benefits_response_variants(): + corpus = gate.load_corpus_metadata(REPO_ROOT / "app" / "data") + suite = gate.load_prompt_suite(REPO_ROOT / "app" / "tests" / "integration" / "suitability_prompts.json") + spec = next(p for p in suite["prompts"] if p["id"] == "s09_chiropractic_benefits_limit") + + accurate_with_coinsurance_context = ( + "Chiropractic treatments are covered up to $500/year/person when performed by a chiropractor registered " + "with the College of Chiropractors of British Columbia; X-rays taken by a chiropractor are not eligible " + "for reimbursement [BC Bargaining Unit Health and Dental Benefits - What's covered by your extended health plan].\n\n" + "General extended health expenses are reimbursed at 80% for the first $2,000 paid in a calendar year per " + "person and 100% for the balance, subject to plan maximums " + "[BC Bargaining Unit Health and Dental Benefits - Extended health benefits at a glance]." + "\n\n### 📄 Reference Documents\n" + "- [BC Bargaining Unit Health and Dental Benefits](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md)" + ) + res = gate.evaluate_response(spec, accurate_with_coinsurance_context, corpus=corpus) + assert res.passed, res.failures + + def test_failure_diagnostics_include_citations_excerpt_and_raw_response(): corpus = gate.load_corpus_metadata(REPO_ROOT / "app" / "data") suite = gate.load_prompt_suite(REPO_ROOT / "app" / "tests" / "integration" / "suitability_prompts.json") @@ -455,6 +474,33 @@ def test_failure_diagnostics_include_citations_excerpt_and_raw_response(): ), "forbidden_fact_present", ), + ( + "s09_chiropractic_benefits_limit", + ( + "Chiropractic services are reimbursed at 80% for the first $2,000 paid in a calendar year per person " + "and then 100% for the balance of the year " + "[BC Bargaining Unit Health and Dental Benefits, Extended health benefits at a glance]." + ), + "missing_factual_anchor", + ), + ( + "s09_chiropractic_benefits_limit", + ( + "Chiropractic services have a $500/year/person limit under paramedical services, though " + "chiropractic cap is $2,000 per calendar year " + "[BC Bargaining Unit Health and Dental Benefits]." + ), + "forbidden_fact_present", + ), + ( + "s09_chiropractic_benefits_limit", + ( + "Chiropractic treatments are covered up to $500/year/person " + "[BC Bargaining Unit Health and Dental Benefits].\n\n" + "- [Grievance - 0 - Instructions](/public/docs/forms/Grievance_-_0_-_Instructions.pdf)" + ), + "forbidden_fact_present", + ), ], ) def test_evaluate_response_fails_closed_on_bad_outputs(prompt_id, bad_response, expected_code): From c5f3008a92f58e8471e3d0178c983e371f5d3307 Mon Sep 17 00:00:00 2001 From: Derek Roberts Date: Tue, 1 Dec 2026 19:46:39 -0700 Subject: [PATCH 2/3] fix(retrieval,llm): scope BM25 synonym stems and tighten s09/condense rules --- .github/scripts/eval_test_space.py | 9 +++ app/indexing.py | 37 +++++++++--- app/services/llm.py | 23 ++++++-- .../integration/suitability_prompts.json | 4 +- app/tests/test_condense_query.py | 15 +++-- app/tests/test_index.py | 10 +++- .../deploy_integrity/test_suitability_gate.py | 59 +++++++++++++++---- 7 files changed, 124 insertions(+), 33 deletions(-) diff --git a/.github/scripts/eval_test_space.py b/.github/scripts/eval_test_space.py index d4342178..fb02fb26 100644 --- a/.github/scripts/eval_test_space.py +++ b/.github/scripts/eval_test_space.py @@ -758,6 +758,15 @@ def build_break_it_cases() -> list[BreakItCase]: ), expected_failure_code="missing_factual_anchor", ), + BreakItCase( + name="chiropractic_reversed_2000_cap_assertion", + prompt_id="s09_chiropractic_benefits_limit", + response=( + "Chiropractic coverage is $500/year/person. However, $2,000 per calendar year is the chiropractic cap " + "[BC Bargaining Unit Health and Dental Benefits]." + ), + expected_failure_code="forbidden_fact_present", + ), ] diff --git a/app/indexing.py b/app/indexing.py index 5d3745bd..bc88f0b1 100644 --- a/app/indexing.py +++ b/app/indexing.py @@ -578,16 +578,35 @@ def _tokenize_bm25(text: str) -> list[str]: return _BM25_TOKEN_RE.findall(text.lower()) +_BM25_SYNONYM_STEMS: dict[str, str] = { + "chiropractic": "chiropract", + "chiropractor": "chiropract", + "chiropractors": "chiropract", + "naturopathic": "naturopath", + "naturopathy": "naturopath", + "naturopaths": "naturopath", + "naturopath": "naturopath", + "physiotherapy": "physiotherap", + "physiotherapist": "physiotherap", + "physiotherapists": "physiotherap", + "podiatry": "podiatr", + "podiatrist": "podiatr", + "podiatrists": "podiatr", + "acupuncture": "acupunctur", + "acupuncturist": "acupunctur", + "acupuncturists": "acupunctur", + "psychology": "psycholog", + "psychological": "psycholog", + "psychologist": "psycholog", + "psychologists": "psycholog", + "orthotic": "orthot", + "orthotics": "orthot", +} + + def _normalize_bm25_token(token: str) -> str: - """Fold common derivational suffixes for BM25 matching without collapsing plurals.""" - if len(token) <= 5 or not token.isalpha(): - return token - for suffix in ("ists", "ical", "ors", "ist", "ic", "or", "y"): - if token.endswith(suffix) and len(token) - len(suffix) >= 5: - return token[: -len(suffix)] - if token.endswith("ure") and len(token) >= 7: - return token[:-1] - return token + """Fold verified health/paramedical discipline-to-practitioner terms for BM25 without merging labour nouns.""" + return _BM25_SYNONYM_STEMS.get(token, token) class _BM25Index: diff --git a/app/services/llm.py b/app/services/llm.py index 210ce4b3..c68c000f 100644 --- a/app/services/llm.py +++ b/app/services/llm.py @@ -2435,8 +2435,20 @@ async def clear_active_status_steps() -> None: r"\n*###\s*(?:📄\s*)?Reference Documents[\s\S]*$", re.IGNORECASE, ) -_CONDENSE_INLINE_CITATION_RE = re.compile(r"\s*\[[^\]\n]{4,160}\](?!\()") +_CONDENSE_BRACKET_SPAN_RE = re.compile(r"\s*\[([^\]\n]{4,160})\](?!\()") +_CONDENSE_DOC_LINK_RE = re.compile(r"\s*\[[^\]]+\]\(/public/docs/[^)]+\)") _CONDENSE_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]+\)") +_CONDENSE_CITATION_PREFIXES = ("BC ", "BCGEU ", "Gov BC ", "Nexus Test") +_CONDENSE_ASSISTANT_MAX_CHARS = 1200 + + +def _strip_condense_citation_match(match: re.Match[str]) -> str: + inner = match.group(1).strip() + if "," in inner or " - " in inner or inner.startswith(_CONDENSE_CITATION_PREFIXES): + return "" + if any(chunk.get("source") == inner for chunk in (_get_active_chunks() or ())): + return "" + return match.group(0) def _format_history(history: list[dict]) -> str: @@ -2463,11 +2475,14 @@ def _format_history_for_condense(history: list[dict]) -> str: content_str = str(content or "") if raw_role.lower() == "assistant": cleaned = _CONDENSE_REFERENCE_SECTION_RE.sub("", content_str) - cleaned = _CONDENSE_INLINE_CITATION_RE.sub("", cleaned) + cleaned = _CONDENSE_BRACKET_SPAN_RE.sub(_strip_condense_citation_match, cleaned) + cleaned = _CONDENSE_DOC_LINK_RE.sub("", cleaned) cleaned = _CONDENSE_MARKDOWN_LINK_RE.sub(r"\1", cleaned) cleaned = " ".join(cleaned.split()) - if len(cleaned) > 300: - cleaned = cleaned[:300] + "..." + if len(cleaned) > _CONDENSE_ASSISTANT_MAX_CHARS: + head_len = _CONDENSE_ASSISTANT_MAX_CHARS // 2 + tail_len = _CONDENSE_ASSISTANT_MAX_CHARS - head_len - 5 + cleaned = f"{cleaned[:head_len]} ... {cleaned[-tail_len:]}" content_str = cleaned lines.append(f"{role}: {content_str}") return "\n".join(lines) + ("\n" if lines else "") diff --git a/app/tests/integration/suitability_prompts.json b/app/tests/integration/suitability_prompts.json index e01b7c97..34b2b8f1 100644 --- a/app/tests/integration/suitability_prompts.json +++ b/app/tests/integration/suitability_prompts.json @@ -276,7 +276,7 @@ "\\bchiropract(?:ic|or)\\b" ], "required_fact_patterns": [ - "(?:\\$500(?:\\.00)?(?!\\d)(?:(?!\\$2,?000|[.!?\\n]).){0,50}(?:/\\s*year|\\bper\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|(?:\\bannual(?:\\s+(?:limit|maximum|cap))?\\b|\\bper\\s+(?:calendar\\s+)?year\\b)(?:(?!\\$2,?000|[.!?\\n]).){0,50}\\$500(?:\\.00)?(?!\\d))" + "(?:\\bchiropract(?:ic|or)s?\\b(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,140}\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,100}\\bchiropract(?:ic|or)s?\\b)" ], "forbidden_patterns": [ "/public/docs/forms/Grievance_-_", @@ -284,7 +284,7 @@ "\\bFiling\\s+a\\s+Grievance\\b", "\\b(?:file|submit|pursue|start|initiate)\\s+(?:a\\s+)?grievance\\b", "\\bgrounds\\s+for\\s+a\\s+grievance\\b", - "\\bchiropract(?:ic|or)s?(?:(?![.!?\\n]).){0,80}(?:\\b(?:cap|limit|maximum|max)\\b(?:(?![.!?\\n]).){0,30}\\$2,?000(?:\\.00)?(?!\\d)|\\$2,?000(?:\\.00)?(?!\\d)(?:(?![.!?\\n]).){0,20}(?:/\\s*year|\\bper\\s+(?:calendar\\s+)?year\\b|\\bannual|\\bcap\\b|\\blimit\\b|\\bmaximum\\b))" + "(?:\\bchiropract(?:ic|or)s?\\b(?:(?!(?:\\b(?:not|no|never|isn't|aren't|general\\s+(?:coinsurance|extended\\s+health))\\b|[.!?;\\n])).){0,80}(?:\\b(?:cap|limit|maximum|max)\\b(?:(?!(?:\\b(?:not|no)\\b|[.!?;\\n])).){0,25}(? Date: Wed, 2 Dec 2026 10:31:35 -0700 Subject: [PATCH 3/3] fix(llm,eval): classify condense doc-link labels and tighten s09 rules --- app/services/llm.py | 22 ++++++++++++----- .../integration/suitability_prompts.json | 5 ++-- app/tests/test_condense_query.py | 5 +++- .../deploy_integrity/test_suitability_gate.py | 24 +++++++++++++++++++ 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/app/services/llm.py b/app/services/llm.py index c68c000f..8c94ca47 100644 --- a/app/services/llm.py +++ b/app/services/llm.py @@ -2436,21 +2436,31 @@ async def clear_active_status_steps() -> None: re.IGNORECASE, ) _CONDENSE_BRACKET_SPAN_RE = re.compile(r"\s*\[([^\]\n]{4,160})\](?!\()") -_CONDENSE_DOC_LINK_RE = re.compile(r"\s*\[[^\]]+\]\(/public/docs/[^)]+\)") +_CONDENSE_DOC_LINK_RE = re.compile(r"(\s*)\[([^\]]+)\]\(/public/docs/[^)]+\)") _CONDENSE_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]+\)") _CONDENSE_CITATION_PREFIXES = ("BC ", "BCGEU ", "Gov BC ", "Nexus Test") _CONDENSE_ASSISTANT_MAX_CHARS = 1200 -def _strip_condense_citation_match(match: re.Match[str]) -> str: - inner = match.group(1).strip() +def _is_condense_citation_label(label: str) -> bool: + inner = label.strip() if "," in inner or " - " in inner or inner.startswith(_CONDENSE_CITATION_PREFIXES): - return "" - if any(chunk.get("source") == inner for chunk in (_get_active_chunks() or ())): + return True + return any(chunk.get("source") == inner for chunk in (_get_active_chunks() or ())) + + +def _strip_condense_citation_match(match: re.Match[str]) -> str: + if _is_condense_citation_label(match.group(1)): return "" return match.group(0) +def _strip_condense_doc_link_match(match: re.Match[str]) -> str: + if _is_condense_citation_label(match.group(2)): + return "" + return f"{match.group(1)}{match.group(2)}" + + def _format_history(history: list[dict]) -> str: """Format conversation history list into a standardized string for LLM prompts.""" history_text = "" @@ -2476,7 +2486,7 @@ def _format_history_for_condense(history: list[dict]) -> str: if raw_role.lower() == "assistant": cleaned = _CONDENSE_REFERENCE_SECTION_RE.sub("", content_str) cleaned = _CONDENSE_BRACKET_SPAN_RE.sub(_strip_condense_citation_match, cleaned) - cleaned = _CONDENSE_DOC_LINK_RE.sub("", cleaned) + cleaned = _CONDENSE_DOC_LINK_RE.sub(_strip_condense_doc_link_match, cleaned) cleaned = _CONDENSE_MARKDOWN_LINK_RE.sub(r"\1", cleaned) cleaned = " ".join(cleaned.split()) if len(cleaned) > _CONDENSE_ASSISTANT_MAX_CHARS: diff --git a/app/tests/integration/suitability_prompts.json b/app/tests/integration/suitability_prompts.json index 34b2b8f1..636a7ea5 100644 --- a/app/tests/integration/suitability_prompts.json +++ b/app/tests/integration/suitability_prompts.json @@ -276,7 +276,7 @@ "\\bchiropract(?:ic|or)\\b" ], "required_fact_patterns": [ - "(?:\\bchiropract(?:ic|or)s?\\b(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,140}\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,100}\\bchiropract(?:ic|or)s?\\b)" + "(?:\\bchiropract(?:ic|or)s?\\b(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,140}(?:(?