Haseeb-001 commited on
Commit
65b8407
Β·
verified Β·
1 Parent(s): 146e3e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +203 -68
app.py CHANGED
@@ -1,86 +1,221 @@
1
- from langchain_google_genai import GoogleGenerativeAI
2
  import streamlit as st
 
 
 
 
 
 
3
 
4
- # --- LLM Initialization ---
5
- llm = GoogleGenerativeAI(
6
- model= "gemini-1.5-flash",
7
- google_api_key= GEMINI_API_KEY,
8
- temperature= 0.7,
9
- top_p= 0.85,
10
- max_tokens= 1024,
11
- stop_sequence = ["take your own life", "kill yourself", "hate you"]
12
- )
13
-
14
- # --- instruction ---
15
- instructions = "Answer the user's question politely and provide accurate information."
16
-
17
- # --- Context & Input Data ---
18
- context =(
19
- "You are DoctorX, an AI medical assistant. Follow these rules STRICTLY:"
20
- "1. Never diagnose - suggest POSSIBLE conditions"
21
- "2. Always recommend consulting a human doctor"
22
- "3. Prioritize patient safety over all else"
23
- "4. Maintain professional, empathetic tone"
24
- "5. Disclose your AI nature clearly"
25
- "6. For emergencies, direct to sidebar contacts"
26
- )
27
-
28
- input_data = (
29
- "Hospital Address:John Smith Hospital, 123 Health St."
30
- "Ambulance:911 (US) / 112 (EU)"
31
- "24/7 Support:+1-800-123-4567"
32
- )
33
-
34
- # --- Streamlit App ---
35
- def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  st.set_page_config(
37
- page_title="DoctorX",
38
- page_icon="🩺",
39
  layout="wide",
40
  initial_sidebar_state="expanded"
41
  )
42
 
43
- # Initialize session state for chat history
44
- if "history" not in st.session_state:
45
- st.session_state.history = []
46
-
47
- # Sidebar for emergency contacts
48
  with st.sidebar:
 
49
  st.header("🚨 Emergency Contacts")
50
- for key, value in input_data.items():
51
  st.subheader(key)
52
  st.caption(value)
53
  st.divider()
