diff --git a/.github/scripts/eval_test_space.py b/.github/scripts/eval_test_space.py index 3aee439a..fb02fb26 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,25 @@ 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", + ), + 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 6e8e5dd6..bc88f0b1 100644 --- a/app/indexing.py +++ b/app/indexing.py @@ -578,6 +578,37 @@ 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 verified health/paramedical discipline-to-practitioner terms for BM25 without merging labour nouns.""" + return _BM25_SYNONYM_STEMS.get(token, token) + + class _BM25Index: """Minimal in-memory Okapi BM25 index over chunk texts.""" @@ -595,7 +626,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 +648,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..8c94ca47 100644 --- a/app/services/llm.py +++ b/app/services/llm.py @@ -2431,6 +2431,36 @@ 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_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 _is_condense_citation_label(label: str) -> bool: + inner = label.strip() + if "," in inner or " - " in inner or inner.startswith(_CONDENSE_CITATION_PREFIXES): + 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 = "" @@ -2442,13 +2472,46 @@ 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_BRACKET_SPAN_RE.sub(_strip_condense_citation_match, 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: + 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 "") + + 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..636a7ea5 100644 --- a/app/tests/integration/suitability_prompts.json +++ b/app/tests/integration/suitability_prompts.json @@ -259,6 +259,39 @@ "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": [ + "(?:\\bchiropract(?:ic|or)s?\\b(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,140}(?:(?