{ "cells": [ { "cell_type": "code", "execution_count": 320, "id": "31c47390", "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", "Medical Chatbot using Ollama and Gradio\n", "This template provides a complete chatbot with sections to customize.\n", "\"\"\"\n", "\n", "import ollama\n", "import gradio as gr" ] }, { "cell_type": "code", "execution_count": 321, "id": "ccc77483", "metadata": {}, "outputs": [], "source": [ "# 1: Customize system prompt for either healthcare professional or patient based on a radio button selection\n", "\n", "import gradio as gr\n", "current_mode = \"patient\" # default\n", "grExamples = None\n", "\n", "def switch_prompt(mode):\n", " \"\"\"Switch between patient and doctor mode\"\"\"\n", " global current_mode, SYSTEM_PROMPT\n", " current_mode = mode\n", " \n", " # patient mode\n", " if mode == \"patient\":\n", " SYSTEM_PROMPT = \"\"\"You are a medical AI assistant specialized in medication questions and management for a patient.\n", "\n", " Your role is to help the patient keep track of their medication schedule and provide information about their medications.\n", "\n", " When answering:\n", " - Tell them they can let you know about any changes in medications at any time.\n", " - Let them know about any upcoming medication times.\n", " - Ask what medications they have taken today so far.\n", " - Be accurate and evidence-based.\n", " - Use clear, simple language.\n", "\n", " Remember: You provide educational information, not personal medical advice.\"\"\"\n", " \n", " # Update the example prompts.\n", " else: # doctor mode\n", " SYSTEM_PROMPT = \"\"\"You are a medical AI assistant specialized in providing information to healthcare professionals about a patient's medications and management.\n", "\n", " 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", "\n", " When answering:\n", " - Present the list of medications the patient is taking.\n", " - Provide a summary of specific questions the patient has asked.\n", " - Detail the schedule of the patient's medications as best as you know, and explain what you don't know.\n", "\n", " Remember: You provide educational information, not personal medical advice.\"\"\"\n", " \n", " \n", " return f\"Switched to {mode} mode\"" ] }, { "cell_type": "code", "execution_count": 322, "id": "9e6e1435", "metadata": {}, "outputs": [], "source": [ "# =============================================\n", "# CONFIGURATION\n", "# =============================================\n", "\n", "# Model selection\n", "MODEL = 'llama3.2:3b' # x your Ollama model name here after downloading it\n", "\n", "# 2: Set your parameters (tune these for your domain!) try different values and see what works best\n", "PARAMS = {\n", " 'temperature': 0.1, # Adjust (0.1 = focused, 0.9 = creative)\n", " 'top_p': 0.9, # Adjust (0.85-0.95 recommended)\n", " 'num_predict': 300, # Adjust max length\n", " 'repeat_penalty': 1.0 # Adjust if needed\n", "}\n", "\n", "# =============================================\n", "# MEMORY & STATE\n", "# =============================================\n", "\n", "# Conversation history (for Feature: Memory)\n", "conversation_history = []\n", "\n" ] }, { "cell_type": "code", "execution_count": 323, "id": "a49ae2ca", "metadata": {}, "outputs": [], "source": [ "# =============================================\n", "# CORE FUNCTIONS\n", "# =============================================\n", "\n", "def chat(user_message):\n", " \"\"\"\n", " Main chat function with conversation memory\n", " \n", " 3: Add your custom logic here\n", " Ideas:\n", " - Pre-process user input\n", " - Add domain-specific checks\n", " - Format output in special ways\n", " - Add citations or references\n", " \"\"\"\n", " \n", " # Validate input\n", " if not user_message.strip():\n", " return \"Please ask a question!\"\n", " \n", " # 4: Add any pre-processing here\n", " \n", " # If emergency is mentioned, instruct user to seek immediate help\n", " if \"emergency\" in user_message.lower() or \"immediate\" in user_message.lower():\n", " return \"Please seek immediate help from a healthcare professional.\"\n", " \n", " # Add user message to history\n", " conversation_history.append({\n", " 'role': 'user',\n", " 'content': user_message\n", " })\n", " \n", " # Get AI response\n", " try:\n", " response = ollama.chat(\n", " model=MODEL,\n", " messages=[\n", " {'role': 'system', 'content': SYSTEM_PROMPT}\n", " ] + conversation_history,\n", " options=PARAMS\n", " )\n", " \n", " # Extract answer\n", " answer = response['message']['content']\n", " \n", " # Add to history\n", " conversation_history.append({\n", " 'role': 'assistant',\n", " 'content': answer\n", " })\n", " \n", " # 5: Add any post-processing here\n", " \n", " # Add disclaimer\n", " disclaimer = \"\\n\\n\" + \"─\"*50 + \"\\n**Disclaimer:** This is educational information only. Always consult qualified healthcare professionals for medical advice.\"\n", " \n", " return answer + disclaimer\n", " \n", " except Exception as e:\n", " return f\"Error: {str(e)}\\n\\nMake sure Ollama is running and the model is downloaded.\"\n" ] }, { "cell_type": "code", "execution_count": 324, "id": "181f4dd1", "metadata": {}, "outputs": [], "source": [ "def clear_conversation():\n", " \"\"\"Clear conversation history\"\"\"\n", " global conversation_history\n", " conversation_history = []\n", " return \"\", \"Conversation cleared! Start fresh.\"" ] }, { "cell_type": "code", "execution_count": 325, "id": "b252a74f", "metadata": {}, "outputs": [], "source": [ "# 6: Add your custom feature functions here\n", "\n", "def switch_examples(mode):\n", " \"\"\"Switch example prompts based on mode\"\"\"\n", " new_dataset = get_examples(mode)\n", " print (\"Switching examples to:\", new_dataset.samples)\n", " return new_dataset\n", "\n", "def export_conversation():\n", " \"\"\"Export chat history to text file\"\"\"\n", " if not conversation_history:\n", " return \"No conversation to export!\"\n", " \n", " text = \"\"\n", " for msg in conversation_history:\n", " role = msg['role'].upper()\n", " content = msg['content']\n", " text += f\"{role}:\\n{content}\\n\\n\" + \"─\"*50 + \"\\n\\n\"\n", "\n", " # Save to file\n", " with open(\"conversation_export.txt\", \"w\") as f:\n", " f.write(text)\n", "\n", " return \"Exported to conversation_export.txt\"\n", "\n", "# Create a dictionary to hold the raw lists\n", "EXAMPLE_SAMPLES = {\n", " \"patient\": [\n", " [\"How should I manage my blood pressure medication schedule?\"],\n", " [\"Why did my doctor change my dosage?\"],\n", " [\"Is it normal to feel dizzy after starting this?\"],\n", " [\"What are the side effects of my current medications?\"],\n", " [\"Which medications should I take with food?\"],\n", " [\"What are the interactions between my medications?\"],\n", " ],\n", " \"doctor\": [\n", " [\"What is the patient's current medication list?\"],\n", " [\"Can you provide a summary of the patient's recent medication schedule?\"],\n", " [\"What are the patient's concerns about their medications?\"],\n", " ]\n", "}\n", "\n", "def get_examples(mode):\n", " # Return the correct examples to the gradio component.\n", " return gr.Dataset(samples=EXAMPLE_SAMPLES[mode])" ] }, { "cell_type": "code", "execution_count": 326, "id": "96c34ddf", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "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", " with gr.Blocks(theme=gr.themes.Soft(), title=\"Medical Chatbot\") as app:\n" ] } ], "source": [ "# =============================================\n", "# GRADIO INTERFACE\n", "# =============================================\n", "\n", "# 7: Customize your interface design\n", "with gr.Blocks(theme=gr.themes.Soft(), title=\"Medical Chatbot\") as app:\n", " \n", " # Header\n", " gr.Markdown(f\"\"\"\n", " # Patient/Doctor Medication Chatbot\n", " ### Patients can ask questions about their medications and schedule. Healthcare professionals can get summaries of the patient's medication experience.\n", " \n", " **Domain:** Medication Management \n", " **Powered by:** {MODEL} via Ollama\n", " \"\"\")\n", " \n", " # Main interface\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " # Input area\n", " question = gr.Textbox(\n", " label=\"đŸ’Ŧ Your Question\",\n", " placeholder=\"Ask anything about your medications...\",\n", " lines=3\n", " )\n", " \n", " # Buttons\n", " with gr.Row():\n", " submit_btn = gr.Button(\"🚀 Ask\", variant=\"primary\", size=\"lg\")\n", " clear_btn = gr.Button(\"đŸ—‘ī¸ Clear\", size=\"lg\")\n", " \n", " # 8: Add your custom controls here\n", " # Add button:\n", " export_btn = gr.Button(\"Export Conversation\")\n", " export_status = gr.Textbox(label=\"Export Status\")\n", " export_btn.click(export_conversation, outputs=export_status)\n", "\n", " with gr.Row():\n", " with gr.Column(scale=2):\n", " # A selector for patient or doctor mode.\n", " mode_selector = gr.Radio(\n", " choices=[\"patient\", \"doctor\"],\n", " value=\"patient\",\n", " label=\"Mode\"\n", " )\n", " \n", " with gr.Column(scale=3):\n", " # Response area\n", " response = gr.Textbox(\n", " label=\"🤖 AI Response\",\n", " lines=15,\n", " interactive=False\n", " )\n", "\n", " grExamples = gr.Examples(\n", " examples=EXAMPLE_SAMPLES[current_mode],\n", " inputs=question,\n", " label=\"💡 Try these examples:\",\n", " cache_examples=False # Required for dynamic swapping\n", " )\n", "\n", " mode_selector.change(switch_prompt, inputs=mode_selector)\n", " mode_selector.change(switch_examples, inputs=mode_selector, outputs=grExamples.dataset)\n", " \n", " # 10: Add an \"About\" section\n", " with gr.Accordion(\"â„šī¸ About This Chatbot\", open=False):\n", " gr.Markdown(\"\"\"\n", " ### About\n", " This chatbot is designed with two modes, patient and doctor, to assist patients and healthcare professionals with medication management. \n", " In patient mode, itt provides a patient information about medication schedules, side effects, interactions, and more based on their prompts.\n", " In doctor mode, it provides the doctor or healthcare professional a summary of what the patient has asked about regarding their medications.\n", " The chatbot will remember the conversation history to provide context-aware responses.\n", " \n", " ### Features\n", " - Feature 1: Answer patient questions about medications and remembers history.\n", " - Feature 2: Provide doctors with summaries of patient inquiries to help with medication management.\n", " - Feature 3: Suggests prompts depending on the mode selected (different prompts for doctors and patients).\n", " - Feature 4: Export conversation history for record-keeping or further analysis.\n", " \n", " ### Technical Details\n", " - **Model:** {model}\n", " - **Framework:** Ollama + Gradio\n", " - **Temperature:** {temp}\n", " - **Max Length:** {max_len} tokens\n", " \n", " ### Important Notes\n", " âš ī¸ This chatbot is for educational purposes only. \n", " âš ī¸ It is NOT a substitute for professional medical advice. \n", " âš ī¸ Always consult qualified healthcare providers for medical concerns.\n", " \n", " ### Creator\n", " **Developed by:** Donnie Goodson\n", " **Course:** Medical AI \n", " **Date:** April 18, 2026\n", " \"\"\".format(\n", " model=MODEL,\n", " temp=PARAMS['temperature'],\n", " max_len=PARAMS['num_predict']\n", " ))\n", " \n", " # Connect buttons to functions\n", " submit_btn.click(\n", " fn=chat,\n", " inputs=question,\n", " outputs=response\n", " )\n", " \n", " clear_btn.click(\n", " fn=clear_conversation,\n", " inputs=None,\n", " outputs=[question, response]\n", " )" ] }, { "cell_type": "code", "execution_count": 327, "id": "2196dac3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "============================================================\n", "LAUNCHING MEDICAL CHATBOT\n", "============================================================\n", "\n", "Model: llama3.2:3b\n", "Domain: Medication Management\n", "Parameters: {'temperature': 0.1, 'top_p': 0.9, 'num_predict': 300, 'repeat_penalty': 1.0}\n", "\n", "Starting server... Open the URL below in your browser.\n", "\n", "* Running on local URL: http://127.0.0.1:7883\n", "* Running on public URL: https://058deb7a179b2a769c.gradio.live\n", "\n", "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" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "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", " Output components:\n", " []\n", " Output values returned:\n", " [\"Switched to doctor mode\"]\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Switching examples to: [[], [], []]\n" ] } ], "source": [ "# =============================================\n", "# LAUNCH\n", "# =============================================\n", "\n", "if __name__ == \"__main__\":\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"LAUNCHING MEDICAL CHATBOT\")\n", " print(\"=\"*60)\n", " print(f\"\\nModel: {MODEL}\")\n", " print(f\"Domain: Medication Management\")\n", " print(f\"Parameters: {PARAMS}\")\n", " print(\"\\nStarting server... Open the URL below in your browser.\\n\")\n", " \n", " app.launch(\n", " share=True, # Set to True to get public URL and False for local only\n", " )" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.4" } }, "nbformat": 4, "nbformat_minor": 5 }