54
- st.caption("⚠️ This is not a substitute for emergency medical care.")
55
-
56
- # Main interface
57
- st.title("🩺 DoctorX")
58
- st.caption("AI-powered preliminary health guidance - Always consult a human doctor for final diagnosis.")
59
-
60
- # Display chat history
61
- for role, message in st.session_state.history:
62
- with st.chat_message(role):
63
- st.markdown(message)
64
-
65
- # User input
66
- user_query = st.text_input("Describe your symptoms or ask a question:", placeholder="e.g., I have a headache")
67
- if user_query:
68
- st.session_state.history.append(("user", user_query))
69
- with st.chat_message("bot"):
70
- with st.spinner("Analyzing your input..."):
71
- response = llm.invoke(user_query)
72
- st.markdown(response)
73
- st.session_state.history.append(("bot", response))
74
-
75
- # Quick response buttons
76
- common_queries = ["What are the symptoms of epilepsy?", "How to manage stress?"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  cols = st.columns(len(common_queries))
78
  for col, query in zip(cols, common_queries):
79
  if col.button(query):
80
- st.session_state.history.append(("user", query))
81
- response = llm.invoke(query)
82
- st.session_state.history.append(("bot", response))
83
- st.markdown(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  if __name__ == "__main__":
86
  main()
 
1
+ from groq import Groq
2
  import streamlit as st
3
+ import re
4
+ from datetime import datetime
5
+ # import os
6
+ from typing import Generator, List, Tuple, Optional
7
+ import logging
8
+ # from dotenv import load_dotenv
9
 
10
+ # --- Load Environment Variables ---
11
+ # load_dotenv()
12
+
13
+ # --- Logging Configuration ---
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # --- Constants ---
18
+ MODEL_CONFIG = {
19
+ "model": "meta-llama/llama-4-scout-17b-16e-instruct",
20
+ "temperature": 0.5,
21
+ "max_completion_tokens": 1024,
22
+ "stream": True,
23
+ "stop": None
24
+ }
25
+
26
+ EMERGENCY_CONTACTS = {
27
+ "Hospital Address": "John Smith Hospital, 123 Health St.",
28
+ "Ambulance": "911 (US) / 112 (EU)",
29
+ "24/7 Support": "+1-800-123-4567"
30
+ }
31
+
32
+ EMERGENCY_KEYWORDS = [
33
+ "emergency", "911", "112", "immediate help",
34
+ "severe pain", "cannot breathe", "chest pain",
35
+ "unconscious", "seizure", "stroke"
36
+ ]
37
+
38
+ SYSTEM_PROMPT = """You are DoctorX, a medical AI assistant. Follow these guidelines:
39
+ 1. Never diagnose - only suggest possible conditions
40
+ 2. Always recommend consulting a medical professional
41
+ 3. Prioritize patient safety and well-being
42
+ 4. Maintain professional yet empathetic tone
43
+ 5. Be clear about being an AI
44
+ 6. For emergencies, direct to emergency services
45
+
46
+ Format your responses as follows:
47
+ πŸ€– AI Assistant: [Your greeting]
48
+ πŸ’­ Understanding: [Brief interpretation of the query]
49
+ πŸ₯ Medical Context: [Relevant medical information]
50
+ πŸ“‹ Suggestions:
51
+ - [Point 1]
52
+ - [Point 2]
53
+ ⚠️ Important: Always consult a healthcare professional for proper diagnosis and treatment."""
54
+
55
+ # --- Security & Input Validation ---
56
+ def sanitize_input(text: str) -> str:
57
+ """Remove potentially harmful patterns from user input."""
58
+ if not text:
59
+ return ""
60
+ # Remove potential XSS and injection patterns
61
+ sanitized = re.sub(r"[<>{}[\]~`]", "", text[:2000])
62
+ return sanitized.strip()
63
+
64
+ def validate_response(response: str) -> bool:
65
+ """Validate AI response for safety concerns."""
66
+ blacklist = ["take your own life", "kill yourself", "hate you"]
67
+ return not any(phrase in response.lower() for phrase in blacklist)
68
+
69
+ def process_emergency(query: str) -> bool:
70
+ """Check if query indicates a medical emergency."""
71
+ return any(keyword in query.lower() for keyword in EMERGENCY_KEYWORDS)
72
+
73
+ def generate_medical_response(query: str, chat_history: List[Tuple[str, str]]) -> Generator[str, None, None]:
74
+ """
75
+ Generate a medical response using the LLM with streaming support.
76
+
77
+ Args:
78
+ query: The user's medical query
79
+ chat_history: List of previous interactions as (role, message) tuples
80
+
81
+ Yields:
82
+ Chunks of the generated response
83
+ """
84
+ try:
85
+ # Format chat history
86
+ history_messages = [
87
+ {"role": "user" if role == "user" else "assistant", "content": msg}
88
+ for role, msg in chat_history[-5:]
89
+ ]
90
+
91
+ # Construct messages with system prompt
92
+ messages = [
93
+ {"role": "system", "content": SYSTEM_PROMPT},
94
+ *history_messages,
95
+ {"role": "user", "content": query}
96
+ ]
97
+
98
+ # Generate streaming response
99
+ completion = client.chat.completions.create(
100
+ messages=messages,
101
+ **MODEL_CONFIG
102
+ )
103
+
104
+ # Process response chunks
105
+ for chunk in completion:
106
+ if chunk.choices[0].delta.content:
107
+ yield chunk.choices[0].delta.content
108
+
109
+ except Exception as e:
110
+ logger.error(f"Error generating response: {str(e)}")
111
+ yield "I apologize, but I encountered an error. Please try again or contact support."
112
+
113
+ # --- Main Application ---
114
+ def initialize_session_state() -> None:
115
+ """Initialize Streamlit session state variables."""
116
+ if "chat_history" not in st.session_state:
117
+ st.session_state.chat_history = []
118
+
119
+ def setup_page() -> None:
120
+ """Configure Streamlit page settings."""
121
  st.set_page_config(
122
+ page_title="DoctorX - Your AI Health Assistant",
123
+ page_icon="🧠",
124
  layout="wide",
125
  initial_sidebar_state="expanded"
126
  )
127
 
128
+ def render_sidebar() -> None:
129
+ """Render the sidebar with emergency information."""
 
 
 
130
  with st.sidebar:
131
+ st.image("https://img.icons8.com/color/96/000000/heart-health.png")
132
  st.header("🚨 Emergency Contacts")
133
+ for key, value in EMERGENCY_CONTACTS.items():
134
  st.subheader(key)
135
  st.caption(value)
136
  st.divider()
137
+ st.warning("⚠️ This is not a substitute for emergency medical care")
138
+
139
+ def handle_user_input(user_input: str) -> None:
140
+ """Process and respond to user input."""
141
+ cleaned_input = sanitize_input(user_input)
142
+
143
+ if process_emergency(cleaned_input):
144
+ st.error("🚨 This appears to be an emergency. Please contact emergency services immediately!")
145
+ st.info("See emergency contacts in the sidebar β†’")
146
+ return
147
+
148
+ st.session_state.chat_history.append(("user", cleaned_input))
149
+
150
+ with st.chat_message("assistant"):
151
+ response_placeholder = st.empty()
152
+ full_response = []
153
+
154
+ with st.spinner("πŸ€” Analyzing your query..."):
155
+ for response_chunk in generate_medical_response(cleaned_input, st.session_state.chat_history):
156
+ full_response.append(response_chunk)
157
+ response_placeholder.markdown("".join(full_response))
158
+
159
+ if validate_response("".join(full_response)):
160
+ st.session_state.chat_history.append(("assistant", "".join(full_response)))
161
+ else:
162
+ safe_response = "I apologize, but I cannot provide that information. Please consult a healthcare professional."
163
+ response_placeholder.markdown(safe_response)
164
+ st.session_state.chat_history.append(("assistant", safe_response))
165
+
166
+ def render_quick_access_buttons() -> None:
167
+ """Render quick access buttons for common health queries."""
168
+ st.divider()
169
+ st.subheader("πŸ“Œ Common Health Topics")
170
+
171
+ common_queries = [
172
+ "What are common symptoms of anxiety?",
173
+ "How to maintain good sleep hygiene?",
174
+ "When should I see a doctor about headaches?",
175
+ "Tips for managing stress",
176
+ "Understanding blood pressure readings"
177
+ ]
178
+
179
  cols = st.columns(len(common_queries))
180
  for col, query in zip(cols, common_queries):
181
  if col.button(query):
182
+ handle_user_input(query)
183
+
184
+ def main() -> None:
185
+ """Main application function."""
186
+ try:
187
+ setup_page()
188
+ initialize_session_state()
189
+ render_sidebar()
190
+
191
+ st.title("🧠 DoctorX")
192
+ st.caption("Preliminary health guidance - Always consult healthcare professionals")
193
+
194
+ # Display chat history
195
+ for role, message in st.session_state.chat_history:
196
+ with st.chat_message(role):
197
+ st.markdown(message)
198
+
199
+ # Handle user input
200
+ if user_input := st.chat_input("Type your health question here...", key="user_input"):
201
+ handle_user_input(user_input)
202
+
203
+ render_quick_access_buttons()
204
+
205
+ except Exception as e:
206
+ logger.error(f"Application error: {str(e)}")
207
+ st.error("An unexpected error occurred. Please refresh the page and try again.")
208
+
209
+ # --- LLM Initialization ---
210
+ try:
211
+ # client = Groq(api_key=os.getenv("GROQ_API_KEY"))
212
+ client = Groq(api_key=GROQ_API_KEY)
213
+ if not client:
214
+ raise ValueError("Failed to initialize Groq client. Please check your API key.")
215
+ except Exception as e:
216
+ logger.error(f"Error initializing Groq client: {str(e)}")
217
+ st.error("Failed to initialize AI model. Please check your API key.")
218
+ st.stop()
219
 
220
  if __name__ == "__main__":
221
  main()