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
27 changes: 27 additions & 0 deletions .github/scripts/eval_test_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
),
}


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


Expand Down
36 changes: 34 additions & 2 deletions app/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand All @@ -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] = {}
Expand All @@ -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
Expand Down
67 changes: 65 additions & 2 deletions app/services/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand All @@ -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)
Comment thread
DerekRoberts marked this conversation as resolved.
Resolved
Comment thread
DerekRoberts marked this conversation as resolved.
Resolved
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,
Expand Down
33 changes: 33 additions & 0 deletions app/tests/integration/suitability_prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}(?:(?<!\\bnot\\s)(?<!\\bno\\s)\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|(?:/\\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|\\$2,?000|[.!?;\\n])).){0,40}(?<!\\bnot\\s)(?<!\\bno\\s)\\$500(?:\\.00)?(?!\\d))|(?:(?<!\\bnot\\s)(?<!\\bno\\s)\\$500(?:\\.00)?(?!\\d)(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|\\$2,?000|[.!?;\\n])).){0,40}(?:/\\s*(?:calendar\\s+)?year|\\b(?:a|per)\\s+(?:calendar\\s+)?year\\b|\\bannual(?:ly)?\\b)|(?:/\\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|\\$2,?000|[.!?;\\n])).){0,40}(?<!\\bnot\\s)(?<!\\bno\\s)\\$500(?:\\.00)?(?!\\d))(?:(?!(?:\\b(?:acupunctur|massage|naturopath|physiotherap|podiatr|orthotic|counselling)\\w*\\b|[.!?;\\n])).){0,100}\\bchiropract(?:ic|or)s?\\b)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 The Roast: The required-fact regex can find $500 plus an annual qualifier and chiropractic in the same generous window without ever establishing that the amount is per person. So a response can claim a $500 annual maximum, then say the family shares it just beyond the separate 40-character family tripwire—and the gate mistakes household math for a personal benefit.

🩹 The Fix: Require an explicit per-person association in the required pattern (in either amount/qualifier order), and add a negative case where the family-wide qualifier is farther than 40 characters from $500.

📏 Severity: warning

],
"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?\\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}(?<!\\bnot\\s)(?<!\\bno\\s)\\$2,?000(?:\\.00)?(?!\\d)|\\b(?:is|are)\\s+(?:reimbursed\\s+at|capped\\s+at|limited\\s+to|up\\s+to)\\s+(?:(?!(?:\\b(?:not|no)\\b|[.!?;\\n])).){0,25}(?<!\\bnot\\s)(?<!\\bno\\s)\\$2,?000(?:\\.00)?(?!\\d))|(?<!\\bnot\\s)(?<!\\bno\\s)\\$2,?000(?:\\.00)?(?!\\d)(?:(?!(?:\\b(?:not|no|general\\s+(?:coinsurance|extended\\s+health))\\b|[.!?;\\n])).){0,60}(?:\\b(?:cap|limit|maximum|max)\\b(?:(?!(?:\\b(?:not|no)\\b|[.!?;\\n])).){0,30}\\bchiropract(?:ic|or)s?\\b|\\b(?:is|are)\\s+the\\s+chiropract(?:ic|or)\\s+(?:cap|limit|maximum|max)\\b|\\bfor\\s+chiropract(?:ic|or)s?\\b))",
"(?:\\$500(?:\\.00)?(?!\\d)(?:(?![.!?;\\n]).){0,40}\\b(?:entire\\s+|combined\\s+)?family\\b|\\b(?:entire\\s+|combined\\s+)?family\\b(?:(?![.!?;\\n]).){0,40}\\$500(?:\\.00)?(?!\\d))"
],
"oracle_terms": [
"Chiropractor",
"Chiropractic treatments",
"$500/year/person"
]
}
]
}
53 changes: 53 additions & 0 deletions app/tests/test_condense_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,56 @@ 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 are stripped while substantive context remains."""
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]. "
"The recommended practitioner is [chiropractor]. "
"See [BC Bargaining Unit Health and Dental Benefits](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md) "
"or consult a [licensed chiropractor](/public/docs/BC_Bargaining_Unit_Health_and_Dental_Benefits.md) or "
"submit via [My Canada Life at Work](https://my.canadalife.com/sign-in). "
+ ("Details about annual claims. " * 60)
+ "FINAL RECOMMENDATION: confirm the $500 chiropractic annual limit."
+ "\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 "BC Bargaining Unit Health and Dental Benefits" not in prompt
assert "licensed chiropractor" in prompt
assert "[chiropractor]" in prompt
assert "https://my.canadalife.com/sign-in" not in prompt
assert "My Canada Life at Work" in prompt
assert "FINAL RECOMMENDATION: confirm the $500 chiropractic annual limit." in prompt
assert "Do not copy document titles" in prompt
assistant_line = next(line for line in prompt.splitlines() if line.startswith("Assistant: "))
from services import llm as llm_service
assert len(assistant_line) <= len("Assistant: ") + llm_service._CONDENSE_ASSISTANT_MAX_CHARS

55 changes: 55 additions & 0 deletions app/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,58 @@ 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, labour nouns, and short legal tokens remain distinct
assert indexing._normalize_bm25_token("contractor") == "contractor"
assert indexing._normalize_bm25_token("contract") == "contract"
assert indexing._normalize_bm25_token("employer") == "employer"
assert indexing._normalize_bm25_token("employ") == "employ"
assert indexing._normalize_bm25_token("labor") == "labor"
assert indexing._normalize_bm25_token("laboratory") == "laboratory"
assert indexing._normalize_bm25_token("motor") == "motor"
assert indexing._normalize_bm25_token("motorist") == "motorist"
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


Loading