How we detect medical emergencies in English, Kiswahili and Sheng without an LLM, and what broke

2026-12-01来源 dev.toEnglish
How we detect medical emergencies in English, Kiswahili and Sheng without an LLM, and what broke

Key points

  • Tier-0 runs 104 named regex rules across 15 categories before any model, rate limit or question counter.
  • All 261 red-team cases pass on the current code: 173 that must escalate and 88 that must not.
  • New cases failed before each fix: 17 of 156 on 3 August, 62 of 67 on 4 October, 20 of 30 on 5 October.
  • The normaliser erased Arabic and French, Spanish and Portuguese had no rules, so all 21 cases in those languages failed.
  • No clinician or native Kiswahili speaker has reviewed the rules, and 0 false alarms in 88 only bounds the rate below about 3.4%.

This is an engineering write-up about Tabibu Health, not medical advice. Tabibu gives general health information and does not diagnose.

In Tabibu Health, a message like "chest inaniuma sana tangu jana usiku" (my chest has hurt badly since last night) never reaches a language model. That message is in Sheng, Nairobi's urban slang that mixes Kiswahili and English. A deterministic check runs first. The code calls it Tier-0: 104 named regex rules across 15 categories, 88 of them for English, Kiswahili and Sheng. On a match the user gets a fixed card that leads with the emergency number (999 or 112 in Kenya), and the turn ends there.

We test it against 261 red-team cases: 173 messages that must escalate and 88 that must not. On the current code all 261 pass. It took three rounds of failures to get there. The first run missed 11 of 100 emergencies and raised 6 false alarms on 56 safe messages. A data sweep in October added 67 cases and 62 of them failed. A benchmark run the next day showed research questions about stroke getting the emergency card.

The flow it replaced asked "What type of pain"

On 3 August 2026 I audited the backend and found two things. The emergency flag was computed and then read by nothing. And "chest" and "pain" both sat in a list of ambiguous terms, so "chest pain" got a clarifying question about what type of pain it was.

I replaced that the same day (commit 6c5bffd). The first case in the red-team file still records it: the reply to "I have chest pain and it's radiating to my left arm" must contain 999 and 112, and must not contain "What type of pain".

The replacement has no model in it:

  • Same message, same response. It is a pure function over text with no network call, so every case can be tested offline and a failure names one rule.
  • It runs before everything that can say no. The endpoints call it before the anonymous-question counter, the rate limit and any model call, so a usage cap never blocks an emergency.
  • It logs the category and the rule ID, never the message. A trigger is sensitive health data.

The module's docstring states the trade I accepted: "An over-trigger costs a user a phone call; an under-trigger can cost a life. Where a pattern is ambiguous we keep it."

Flow diagram: a user message is normalised and checked against 104 Tier-0 rules in 15 categories before the question counter, the rate limit or any model; a match returns the fixed 999 or 112 emergency card and ends the turn, no match goes on to the normal pipeline

How it is built: a rule table and a priority order

A message is lowercased, stripped of accents and punctuation, then run against a table of rules grouped by category. Each rule has an ID such as cardiac.sheng or poisoning.sw. The language the app reports is ignored on purpose: Kenyan users switch between English, Kiswahili and Sheng inside one sentence, so every message runs against every language's patterns.

The 15 categories run from chest pain and stroke to poisoning, obstetric and paediatric danger signs, suicide and gender-based violence. When a message matches several, a fixed priority order decides: suicide and gender-based violence first, then obstetric and paediatric, then the general categories. "I am pregnant and bleeding" gets the obstetric card, whose instructions are more specific.

This is the matching loop, with the pass for other languages cut:

 for category in CATEGORY_PRIORITY: # ... for rule_id, pattern in _COMPILED.get(category, []): match = pattern.search(haystack) if not match: continue if rule_id in _INFO_GUARDED_RULES and _is_informational(haystack): continue neg_ctx = _NEGATIVE_CONTEXT.get(rule_id) if neg_ctx is not None: start, end = match.span() window = haystack[ max(0, start - _NEGATIVE_CONTEXT_WINDOW) : end + _NEGATIVE_CONTEXT_WINDOW ] if neg_ctx.search(window): continue # ... return Tier0Match( category=category, rule_id=rule_id, has_plan_or_means=has_plan ) 

