IDAgents Developer commited on
Commit
1034e15
Β·
1 Parent(s): 99fb4db

Deploy memory-optimized version to fix JS heap error

Browse files

- Replace complex app with streamlined optimized version
- Reduced from 2323 lines to ~350 lines for memory efficiency
- Retained core multi-agent builder functionality
- Simplified UI with tabbed interface
- Graceful fallbacks for missing modules
- Should resolve HF Spaces memory limit issues
- Backup original complex app as app_original_complex.py

app.py CHANGED
The diff for this file is too large to render. See raw diff
 
app_backup_complex.py ADDED
The diff for this file is too large to render. See raw diff
 
app_fixed.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app_fixed.py
3
+ -----------
4
+
5
+ Simplified version of the ID Agents app with working Gradio authentication.
6
+ This version removes the complex custom authentication that was causing initialization failures.
7
+ """
8
+
9
+ # --- Imports ---
10
+ import gradio as gr
11
+ import json
12
+ import re
13
+ import os
14
+ import asyncio
15
+ import logging
16
+ from typing import Dict, Optional, Any, cast
17
+
18
+ # Try to import OpenAI
19
+ try:
20
+ import openai
21
+ from openai import RateLimitError, APIError, APIConnectionError, OpenAI
22
+ OPENAI_AVAILABLE = True
23
+ print("βœ… OpenAI client loaded")
24
+ except ImportError as e:
25
+ print(f"⚠️ OpenAI not available: {e}")
26
+ OPENAI_AVAILABLE = False
27
+
28
+ # Try to import core modules
29
+ try:
30
+ from orchestrator import AIOrchestrator
31
+ from llm_connector import LLMConnector
32
+ from rag import RAGRetriever
33
+ CORE_MODULES_AVAILABLE = True
34
+ print("βœ… Core modules loaded")
35
+ except ImportError as e:
36
+ print(f"⚠️ Core modules not available: {e}")
37
+ CORE_MODULES_AVAILABLE = False
38
+
39
+ # Set up logging
40
+ logging.basicConfig(level=logging.INFO)
41
+ logger = logging.getLogger(__name__)
42
+
43
+ # --- Global Variables ---
44
+ current_llm_connector = None
45
+ current_orchestrator = None
46
+ current_rag_retriever = None
47
+
48
+ # --- Helper Functions ---
49
+
50
+ def initialize_components():
51
+ """Initialize core components if available"""
52
+ global current_llm_connector, current_orchestrator, current_rag_retriever
53
+
54
+ if not CORE_MODULES_AVAILABLE:
55
+ return False
56
+
57
+ try:
58
+ # Initialize LLM Connector
59
+ current_llm_connector = LLMConnector()
60
+
61
+ # Initialize RAG Retriever
62
+ current_rag_retriever = RAGRetriever()
63
+
64
+ # Initialize Orchestrator
65
+ current_orchestrator = AIOrchestrator(current_llm_connector, current_rag_retriever)
66
+
67
+ print("βœ… All components initialized successfully")
68
+ return True
69
+ except Exception as e:
70
+ print(f"❌ Component initialization failed: {e}")
71
+ return False
72
+
73
+ def safe_chat_response(message: str, history: list) -> tuple:
74
+ """Safe chat response with fallback"""
75
+ if not CORE_MODULES_AVAILABLE or not current_orchestrator:
76
+ response = """
77
+ πŸ”§ **System Status**: Core modules are not fully available.
78
+
79
+ This is a demo version of ID Agents. In the full version, you would have access to:
80
+
81
+ β€’ **AI-Powered Clinical Assistance**: Advanced infectious disease consultation
82
+ β€’ **Multi-Agent Orchestration**: Coordinated responses from specialized agents
83
+ β€’ **Knowledge Base Integration**: Access to medical literature and guidelines
84
+ β€’ **Patient Scenario Analysis**: Context-aware clinical decision support
85
+
86
+ **Available Test Accounts:**
87
+ β€’ dr_smith / idweek2025 (ID Physician)
88
+ β€’ id_fellow / hello (ID Fellow)
89
+ β€’ pharmacist / stewardship (Clinical Pharmacist)
90
+ β€’ ipc_nurse / infection (IPC Coordinator)
91
+ β€’ researcher / research (Clinical Researcher)
92
+
93
+ Please contact the administrator for full access.
94
+ """
95
+ return response, history + [[message, response]]
96
+
97
+ try:
98
+ # Get response from orchestrator
99
+ response = current_orchestrator.process_query(message)
100
+
101
+ # Update history
102
+ updated_history = history + [[message, response]]
103
+
104
+ return response, updated_history
105
+
106
+ except Exception as e:
107
+ error_response = f"❌ Error processing your request: {str(e)}"
108
+ return error_response, history + [[message, error_response]]
109
+
110
+ def convert_messages_for_gradio(messages):
111
+ """Convert messages to Gradio 4.20.0 format"""
112
+ if not messages:
113
+ return []
114
+
115
+ converted = []
116
+ for msg in messages:
117
+ if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
118
+ if msg['role'] == 'user':
119
+ converted.append([msg['content'], None])
120
+ elif msg['role'] == 'assistant' and converted:
121
+ converted[-1][1] = msg['content']
122
+ elif msg['role'] == 'assistant':
123
+ converted.append([None, msg['content']])
124
+ elif isinstance(msg, list) and len(msg) == 2:
125
+ converted.append(msg)
126
+
127
+ return converted
128
+
129
+ # Patient loading functions (simplified)
130
+ def load_patient_1():
131
+ patient_data = {
132
+ "name": "Maria Santos",
133
+ "age": 67,
134
+ "gender": "Female",
135
+ "chief_complaint": "Fever and shortness of breath",
136
+ "history": "3 days of progressive fever (up to 101.8Β°F), productive cough with yellow sputum, and increasing shortness of breath...",
137
+ "vitals": "Temp: 101.8Β°F, HR: 110, BP: 145/85, RR: 22, O2 Sat: 89% on room air",
138
+ "presentation": "Elderly female with fever, productive cough, and hypoxemia concerning for pneumonia"
139
+ }
140
+
141
+ context_message = f"""
142
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
143
+
144
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
145
+ **Chief Complaint:** {patient_data['chief_complaint']}
146
+ **Current Vitals:** {patient_data['vitals']}
147
+
148
+ **Clinical Presentation:** {patient_data['presentation']}
149
+
150
+ How can I assist with this case?
151
+ """
152
+
153
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
154
+ return convert_messages_for_gradio([]), history
155
+
156
+ def load_patient_2():
157
+ patient_data = {
158
+ "name": "James Wilson",
159
+ "age": 34,
160
+ "gender": "Male",
161
+ "chief_complaint": "Painful urination and fever",
162
+ "presentation": "Young male with UTI symptoms and systemic signs of infection"
163
+ }
164
+
165
+ context_message = f"""
166
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
167
+
168
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
169
+ **Chief Complaint:** {patient_data['chief_complaint']}
170
+
171
+ **Clinical Presentation:** {patient_data['presentation']}
172
+
173
+ How can I assist with this case?
174
+ """
175
+
176
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
177
+ return convert_messages_for_gradio([]), history
178
+
179
+ def load_patient_3():
180
+ patient_data = {
181
+ "name": "Sarah Chen",
182
+ "age": 28,
183
+ "gender": "Female",
184
+ "chief_complaint": "Skin rash and joint pain",
185
+ "presentation": "Young female with systemic symptoms and dermatologic findings"
186
+ }
187
+
188
+ context_message = f"""
189
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
190
+
191
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
192
+ **Chief Complaint:** {patient_data['chief_complaint']}
193
+
194
+ **Clinical Presentation:** {patient_data['presentation']}
195
+
196
+ How can I assist with this case?
197
+ """
198
+
199
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
200
+ return convert_messages_for_gradio([]), history
201
+
202
+ def load_patient_4():
203
+ patient_data = {
204
+ "name": "Robert Martinez",
205
+ "age": 45,
206
+ "gender": "Male",
207
+ "chief_complaint": "Persistent cough and weight loss",
208
+ "presentation": "Middle-aged male with chronic respiratory symptoms and constitutional signs"
209
+ }
210
+
211
+ context_message = f"""
212
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
213
+
214
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
215
+ **Chief Complaint:** {patient_data['chief_complaint']}
216
+
217
+ **Clinical Presentation:** {patient_data['presentation']}
218
+
219
+ How can I assist with this case?
220
+ """
221
+
222
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
223
+ return convert_messages_for_gradio([]), history
224
+
225
+ def load_patient_5():
226
+ patient_data = {
227
+ "name": "Emma Thompson",
228
+ "age": 19,
229
+ "gender": "Female",
230
+ "chief_complaint": "Headache and neck stiffness",
231
+ "presentation": "Young female with meningeal signs requiring urgent evaluation"
232
+ }
233
+
234
+ context_message = f"""
235
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
236
+
237
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
238
+ **Chief Complaint:** {patient_data['chief_complaint']}
239
+
240
+ **Clinical Presentation:** {patient_data['presentation']}
241
+
242
+ How can I assist with this case?
243
+ """
244
+
245
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
246
+ return convert_messages_for_gradio([]), history
247
+
248
+ def load_patient_6():
249
+ patient_data = {
250
+ "name": "Michael Brown",
251
+ "age": 72,
252
+ "gender": "Male",
253
+ "chief_complaint": "Abdominal pain and diarrhea",
254
+ "presentation": "Elderly male with GI symptoms and potential infectious etiology"
255
+ }
256
+
257
+ context_message = f"""
258
+ πŸ₯ **Patient Case Loaded: {patient_data['name']}**
259
+
260
+ **Demographics:** {patient_data['age']}-year-old {patient_data['gender']}
261
+ **Chief Complaint:** {patient_data['chief_complaint']}
262
+
263
+ **Clinical Presentation:** {patient_data['presentation']}
264
+
265
+ How can I assist with this case?
266
+ """
267
+
268
+ history = [[f"Load patient case: {patient_data['name']}", context_message]]
269
+ return convert_messages_for_gradio([]), history
270
+
271
+ # --- Main UI Builder ---
272
+
273
+ def build_ui():
274
+ """Build the main Gradio interface"""
275
+
276
+ # Initialize components on startup
277
+ initialize_components()
278
+
279
+ # Custom CSS
280
+ css = """
281
+ :root {
282
+ --id-primary: #1e40af;
283
+ --id-secondary: #3b82f6;
284
+ --id-accent: #06d6a0;
285
+ --id-success: #059669;
286
+ --id-warning: #d97706;
287
+ --id-error: #dc2626;
288
+ --id-bg: #f8fafc;
289
+ --id-surface: #ffffff;
290
+ --id-text: #1e293b;
291
+ --id-text-muted: #64748b;
292
+ }
293
+
294
+ .gradio-container {
295
+ background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
296
+ min-height: 100vh;
297
+ }
298
+
299
+ .id-header {
300
+ background: linear-gradient(90deg, var(--id-primary), var(--id-secondary));
301
+ color: white;
302
+ padding: 1.5rem;
303
+ border-radius: 12px;
304
+ margin-bottom: 1.5rem;
305
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
306
+ }
307
+
308
+ .id-card {
309
+ background: var(--id-surface);
310
+ border-radius: 12px;
311
+ padding: 1.5rem;
312
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
313
+ border: 1px solid #e2e8f0;
314
+ }
315
+
316
+ .patient-card {
317
+ background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
318
+ border: 2px solid var(--id-secondary);
319
+ border-radius: 8px;
320
+ padding: 1rem;
321
+ margin: 0.5rem 0;
322
+ cursor: pointer;
323
+ transition: all 0.2s ease;
324
+ }
325
+
326
+ .patient-card:hover {
327
+ transform: translateY(-2px);
328
+ box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
329
+ }
330
+
331
+ .chat-container {
332
+ background: var(--id-surface);
333
+ border-radius: 12px;
334
+ border: 1px solid #e2e8f0;
335
+ }
336
+ """
337
+
338
+ with gr.Blocks(title="🦠 ID Agents - Infectious Disease AI", css=css, theme=gr.themes.Soft()) as app:
339
+
340
+ # Header
341
+ gr.HTML("""
342
+ <div class="id-header">
343
+ <h1 style="margin: 0; display: flex; align-items: center; gap: 12px;">
344
+ 🦠 <span>ID Agents</span>
345
+ <span style="font-size: 0.7em; background: rgba(255,255,255,0.2); padding: 4px 8px; border-radius: 6px;">BETA</span>
346
+ </h1>
347
+ <p style="margin: 8px 0 0 0; opacity: 0.9;">AI-Powered Infectious Disease Clinical Decision Support</p>
348
+ </div>
349
+ """)
350
+
351
+ with gr.Row():
352
+ # Left column - Chat interface
353
+ with gr.Column(scale=7):
354
+ with gr.Group(elem_classes="id-card"):
355
+ gr.Markdown("### πŸ’¬ Clinical Consultation Chat")
356
+
357
+ chatbot = gr.Chatbot(
358
+ value=[],
359
+ height=400,
360
+ elem_classes="chat-container",
361
+ show_label=False,
362
+ avatar_images=(None, "🦠")
363
+ )
364
+
365
+ with gr.Row():
366
+ msg_input = gr.Textbox(
367
+ placeholder="Ask about infectious diseases, patient cases, or clinical guidelines...",
368
+ show_label=False,
369
+ scale=4
370
+ )
371
+ submit_btn = gr.Button("Send", variant="primary", scale=1)
372
+
373
+ gr.Examples(
374
+ examples=[
375
+ "What are the current guidelines for treating MRSA pneumonia?",
376
+ "Help me interpret these blood culture results",
377
+ "What empirical antibiotics should I start for severe sepsis?",
378
+ "Explain the mechanism of carbapenem resistance",
379
+ "What's the latest on COVID-19 treatment protocols?"
380
+ ],
381
+ inputs=msg_input,
382
+ label="πŸ’‘ Example Queries"
383
+ )
384
+
385
+ # Right column - Tools and patient scenarios
386
+ with gr.Column(scale=3):
387
+ with gr.Group(elem_classes="id-card"):
388
+ gr.Markdown("### πŸ₯ Patient Scenarios")
389
+ gr.Markdown("*Click to load a clinical case*")
390
+
391
+ # Patient scenario buttons
392
+ with gr.Column():
393
+ patient1_btn = gr.Button("πŸ‘΅ Maria S. - Pneumonia (67F)", elem_classes="patient-card")
394
+ patient2_btn = gr.Button("πŸ‘¨ James W. - UTI/Sepsis (34M)", elem_classes="patient-card")
395
+ patient3_btn = gr.Button("πŸ‘© Sarah C. - Rash/Arthritis (28F)", elem_classes="patient-card")
396
+ patient4_btn = gr.Button("πŸ‘¨ Robert M. - Chronic Cough (45M)", elem_classes="patient-card")
397
+ patient5_btn = gr.Button("πŸ‘© Emma T. - Meningitis (19F)", elem_classes="patient-card")
398
+ patient6_btn = gr.Button("πŸ‘΄ Michael B. - GI Infection (72M)", elem_classes="patient-card")
399
+
400
+ with gr.Group(elem_classes="id-card"):
401
+ gr.Markdown("### πŸ”§ System Status")
402
+
403
+ if CORE_MODULES_AVAILABLE:
404
+ status_msg = "βœ… **Core modules loaded**\nβœ… **AI orchestrator active**\nβœ… **Knowledge base ready**"
405
+ else:
406
+ status_msg = "⚠️ **Limited functionality**\nπŸ”§ **Core modules unavailable**\nπŸ’‘ **Demo mode active**"
407
+
408
+ gr.Markdown(status_msg)
409
+
410
+ # Event handlers
411
+ def handle_submit(message, history):
412
+ if not message.strip():
413
+ return "", history
414
+
415
+ response, updated_history = safe_chat_response(message, history)
416
+ return "", updated_history
417
+
418
+ # Wire up the chat interface
419
+ submit_btn.click(
420
+ fn=handle_submit,
421
+ inputs=[msg_input, chatbot],
422
+ outputs=[msg_input, chatbot]
423
+ )
424
+
425
+ msg_input.submit(
426
+ fn=handle_submit,
427
+ inputs=[msg_input, chatbot],
428
+ outputs=[msg_input, chatbot]
429
+ )
430
+
431
+ # Wire up patient loading buttons
432
+ patient1_btn.click(fn=load_patient_1, outputs=[msg_input, chatbot])
433
+ patient2_btn.click(fn=load_patient_2, outputs=[msg_input, chatbot])
434
+ patient3_btn.click(fn=load_patient_3, outputs=[msg_input, chatbot])
435
+ patient4_btn.click(fn=load_patient_4, outputs=[msg_input, chatbot])
436
+ patient5_btn.click(fn=load_patient_5, outputs=[msg_input, chatbot])
437
+ patient6_btn.click(fn=load_patient_6, outputs=[msg_input, chatbot])
438
+
439
+ return app
440
+
441
+ # --- Main Application Entry Point ---
442
+
443
+ if __name__ == "__main__":
444
+ try:
445
+ print("πŸš€ Launching ID Agents with Beta Authentication...")
446
+
447
+ # Create main app
448
+ app = build_ui()
449
+
450
+ # Simple Gradio authentication credentials
451
+ auth_credentials = [
452
+ ("dr_smith", "idweek2025"),
453
+ ("id_fellow", "hello"),
454
+ ("pharmacist", "stewardship"),
455
+ ("ipc_nurse", "infection"),
456
+ ("researcher", "research"),
457
+ ("educator", "education"),
458
+ ("student", "learning"),
459
+ ("admin", "idagents2025"),
460
+ ("guest1", "guest123"),
461
+ ("guest2", "guest456")
462
+ ]
463
+
464
+ auth_message = """
465
+ 🦠 **ID Agents Beta Testing Access**
466
+
467
+ Welcome to the ID Agents beta testing environment!
468
+
469
+ **Available Test Accounts:**
470
+ β€’ **dr_smith** / idweek2025 (ID Physician)
471
+ β€’ **id_fellow** / hello (ID Fellow)
472
+ β€’ **pharmacist** / stewardship (Clinical Pharmacist)
473
+ β€’ **ipc_nurse** / infection (IPC Coordinator)
474
+ β€’ **researcher** / research (Clinical Researcher)
475
+ β€’ **educator** / education (Medical Educator)
476
+ β€’ **student** / learning (Medical Student - Limited Access)
477
+ β€’ **admin** / idagents2025 (Administrator)
478
+ β€’ **guest1** / guest123 (Guest Access - Limited)
479
+ β€’ **guest2** / guest456 (Guest Access - Limited)
480
+
481
+ Please use your assigned credentials to access the application.
482
+ Built with ❀️ for ID Week 2025 β€” Empowering Infectious Diseases Innovation
483
+ """
484
+
485
+ # Check if running on Hugging Face Spaces
486
+ try:
487
+ import os
488
+ if os.getenv("SPACE_ID"):
489
+ # Running on HF Spaces
490
+ launch_config = {
491
+ "auth": auth_credentials,
492
+ "auth_message": auth_message,
493
+ "show_error": True
494
+ }
495
+ print("πŸ” Authentication enabled for HF Spaces deployment")
496
+ else:
497
+ # Local development
498
+ launch_config = {
499
+ "auth": auth_credentials,
500
+ "auth_message": auth_message,
501
+ "share": False,
502
+ "server_name": "127.0.0.1",
503
+ "server_port": 7860,
504
+ "show_error": True
505
+ }
506
+ print("πŸ” Authentication enabled for local testing")
507
+ except Exception:
508
+ # Fallback configuration with authentication
509
+ launch_config = {
510
+ "auth": auth_credentials,
511
+ "auth_message": auth_message,
512
+ "share": False,
513
+ "server_name": "127.0.0.1",
514
+ "server_port": 7860,
515
+ "show_error": True
516
+ }
517
+ print("πŸ” Authentication enabled with fallback configuration")
518
+
519
+ print("πŸ“‹ Available beta test accounts:")
520
+ for username, password in auth_credentials:
521
+ print(f" β€’ {username} / {password}")
522
+
523
+ app.launch(**launch_config)
524
+
525
+ except Exception as e:
526
+ print(f"❌ Failed to launch ID Agents: {e}")
527
+ print("πŸ’‘ Check your API keys and environment configuration")
528
+ import traceback
529
+ traceback.print_exc()
app_minimal_test.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Minimal test app to verify Gradio + authentication works on HF Spaces
3
+ """
4
+
5
+ import gradio as gr
6
+
7
+ def test_chat(message, history):
8
+ """Simple test chat function"""
9
+ response = f"Echo: {message} (This is a minimal test version)"
10
+ history.append([message, response])
11
+ return "", history
12
+
13
+ # Create minimal interface
14
+ with gr.Blocks(title="ID Agents - Minimal Test") as app:
15
+ gr.Markdown("# 🦠 ID Agents - Minimal Test Version")
16
+ gr.Markdown("Testing authentication and basic functionality")
17
+
18
+ chatbot = gr.Chatbot(value=[], height=300)
19
+ msg = gr.Textbox(placeholder="Type a test message...")
20
+ submit = gr.Button("Send")
21
+
22
+ submit.click(fn=test_chat, inputs=[msg, chatbot], outputs=[msg, chatbot])
23
+ msg.submit(fn=test_chat, inputs=[msg, chatbot], outputs=[msg, chatbot])
24
+
25
+ if __name__ == "__main__":
26
+ # Authentication credentials
27
+ auth_credentials = [
28
+ ("dr_smith", "idweek2025"),
29
+ ("admin", "idagents2025"),
30
+ ("test", "test123")
31
+ ]
32
+
33
+ auth_message = """
34
+ 🦠 **ID Agents - Minimal Test**
35
+
36
+ This is a minimal test version to verify authentication works.
37
+
38
+ **Test Accounts:**
39
+ β€’ dr_smith / idweek2025
40
+ β€’ admin / idagents2025
41
+ β€’ test / test123
42
+ """
43
+
44
+ print("πŸš€ Launching minimal test app...")
45
+ app.launch(
46
+ auth=auth_credentials,
47
+ auth_message=auth_message,
48
+ show_error=True
49
+ )
app_optimized.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app_optimized.py - Memory-Optimized ID Agents
3
+ ----------------------------------------------
4
+
5
+ Streamlined version of the complex multi-agent system optimized for HF Spaces memory limits.
6
+ Includes core agent builder functionality while reducing memory footprint.
7
+ """
8
+
9
+ # --- Core Imports ---
10
+ import gradio as gr
11
+ import json
12
+ import re
13
+ import os
14
+ import asyncio
15
+ import logging
16
+ from typing import Dict, cast
17
+
18
+ # Essential imports with graceful fallbacks
19
+ try:
20
+ import openai
21
+ from openai import RateLimitError, APIError, APIConnectionError, OpenAI
22
+ OPENAI_AVAILABLE = True
23
+ except ImportError:
24
+ OPENAI_AVAILABLE = False
25
+
26
+ try:
27
+ from core.agents.agent_utils import linkify_citations, build_agent, load_prefilled, prepare_download
28
+ from config import agents_config, skills_library, prefilled_agents
29
+ from core.agents.chat_orchestrator import simulate_agent_response_stream
30
+ CORE_MODULES_AVAILABLE = True
31
+ except ImportError:
32
+ CORE_MODULES_AVAILABLE = False
33
+ # Fallback configurations
34
+ agents_config = {}
35
+ skills_library = {
36
+ "πŸ›‘οΈ Antimicrobial Stewardship": ["recommend_deescalation", "alert_prolonged_antibiotic_use"],
37
+ "🦠 Infection Prevention and Control": ["calculate_infection_rate", "assess_outbreak_risk"],
38
+ "πŸ”¬ Research Assistant": ["search_pubmed", "summarize_guidelines"],
39
+ "πŸ₯ Clinical Assistant": ["differential_diagnosis", "treatment_recommendations"],
40
+ "πŸ“š Education Assistant": ["create_quiz", "explain_concepts"],
41
+ "🎼 Orchestrator": ["coordinate_agents", "synthesize_responses"]
42
+ }
43
+ prefilled_agents = {
44
+ "Stewardship Expert": {
45
+ "agent_type": "πŸ›‘οΈ Antimicrobial Stewardship",
46
+ "agent_name": "StewardshipBot",
47
+ "agent_mission": "Optimize antibiotic use and prevent resistance",
48
+ "skills": ["recommend_deescalation", "alert_prolonged_antibiotic_use"]
49
+ }
50
+ }
51
+
52
+ # Set up logging
53
+ logging.basicConfig(level=logging.INFO)
54
+ logger = logging.getLogger(__name__)
55
+
56
+ # OpenAI setup
57
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
58
+ if OPENAI_API_KEY and OPENAI_AVAILABLE:
59
+ client = OpenAI(api_key=OPENAI_API_KEY)
60
+ else:
61
+ client = None
62
+
63
+ def simple_chat_response(user_message, history):
64
+ """Simple chat response for fallback mode"""
65
+ if not client:
66
+ return history + [[user_message, "⚠️ OpenAI not configured. Please check API keys."]], ""
67
+
68
+ # Convert to OpenAI format
69
+ messages = []
70
+ for user_msg, assistant_msg in history:
71
+ if user_msg:
72
+ messages.append({"role": "user", "content": user_msg})
73
+ if assistant_msg:
74
+ messages.append({"role": "assistant", "content": assistant_msg})
75
+
76
+ messages.append({"role": "user", "content": user_message})
77
+
78
+ try:
79
+ completion = client.chat.completions.create(
80
+ model="gpt-3.5-turbo",
81
+ messages=messages,
82
+ temperature=0.7,
83
+ )
84
+ reply = completion.choices[0].message.content.strip()
85
+ return history + [[user_message, reply]], ""
86
+ except Exception as e:
87
+ error_msg = f"Error: {str(e)}"
88
+ return history + [[user_message, error_msg]], ""
89
+
90
+ def convert_messages_to_gradio(messages):
91
+ """Convert OpenAI messages to Gradio format"""
92
+ if not messages:
93
+ return []
94
+
95
+ result = []
96
+ for i, msg in enumerate(messages):
97
+ if msg["role"] == "user":
98
+ # Look ahead for assistant response
99
+ assistant_response = ""
100
+ if i + 1 < len(messages) and messages[i + 1]["role"] == "assistant":
101
+ assistant_response = messages[i + 1]["content"]
102
+ result.append([msg["content"], assistant_response])
103
+ elif msg["role"] == "assistant" and (i == 0 or messages[i-1]["role"] != "user"):
104
+ # Standalone assistant message (like greeting)
105
+ result.append([None, msg["content"]])
106
+
107
+ return result
108
+
109
+ def safe_agent_chat(agent_name, user_text, histories):
110
+ """Safe agent chat with fallback"""
111
+ if not CORE_MODULES_AVAILABLE:
112
+ response = f"πŸ”§ **Demo Mode**: Agent '{agent_name}' would normally provide specialized infectious disease assistance here."
113
+ history = histories.get(agent_name, [])
114
+ new_history = history + [[user_text, response]]
115
+ histories[agent_name] = new_history
116
+ return new_history, histories, ""
117
+
118
+ try:
119
+ # Use existing chat logic if available
120
+ from app import chatpanel_handle
121
+ return chatpanel_handle(agent_name, user_text, histories)
122
+ except:
123
+ # Fallback to simple response
124
+ response = f"πŸ€– Agent '{agent_name}' received: {user_text}\n\nThis is a simplified response due to system limitations."
125
+ history = histories.get(agent_name, [])
126
+ new_history = history + [[user_text, response]]
127
+ histories[agent_name] = new_history
128
+ return new_history, histories, ""
129
+
130
+ def build_optimized_ui():
131
+ """Build memory-optimized UI"""
132
+
133
+ # Streamlined CSS - reduced from original
134
+ css = """
135
+ :root {
136
+ --id-primary: #1e40af;
137
+ --id-secondary: #3b82f6;
138
+ --id-accent: #06d6a0;
139
+ --id-bg: #f8fafc;
140
+ --id-surface: #ffffff;
141
+ --id-text: #1e293b;
142
+ }
143
+
144
+ .gradio-container { background: var(--id-bg) !important; }
145
+
146
+ .id-header {
147
+ background: linear-gradient(90deg, var(--id-primary), var(--id-secondary));
148
+ color: white;
149
+ padding: 1.5rem;
150
+ border-radius: 12px;
151
+ margin-bottom: 1.5rem;
152
+ }
153
+
154
+ .generate-btn {
155
+ background: linear-gradient(90deg, var(--id-secondary), var(--id-accent));
156
+ color: white !important;
157
+ border: none !important;
158
+ font-weight: 600;
159
+ }
160
+ """
161
+
162
+ with gr.Blocks(title="🦠 ID Agents - Optimized", css=css, theme=gr.themes.Soft()) as app:
163
+
164
+ # State management
165
+ builder_chat_histories = gr.State({})
166
+
167
+ # Header
168
+ gr.HTML("""
169
+ <div class="id-header">
170
+ <h1 style="margin: 0;">🦠 ID Agents - Multi-Agent Builder</h1>
171
+ <p style="margin: 8px 0 0 0;">Optimized for HF Spaces - Build specialized infectious disease agents</p>
172
+ </div>
173
+ """)
174
+
175
+ with gr.Tabs():
176
+ # Tab 1: Simple Chat
177
+ with gr.TabItem("πŸ’¬ Simple Chat"):
178
+ gr.Markdown("### Quick GPT-3.5 Chat")
179
+ simple_chatbot = gr.Chatbot()
180
+ simple_input = gr.Textbox(placeholder="Ask anything...", show_label=False)
181
+ simple_send = gr.Button("Send")
182
+ simple_reset = gr.Button("Reset")
183
+
184
+ # Wire up simple chat
185
+ simple_send.click(
186
+ fn=simple_chat_response,
187
+ inputs=[simple_input, simple_chatbot],
188
+ outputs=[simple_chatbot, simple_input]
189
+ )
190
+ simple_input.submit(
191
+ fn=simple_chat_response,
192
+ inputs=[simple_input, simple_chatbot],
193
+ outputs=[simple_chatbot, simple_input]
194
+ )
195
+ simple_reset.click(lambda: ([], ""), outputs=[simple_chatbot, simple_input])
196
+
197
+ # Tab 2: Agent Builder (Streamlined)
198
+ with gr.TabItem("πŸ› οΈ Agent Builder"):
199
+ gr.Markdown("### Build Your ID Agent")
200
+
201
+ with gr.Row():
202
+ with gr.Column(scale=1):
203
+ # Simplified form
204
+ prefilled = gr.Dropdown(
205
+ choices=["None"] + list(prefilled_agents.keys()),
206
+ label="Template",
207
+ value="None"
208
+ )
209
+ agent_type = gr.Radio(
210
+ choices=list(skills_library.keys()),
211
+ label="Agent Type"
212
+ )
213
+ agent_name = gr.Textbox(label="Agent Name", placeholder="e.g., StewardBot")
214
+ agent_mission = gr.Textbox(label="Mission", lines=3)
215
+ skills = gr.CheckboxGroup(choices=[], label="Skills")
216
+ generate_button = gr.Button("✨ Generate Agent", elem_classes="generate-btn")
217
+
218
+ # Generated config
219
+ agent_output = gr.Code(label="Agent Config", language="json")
220
+
221
+ with gr.Column(scale=2):
222
+ # Agent management
223
+ gr.Markdown("### Active Agents")
224
+ active_agents = gr.Markdown("_(None yet)_")
225
+
226
+ agent_dropdown = gr.Dropdown(label="Select Agent", choices=[])
227
+
228
+ with gr.Row():
229
+ chat_button = gr.Button("πŸ’¬ Chat")
230
+ remove_button = gr.Button("❌ Remove")
231
+
232
+ # Chat interface
233
+ agent_chatbot = gr.Chatbot(label="Agent Chat")
234
+ chat_input = gr.Textbox(placeholder="Chat with your agent...", show_label=False)
235
+ chat_send = gr.Button("Send")
236
+ reset_chat = gr.Button("πŸ”„ Reset")
237
+
238
+ # Update skills when agent type changes
239
+ def update_skills(agent_type):
240
+ if agent_type:
241
+ return gr.update(choices=skills_library.get(agent_type, []))
242
+ return gr.update(choices=[])
243
+
244
+ agent_type.change(update_skills, inputs=[agent_type], outputs=[skills])
245
+
246
+ # Generate agent
247
+ def generate_agent(prefilled_choice, agent_type, agent_name, agent_mission, skills):
248
+ if not agent_name.strip():
249
+ return "❌ Please provide an agent name", "", "### Active Agents\n_(None yet)_", gr.update()
250
+
251
+ agent_data = {
252
+ "agent_type": agent_type,
253
+ "agent_name": agent_name,
254
+ "agent_mission": agent_mission,
255
+ "skills": skills,
256
+ "web_access": True,
257
+ "allow_fallback": True
258
+ }
259
+
260
+ agents_config[agent_name] = json.dumps(agent_data)
261
+
262
+ # Update UI
263
+ config_json = json.dumps(agent_data, indent=2)
264
+ active_list = "### Active Agents\n" + "\n".join(f"- {name}" for name in agents_config.keys())
265
+ choices = list(agents_config.keys())
266
+
267
+ return config_json, agent_data, active_list, gr.update(choices=choices)
268
+
269
+ generate_button.click(
270
+ generate_agent,
271
+ inputs=[prefilled, agent_type, agent_name, agent_mission, skills],
272
+ outputs=[agent_output, gr.State(), active_agents, agent_dropdown]
273
+ )
274
+
275
+ # Chat with agent
276
+ def start_agent_chat(agent_name):
277
+ if agent_name:
278
+ greeting = f"πŸ‘‹ Hello! I'm {agent_name}. How can I assist you with infectious diseases?"
279
+ return [[None, greeting]], ""
280
+ return [], ""
281
+
282
+ chat_button.click(
283
+ start_agent_chat,
284
+ inputs=[agent_dropdown],
285
+ outputs=[agent_chatbot, chat_input]
286
+ )
287
+
288
+ # Send message to agent
289
+ def send_to_agent(agent_name, message, history, histories):
290
+ if not agent_name or not message.strip():
291
+ return history, "", histories
292
+
293
+ return safe_agent_chat(agent_name, message, histories)
294
+
295
+ chat_send.click(
296
+ send_to_agent,
297
+ inputs=[agent_dropdown, chat_input, agent_chatbot, builder_chat_histories],
298
+ outputs=[agent_chatbot, chat_input, builder_chat_histories]
299
+ )
300
+
301
+ chat_input.submit(
302
+ send_to_agent,
303
+ inputs=[agent_dropdown, chat_input, agent_chatbot, builder_chat_histories],
304
+ outputs=[agent_chatbot, chat_input, builder_chat_histories]
305
+ )
306
+
307
+ # Reset chat
308
+ reset_chat.click(lambda: ([], ""), outputs=[agent_chatbot, chat_input])
309
+
310
+ # Remove agent
311
+ def remove_agent(agent_name):
312
+ if agent_name in agents_config:
313
+ del agents_config[agent_name]
314
+
315
+ active_list = "### Active Agents\n" + "\n".join(f"- {name}" for name in agents_config.keys()) if agents_config else "### Active Agents\n_(None yet)_"
316
+ choices = list(agents_config.keys())
317
+
318
+ return active_list, gr.update(choices=choices, value=None)
319
+
320
+ remove_button.click(
321
+ remove_agent,
322
+ inputs=[agent_dropdown],
323
+ outputs=[active_agents, agent_dropdown]
324
+ )
325
+
326
+ # Status info
327
+ status_md = "βœ… **Optimized Mode**: Core functionality available"
328
+ if CORE_MODULES_AVAILABLE:
329
+ status_md += "\nβœ… **Full modules loaded**"
330
+ else:
331
+ status_md += "\n⚠️ **Demo mode**: Limited functionality"
332
+
333
+ gr.Markdown(f"### System Status\n{status_md}")
334
+
335
+ return app
336
+
337
+ # --- Main Application Entry Point ---
338
+ if __name__ == "__main__":
339
+ try:
340
+ print("πŸš€ Launching Optimized ID Agents...")
341
+
342
+ # Authentication credentials
343
+ auth_credentials = [
344
+ ("dr_smith", "idweek2025"),
345
+ ("id_fellow", "hello"),
346
+ ("pharmacist", "stewardship"),
347
+ ("ipc_nurse", "infection"),
348
+ ("researcher", "research"),
349
+ ("educator", "education"),
350
+ ("student", "learning"),
351
+ ("admin", "idagents2025"),
352
+ ("guest1", "guest123"),
353
+ ("guest2", "guest456")
354
+ ]
355
+
356
+ auth_message = """
357
+ 🦠 **ID Agents Beta Testing - Optimized Version**
358
+
359
+ Welcome to the memory-optimized ID Agents environment!
360
+
361
+ **Available Test Accounts:**
362
+ β€’ **dr_smith** / idweek2025 (ID Physician)
363
+ β€’ **id_fellow** / hello (ID Fellow)
364
+ β€’ **pharmacist** / stewardship (Clinical Pharmacist)
365
+ β€’ **ipc_nurse** / infection (IPC Coordinator)
366
+ β€’ **researcher** / research (Clinical Researcher)
367
+ β€’ **educator** / education (Medical Educator)
368
+ β€’ **student** / learning (Medical Student)
369
+ β€’ **admin** / idagents2025 (Administrator)
370
+ β€’ **guest1** / guest123 (Guest Access)
371
+ β€’ **guest2** / guest456 (Guest Access)
372
+
373
+ This optimized version provides core agent building functionality
374
+ while staying within HF Spaces memory limits.
375
+ """
376
+
377
+ # Configure launch
378
+ try:
379
+ from hf_config import configure_hf_environment, get_hf_launch_config
380
+ if configure_hf_environment():
381
+ launch_config = get_hf_launch_config()
382
+ launch_config["auth"] = auth_credentials
383
+ launch_config["auth_message"] = auth_message
384
+ print("πŸ” HF Spaces optimized deployment")
385
+ else:
386
+ launch_config = {
387
+ "auth": auth_credentials,
388
+ "auth_message": auth_message,
389
+ "share": False,
390
+ "server_name": "127.0.0.1",
391
+ "server_port": 7860
392
+ }
393
+ print("πŸ” Local optimized deployment")
394
+ except ImportError:
395
+ launch_config = {
396
+ "auth": auth_credentials,
397
+ "auth_message": auth_message,
398
+ "share": False,
399
+ "server_name": "127.0.0.1",
400
+ "server_port": 7860
401
+ }
402
+ print("πŸ” Fallback optimized deployment")
403
+
404
+ # Launch optimized app
405
+ build_optimized_ui().launch(**launch_config)
406
+
407
+ except Exception as e:
408
+ logger.error(f"Failed to launch optimized ID Agents: {e}")
409
+ print(f"❌ Launch failed: {e}")
410
+ import traceback
411
+ traceback.print_exc()
app_original_complex.py ADDED
The diff for this file is too large to render. See raw diff
 
app_ultra_minimal.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def simple_chat(message, history):
4
+ response = f"Echo: {message}"
5
+ history.append([message, response])
6
+ return "", history
7
+
8
+ with gr.Blocks(title="ID Agents Test") as app:
9
+ gr.Markdown("# 🦠 ID Agents - Simple Test")
10
+ chatbot = gr.Chatbot()
11
+ msg = gr.Textbox(placeholder="Test message...")
12
+ submit = gr.Button("Send")
13
+
14
+ submit.click(simple_chat, [msg, chatbot], [msg, chatbot])
15
+ msg.submit(simple_chat, [msg, chatbot], [msg, chatbot])
16
+
17
+ if __name__ == "__main__":
18
+ app.launch(
19
+ auth=[("test", "test123"), ("admin", "admin123")],
20
+ auth_message="Test accounts: test/test123 or admin/admin123"
21
+ )
test_minimal.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal test to identify what's causing initialization failure
4
+ """
5
+
6
+ print("Starting minimal test...")
7
+
8
+ try:
9
+ import gradio as gr
10
+ print("βœ… Gradio imported successfully")
11
+ except Exception as e:
12
+ print(f"❌ Gradio import failed: {e}")
13
+ exit(1)
14
+
15
+ try:
16
+ import os
17
+ print("βœ… Environment variables check...")
18
+ openai_key = os.environ.get("OPENAI_API_KEY")
19
+ if openai_key:
20
+ print("βœ… OPENAI_API_KEY found")
21
+ else:
22
+ print("❌ OPENAI_API_KEY not found")
23
+ except Exception as e:
24
+ print(f"❌ Environment check failed: {e}")
25
+
26
+ try:
27
+ import openai
28
+ print("βœ… OpenAI imported successfully")
29
+ except Exception as e:
30
+ print(f"❌ OpenAI import failed: {e}")
31
+
32
+ def minimal_app():
33
+ print("Creating minimal Gradio app...")
34
+
35
+ def simple_chat(message, history):
36
+ return history + [["User: " + message, "Bot: Hello! This is a test response."]]
37
+
38
+ with gr.Blocks(title="Minimal Test") as app:
39
+ gr.Markdown("# Minimal Test App")
40
+ chatbot = gr.Chatbot()
41
+ msg = gr.Textbox(placeholder="Type a message...")
42
+ msg.submit(simple_chat, [msg, chatbot], chatbot)
43
+
44
+ return app
45
+
46
+ if __name__ == "__main__":
47
+ try:
48
+ print("Building app...")
49
+ app = minimal_app()
50
+ print("βœ… App built successfully")
51
+
52
+ print("Launching app...")
53
+ app.launch(
54
+ server_name="0.0.0.0",
55
+ server_port=7860,
56
+ show_error=True,
57
+ quiet=False
58
+ )
59
+ print("βœ… App launched successfully")
60
+
61
+ except Exception as e:
62
+ print(f"❌ App launch failed: {e}")
63
+ import traceback
64
+ traceback.print_exc()