dhillonv10 commited on
Commit
3073e02
·
verified ·
1 Parent(s): e162956

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -78
app.py CHANGED
@@ -7,42 +7,31 @@ from psycopg2.extras import Json
7
  from contextlib import contextmanager
8
 
9
  # Initialize the Anthropic client with your API key
10
- # For Hugging Face Spaces, set this as a secret named ANTHROPIC_API_KEY
11
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
12
  MODEL = "claude-3-5-sonnet-20241022"
13
  SYSTEM_PROMPT = """
14
- You are a helpful AI medical assistant
15
  """
16
 
17
  # Database configuration
18
- # For Hugging Face Spaces, set this as a secret named DATABASE_URL
19
  DATABASE_URL = os.getenv('DATABASE_URL')
20
 
21
  @contextmanager
22
- def get_db_connection():
23
- """Context manager for database connections"""
24
  conn = psycopg2.connect(DATABASE_URL)
25
  try:
26
- yield conn
 
 
 
27
  finally:
 
28
  conn.close()
29
 
30
- @contextmanager
31
- def get_db_cursor(commit=False):
32
- """Context manager for database cursors"""
33
- with get_db_connection() as conn:
34
- cur = conn.cursor()
35
- try:
36
- yield cur
37
- if commit:
38
- conn.commit()
39
- finally:
40
- cur.close()
41
-
42
  def init_db():
43
  """Initialize database and create tables if they don't exist"""
44
  with get_db_cursor(commit=True) as cur:
