dhillonv10 commited on
Commit
a1268ef
·
verified ·
1 Parent(s): f94c605

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +251 -119
app.py CHANGED
@@ -1,88 +1,130 @@
1
  import os
2
  import gradio as gr
3
  import anthropic
 
 
 
 
 
 
 
 
 
4
 
5
  # Initialize the Anthropic client with your API key
6
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
7
  MODEL = "claude-3-5-sonnet-20241022"
8
 
9
- SYSTEM_PROMPT = """
10
- You are a compassionate AI medical assistant that uses Logic-of-Thought (LoT) and Self-Consistency (SC) reasoning techniques to analyze patient symptoms and provide medical education. Your goal is to deliver clear, empathetic explanations of possible conditions, treatments, and next steps based on the information provided. You will only offer a differential diagnosis if there is enough detail to make an informed response. Always remind the patient to consult a healthcare provider for a formal diagnosis and treatment when necessary.
11
-
12
- Core Responsibilities:
13
-
14
- Initial Inquiry and Ongoing Interaction:
15
-
16
- Listen and Extract Key Information:
17
-
18
- When a patient shares their concerns in a conversational format, begin by identifying key symptoms, durations, and any relevant medical history.
19
- If a patient's response is too brief or lacks detail, ask follow-up questions (e.g., medical history, medications, allergies) before making a differential diagnosis.
20
- Integrate New Information:
21
-
22
- When the patient provides new information in subsequent messages, incorporate it into your existing analysis without starting a new diagnostic inquiry. Ensure the conversation remains coherent and contextually accurate.
23
- Provide Educational Explanations:
24
-
25
- Offer possible explanations based on the symptoms and data provided. If enough information is available, present the most likely causes in clear, understandable language. If not, request additional information.
26
- Avoid jumping to conclusions when there are insufficient details. Ask relevant follow-up questions to clarify the patient's situation.
27
- Offer General Treatment Suggestions:
28
-
29
- Present over-the-counter remedies, lifestyle changes, or home management strategies based on the symptoms described. Emphasize that these are general educational suggestions and should not replace a healthcare provider's advice.
30
- Suggest Next Steps:
31
-
32
- Offer guidance on whether the patient should seek further evaluation (e.g., visiting a doctor or specialist), go to urgent care, or the Emergency Department but make it clear these are educational recommendations, not medical advice.
33
- Internal Reasoning Process (Not Shown to the Patient):
34
-
35
- Extract Key Information (Logical Propositions):
36
 
37
- Internally capture the patient's symptoms and medical history as logical propositions (e.g., P1: stomach pain for 2 days, P2: diarrhea). Use these details to form your reasoning but do not display this internal process.
38
- Apply Logical Reasoning Principles (Logic-of-Thought):
39
-
40
- Based on the gathered information, explore relationships between symptoms and potential conditions. If not enough data is provided, ask for more detail before proceeding with any diagnosis.
41
- Generate Multiple Reasoning Paths (Self-Consistency):
42
-
43
- Form multiple independent lines of reasoning and explanations. Ensure the reasoning is logically sound and consistent with the available data, but only share the best-supported conclusions.
44
- Translate Reasoning into Simple, Educational Language:
45
-
46
- Present your conclusions in a clear, concise, and supportive way. Always ensure the patient understands that this is educational content and not medical advice.
47
- Synthesize Findings and Update Differential Diagnosis:
48
-
49
- Compare multiple reasoning paths and present the most consistent explanations when enough information is available. If new symptoms or history are shared, update the differential diagnosis accordingly.
50
- Empathetic Communication and Disclaimers:
51
-
52
- Provide Empathetic Responses:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- Always communicate with empathy and respect. Ensure the patient feels heard and understood. Use warm, conversational language to explain possible conditions and next steps.
55
- Include Clear Disclaimers:
 
56
 
57
- Subtly remind the patient that this information is for educational purposes and not a substitute for professional medical advice. Avoid being repetitive but ensure this message is clear.
58
- Maintaining Context:
 
 
59
 
60
- Session Continuity:
61
- Maintain context across multiple messages. Seamlessly integrate any new symptoms or updates into the existing analysis. Keep the conversation coherent and refer back to previous details to ensure continuity.
62
- """
 
 
 
