Spaces:
Runtime error

File size: 4,021 Bytes
4adf7aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
"""Four LangChain tools for the MediBot ReAct agent."""
from langchain_core.tools import tool
from rag.retriever import (
    search_diseases as _search,
    get_disease_details as _details,
    get_severity_map,
    get_all_symptoms,
)
from config import TOP_K_RESULTS


@tool
def search_diseases(symptoms: str) -> str:
    """Search the medical database for diseases that match the given symptoms.
    Input should be a comma-separated list of symptoms (e.g. 'fever, headache, chills').
    Returns the top matching diseases with similarity scores."""
    results = _search(symptoms, k=TOP_K_RESULTS)
    if not results:
        return "No matching diseases found. Please provide more specific symptoms."
    lines = [f"Top {len(results)} disease matches for: '{symptoms}'\n"]
    for i, r in enumerate(results, 1):
        lines.append(f"{i}. {r['disease']} (relevance: {r['score']:.2f})")
    return "\n".join(lines)


@tool
def get_disease_details(disease_name: str) -> str:
    """Get detailed information about a specific disease including description,
    symptoms, precautions, and severity level. Input should be the disease name."""
    details = _details(disease_name)
    if not details:
        return f"Disease '{disease_name}' not found in the database."
    syms = ", ".join(details["symptoms"][:10])
    precs = "; ".join(details["precautions"]) if details["precautions"] else "Consult a doctor"
    desc = details["description"][:300] + "..." if len(details["description"]) > 300 else details["description"]
    return (
        f"**{details['disease']}**\n"
        f"Severity Level: {details['severity_label']} (score: {details['avg_severity']})\n\n"
        f"Description: {desc}\n\n"
        f"Common Symptoms: {syms}\n\n"
        f"Precautions: {precs}"
    )


@tool
def calculate_severity(symptoms: str) -> str:
    """Calculate the medical severity score for a list of symptoms based on clinical weights.
    Input should be a comma-separated list of symptoms.
    Returns a severity level: Mild, Moderate, Severe, or Critical."""
    sev_map = get_severity_map()
    symptom_list = [s.strip().lower().replace(" ", "_") for s in symptoms.split(",")]
    matched = []
    unmatched = []
    total = 0
    for sym in symptom_list:
        if sym in sev_map:
            w = sev_map[sym]
            matched.append(f"{sym} (weight: {w})")
            total += w
        elif sym:
            unmatched.append(sym)

    if not matched:
        return (
            f"None of the symptoms ({symptoms}) were found in the severity database. "
            "Try using underscore-separated symptom names (e.g. 'skin_rash' instead of 'skin rash')."
        )

    from config import SEVERITY_THRESHOLDS
    level = "Unknown"
    for label, (lo, hi) in SEVERITY_THRESHOLDS.items():
        if lo <= total < hi:
            level = label
            break

    result = f"Severity Assessment for: {', '.join(symptom_list)}\n"
    result += f"Total severity score: {total}\n"
    result += f"Severity Level: **{level}**\n\n"
    result += "Matched symptoms:\n" + "\n".join(f"  - {m}" for m in matched)
    if unmatched:
        result += f"\n\nUnrecognized symptoms (may be misspelled): {', '.join(unmatched)}"
    return result


@tool
def list_common_symptoms(category: str = "all") -> str:
    """List recognized medical symptoms from the database to help users identify what they have.
    Optionally filter by category keyword. Use 'all' to list everything."""
    symptoms = get_all_symptoms()
    if category.lower() != "all":
        symptoms = [s for s in symptoms if category.lower() in s]
    if not symptoms:
        return f"No symptoms found matching '{category}'."
    grouped = {}
    for sym in symptoms:
        key = sym[0].upper()
        grouped.setdefault(key, []).append(sym.replace("_", " "))
    lines = [f"Recognized symptoms ({len(symptoms)} total):\n"]
    for letter in sorted(grouped):
        lines.append(f"{letter}: {', '.join(grouped[letter])}")
    return "\n".join(lines)