drAIML / tests /test_core.py
Gregory-L's picture
Bonsai in this browser: drAIML Agreement, browseML engine (bankML on WebAssembly), evidence notes, bankML receipts; cross-origin isolation for threads
23d27dd verified
Raw History Blame Contribute Delete
7.7 kB
import asyncio
import json
from pathlib import Path
import pytest
from draiml import catalogue, consult, engines, licences, net, rag, safety
ROOT = Path(__file__).resolve().parents[1]
# ── licence gate ──
@pytest.mark.parametrize("lic,kind,ok", [
("apache-2.0", "model", True), ("mit", "model", True), ("gpl-3.0", "model", True),
("other", "model", False), ("llama3", "model", False), ("gemma", "model", False), (None, "model", False),
("cc-by-4.0", "model", False), ("cc-by-4.0", "dataset", True), ("cc0-1.0", "dataset", True),
("cc-by-nc-4.0", "dataset", False), ("cc", "dataset", False), ("unknown", "dataset", False),
])
def test_gate(lic, kind, ok):
assert licences.is_open(lic, kind) is ok
def test_licence_of_tags_and_lists():
assert licences.licence_of({"tags": ["license:MIT"]}) == "mit"
assert licences.licence_of({"cardData": {"license": ["apache-2.0"]}}) == "apache-2.0"
assert not licences.is_open(licences.licence_of({"cardData": {"license": ["mit", "other"]}}), "model")
def test_curated_catalogue_is_all_open():
cat = json.loads((ROOT / "app/data/catalogue.json").read_text())
ids = {m["id"] for m in cat["models"]}
assert "google/medgemma-4b-it" not in ids and "aaditya/Llama3-OpenBioLLM-8B" not in ids
assert "FreedomIntelligence/HuatuoGPT-o1-8B" not in ids # apache card over a Llama-3.1 base
for m in cat["models"]:
assert licences.is_open(m["licence"], "model"), m["id"]
for d in cat["datasets"]:
assert licences.is_open(d["licence"], "dataset"), d["id"]
for mid in cat["router_open"]:
assert mid not in cat["router_closed"]
def test_unsuited_filter():
assert catalogue.UNSUITED.search("Qwen/Qwen3-Coder-480B-A35B-Instruct")
assert catalogue.UNSUITED.search("dphn/Dolphin-Mistral-24B-Venice-Edition")
assert not catalogue.UNSUITED.search("openai/gpt-oss-120b")
# ── triage ──
@pytest.mark.parametrize("text,cat", [
("crushing chest pain radiating to my left arm", "cardiac"),
("she suddenly can't speak and her face is drooping", "stroke"),
("I can't breathe and my lips are turning blue", "breathing"),
("I took an overdose of paracetamol", "poisoning"),
("I want to die", "mental health"),
("my baby is not breathing", "obstetric"),
])
def test_triage_positive(text, cat):
t = safety.triage(text)
assert t.emergency and cat in t.categories
@pytest.mark.parametrize("text", ["what is a normal blood pressure", "severe acne treatment options",
"is it urgent to get a flu shot", "how much vitamin D per day"])
def test_triage_negative(text):
assert not safety.triage(text).emergency
def test_validation_runs_without_disk(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
r = safety.validate("Likely a tension headache. Rest, fluids; see a doctor if it worsens.", "headache")
assert "overall_score" in r and r["risk"]["level"] == "low"
assert not any(tmp_path.iterdir()) # v1 wrote ./memory/logs; 2.0 must not
# ── retrieval ──
PASSAGES = {"sources": [{"repo": "x/a", "licence": "mit", "count": 3}],
"passages": [["Nitrofurantoin is a safe antibiotic for cystitis in pregnancy.", 0, "a:1", ""],
["Metformin is first-line therapy for type 2 diabetes.", 0, "a:2", ""],
["Aspirin and nitroglycerin for suspected myocardial infarction.", 0, "a:3", ""]]}
def test_bm25_ranks_and_cites():
idx = rag.EvidenceIndex(PASSAGES)
hits, method = asyncio.run(rag.search(idx, "antibiotic for bladder cystitis in pregnancy", 2))
assert method == "bm25" and hits[0].ref == "a:1" and hits[0].licence == "mit"
def test_bm25_arrays_roundtrip(tmp_path):
a = rag.bm25_arrays(PASSAGES["passages"])
rag.save_bm25(tmp_path / "b.npz", a)
idx = rag.EvidenceIndex(PASSAGES, bm25=rag.read_bm25(tmp_path / "b.npz"))
assert idx.bm25("metformin diabetes")[0][0] == 1
def test_rrf():
assert rag.rrf([[(1, 9), (2, 8)], [(2, 1), (3, 0.5)]])[0][0] == 2
def test_prepare_includes_evidence_and_triage():
idx = rag.EvidenceIndex(PASSAGES)
p = asyncio.run(consult.prepare("crushing chest pain, should I take aspirin?", [], idx, k=2))
assert p.triage.emergency and "TRIAGE ALERT" in p.messages[0]["content"]
assert "EVIDENCE" in p.messages[-1]["content"] and "[1]" in p.messages[-1]["content"]
# ── engines (mocked SSE) ──
def test_stream_chat_parses_reasoning_and_content(monkeypatch):
events = [json.dumps({"choices": [{"delta": {"reasoning_content": "think "}}]}),
json.dumps({"choices": [{"delta": {"content": "Hello"}}]}),
json.dumps({"choices": [{"delta": {"content": " world"}}]}), "[DONE]"]
async def fake_sse(url, payload, headers=None):
assert url.endswith("/chat/completions") and payload["stream"] is True
assert headers == {"Authorization": "Bearer k"}
for e in events:
yield e
monkeypatch.setattr(net, "post_sse", fake_sse)
r, a = asyncio.run(engines.complete(engines.ENDPOINTS["hf"], "openai/gpt-oss-120b", [], key="k"))
assert (r, a) == ("think", "Hello world")
def test_split_think():
assert engines.split_think("<think>hmm</think>Answer") == ("hmm", "Answer")
assert engines.split_think("plain") == ("", "plain")
def test_http_error_message():
e = net.HTTPError(402, '{"error":"Purchase pre-paid credits"}', "u")
assert "pre-paid credits" in e.message()
@pytest.mark.parametrize("mode,needle", [("physiotherapy", "PHYSIOTHERAPY"), ("psychotherapy", "PSYCHOTHERAPY")])
def test_modes_change_prompt(mode, needle):
idx = rag.EvidenceIndex(PASSAGES)
p = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1, mode=mode))
assert needle in p.messages[0]["content"]
g = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1))
assert needle not in g.messages[0]["content"]
# ── Bonsai in the browser (browseML) ──
def test_compact_prepare_is_short():
idx = rag.EvidenceIndex(PASSAGES)
hist = [{"role": "user", "content": f"q{i}"} for i in range(10)]
full = asyncio.run(consult.prepare("antibiotic for cystitis", hist, idx, k=6))
small = asyncio.run(consult.prepare("antibiotic for cystitis", hist, idx, k=6, compact=True))
assert len(small.hits) <= 2 and len(small.messages) == 1 + 2 + 1
assert small.messages[0]["content"].startswith("You are drAIML, a friendly") and "[1]" in small.messages[0]["content"]
assert small.messages[-1]["content"] == "antibiotic for cystitis"
assert len(small.messages[0]["content"]) < len(full.messages[0]["content"])
def test_bonsai_engine_uses_the_page_bridge(monkeypatch):
from draiml import bonsai
seen = {}
async def fake_stream(msgs, max_tokens, temperature):
seen.update(last=msgs[-1]["content"], max_tokens=max_tokens)
for kind, d in [("content", "<think>\n\n</think>"), ("content", "Rest"), ("content", " and fluids."),
("receipt", "✓ bankML receipt")]:
yield kind, d
monkeypatch.setattr(bonsai, "stream", fake_stream)
ep = engines.ENDPOINTS["bonsai"]
assert not ep.needs_key
r, a = asyncio.run(engines.complete(ep, bonsai.MODEL_ID, [{"role": "user", "content": "cold?"}], max_tokens=4096))
assert a == "Rest and fluids." and seen["last"].endswith("/no_think") and seen["max_tokens"] == 600
def test_bonsai_unavailable_outside_browser():
from draiml import bonsai
assert not bonsai.available()
assert asyncio.run(bonsai.status()) == {}
with pytest.raises(bonsai.BonsaiError):
asyncio.run(bonsai.ensure())