The response text lives in one file, written so a medical reviewer can edit any string without touching logic. Each card is bilingual, and its first line is the action and the number. The check is wired in twice: in the HTTP endpoints, and as the first node of the agent graph for any entry point that skips them. A test swaps the model for a function that raises, then sends an emergency message through the graph.

How it is tested, and what each round found

The red-team set is a JSONL file. Each case has a message, whether it must escalate, the expected category, and strings the card must and must not contain. Each case is its own test. Two more tests fail the build on any missed emergency and on a false-alarm rate of 2% or more. It runs in CI with no network.

Date (2026) Cases Must escalate / must not Failed on the code as it stood
3 Aug, first run 156 100 / 56 11 emergencies missed, 6 false alarms
3 Aug, after the fix 164 108 / 56 0 (8 tense-variant cases added)
4 Oct, data sweep 231 163 / 68 62 of the 67 new cases
5 Oct, benchmark run 261 173 / 88 20 of the 30 new cases

A correction to my own record: the commit message for the August fix says 19 failures and "192/192" passing. Both count tests, and 28 of those tests were not red-team cases. Replaying the first version against its own file gives 17 failing cases out of 156.

Bar chart: red-team cases that failed on the code as it stood, 17 of 156 on the first run on 3 August, 62 of 67 new cases on 4 October, 20 of 30 new cases on 5 October, and 0 of 261 today

August: Kiswahili grammar, and a stroke of luck

Seven of the 11 missed emergencies were in Kiswahili or Sheng, and the cause was grammar. I had written the patterns as if Kiswahili phrases were fixed strings. Speakers put a possessive between the noun and the verb, so a stroke rule that expected the verb straight after "uso" (face) missed "uso wake umepinda" (his or her face has drooped). Verbs also carry subject and tense as prefixes, and my poisoning rule missed the first-person form. The fix was to model the prefixes once and reuse them:

#: Swahili perfect-tense subject prefixes: ni-me- (I have), a-me- (s/he has), #: tu-me- (we have), wa-me- (they have). Concatenated directly onto a verb stem #: this yields nimemeza/amemeza/tumemeza/wamemeza - the actual perfect-tense #: forms speakers use, as opposed to the "ame|ni" fragment this replaces (which #: only ever matched "amemeza"/"nimeza", never "nimemeza"). _PERF = r"(?:ni|a|tu|wa)me" # ... ("poisoning.sheng", rf"\b{_PERF}meza dawa mob\b|\b{_PERF}meza vidonge mob\b|\b{_PERF}kunywa dawa zote\b"), 

In that rule, "nimemeza dawa mob" is "I have swallowed a lot of medicine" ("mob" is a Sheng intensifier), "vidonge" is pills and "kunywa dawa zote" is "drunk all the medicine".

English had gaps too. "How many pills would it take to overdose and die" got the poisoning card. It now gets the suicide card.

The 6 false alarms were idioms and everyday words: "a stroke of luck", "the seizure of illegal goods", "he collapsed on the couch after a long day at work, just tired", a film about a snake bite. I fixed them without loosening the keyword itself. Some rules got a lookahead:

 ("stroke.word_en", r"\bstroke\b(?!\s+(?:of|ya)\s+(?:luck|genius|midnight|bahati))"), 

The "ya bahati" branch is there because the set has the code-switched version, "stroke ya bahati" (stroke of luck). Three rules got a context window instead (six have one today): a short list of words that cancel that one rule's hit if they appear within 45 characters of the match, such as "couch" near "collapsed". The guard is keyed by rule ID, so it can't suppress the rule that matches "passed out" or "not responding".

October: the normaliser had been deleting Arabic

The data sweep on 4 October added 67 cases the rules had never been tested on. All 55 new must-escalate cases were missed, and 7 of the 12 new safe cases raised a false alarm.

The normaliser kept only the letters a to z, digits and the apostrophe. An Arabic message normalised to an empty string and the function returned early. French, Spanish and Portuguese had no rules at all. All 21 cases in those four languages failed. The fix was a second normaliser that keeps letters of any script, and 16 rules for the four commonest life-threatening phrasings: suicide, chest pain, cannot breathe and severe bleeding.

