File size: 3,368 Bytes
18bfaa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import json
from pathlib import Path
from typing import Any, Dict, List


ROOT = Path(__file__).resolve().parents[1]
CASES_PATH = ROOT / "eval" / "real_symptom_queries.json"


def load_cases() -> List[Dict[str, Any]]:
    return json.loads(CASES_PATH.read_text(encoding="utf-8"))


def build_deterministic_app():
    from app import MedicalChatbotApp

    app = MedicalChatbotApp()
    # Keep evaluations stable by bypassing live planner calls during tests.
    app.router.llm_plan = lambda user_input, history, structured_context=None: app.router._fallback_plan(  # type: ignore[method-assign]
        user_input,
        structured_context,
    )
    # Preserve the engine's candidate generation but skip nondeterministic reranking.
    app.agents["disease_diagnosis"].reranker.rerank = (
        lambda user_symptoms, candidates, collapsed_df, top_k=5: candidates[:top_k]
    )
    return app


def _resolve_path(payload: Dict[str, Any], path: str) -> Any:
    current: Any = payload
    for part in path.split("."):
        if not isinstance(current, dict):
            return None
        current = current.get(part)
    return current


def evaluate_case(app, case: Dict[str, Any]) -> Dict[str, Any]:
    state = None
    history = []
    summary = ""
    card_html = ""

    # Some scenarios intentionally span multiple turns so session state can accumulate.
    for turn in case["turns"]:
        history, state, summary, card_html = app.chat(turn, state)

    checks = case.get("checks", {})
    failures: List[str] = []
    final_answer = history[-1]["content"] if history else ""

    for expected in checks.get("final_contains", []):
        if expected not in final_answer:
            failures.append(f"missing final text: {expected}")

    for path, expected in checks.get("state_equals", {}).items():
        actual = _resolve_path(state or {}, path)
        if actual != expected:
            failures.append(f"{path}: expected {expected!r}, got {actual!r}")

    for path, expected_values in checks.get("state_contains", {}).items():
        actual = _resolve_path(state or {}, path)
        if not isinstance(actual, list):
            failures.append(f"{path}: expected a list, got {type(actual).__name__}")
            continue
        for value in expected_values:
            if value not in actual:
                failures.append(f"{path}: missing {value!r}")

    return {
        "id": case["id"],
        "description": case.get("description", ""),
        "turns": case["turns"],
        "passed": not failures,
        "failures": failures,
        "final_answer": final_answer,
        "state": state,
        "summary": summary,
        "card_html": card_html,
    }


def format_results(results: List[Dict[str, Any]]) -> str:
    lines = []
    passed = 0
    for result in results:
        status = "PASS" if result["passed"] else "FAIL"
        if result["passed"]:
            passed += 1
        lines.append(f"[{status}] {result['id']}: {result['description']}")
        if not result["passed"]:
            for failure in result["failures"]:
                lines.append(f"  - {failure}")
        excerpt = result["final_answer"].strip().splitlines()
        if excerpt:
            lines.append(f"  answer: {excerpt[0]}")
    lines.append(f"\nPassed {passed}/{len(results)} real-query evaluations.")
    return "\n".join(lines)