dogoodson commited on
Commit
4aaabca
·
1 Parent(s): e0b361b

Initialize P2

Browse files
Files changed (4) hide show
  1. .gradio/certificate.pem +31 -0
  2. README.md +54 -0
  3. app.py +314 -0
  4. chatBotOllama.ipynb +467 -0
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ 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
31
+ -----END CERTIFICATE-----
README.md CHANGED
@@ -10,3 +10,57 @@ pinned: false
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
13
+
14
+ # Medical Chat Bot
15
+
16
+ ## Domain
17
+ [Your chosen domain]
18
+
19
+ ## Setup Instructions
20
+ ### Prerequisites
21
+ - Python 3.14.4+
22
+ - [Ollama OR HuggingFace account]
23
+
24
+ ### Installation
25
+ 1. Install Ollama
26
+ ```bash
27
+ # Mac:
28
+ brew install ollama
29
+
30
+ # Windows: Download from https://ollama.ai
31
+
32
+ # Linux:
33
+ curl -fsSL https://ollama.com/install.sh | sh
34
+ ```
35
+
36
+ 1. Download llama3.2:3b model:
37
+ ```bash
38
+ ollama pull llama3.2:3b
39
+ ```
40
+ 1. Install Python packages
41
+ ```bash
42
+ pip install ollama gradio
43
+ ```
44
+
45
+ ### Running
46
+ ```bash
47
+ python your_file.py
48
+ ```
49
+
50
+ ## Features
51
+ - Feature 1: [Description]
52
+ - Feature 2: [Description]
53
+
54
+ ## Technical Details
55
+ - Model: llama3.2:3b
56
+ - Framework: Ollama
57
+ - Special considerations: [Any important notes]
58
+
59
+ ## Demo
60
+ [Link to video OR screenshots]
61
+
62
+ ## Known Limitations
63
+ [What your chatbot cannot do]
64
+
65
+ ## Future Improvements
66
+ [What you would add with more time]
app.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Medical Chatbot using Ollama and Gradio
3
+ This template provides a complete chatbot with sections to customize.
4
+ """
5
+
6
+ import ollama
7
+ import gradio as gr
8
+
9
+ # 1: Customize system prompt for either healthcare professional or patient based on a radio button selection
10
+
11
+ import gradio as gr
12
+ current_mode = "patient" # default
13
+ grExamples = None
14
+
15
+ def switch_prompt(mode):
16
+ """Switch between patient and doctor mode"""
17
+ global current_mode, SYSTEM_PROMPT
18
+ current_mode = mode
19
+
20
+ # patient mode
21
+ if mode == "patient":
22
+ SYSTEM_PROMPT = """You are a medical AI assistant specialized in medication questions and management for a patient.
23
+
24
+ Your role is to help the patient keep track of their medication schedule and provide information about their medications.
25
+
26
+ When answering:
27
+ - Tell them they can let you know about any changes in medications at any time.
28
+ - Let them know about any upcoming medication times.
29
+ - Ask what medications they have taken today so far.
30
+ - Be accurate and evidence-based.
31
+ - Use clear, simple language.
32
+
33
+ Remember: You provide educational information, not personal medical advice."""
34
+
35
+ # Update the example prompts.
36
+ else: # doctor mode
37
+ SYSTEM_PROMPT = """You are a medical AI assistant specialized in providing information to healthcare professionals about a patient's medications and management.
38
+
39
+ Your role is to inform the healthcare professional so they understand the patient's medication list, recent medication schedule, and any concerns the patient has asked about their medications.
40
+
41
+ When answering:
42
+ - Present the list of medications the patient is taking.
43
+ - Provide a summary of specific questions the patient has asked.
44
+ - Detail the schedule of the patient's medications as best as you know, and explain what you don't know.
45
+
46
+ Remember: You provide educational information, not personal medical advice."""
47
+
48
+
49
+ return f"Switched to {mode} mode"
50
+
51
+ # =============================================
52
+ # CONFIGURATION
53
+ # =============================================
54
+
55
+ # Model selection
56
+ MODEL = 'llama3.2:3b' # x your Ollama model name here after downloading it
57
+
58
+ # 2: Set your parameters (tune these for your domain!) try different values and see what works best
59
+ PARAMS = {
60
+ 'temperature': 0.1, # Adjust (0.1 = focused, 0.9 = creative)
61
+ 'top_p': 0.9, # Adjust (0.85-0.95 recommended)
62
+ 'num_predict': 300, # Adjust max length
63
+ 'repeat_penalty': 1.0 # Adjust if needed
64
+ }
65
+
66
+ # =============================================
67
+ # MEMORY & STATE
68
+ # =============================================
69
+
70
+ # Conversation history (for Feature: Memory)
71
+ conversation_history = []
72
+
73
+ # =============================================
74
+ # CORE FUNCTIONS
75
+ # =============================================
76
+
77
+ def chat(user_message):
78
+ """
79
+ Main chat function with conversation memory
80
+
81
+ 3: Add your custom logic here
82
+ Ideas:
83
+ - Pre-process user input
84
+ - Add domain-specific checks
85
+ - Format output in special ways
86
+ - Add citations or references
87
+ """
88
+
89
+ # Validate input
90
+ if not user_message.strip():
91
+ return "Please ask a question!"
92
+
93
+ # 4: Add any pre-processing here
94
+
95
+ # If emergency is mentioned, instruct user to seek immediate help
96
+ if "emergency" in user_message.lower() or "immediate" in user_message.lower():
97
+ return "Please seek immediate help from a healthcare professional."
98
+
99
+ # Add user message to history
100
+ conversation_history.append({
101
+ 'role': 'user',
102
+ 'content': user_message
103
+ })
104
+
105
+ # Get AI response
106
+ try:
107
+ response = ollama.chat(
108
+ model=MODEL,
109
+ messages=[
110
+ {'role': 'system', 'content': SYSTEM_PROMPT}
111
+ ] + conversation_history,
112
+ options=PARAMS
113
+ )
114
+
115
+ # Extract answer
116
+ answer = response['message']['content']
117
+
118
+ # Add to history
119
+ conversation_history.append({
120
+ 'role': 'assistant',
121
+ 'content': answer
122
+ })
123
+
124
+ # 5: Add any post-processing here
125
+
126
+ # Add disclaimer
127
+ disclaimer = "\n\n" + "─"*50 + "\n**Disclaimer:** This is educational information only. Always consult qualified healthcare professionals for medical advice."
128
+
129
+ return answer + disclaimer
130
+
131
+ except Exception as e:
132
+ return f"Error: {str(e)}\n\nMake sure Ollama is running and the model is downloaded."
133
+
134
+ def clear_conversation():
135
+ """Clear conversation history"""
136
+ global conversation_history
137
+ conversation_history = []
138
+ return "", "Conversation cleared! Start fresh."
139
+
140
+ # 6: Add your custom feature functions here
141
+
142
+ def switch_examples(mode):
143
+ """Switch example prompts based on mode"""
144
+ new_dataset = get_examples(mode)
145
+ print ("Switching examples to:", new_dataset.samples)
146
+ return new_dataset
147
+
148
+ def export_conversation():
149
+ """Export chat history to text file"""
150
+ if not conversation_history:
151
+ return "No conversation to export!"
152
+
153
+ text = ""
154
+ for msg in conversation_history:
155
+ role = msg['role'].upper()
156
+ content = msg['content']
157
+ text += f"{role}:\n{content}\n\n" + "─"*50 + "\n\n"
158
+
159
+ # Save to file
160
+ with open("conversation_export.txt", "w") as f:
161
+ f.write(text)
162
+
163
+ return "Exported to conversation_export.txt"
164
+
165
+ # Create a dictionary to hold the raw lists
166
+ EXAMPLE_SAMPLES = {
167
+ "patient": [
168
+ ["How should I manage my blood pressure medication schedule?"],
169
+ ["Why did my doctor change my dosage?"],
170
+ ["Is it normal to feel dizzy after starting this?"],
171
+ ["What are the side effects of my current medications?"],
172
+ ["Which medications should I take with food?"],
173
+ ["What are the interactions between my medications?"],
174
+ ],
175
+ "doctor": [
176
+ ["What is the patient's current medication list?"],
177
+ ["Can you provide a summary of the patient's recent medication schedule?"],
178
+ ["What are the patient's concerns about their medications?"],
179
+ ]
180
+ }
181
+
182
+ def get_examples(mode):
183
+ # Return the correct examples to the gradio component.
184
+ return gr.Dataset(samples=EXAMPLE_SAMPLES[mode])
185
+
186
+ # =============================================
187
+ # GRADIO INTERFACE
188
+ # =============================================
189
+
190
+ # 7: Customize your interface design
191
+ with gr.Blocks(theme=gr.themes.Soft(), title="Medical Chatbot") as app:
192
+
193
+ # Header
194
+ gr.Markdown(f"""
195
+ # Patient/Doctor Medication Chatbot
196
+ ### Patients can ask questions about their medications and schedule. Healthcare professionals can get summaries of the patient's medication experience.
197
+
198
+ **Domain:** Medication Management
199
+ **Powered by:** {MODEL} via Ollama
200
+ """)
201
+
202
+ # Main interface
203
+ with gr.Row():
204
+ with gr.Column(scale=2):
205
+ # Input area
206
+ question = gr.Textbox(
207
+ label="💬 Your Question",
208
+ placeholder="Ask anything about your medications...",
209
+ lines=3
210
+ )
211
+
212
+ # Buttons
213
+ with gr.Row():
214
+ submit_btn = gr.Button("🚀 Ask", variant="primary", size="lg")
215
+ clear_btn = gr.Button("🗑️ Clear", size="lg")
216
+
217
+ # 8: Add your custom controls here
218
+ # Add button:
219
+ export_btn = gr.Button("Export Conversation")
220
+ export_status = gr.Textbox(label="Export Status")
221
+ export_btn.click(export_conversation, outputs=export_status)
222
+
223
+ with gr.Row():
224
+ with gr.Column(scale=2):
225
+ # A selector for patient or doctor mode.
226
+ mode_selector = gr.Radio(
227
+ choices=["patient", "doctor"],
228
+ value="patient",
229
+ label="Mode"
230
+ )
231
+
232
+ with gr.Column(scale=3):
233
+ # Response area
234
+ response = gr.Textbox(
235
+ label="🤖 AI Response",
236
+ lines=15,
237
+ interactive=False
238
+ )
239
+
240
+ grExamples = gr.Examples(
241
+ examples=EXAMPLE_SAMPLES[current_mode],
242
+ inputs=question,
243
+ label="💡 Try these examples:",
244
+ cache_examples=False # Required for dynamic swapping
245
+ )
246
+
247
+ mode_selector.change(switch_prompt, inputs=mode_selector)
248
+ mode_selector.change(switch_examples, inputs=mode_selector, outputs=grExamples.dataset)
249
+
250
+ # 10: Add an "About" section
251
+ with gr.Accordion("ℹ️ About This Chatbot", open=False):
252
+ gr.Markdown("""
253
+ ### About
254
+ This chatbot is designed with two modes, patient and doctor, to assist patients and healthcare professionals with medication management.
255
+ In patient mode, itt provides a patient information about medication schedules, side effects, interactions, and more based on their prompts.
256
+ In doctor mode, it provides the doctor or healthcare professional a summary of what the patient has asked about regarding their medications.
257
+ The chatbot will remember the conversation history to provide context-aware responses.
258
+
259
+ ### Features
260
+ - Feature 1: Answer patient questions about medications and remembers history.
261
+ - Feature 2: Provide doctors with summaries of patient inquiries to help with medication management.
262
+ - Feature 3: Suggests prompts depending on the mode selected (different prompts for doctors and patients).
263
+ - Feature 4: Export conversation history for record-keeping or further analysis.
264
+
265
+ ### Technical Details
266
+ - **Model:** {model}
267
+ - **Framework:** Ollama + Gradio
268
+ - **Temperature:** {temp}
269
+ - **Max Length:** {max_len} tokens
270
+
271
+ ### Important Notes
272
+ ⚠️ This chatbot is for educational purposes only.
273
+ ⚠️ It is NOT a substitute for professional medical advice.
274
+ ⚠️ Always consult qualified healthcare providers for medical concerns.
275
+
276
+ ### Creator
277
+ **Developed by:** Donnie Goodson
278
+ **Course:** Medical AI
279
+ **Date:** April 18, 2026
280
+ """.format(
281
+ model=MODEL,
282
+ temp=PARAMS['temperature'],
283
+ max_len=PARAMS['num_predict']
284
+ ))
285
+
286
+ # Connect buttons to functions
287
+ submit_btn.click(
288
+ fn=chat,
289
+ inputs=question,
290
+ outputs=response
291
+ )
292
+
293
+ clear_btn.click(
294
+ fn=clear_conversation,
295
+ inputs=None,
296
+ outputs=[question, response]
297
+ )
298
+
299
+ # =============================================
300
+ # LAUNCH
301
+ # =============================================
302
+
303
+ if __name__ == "__main__":
304
+ print("\n" + "="*60)
305
+ print("LAUNCHING MEDICAL CHATBOT")
306
+ print("="*60)
307
+ print(f"\nModel: {MODEL}")
308
+ print(f"Domain: Medication Management")
309
+ print(f"Parameters: {PARAMS}")
310
+ print("\nStarting server... Open the URL below in your browser.\n")
311
+
312
+ app.launch(
313
+ share=True, # Set to True to get public URL and False for local only
314
+ )
chatBotOllama.ipynb ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 320,
6
+ "id": "31c47390",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "\"\"\"\n",
11
+ "Medical Chatbot using Ollama and Gradio\n",
12
+ "This template provides a complete chatbot with sections to customize.\n",
13
+ "\"\"\"\n",
14
+ "\n",
15
+ "import ollama\n",
16
+ "import gradio as gr"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": 321,
22
+ "id": "ccc77483",
23
+ "metadata": {},
24
+ "outputs": [],
25
+ "source": [
26
+ "# 1: Customize system prompt for either healthcare professional or patient based on a radio button selection\n",
27
+ "\n",
28
+ "import gradio as gr\n",
29
+ "current_mode = \"patient\" # default\n",
30
+ "grExamples = None\n",
31
+ "\n",
32
+ "def switch_prompt(mode):\n",
33
+ " \"\"\"Switch between patient and doctor mode\"\"\"\n",
34
+ " global current_mode, SYSTEM_PROMPT\n",
35
+ " current_mode = mode\n",
36
+ " \n",
37
+ " # patient mode\n",
38
+ " if mode == \"patient\":\n",
39
+ " SYSTEM_PROMPT = \"\"\"You are a medical AI assistant specialized in medication questions and management for a patient.\n",
40
+ "\n",
41
+ " Your role is to help the patient keep track of their medication schedule and provide information about their medications.\n",
42
+ "\n",
43
+ " When answering:\n",
44
+ " - Tell them they can let you know about any changes in medications at any time.\n",
45
+ " - Let them know about any upcoming medication times.\n",
46
+ " - Ask what medications they have taken today so far.\n",
47
+ " - Be accurate and evidence-based.\n",
48
+ " - Use clear, simple language.\n",
49
+ "\n",
50
+ " Remember: You provide educational information, not personal medical advice.\"\"\"\n",
51
+ " \n",
52
+ " # Update the example prompts.\n",
53
+ " else: # doctor mode\n",
54
+ " SYSTEM_PROMPT = \"\"\"You are a medical AI assistant specialized in providing information to healthcare professionals about a patient's medications and management.\n",
55
+ "\n",
56
+ " Your role is to inform the healthcare professional so they understand the patient's medication list, recent medication schedule, and any concerns the patient has asked about their medications.\n",
57
+ "\n",
58
+ " When answering:\n",
59
+ " - Present the list of medications the patient is taking.\n",
60
+ " - Provide a summary of specific questions the patient has asked.\n",
61
+ " - Detail the schedule of the patient's medications as best as you know, and explain what you don't know.\n",
62
+ "\n",
63
+ " Remember: You provide educational information, not personal medical advice.\"\"\"\n",
64
+ " \n",
65
+ " \n",
66
+ " return f\"Switched to {mode} mode\""
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": 322,
72
+ "id": "9e6e1435",
73
+ "metadata": {},
74
+ "outputs": [],
75
+ "source": [
76
+ "# =============================================\n",
77
+ "# CONFIGURATION\n",
78
+ "# =============================================\n",
79
+ "\n",
80
+ "# Model selection\n",
81
+ "MODEL = 'llama3.2:3b' # x your Ollama model name here after downloading it\n",
82
+ "\n",
83
+ "# 2: Set your parameters (tune these for your domain!) try different values and see what works best\n",
84
+ "PARAMS = {\n",
85
+ " 'temperature': 0.1, # Adjust (0.1 = focused, 0.9 = creative)\n",
86
+ " 'top_p': 0.9, # Adjust (0.85-0.95 recommended)\n",
87
+ " 'num_predict': 300, # Adjust max length\n",
88
+ " 'repeat_penalty': 1.0 # Adjust if needed\n",
89
+ "}\n",
90
+ "\n",
91
+ "# =============================================\n",
92
+ "# MEMORY & STATE\n",
93
+ "# =============================================\n",
94
+ "\n",
95
+ "# Conversation history (for Feature: Memory)\n",
96
+ "conversation_history = []\n",
97
+ "\n"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": 323,
103
+ "id": "a49ae2ca",
104
+ "metadata": {},
105
+ "outputs": [],
106
+ "source": [
107
+ "# =============================================\n",
108
+ "# CORE FUNCTIONS\n",
109
+ "# =============================================\n",
110
+ "\n",
111
+ "def chat(user_message):\n",
112
+ " \"\"\"\n",
113
+ " Main chat function with conversation memory\n",
114
+ " \n",
115
+ " 3: Add your custom logic here\n",
116
+ " Ideas:\n",
117
+ " - Pre-process user input\n",
118
+ " - Add domain-specific checks\n",
119
+ " - Format output in special ways\n",
120
+ " - Add citations or references\n",
121
+ " \"\"\"\n",
122
+ " \n",
123
+ " # Validate input\n",
124
+ " if not user_message.strip():\n",
125
+ " return \"Please ask a question!\"\n",
126
+ " \n",
127
+ " # 4: Add any pre-processing here\n",
128
+ " \n",
129
+ " # If emergency is mentioned, instruct user to seek immediate help\n",
130
+ " if \"emergency\" in user_message.lower() or \"immediate\" in user_message.lower():\n",
131
+ " return \"Please seek immediate help from a healthcare professional.\"\n",
132
+ " \n",
133
+ " # Add user message to history\n",
134
+ " conversation_history.append({\n",
135
+ " 'role': 'user',\n",
136
+ " 'content': user_message\n",
137
+ " })\n",
138
+ " \n",
139
+ " # Get AI response\n",
140
+ " try:\n",
141
+ " response = ollama.chat(\n",
142
+ " model=MODEL,\n",
143
+ " messages=[\n",
144
+ " {'role': 'system', 'content': SYSTEM_PROMPT}\n",
145
+ " ] + conversation_history,\n",
146
+ " options=PARAMS\n",
147
+ " )\n",
148
+ " \n",
149
+ " # Extract answer\n",
150
+ " answer = response['message']['content']\n",
151
+ " \n",
152
+ " # Add to history\n",
153
+ " conversation_history.append({\n",
154
+ " 'role': 'assistant',\n",
155
+ " 'content': answer\n",
156
+ " })\n",
157
+ " \n",
158
+ " # 5: Add any post-processing here\n",
159
+ " \n",
160
+ " # Add disclaimer\n",
161
+ " disclaimer = \"\\n\\n\" + \"─\"*50 + \"\\n**Disclaimer:** This is educational information only. Always consult qualified healthcare professionals for medical advice.\"\n",
162
+ " \n",
163
+ " return answer + disclaimer\n",
164
+ " \n",
165
+ " except Exception as e:\n",
166
+ " return f\"Error: {str(e)}\\n\\nMake sure Ollama is running and the model is downloaded.\"\n"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "execution_count": 324,
172
+ "id": "181f4dd1",
173
+ "metadata": {},
174
+ "outputs": [],
175
+ "source": [
176
+ "def clear_conversation():\n",
177
+ " \"\"\"Clear conversation history\"\"\"\n",
178
+ " global conversation_history\n",
179
+ " conversation_history = []\n",
180
+ " return \"\", \"Conversation cleared! Start fresh.\""
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "execution_count": 325,
186
+ "id": "b252a74f",
187
+ "metadata": {},
188
+ "outputs": [],
189
+ "source": [
190
+ "# 6: Add your custom feature functions here\n",
191
+ "\n",
192
+ "def switch_examples(mode):\n",
193
+ " \"\"\"Switch example prompts based on mode\"\"\"\n",
194
+ " new_dataset = get_examples(mode)\n",
195
+ " print (\"Switching examples to:\", new_dataset.samples)\n",
196
+ " return new_dataset\n",
197
+ "\n",
198
+ "def export_conversation():\n",
199
+ " \"\"\"Export chat history to text file\"\"\"\n",
200
+ " if not conversation_history:\n",
201
+ " return \"No conversation to export!\"\n",
202
+ " \n",
203
+ " text = \"\"\n",
204
+ " for msg in conversation_history:\n",
205
+ " role = msg['role'].upper()\n",
206
+ " content = msg['content']\n",
207
+ " text += f\"{role}:\\n{content}\\n\\n\" + \"─\"*50 + \"\\n\\n\"\n",
208
+ "\n",
209
+ " # Save to file\n",
210
+ " with open(\"conversation_export.txt\", \"w\") as f:\n",
211
+ " f.write(text)\n",
212
+ "\n",
213
+ " return \"Exported to conversation_export.txt\"\n",
214
+ "\n",
215
+ "# Create a dictionary to hold the raw lists\n",
216
+ "EXAMPLE_SAMPLES = {\n",
217
+ " \"patient\": [\n",
218
+ " [\"How should I manage my blood pressure medication schedule?\"],\n",
219
+ " [\"Why did my doctor change my dosage?\"],\n",
220
+ " [\"Is it normal to feel dizzy after starting this?\"],\n",
221
+ " [\"What are the side effects of my current medications?\"],\n",
222
+ " [\"Which medications should I take with food?\"],\n",
223
+ " [\"What are the interactions between my medications?\"],\n",
224
+ " ],\n",
225
+ " \"doctor\": [\n",
226
+ " [\"What is the patient's current medication list?\"],\n",
227
+ " [\"Can you provide a summary of the patient's recent medication schedule?\"],\n",
228
+ " [\"What are the patient's concerns about their medications?\"],\n",
229
+ " ]\n",
230
+ "}\n",
231
+ "\n",
232
+ "def get_examples(mode):\n",
233
+ " # Return the correct examples to the gradio component.\n",
234
+ " return gr.Dataset(samples=EXAMPLE_SAMPLES[mode])"
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": 326,
240
+ "id": "96c34ddf",
241
+ "metadata": {},
242
+ "outputs": [
243
+ {
244
+ "name": "stderr",
245
+ "output_type": "stream",
246
+ "text": [
247
+ "C:\\Users\\donni\\AppData\\Local\\Temp\\ipykernel_29884\\4222941924.py:6: UserWarning: The parameters have been moved from the Blocks constructor to the launch() method in Gradio 6.0: theme. Please pass these parameters to launch() instead.\n",
248
+ " with gr.Blocks(theme=gr.themes.Soft(), title=\"Medical Chatbot\") as app:\n"
249
+ ]
250
+ }
251
+ ],
252
+ "source": [
253
+ "# =============================================\n",
254
+ "# GRADIO INTERFACE\n",
255
+ "# =============================================\n",
256
+ "\n",
257
+ "# 7: Customize your interface design\n",
258
+ "with gr.Blocks(theme=gr.themes.Soft(), title=\"Medical Chatbot\") as app:\n",
259
+ " \n",
260
+ " # Header\n",
261
+ " gr.Markdown(f\"\"\"\n",
262
+ " # Patient/Doctor Medication Chatbot\n",
263
+ " ### Patients can ask questions about their medications and schedule. Healthcare professionals can get summaries of the patient's medication experience.\n",
264
+ " \n",
265
+ " **Domain:** Medication Management \n",
266
+ " **Powered by:** {MODEL} via Ollama\n",
267
+ " \"\"\")\n",
268
+ " \n",
269
+ " # Main interface\n",
270
+ " with gr.Row():\n",
271
+ " with gr.Column(scale=2):\n",
272
+ " # Input area\n",
273
+ " question = gr.Textbox(\n",
274
+ " label=\"💬 Your Question\",\n",
275
+ " placeholder=\"Ask anything about your medications...\",\n",
276
+ " lines=3\n",
277
+ " )\n",
278
+ " \n",
279
+ " # Buttons\n",
280
+ " with gr.Row():\n",
281
+ " submit_btn = gr.Button(\"🚀 Ask\", variant=\"primary\", size=\"lg\")\n",
282
+ " clear_btn = gr.Button(\"🗑️ Clear\", size=\"lg\")\n",
283
+ " \n",
284
+ " # 8: Add your custom controls here\n",
285
+ " # Add button:\n",
286
+ " export_btn = gr.Button(\"Export Conversation\")\n",
287
+ " export_status = gr.Textbox(label=\"Export Status\")\n",
288
+ " export_btn.click(export_conversation, outputs=export_status)\n",
289
+ "\n",
290
+ " with gr.Row():\n",
291
+ " with gr.Column(scale=2):\n",
292
+ " # A selector for patient or doctor mode.\n",
293
+ " mode_selector = gr.Radio(\n",
294
+ " choices=[\"patient\", \"doctor\"],\n",
295
+ " value=\"patient\",\n",
296
+ " label=\"Mode\"\n",
297
+ " )\n",
298
+ " \n",
299
+ " with gr.Column(scale=3):\n",
300
+ " # Response area\n",
301
+ " response = gr.Textbox(\n",
302
+ " label=\"🤖 AI Response\",\n",
303
+ " lines=15,\n",
304
+ " interactive=False\n",
305
+ " )\n",
306
+ "\n",
307
+ " grExamples = gr.Examples(\n",
308
+ " examples=EXAMPLE_SAMPLES[current_mode],\n",
309
+ " inputs=question,\n",
310
+ " label=\"💡 Try these examples:\",\n",
311
+ " cache_examples=False # Required for dynamic swapping\n",
312
+ " )\n",
313
+ "\n",
314
+ " mode_selector.change(switch_prompt, inputs=mode_selector)\n",
315
+ " mode_selector.change(switch_examples, inputs=mode_selector, outputs=grExamples.dataset)\n",
316
+ " \n",
317
+ " # 10: Add an \"About\" section\n",
318
+ " with gr.Accordion(\"ℹ️ About This Chatbot\", open=False):\n",
319
+ " gr.Markdown(\"\"\"\n",
320
+ " ### About\n",
321
+ " This chatbot is designed with two modes, patient and doctor, to assist patients and healthcare professionals with medication management. \n",
322
+ " In patient mode, itt provides a patient information about medication schedules, side effects, interactions, and more based on their prompts.\n",
323
+ " In doctor mode, it provides the doctor or healthcare professional a summary of what the patient has asked about regarding their medications.\n",
324
+ " The chatbot will remember the conversation history to provide context-aware responses.\n",
325
+ " \n",
326
+ " ### Features\n",
327
+ " - Feature 1: Answer patient questions about medications and remembers history.\n",
328
+ " - Feature 2: Provide doctors with summaries of patient inquiries to help with medication management.\n",
329
+ " - Feature 3: Suggests prompts depending on the mode selected (different prompts for doctors and patients).\n",
330
+ " - Feature 4: Export conversation history for record-keeping or further analysis.\n",
331
+ " \n",
332
+ " ### Technical Details\n",
333
+ " - **Model:** {model}\n",
334
+ " - **Framework:** Ollama + Gradio\n",
335
+ " - **Temperature:** {temp}\n",
336
+ " - **Max Length:** {max_len} tokens\n",
337
+ " \n",
338
+ " ### Important Notes\n",
339
+ " ⚠️ This chatbot is for educational purposes only. \n",
340
+ " ⚠️ It is NOT a substitute for professional medical advice. \n",
341
+ " ⚠️ Always consult qualified healthcare providers for medical concerns.\n",
342
+ " \n",
343
+ " ### Creator\n",
344
+ " **Developed by:** Donnie Goodson\n",
345
+ " **Course:** Medical AI \n",
346
+ " **Date:** April 18, 2026\n",
347
+ " \"\"\".format(\n",
348
+ " model=MODEL,\n",
349
+ " temp=PARAMS['temperature'],\n",
350
+ " max_len=PARAMS['num_predict']\n",
351
+ " ))\n",
352
+ " \n",
353
+ " # Connect buttons to functions\n",
354
+ " submit_btn.click(\n",
355
+ " fn=chat,\n",
356
+ " inputs=question,\n",
357
+ " outputs=response\n",
358
+ " )\n",
359
+ " \n",
360
+ " clear_btn.click(\n",
361
+ " fn=clear_conversation,\n",
362
+ " inputs=None,\n",
363
+ " outputs=[question, response]\n",
364
+ " )"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "code",
369
+ "execution_count": 327,
370
+ "id": "2196dac3",
371
+ "metadata": {},
372
+ "outputs": [
373
+ {
374
+ "name": "stdout",
375
+ "output_type": "stream",
376
+ "text": [
377
+ "\n",
378
+ "============================================================\n",
379
+ "LAUNCHING MEDICAL CHATBOT\n",
380
+ "============================================================\n",
381
+ "\n",
382
+ "Model: llama3.2:3b\n",
383
+ "Domain: Medication Management\n",
384
+ "Parameters: {'temperature': 0.1, 'top_p': 0.9, 'num_predict': 300, 'repeat_penalty': 1.0}\n",
385
+ "\n",
386
+ "Starting server... Open the URL below in your browser.\n",
387
+ "\n",
388
+ "* Running on local URL: http://127.0.0.1:7883\n",
389
+ "* Running on public URL: https://058deb7a179b2a769c.gradio.live\n",
390
+ "\n",
391
+ "This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
392
+ ]
393
+ },
394
+ {
395
+ "data": {
396
+ "text/html": [
397
+ "<div><iframe src=\"https://058deb7a179b2a769c.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
398
+ ],
399
+ "text/plain": [
400
+ "<IPython.core.display.HTML object>"
401
+ ]
402
+ },
403
+ "metadata": {},
404
+ "output_type": "display_data"
405
+ },
406
+ {
407
+ "name": "stderr",
408
+ "output_type": "stream",
409
+ "text": [
410
+ "c:\\Users\\donni\\AppData\\Local\\Python\\pythoncore-3.14-64\\Lib\\site-packages\\gradio\\blocks.py:1851: UserWarning: A function (switch_prompt) returned too many output values (needed: 0, returned: 1). Ignoring extra values.\n",
411
+ " Output components:\n",
412
+ " []\n",
413
+ " Output values returned:\n",
414
+ " [\"Switched to doctor mode\"]\n",
415
+ " warnings.warn(\n"
416
+ ]
417
+ },
418
+ {
419
+ "name": "stdout",
420
+ "output_type": "stream",
421
+ "text": [
422
+ "Switching examples to: [[], [], []]\n"
423
+ ]
424
+ }
425
+ ],
426
+ "source": [
427
+ "# =============================================\n",
428
+ "# LAUNCH\n",
429
+ "# =============================================\n",
430
+ "\n",
431
+ "if __name__ == \"__main__\":\n",
432
+ " print(\"\\n\" + \"=\"*60)\n",
433
+ " print(\"LAUNCHING MEDICAL CHATBOT\")\n",
434
+ " print(\"=\"*60)\n",
435
+ " print(f\"\\nModel: {MODEL}\")\n",
436
+ " print(f\"Domain: Medication Management\")\n",
437
+ " print(f\"Parameters: {PARAMS}\")\n",
438
+ " print(\"\\nStarting server... Open the URL below in your browser.\\n\")\n",
439
+ " \n",
440
+ " app.launch(\n",
441
+ " share=True, # Set to True to get public URL and False for local only\n",
442
+ " )"
443
+ ]
444
+ }
445
+ ],
446
+ "metadata": {
447
+ "kernelspec": {
448
+ "display_name": "Python 3",
449
+ "language": "python",
450
+ "name": "python3"
451
+ },
452
+ "language_info": {
453
+ "codemirror_mode": {
454
+ "name": "ipython",
455
+ "version": 3
456
+ },
457
+ "file_extension": ".py",
458
+ "mimetype": "text/x-python",
459
+ "name": "python",
460
+ "nbconvert_exporter": "python",
461
+ "pygments_lexer": "ipython3",
462
+ "version": "3.14.4"
463
+ }
464
+ },
465
+ "nbformat": 4,
466
+ "nbformat_minor": 5
467
+ }