45
- # Create chats table
46
  cur.execute("""
47
  CREATE TABLE IF NOT EXISTS chats (
48
  id SERIAL PRIMARY KEY,
@@ -55,27 +44,21 @@ def init_db():
55
  def save_chat(history, chat_id=None):
56
  """Save chat history to database"""
57
  try:
58
- # Get the first message or timestamp as title
59
- title = (history[0][0][:50] if history
60
- else f"Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}")
61
-
62
  with get_db_cursor(commit=True) as cur:
63
  if chat_id:
64
- # Update existing chat
65
  cur.execute("""
66
  UPDATE chats
67
- SET history = %s, title = %s
68
  WHERE id = %s
69
  RETURNING id
70
- """, (Json(history), title, chat_id))
71
  else:
72
- # Create new chat
73
  cur.execute("""
74
  INSERT INTO chats (history, title)
75
  VALUES (%s, %s)
76
  RETURNING id
77
  """, (Json(history), title))
78
-
79
  result = cur.fetchone()
80
  return str(result[0]) if result else None
81
  except Exception as e:
@@ -109,12 +92,17 @@ def list_saved_chats():
109
  print(f"Error listing chats: {e}")
110
  return []
111
 
112
- def chat_with_claude(message, history, state):
113
- """Chat function with persistent state handling"""
 
 
 
 
 
 
114
  try:
115
  messages = []
116
  response_content = ""
117
- chat_id = state.get('chat_id', '')
118
 
119
  # Process the conversation history
120
  for user_msg, assistant_msg in history:
@@ -137,9 +125,7 @@ def chat_with_claude(message, history, state):
137
 
138
  # Save chat after response
139
  updated_history = history + [(message, response_content)]
140
- new_chat_id = save_chat(updated_history, chat_id)
141
- if new_chat_id:
142
- state['chat_id'] = new_chat_id
143
 
144
  except Exception as e:
145
  print(f"Error in chat: {e}")
@@ -150,78 +136,66 @@ def create_demo():
150
  init_db()
151
 
152
  with gr.Blocks() as demo:
153
- # Persistent state
154
- state = gr.State({'chat_id': ''})
155
 
156
  with gr.Row():
157
- with gr.Column(scale=4):
158
- gr.Markdown("# docAI - Your personal AI health assistant")
159
- with gr.Column(scale=1):
160
- load_chat_dropdown = gr.Dropdown(
161
- choices=list_saved_chats(),
162
- label="Load Previous Chat",
163
- type="value",
164
- allow_custom_value=False
165
- )
 
166
 
167
  chatbot = gr.ChatInterface(
168
- fn=lambda msg, history: chat_with_claude(msg, history, state.value),
169
- chatbot=gr.Chatbot(
170
- height=500,
171
- show_copy_button=True,
172
- render_markdown=True,
173
- type='messages' # Added this to fix the warning
174
- ),
175
- textbox=gr.Textbox(
176
- placeholder="Type your message here...",
177
- container=False,
178
- scale=7
179
- ),
180
  title="",
181
  description="How can I educate you today?",
182
  examples=[
183
  "What causes chest pain?",
184
  "Tell me about iron deficiency",
185
  "How does a cell make energy?"
186
- ],
187
- theme=gr.themes.Base()
188
  )
189
 
190
- def load_selected_chat(selected_chat_id, state):
 
 
 
 
 
 
191
  if selected_chat_id:
 
192
  history = load_chat(selected_chat_id)
193
- state['chat_id'] = selected_chat_id
194
- return history, state
195
- return [], state
196
 
197
  # Update chat history when a saved chat is selected
198
  load_chat_dropdown.change(
199
  fn=load_selected_chat,
200
- inputs=[load_chat_dropdown, state],
201
- outputs=[chatbot.chatbot, state]
202
  )
203
 
204
- # Fixed periodic refresh using newer Gradio syntax
205
- refresh_button = gr.Button("Refresh Chat List", visible=False)
206
- refresh_button.click(
207
- fn=list_saved_chats,
208
- outputs=[load_chat_dropdown],
209
- )
210
- demo.load(
211
- fn=list_saved_chats,
212
- outputs=[load_chat_dropdown],
213
  )
214
 
215
- # Set up periodic refresh
216
- gr.on(
217
- triggers=[demo.every(30)], # Refresh every 30 seconds
218
  fn=list_saved_chats,
219
  outputs=[load_chat_dropdown]
220
  )
221
 
222
  return demo
223
 
224
- # Create and launch the interface
225
  if __name__ == "__main__":
226
  demo = create_demo()
227
  demo.launch()
 
7
  from contextlib import contextmanager
8
 
9
  # Initialize the Anthropic client with your API key
 
10
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
11
  MODEL = "claude-3-5-sonnet-20241022"
12
  SYSTEM_PROMPT = """
13
+ You are a compassionate AI medical assistant
14
  """
15
 
16
  # Database configuration
 
17
  DATABASE_URL = os.getenv('DATABASE_URL')
18
 
19
  @contextmanager
20
+ def get_db_cursor(commit=False):
21
+ """Context manager for database cursors"""
22
  conn = psycopg2.connect(DATABASE_URL)
23
  try:
24
+ cur = conn.cursor()
25
+ yield cur
26
+ if commit:
27
+ conn.commit()
28
  finally:
29
+ cur.close()
30
  conn.close()
31
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def init_db():
33
  """Initialize database and create tables if they don't exist"""
34
  with get_db_cursor(commit=True) as cur:
 
35
  cur.execute("""
36
  CREATE TABLE IF NOT EXISTS chats (
37
  id SERIAL PRIMARY KEY,
 
44
  def save_chat(history, chat_id=None):
45
  """Save chat history to database"""
46
  try:
47
+ title = f"Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}"
 
 
 
48
  with get_db_cursor(commit=True) as cur:
49
  if chat_id:
 
50
  cur.execute("""
51
  UPDATE chats
52
+ SET history = %s
53
  WHERE id = %s
54
  RETURNING id
55
+ """, (Json(history), chat_id))
56
  else:
 
57
  cur.execute("""
58
  INSERT INTO chats (history, title)
59
  VALUES (%s, %s)
60
  RETURNING id
61
  """, (Json(history), title))
 
62
  result = cur.fetchone()
63
  return str(result[0]) if result else None
64
  except Exception as e:
 
92
  print(f"Error listing chats: {e}")
93
  return []
94
 
95
+ class State:
96
+ def __init__(self):
97
+ self.chat_id = None
98
+
99
+ state = State()
100
+
101
+ def chat_with_claude(message, history):
102
+ """Chat function with persistent state"""
103
  try:
104
  messages = []
105
  response_content = ""
 
106
 
107
  # Process the conversation history
108
  for user_msg, assistant_msg in history:
 
125
 
126
  # Save chat after response
127
  updated_history = history + [(message, response_content)]
128
+ state.chat_id = save_chat(updated_history, state.chat_id)
 
 
129
 
130
  except Exception as e:
131
  print(f"Error in chat: {e}")
 
136
  init_db()
137
 
138
  with gr.Blocks() as demo:
139
+ gr.Markdown("# docAI - Your personal AI health assistant")
 
140
 
141
  with gr.Row():
142
+ # Dropdown for loading previous chats
143
+ load_chat_dropdown = gr.Dropdown(
144
+ choices=list_saved_chats(),
145
+ label="Load Previous Chat",
146
+ type="value",
147
+ allow_custom_value=False
148
+ )
149
+
150
+ # New Chat button
151
+ new_chat_btn = gr.Button("New Chat")
152
 
153
  chatbot = gr.ChatInterface(
154
+ fn=chat_with_claude,
 
 
 
 
 
 
 
 
 
 
 
155
  title="",
156
  description="How can I educate you today?",
157
  examples=[
158
  "What causes chest pain?",
159
  "Tell me about iron deficiency",
160
  "How does a cell make energy?"
161
+ ]
 
162
  )
163
 
164
+ def start_new_chat():
165
+ """Reset the chat state"""
166
+ state.chat_id = None
167
+ return None, []
168
+
169
+ def load_selected_chat(selected_chat_id):
170
+ """Load selected chat"""
171
  if selected_chat_id:
172
+ state.chat_id = selected_chat_id
173
  history = load_chat(selected_chat_id)
174
+ return history
175
+ return []
 
176
 
177
  # Update chat history when a saved chat is selected
178
  load_chat_dropdown.change(
179
  fn=load_selected_chat,
180
+ inputs=[load_chat_dropdown],
181
+ outputs=[chatbot.chatbot]
182
  )
183
 
184
+ # Set up new chat button
185
+ new_chat_btn.click(
186
+ fn=start_new_chat,
187
+ inputs=[],
188
+ outputs=[load_chat_dropdown, chatbot.chatbot]
 
 
 
 
189
  )
190
 
191
+ # Refresh chat list on page load
192
+ demo.load(
 
193
  fn=list_saved_chats,
194
  outputs=[load_chat_dropdown]
195
  )
196
 
197
  return demo
198
 
 
199
  if __name__ == "__main__":
200
  demo = create_demo()
201
  demo.launch()