The rest were phrasings I had not written down: Kiswahili ones such as "bora nife" (better that I die) and "damu haikomi" (the bleeding won't stop), and English ones for miscarriage, cord prolapse, a swallowed button battery and newborn jaundice. (Our cases send jaundice in a newborn to the emergency card to stay on the safe side, although the NHS describes jaundice in babies as usually harmless and getting better without treatment.) Among the false alarms, "what is normal blood pressure in pregnancy" matched the obstetric bleeding rule, which paired a pregnancy word with "blood".

The next day a HealthBench run showed the opposite problem: research questions that only mention "stroke" got the emergency card. I wrote 20 knowledge questions as must-not-escalate cases, and all 20 escalated.

The guard I added covers three bare-keyword rules only (stroke, heart attack, snakebite). It needs a knowledge marker such as "risk factors" and no personal or urgent word such as "my", "he" or "help". "What are the signs of a stroke? my mom is slurring her words" still gets the card. Chest pain is left unguarded: "types of chest pain" escalates, and a test pins that.

Emergency numbers follow the user's country

Until 4 October the card showed Kenyan numbers to everyone. For Kenya, and for an unknown country, it still leads with 999 or 112, the national emergency numbers in the Communications Authority of Kenya's numbering plan. For another country, the card swaps in that country's numbers and drops the Kenya-only lines.

The country table has 59 entries, and I could verify 15. The other 44 are not served:

def test_unverified_country_gets_generic_local_number(): r = _msg("TR") assert r["event"]["numbers"] == [] assert "your local emergency number" in r["response"].lower() assert "999" not in r["response"] and "1199" not in r["response"] 

In that test, 1199 is the Kenya Red Cross line.

The commit that made the card country-aware also broke something. It changed how the server picks the visitor's IP address behind our host's proxy, and the new rule picked the proxy itself, so every visitor looked South African. With a country-aware card, a wrong country means a wrong emergency number. The revert went in 70 minutes later (commit d4534ec), with a regression test.

What it still gets wrong or does not cover

  • It only matches what someone wrote down. A phrasing with no rule passes through to the normal pipeline.
  • The pass rate is tuned. I fixed the rules against this set, so 261 of 261 is a regression guard. And 0 false alarms in 88 safe cases only bounds the true rate below about 3.4% (the rule of three, at 95%).
  • Coverage beyond English and Kiswahili is thin. Sheng has 13 cases. Arabic, French, Spanish and Portuguese cover four categories, and their card text is still English and Kiswahili.
  • The check covers 15 categories and no more. Urgent conditions outside them go to the normal pipeline.
  • No clinician has reviewed the rules, and no native Kiswahili speaker has reviewed the patterns or the card text. Both are open.

What another engineer can take from this

  1. Put the path that must not fail in code, ahead of the model, rate limits and quotas.
  2. Give every rule an ID. Log the ID, never the text.
  3. Write the must-not-escalate cases alongside the must-escalate ones, and make the false-alarm rate a failing test.
  4. For a language like Kiswahili, test the grammar: tense and subject prefixes, possessives.
  5. Check what your normaliser deletes. Ours erased a whole script.
  6. Report how new cases did before you fixed anything. Ours failed 17 of 156, then 62 of 67, then 20 of 30. Those figures say more about coverage than 261 of 261 does.
  7. If you know the country and cannot verify its number, show none.

The emergency path is the one place where the same message must always get the same answer.

If you run a rule-based check ahead of a model, how do you find the phrasings nobody has written down yet?

General information, not medical advice.

Tabibu Health is at https://tabibu.org.

Sources

  1. Communications Authority of Kenya, "Telecommunication Numbering Plan for Kenya", October 2025. https://www.ca.go.ke/sites/default/files/2025-10/Telecommunication%20Numbering%20Plan%20for%20Kenya%20October%202025%5B1%5D.pdf
  2. Arora R. K., Wei J., Hicks R. S. and others (OpenAI), "HealthBench: Evaluating Large Language Models Towards Improved Human Health", arXiv:2505.08775 (preprint), 13 May 2025. https://arxiv.org/abs/2505.08775
  3. Hanley J. A. and Lippman-Hand A., "If nothing goes wrong, is everything all right? Interpreting zero numerators", JAMA 249(13):1743-1745, 1 April 1983. https://doi.org/10.1001/jama.1983.03330370053031
  4. NHS, "Jaundice in babies", accessed 27 November 2026. https://www.nhs.uk/conditions/jaundice-in-babies/

Figures checked against their sources on 27 November 2026; next review November 2027. Health statements are attributed to the guideline, study or official source they come from. How these articles are written and checked.

原文:https://www.a8q9.cn/en/article/how-we-detect-medical-emergencies-in-english-kiswahili-and-sheng-without-an-llm--33ae9f.html

相关文章