diff --git a/.github/scripts/eval_test_space.py b/.github/scripts/eval_test_space.py index 1f3d9e56..3aee439a 100644 --- a/.github/scripts/eval_test_space.py +++ b/.github/scripts/eval_test_space.py @@ -567,8 +567,9 @@ def evaluate_response( if not re.search(pat, answer_body, re.IGNORECASE): failures.append(f"missing_factual_anchor: pattern '{pat}' not found") + forbidden_haystack = f"{answer_body}\n{reference_section}".strip() if reference_section else answer_body for pat in prompt_spec.get("forbidden_patterns", []): - if re.search(pat, answer_body, re.IGNORECASE): + if re.search(pat, forbidden_haystack, re.IGNORECASE): failures.append(f"forbidden_fact_present: matched '{pat}'") elif expected_type == "abstention": @@ -657,6 +658,14 @@ def build_synthetic_passing_responses() -> dict[str, str]: "\n\n### πŸ“„ Reference Documents\n" "- [BCGEU 20th Main Agreement](/public/docs/BCGEU_20th_Main_Agreement.pdf)" ), + "s08_dental_benefits_coverage": ( + "Under the bargaining unit dental plan, Basic services (such as cleaning, polishing, and topical fluoride) " + "are reimbursed at 100%, Major services (such as crowns, bridges, and dentures) at 65%, and Orthodontic " + "services at 55% up to a $3,500 lifetime maximum per covered person " + "[BC Bargaining Unit Health and Dental Benefits - Dental 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)" + ), } @@ -720,6 +729,17 @@ def build_break_it_cases() -> list[BreakItCase]: ), expected_failure_code="leaked_think_tag", ), + BreakItCase( + name="unsolicited_grievance_forms_on_dental_lookup", + prompt_id="s08_dental_benefits_coverage", + response=( + "Dental coverage includes Basic services at 100%, Major services at 65%, and Orthodontic services " + "at 55% with a $3,500 lifetime maximum [BC Bargaining Unit Health and Dental Benefits].\n\n" + "### Filing a Grievance\n" + "- [Grievance - 0 - Instructions](/public/docs/forms/Grievance_-_0_-_Instructions.pdf)" + ), + expected_failure_code="forbidden_fact_present", + ), ] @@ -765,45 +785,57 @@ def check_space_health(base_url: str, timeout_seconds: int = 30, attempts: int = raise RuntimeError(f"Pre-flight /api/health check failed at {health_url}: {last_exc}") -_EXTRACT_ASSISTANT_BUBBLE_JS = """([beforeTexts, userQuery]) => { +_CLONE_MESSAGE_TEXT_JS = """(el) => { + const clone = el.cloneNode(true); + clone.querySelectorAll('button, [class*="actions"], [role="status"]').forEach((n) => n.remove()); + clone.querySelectorAll('a[href]').forEach((a) => { + const href = (a.getAttribute('href') || '').trim(); + const label = (a.innerText || a.textContent || '').trim(); + if (href && label && !href.startsWith('#') && !label.includes('](')) { + a.textContent = `[${label}](${href})`; + } + }); + return (clone.innerText || clone.textContent || '').trim(); +}""" + + +_EXTRACT_ASSISTANT_BUBBLE_JS = f"""([beforeTexts, userQuery]) => {{ + const extractText = {_CLONE_MESSAGE_TEXT_JS}; const candidates = document.querySelectorAll( '.message, [class*="message"]:not(.message-list):not([class*="actions"]):not(#message-composer)' ); const matches = []; - for (const el of candidates) { + for (const el of candidates) {{ if (el.closest('#message-composer')) continue; if (el.querySelector('.message')) continue; - const clone = el.cloneNode(true); - clone.querySelectorAll('button, [class*="actions"], [role="status"]').forEach((n) => n.remove()); - const text = (clone.innerText || clone.textContent || '').trim(); + const text = extractText(el); if (!text || text === userQuery) continue; matches.push(text); - } + }} if (!matches.length) return ''; - for (let i = matches.length - 1; i >= 0; i--) { - if (!beforeTexts.includes(matches[i])) { + for (let i = matches.length - 1; i >= 0; i--) {{ + if (!beforeTexts.includes(matches[i])) {{ return matches[i]; - } - } + }} + }} return matches.length > beforeTexts.length ? matches[matches.length - 1] : ''; -}""" +}}""" -_SNAPSHOT_BUBBLES_JS = """() => { +_SNAPSHOT_BUBBLES_JS = f"""() => {{ + const extractText = {_CLONE_MESSAGE_TEXT_JS}; const candidates = document.querySelectorAll( '.message, [class*="message"]:not(.message-list):not([class*="actions"]):not(#message-composer)' ); const out = []; - for (const el of candidates) { + for (const el of candidates) {{ if (el.closest('#message-composer')) continue; if (el.querySelector('.message')) continue; - const clone = el.cloneNode(true); - clone.querySelectorAll('button, [class*="actions"], [role="status"]').forEach((n) => n.remove()); - const text = (clone.innerText || clone.textContent || '').trim(); + const text = extractText(el); if (text) out.push(text); - } + }} return out; -}""" +}}""" def query_chainlit_ui( diff --git a/app/indexing.py b/app/indexing.py index 52fac075..6e8e5dd6 100644 --- a/app/indexing.py +++ b/app/indexing.py @@ -86,7 +86,20 @@ def __init__(self, pdf_path: Path) -> None: _BM25_TOKEN_RE = re.compile(r"\d+(?:\.\d+)+|[a-z0-9]+") _BM25_K1 = 1.5 _BM25_B = 0.75 -_RRF_K = 60 +# Small RRF k keeps 1/(k+r) steep enough that a 1.5x Tier 1/Tier 3 boost +# only breaks close ties (ranks 1-2) instead of letting distant Tier 1 chunks +# override a rank-1 statutory/benefits chunk. +_RRF_K = 3 +_BM25_STOPWORDS = frozenset({ + "a", "an", "and", "are", "as", "at", "be", "been", "being", "but", "by", + "can", "could", "did", "do", "does", "doing", "for", "from", "get", "gets", + "getting", "got", "had", "has", "have", "having", "he", "her", "hers", + "him", "his", "how", "i", "if", "in", "into", "is", "it", "its", "me", + "my", "of", "on", "or", "our", "ours", "she", "so", "that", "the", + "their", "theirs", "them", "they", "these", "this", "those", "to", "us", + "was", "we", "were", "what", "when", "where", "which", "who", "whom", + "why", "will", "with", "would", "you", "your", "yours", +}) _embed_model: Any = None @@ -600,9 +613,11 @@ def search(self, query: str, top_k: int) -> list[int]: """Return up to top_k chunk indices with positive BM25 scores, sorted descending.""" if self.n_docs == 0 or top_k <= 0 or self.avgdl <= 0.0: return [] - query_tokens = _tokenize_bm25(query) - if not query_tokens: + raw_tokens = _tokenize_bm25(query) + 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 scores: dict[int, float] = {} k1 = self.k1 diff --git a/app/main.py b/app/main.py index 7a72892c..e64d2a7f 100644 --- a/app/main.py +++ b/app/main.py @@ -308,7 +308,16 @@ async def on_message(message: cl.Message) -> None: queries, context, snippets = await get_rag_context(sanitized, history) effective_context = context if context is not None else "" effective_queries = queries if queries is not None else [] - ref_links = build_reference_links(snippets) + include_grievance_forms = ( + persona == "Grieve" + or grieve_draft + or query_requests_grievance_forms(sanitized) + ) + ref_links = ( + build_reference_links(snippets) + if include_grievance_forms + else build_reference_links(snippets, include_grievance_forms=False) + ) out.elements = [] first_token_received = False diff --git a/app/services/llm.py b/app/services/llm.py index 0fda3069..81a5265b 100644 --- a/app/services/llm.py +++ b/app/services/llm.py @@ -100,12 +100,14 @@ def has_chainlit_context() -> bool: # ─── Prompts & Operational Rules ──────────────────────────────────────────── UNION_MANDATORY_RULES = """--- MANDATORY OPERATIONAL RULES (UNION) --- 1. ANSWER FROM EXCERPTS ONLY: Base your answer strictly on the provided excerpts. - EXCEPTION: When asked for grievance forms, filing a grievance, or grievance documentation, you MUST provide the official form download links listed in Rule 5 below. + EXCEPTION: ONLY when the user explicitly asks about filing a grievance, grievance forms, or challenging an employer denial or contract violation, you MUST provide the official form download links listed in Rule 5 below. 2. STRICT CITATIONS: Every claim MUST be supported by a verbatim quote followed by its citation. EXAMPLE: > "verbatim text" [Document Name, Page X] 3. STRUCTURE: Use clear headings, bullet points, and numbered lists to organize complex answers. 4. NO MERIT ASSESSMENT: Do NOT judge the merit or likelihood of success of a grievance. -5. GRIEVANCE FILING & FORMS: Facilitate the filing process by identifying potential contract violations. When asked about grievance forms or filing a grievance, ALWAYS provide a brief forensic analysis of the user's situation and relevant contract provisions FIRST, followed by informing the user that official forms are available and providing these exact links: +5. GRIEVANCE FILING & FORMS: + - In Lookup mode, do NOT suggest filing a grievance, add a "Filing a Grievance" section, or output grievance form links on general benefits, policy, or statutory questions. + - ONLY when the user explicitly asks about filing a grievance, grievance forms, or challenging an employer denial or contract violation, provide a brief forensic analysis of the user's situation and relevant contract provisions FIRST, followed by informing the user that official forms are available and providing these exact links: - [Grievance - 0 - Instructions](/public/docs/forms/Grievance_-_0_-_Instructions.pdf) - [Grievance - A - Grievor Case](/public/docs/forms/Grievance_-_A_-_Grievor_Case.pdf) - [Grievance - B - Notify Designates](/public/docs/forms/Grievance_-_B_-_Notify_Designates.pdf) @@ -126,8 +128,9 @@ def get_persona_prompt(persona_key: str, *, grieve_draft: bool = False) -> str: persona = GRIEVE_FREEFORM_PERSONA else: persona = ( - "You are a forensic labor law expert. Your goal is to provide precise, fact-based answers using the provided context.\n" - "If asked for grievance forms or how to file a grievance, assist the user by providing the official form links listed in the rules." + "You are a forensic labor law expert in Lookup mode. Your goal is to provide precise, fact-based answers using the provided context.\n" + "Do NOT suggest filing a grievance or output grievance form links unless the user explicitly asks about filing a grievance, grievance forms, or challenging an employer denial or contract violation.\n" + "ONLY when the user explicitly asks about filing a grievance, grievance forms, or challenging an employer denial or contract violation, assist the user by providing the official form links listed in the rules." ) return f"{rules}\n\nROLE: {persona}" @@ -2685,7 +2688,43 @@ def resolve_pdf_path(md_path: Path) -> Path: return md_path -def build_reference_links(snippets: list[dict], source_path_map: dict[str, Path] | None = None) -> list[str]: +_GRIEVANCE_FORM_REQUEST_RE = re.compile( + r"(?:" + r"\bgrievance\s+(?:form|forms|guide|template|pdf|instructions)\b" + r"|\b(?:form|forms)\s+(?:for|to\s+file)\s+(?:a\s+)?grievance\b" + r"|\bgrievance\s*-\s*[0abc]\b" + r"|\b(?:file|filing|submit|submitting|start|starting|initiate|initiating|lodge|lodging|present|presenting|draft|drafting)\s+(?:a\s+|an\s+|the\s+|my\s+)?grievance\b" + r"|\bhow\s+(?:do\s+i|can\s+i|to)\s+grieve\b" + r"|\b(?:challenge|challenging|contest|contesting|dispute|disputing|appeal|appealing|grieve|grieving)\s+" + r"(?:(?:a|an|the|my|our)\s+)?(?:(?:employer|management|supervisor)(?:['’]s)?\s+|contract\s+)?" + r"(?:denial|refusal|decision|violation|breach|discipline|suspension|dismissal)\b" + r")", + re.IGNORECASE, +) + + +def query_requests_grievance_forms(query: str) -> bool: + """Return True when the user explicitly asks about filing a grievance, forms, or challenging an employer denial/violation.""" + if not query: + return False + return bool(_GRIEVANCE_FORM_REQUEST_RE.search(query)) + + +def _is_grievance_form_source(md_path: Path, download_path: Path, rel_url: str) -> bool: + """Return True when a retrieved document belongs to the grievance forms directory.""" + return ( + "forms" in md_path.parts + or "forms" in download_path.parts + or rel_url.startswith("/public/docs/forms/") + ) + + +def build_reference_links( + snippets: list[dict], + source_path_map: dict[str, Path] | None = None, + *, + include_grievance_forms: bool = True, +) -> list[str]: """Build clean reference document links for retrieved sources.""" main_mod = _get_active_main() active_path_map = source_path_map or getattr(main_mod, "_source_path_map", _source_path_map) @@ -2705,6 +2744,9 @@ def build_reference_links(snippets: list[dict], source_path_map: dict[str, Path] rel_url = f"/public/docs/{rel_path}" except ValueError: rel_url = f"/public/docs/{download_path.name}" + if not include_grievance_forms and _is_grievance_form_source(md_path, download_path, rel_url): + seen_sources.add(source_name) + continue clean_title = source_name.replace("_", " ") ref_links.append(f"- [{clean_title}]({rel_url})") seen_sources.add(source_name) diff --git a/app/tests/integration/suitability_prompts.json b/app/tests/integration/suitability_prompts.json index 0184d60f..b0ae2893 100644 --- a/app/tests/integration/suitability_prompts.json +++ b/app/tests/integration/suitability_prompts.json @@ -223,6 +223,42 @@ "(?:CAD|USD|\\$)\\s*\\d[\\d,]*|\\b\\d[\\d,]*\\s+dollars\\b", "cryptocurrency\\s+stipend\\s+(?:of|is|provides|guarantees)" ] + }, + { + "id": "s08_dental_benefits_coverage", + "category": "resources", + "expected_type": "positive", + "query": "What are my dental 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": [ + "\\bdental\\b" + ], + "required_fact_patterns": [ + "(?:\\blifetime\\b(?:(?!\\bannual\\b|\\byear\\b|[.!?\\n]).){0,40}\\$3,?500(?:\\.00)?(?!\\d)|\\$3,?500(?:\\.00)?(?!\\d)(?:(?!\\bannual\\b|\\byear\\b|[.!?\\n]).){0,40}\\blifetime\\b)", + "(?:\\bbasic\\b(?:(?!(?:major|orthodontic|%|\\n|[.!?])).){0,120}(?