Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 51 additions & 19 deletions .github/scripts/eval_test_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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)"
),
}


Expand Down Expand Up @@ -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",
),
]


Expand Down Expand Up @@ -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(
Expand Down
21 changes: 18 additions & 3 deletions app/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 47 additions & 5 deletions app/services/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Comment thread
DerekRoberts marked this conversation as resolved.
Resolved
- 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)
Expand All @@ -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}"
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions app/tests/integration/suitability_prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}(?<!\\d)100%|(?<!\\d)100%(?:(?!(?:major|orthodontic|%|\\n|[.!?])).){0,40}\\bbasic\\b)",
"(?:\\bmajor\\b(?:(?!(?:basic|orthodontic|%|\\n|[.!?])).){0,120}(?<!\\d)65%|(?<!\\d)65%(?:(?!(?:basic|orthodontic|%|\\n|[.!?])).){0,40}\\bmajor\\b)",
"(?:\\borthodontic(?:s)?\\b(?:(?!(?:basic|major|%|\\n|[.!?])).){0,120}(?<!\\d)55%|(?<!\\d)55%(?:(?!(?:basic|major|%|\\n|[.!?])).){0,40}\\borthodontic(?:s)?\\b)"
],
"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"
],
"oracle_terms": [
"Dental benefits at a glance",
"Basic services",
"Major services",
"Orthodontic services",
"$3,500"
]
}
]
}
74 changes: 74 additions & 0 deletions app/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,77 @@ def test_search_index_batch_per_query_top_ks_and_empty_inputs(monkeypatch):
assert [len(r) for r in batch_res] == [2, 1]
assert batch_res[0][0] == chunks[1]
assert batch_res[1][0] == chunks[3]


def test_bm25_search_filters_conversational_stopwords():
"""Conversational stopwords must not outrank domain terms in BM25 search."""
texts = [
"what are my social media guidelines when i post online",
"what are my work hours",
"dental benefits coverage table",
"general collective agreement provisions",
"unrelated policy document",
]
bm25 = indexing._BM25Index(texts)
# Without stopword filtering, high-IDF 'social'/'media' filler shares 'what'/'are'/'my'
# and can compete; with stopword filtering, only 'dental' and 'benefits' match doc 2.
hits = bm25.search("What are my dental benefits?", top_k=5)
assert hits == [2]


def test_bm25_search_preserves_section_marker_and_stopword_fallback():
"""Stopword filtering must preserve 's' in 's. 21' and fall back when all tokens are stopwords."""
texts = [
"employer general duties under s. 21 of the Act",
"section 210 unrelated reference",
"what is it about",
]
bm25 = indexing._BM25Index(texts)
# 's' is preserved so 's. 21' matches doc 0 specifically
assert bm25.search("What does s. 21 require?", top_k=2)[0] == 0
# Query consisting solely of stopwords falls back to unfiltered tokens instead of returning []
assert bm25.search("what is it", top_k=2) == [2]


def test_search_index_distant_tier1_does_not_beat_rank1_tier3(monkeypatch):
"""A Tier 1 chunk ranked #4-#31 in FAISS must not beat a #1 Tier 3 benefits/statutory chunk."""
chunks = [
{
"text": "dental coverage summary",
"source": "BC Bargaining Unit Health and Dental Benefits",
"path": "03_resources/BC_Bargaining_Unit_Health_and_Dental_Benefits.md",
"chunk_index": 0,
}
]
for i in range(1, 31):
is_tier2 = i in (1, 2)
chunks.append(
{
"text": f"unrelated clause {i}",
"source": "Nexus Test and Off-Duty Conduct" if is_tier2 else "BCGEU 20th Main Agreement",
"path": (
"04_jurisprudence/Nexus_Test_and_Off-Duty_Conduct.md"
if is_tier2
else "01_primary/BCGEU_20th_Main_Agreement.md"
),
"chunk_index": i,
}
)

q = np.zeros((1, indexing.EMBED_DIM), dtype=np.float32)
q[0, 0] = 1.0

vecs = np.zeros((len(chunks), indexing.EMBED_DIM), dtype=np.float32)
# Chunk 0 (Tier 3) is closest to query; chunks 1..30 descend in cosine similarity.
for idx in range(len(chunks)):
sim = 0.98 - idx * 0.01
vecs[idx, 0] = sim
vecs[idx, 1] = np.sqrt(1.0 - sim**2)

monkeypatch.setattr(indexing, "embed_texts", _make_embed_fn(vecs))
index = indexing.build_index(chunks)
monkeypatch.setattr(indexing, "embed_texts", lambda _texts: q.copy())

results = indexing.search_index(index, chunks, "xyzzy", top_k=5)
assert results[0] == chunks[0]

Loading
Loading