63
 
64
- def chat_with_claude(message, history):
65
- messages = []
 
 
 
 
 
 
 
 
 
 
 
 
66
  response_content = ""
67
 
68
- # Process the conversation history with proper message formatting
69
- for user_msg, assistant_msg in history:
70
- messages.append({
71
- "role": "user",
72
- "content": user_msg
73
- })
74
- messages.append({
75
- "role": "assistant",
76
- "content": assistant_msg
77
- })
78
-
79
- # Add the new user message
80
- messages.append({
81
- "role": "user",
82
- "content": str(message)
83
- })
84
-
85
- # Stream response from Claude with system prompt at top level
86
  with client.messages.stream(
87
  max_tokens=5000,
88
  system=SYSTEM_PROMPT,
@@ -92,56 +134,146 @@ def chat_with_claude(message, history):
92
  for text in stream.text_stream:
93
  response_content += text
94
  yield response_content
 
 
 
95
 
96
- # CSS for full-screen layout
97
- custom_css = """
98
- .gradio-container {
99
- height: 100vh !important;
100
- }
101
-
102
- .wrapper > .gap {
103
- height: 100vh !important;
104
- padding: 0 !important;
105
- margin: 0 !important;
106
- }
107
-
108
- .overflow-y-auto {
109
- height: calc(100vh - 200px) !important;
110
- }
111
-
112
- .fixed-height {
113
- height: 100px !important;
114
- margin: 10px !important;
115
- }
116
-
117
- /* Additional styling for white theme */
118
- .message {
119
- border-radius: 8px !important;
120
- }
121
-
122
- .user-message {
123
- background-color: #f9f9f9 !important;
124
- }
125
-
126
- .assistant-message {
127
- background-color: #ffffff !important;
128
- }
129
- """
130
-
131
- # Create a Gradio interface for the chatbot
132
- demo = gr.ChatInterface(
133
- fn=chat_with_claude,
134
- title="docAI - Your personal AI health assistant",
135
- description="How can I educate you today?",
136
- examples=[
137
- "What causes chest pain?",
138
- "Tell me about iron deficiency",
139
- "How does a cell make energy?"
140
- ],
141
- theme=gr.themes.Base(),
142
- css=custom_css,
143
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  # Launch the interface
146
  if __name__ == "__main__":
147
- demo.launch(share=True)
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import anthropic
4
+ from datetime import datetime
5
+ import uuid
6
+ from typing import List, Dict
7
+ import asyncio
8
+ import asyncpg
9
+ from dotenv import load_dotenv
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
 
14
  # Initialize the Anthropic client with your API key
15
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
16
  MODEL = "claude-3-5-sonnet-20241022"
17
 
18
+ class DatabaseManager:
19
+ def __init__(self):
20
+ self.pool = None
21
+
22
+ async def initialize(self):
23
+ # Connect to Neon.tech PostgreSQL database
24
+ self.pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
25
+
26
+ # Create necessary tables if they don't exist
27
+ async with self.pool.acquire() as conn:
28
+ await conn.execute('''
29
+ CREATE TABLE IF NOT EXISTS chat_sessions (
30
+ session_id UUID PRIMARY KEY,
31
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
32
+ )
33
+ ''')
34
+
35
+ await conn.execute('''
36
+ CREATE TABLE IF NOT EXISTS messages (
37
+ message_id UUID PRIMARY KEY,
38
+ session_id UUID REFERENCES chat_sessions(session_id),
39
+ role TEXT NOT NULL,
40
+ content TEXT NOT NULL,
41
+ timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
42
+ )
43
+ ''')
 
44
 
45
+ class ChatManager:
46
+ def __init__(self, db_manager: DatabaseManager):
47
+ self.db = db_manager
48
+ self.current_session_id = None
49
+
50
+ async def new_session(self) -> str:
51
+ """Create a new chat session and return its ID"""
52
+ session_id = uuid.uuid4()
53
+ async with self.db.pool.acquire() as conn:
54
+ await conn.execute(
55
+ 'INSERT INTO chat_sessions (session_id) VALUES ($1)',
56
+ session_id
57
+ )
58
+ self.current_session_id = session_id
59
+ return str(session_id)
60
+
61
+ async def add_message(self, session_id: str, role: str, content: str):
62
+ """Add a message to a chat session"""
63
+ async with self.db.pool.acquire() as conn:
64
+ await conn.execute(
65
+ 'INSERT INTO messages (message_id, session_id, role, content) VALUES ($1, $2, $3, $4)',
66
+ uuid.uuid4(), uuid.UUID(session_id), role, content
67
+ )
68
+
69
+ async def get_session_history(self, session_id: str) -> List[Dict]:
70
+ """Get all messages for a chat session"""
71
+ async with self.db.pool.acquire() as conn:
72
+ rows = await conn.fetch('''
73
+ SELECT role, content, timestamp
74
+ FROM messages
75
+ WHERE session_id = $1
76
+ ORDER BY timestamp ASC
77
+ ''', uuid.UUID(session_id))
78
+ return [dict(row) for row in rows]
79
+
80
+ async def list_sessions(self) -> List[Dict]:
81
+ """Get all chat sessions with their message counts"""
82
+ async with self.db.pool.acquire() as conn:
83
+ sessions = await conn.fetch('''
84
+ SELECT
85
+ cs.session_id,
86
+ cs.created_at,
87
+ COUNT(m.message_id) as message_count
88
+ FROM chat_sessions cs
89
+ LEFT JOIN messages m ON cs.session_id = m.session_id
90
+ GROUP BY cs.session_id, cs.created_at
91
+ ORDER BY cs.created_at DESC
92
+ ''')
93
+ return [dict(session) for session in sessions]
94
 
95
+ # Initialize database and chat managers
96
+ db_manager = DatabaseManager()
97
+ chat_manager = None
98
 
99
+ async def initialize_managers():
100
+ global chat_manager
101
+ await db_manager.initialize()
102
+ chat_manager = ChatManager(db_manager)
103
 
104
+ def format_message(msg):
105
+ """Format message for Claude API"""
106
+ return {
107
+ "role": msg["role"],
108
+ "content": msg["content"]
109
+ }
110
 
111
+ async def chat_with_claude(message, history, session_id: str = None):
112
+ """Main chat function with persistence"""
113
+
114
+ # Create new session if none exists
115
+ if not session_id:
116
+ session_id = await chat_manager.new_session()
117
+
118
+ # Add user message to database
119
+ await chat_manager.add_message(session_id, "user", message)
120
+
121
+ # Get session history and prepare messages for Claude
122
+ session_history = await chat_manager.get_session_history(session_id)
123
+ messages = [format_message(msg) for msg in session_history[:-1]] # Exclude latest user message
124
+
125
  response_content = ""
126
 
127
+ # Stream response from Claude
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  with client.messages.stream(
129
  max_tokens=5000,
130
  system=SYSTEM_PROMPT,
 
134
  for text in stream.text_stream:
135
  response_content += text
136
  yield response_content
137
+
138
+ # Add assistant response to database
139
+ await chat_manager.add_message(session_id, "assistant", response_content)
140
 
141
+ def create_chat_interface():
142
+ """Create the Gradio interface with ChatGPT-like styling"""
143
+
144
+ css = """
145
+ .gradio-container {
146
+ max-width: 1200px !important;
147
+ margin: auto !important;
148
+ padding-top: 20px !important;
149
+ height: 100vh !important;
150
+ }
151
+
152
+ .chat-history {
153
+ height: calc(100vh - 200px) !important;
154
+ overflow-y: auto !important;
155
+ padding: 20px !important;
156
+ border-radius: 10px !important;
157
+ background: #ffffff !important;
158
+ }
159
+
160
+ .message {
161
+ padding: 15px !important;
162
+ margin: 10px 0 !important;
163
+ border-radius: 8px !important;
164
+ max-width: 85% !important;
165
+ }
166
+
167
+ .user-message {
168
+ background: #f7f7f8 !important;
169
+ margin-left: auto !important;
170
+ }
171
+
172
+ .assistant-message {
173
+ background: #ffffff !important;
174
+ border: 1px solid #e5e5e5 !important;
175
+ }
176
+
177
+ .input-area {
178
+ position: fixed !important;
179
+ bottom: 20px !important;
180
+ width: calc(100% - 40px) !important;
181
+ max-width: 1160px !important;
182
+ background: white !important;
183
+ padding: 15px !important;
184
+ border-radius: 10px !important;
185
+ box-shadow: 0 0 10px rgba(0,0,0,0.1) !important;
186
+ }
187
+ """
188
+
189
+ with gr.Blocks(css=css) as demo:
190
+ session_id = gr.State(value=None)
191
+
192
+ with gr.Row():
193
+ with gr.Column(scale=3):
194
+ chatbot = gr.Chatbot(
195
+ elem_id="chatbot",
196
+ height=700,
197
+ show_label=False,
198
+ layout="bubble"
199
+ )
200
+
201
+ with gr.Column(scale=1):
202
+ session_list = gr.Dropdown(
203
+ choices=lambda: [(str(s["session_id"]), f"Chat {i+1}")
204
+ for i, s in enumerate(asyncio.run(chat_manager.list_sessions()))],
205
+ label="Previous Chats",
206
+ interactive=True
207
+ )
208
+ new_chat_btn = gr.Button("New Chat")
209
+
210
+ with gr.Row(elem_classes="input-area"):
211
+ msg = gr.Textbox(
212
+ show_label=False,
213
+ placeholder="Type your message here...",
214
+ lines=2
215
+ )
216
+ submit_btn = gr.Button("Send", variant="primary")
217
+
218
+ async def load_chat(selected_id):
219
+ if selected_id:
220
+ history = await chat_manager.get_session_history(selected_id)
221
+ chat_history = [(msg["content"], msg["content"])
222
+ for msg in history
223
+ if msg["role"] in ["user", "assistant"]]
224
+ return chat_history, selected_id
225
+ return [], None
226
+
227
+ async def new_chat():
228
+ session_id = await chat_manager.new_session()
229
+ sessions = await chat_manager.list_sessions()
230
+ return [], session_id, gr.Dropdown.update(
231
+ choices=[(str(s["session_id"]), f"Chat {i+1}") for i, s in enumerate(sessions)]
232
+ )
233
+
234
+ # Connect event handlers
235
+ session_list.change(
236
+ lambda x: asyncio.run(load_chat(x)),
237
+ inputs=[session_list],
238
+ outputs=[chatbot, session_id]
239
+ )
240
+
241
+ new_chat_btn.click(
242
+ lambda: asyncio.run(new_chat()),
243
+ outputs=[chatbot, session_id, session_list]
244
+ )
245
+
246
+ # Chat submission
247
+ submit_btn.click(
248
+ chat_with_claude,
249
+ inputs=[msg, chatbot, session_id],
250
+ outputs=[chatbot],
251
+ queue=False
252
+ ).then(
253
+ lambda: "",
254
+ None,
255
+ [msg]
256
+ )
257
+
258
+ msg.submit(
259
+ chat_with_claude,
260
+ inputs=[msg, chatbot, session_id],
261
+ outputs=[chatbot],
262
+ queue=False
263
+ ).then(
264
+ lambda: "",
265
+ None,
266
+ [msg]
267
+ )
268
+
269
+ return demo
270
 
271
  # Launch the interface
272
  if __name__ == "__main__":
273
+ # Initialize database connection
274
+ asyncio.run(initialize_managers())
275
+
276
+ # Create and launch the interface
277
+ demo = create_chat_interface()
278
+ demo.queue()
279
+ demo.launch(share=True)