File size: 3,002 Bytes
788074d
 
 
b8dee1d
63b0a52
9c32b8a
 
fc636ce
 
 
 
 
 
63b0a52
 
 
 
9c32b8a
 
 
 
 
fc636ce
63b0a52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788074d
fc636ce
 
 
63b0a52
fc636ce
9c32b8a
 
63b0a52
9c32b8a
 
 
 
 
 
 
 
 
 
63b0a52
 
 
 
 
 
 
 
 
9c32b8a
 
788074d
63b0a52
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
import streamlit as st
from langchain_groq import ChatGroq
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.tools import tool
from typing import TypedDict, Annotated, List, Optional
import json

# Configuration
class MedicalConfig:
    SYSTEM_PROMPT = """You are an AI clinical assistant. Follow these rules:
1. Analyze patient data using latest medical guidelines
2. Always check for drug interactions
3. Use structured actions when needed:
   - lab_order: Order lab tests
   - prescribe: Prescribe medication
4. Flag high-risk conditions immediately"""

    RED_FLAGS = {
        "symptoms": ["chest pain", "shortness of breath", "severe headache"],
        "vitals": {"temp": (38.5, "°C"), "hr": (120, "bpm"), "bp": ("180/120", "mmHg")}
    }

# Define tools with proper schemas
@tool
def order_lab_test(test_name: str, reason: str) -> str:
    """Orders a lab test with specified parameters.
    
    Args:
        test_name: Name of the lab test to order
        reason: Clinical justification for the test
        
    Returns:
        Confirmation message with test details
    """
    return f"Lab ordered: {test_name} ({reason})"

@tool
def prescribe_medication(name: str, dosage: str, frequency: str) -> str:
    """Prescribes medication with specific dosage instructions.
    
    Args:
        name: Name of the medication
        dosage: Dosage amount (e.g., '500mg')
        frequency: Administration frequency (e.g., 'every 6 hours')
        
    Returns:
        Confirmation message with prescription details
    """
    return f"Prescribed: {name} {dosage} {frequency}"

# Initialize tools
tools = [order_lab_test, prescribe_medication, TavilySearchResults(max_results=3)]

class MedicalAgent:
    def __init__(self):
        self.model = ChatGroq(temperature=0.1, model="Llama-3.3-70b-Specdec")
        self.model_with_tools = self.model.bind_tools(tools)

    def analyze_patient(self, patient_data: dict) -> Optional[dict]:
        try:
            response = self.model_with_tools.invoke([
                SystemMessage(content=MedicalConfig.SYSTEM_PROMPT),
                HumanMessage(content=f"Patient Data: {json.dumps(patient_data)}")
            ])
            return response
        except Exception as e:
            st.error(f"Error analyzing patient data: {str(e)}")
            return None

    def process_action(self, action: dict) -> str:
        try:
            tool_name = action['name']
            args = action['args']
            
            if tool_name == "order_lab_test":
                return order_lab_test.invoke(args)
            elif tool_name == "prescribe_medication":
                return prescribe_medication.invoke(args)
            else:
                return f"Unknown action: {tool_name}"
        except Exception as e:
            return f"Error processing action: {str(e)}"

# Rest of the Streamlit UI code remains the same...