Spaces:
Sleeping
Sleeping
Initialize P2
Browse filesFiles changed (4)
- .gradio/certificate.pemAdded+31
- README.md+54
- app.pyAdded+314
- chatBotOllama.ipynbAdded+467
12345678910111213141516171819202122232425262728293031-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----9 unmodified lines1011129 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465669 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Medical Chat Bot## Domain[Your chosen domain]## Setup Instructions### Prerequisites- Python 3.14.4+- [Ollama OR HuggingFace account]### Installation1. Install Ollama```bash# Mac:brew install ollama# Windows: Download from https://ollama.ai# Linux:curl -fsSL https://ollama.com/install.sh | sh```1. Download llama3.2:3b model:```bashollama pull llama3.2:3b```1. Install Python packages```bashpip install ollama gradio```### Running```bashpython your_file.py```## Features- Feature 1: [Description]- Feature 2: [Description]## Technical Details- Model: llama3.2:3b- Framework: Ollama- Special considerations: [Any important notes]## Demo[Link to video OR screenshots]## Known Limitations[What your chatbot cannot do]## Future Improvements[What you would add with more time]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Medical Chatbot using Ollama and GradioThis template provides a complete chatbot with sections to customize."""
import ollamaimport gradio as gr
# 1: Customize system prompt for either healthcare professional or patient based on a radio button selection
import gradio as grcurrent_mode = "patient" # defaultgrExamples = None
def switch_prompt(mode): """Switch between patient and doctor mode""" global current_mode, SYSTEM_PROMPT current_mode = mode # patient mode if mode == "patient": SYSTEM_PROMPT = """You are a medical AI assistant specialized in medication questions and management for a patient.
Your role is to help the patient keep track of their medication schedule and provide information about their medications.
When answering: - Tell them they can let you know about any changes in medications at any time. - Let them know about any upcoming medication times. - Ask what medications they have taken today so far. - Be accurate and evidence-based. - Use clear, simple language.
Remember: You provide educational information, not personal medical advice.""" # Update the example prompts. else: # doctor mode SYSTEM_PROMPT = """You are a medical AI assistant specialized in providing information to healthcare professionals about a patient's medications and management.
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.
When answering: - Present the list of medications the patient is taking. - Provide a summary of specific questions the patient has asked. - Detail the schedule of the patient's medications as best as you know, and explain what you don't know.
Remember: You provide educational information, not personal medical advice.""" return f"Switched to {mode} mode"
# =============================================# CONFIGURATION# =============================================
# Model selectionMODEL = 'llama3.2:3b' # x your Ollama model name here after downloading it
# 2: Set your parameters (tune these for your domain!) try different values and see what works bestPARAMS = { 'temperature': 0.1, # Adjust (0.1 = focused, 0.9 = creative) 'top_p': 0.9, # Adjust (0.85-0.95 recommended) 'num_predict': 300, # Adjust max length 'repeat_penalty': 1.0 # Adjust if needed}
# =============================================# MEMORY & STATE# =============================================
# Conversation history (for Feature: Memory)conversation_history = []
# =============================================# CORE FUNCTIONS# =============================================
def chat(user_message): """ Main chat function with conversation memory 3: Add your custom logic here Ideas: - Pre-process user input - Add domain-specific checks - Format output in special ways - Add citations or references """ # Validate input if not user_message.strip(): return "Please ask a question!" # 4: Add any pre-processing here # If emergency is mentioned, instruct user to seek immediate help if "emergency" in user_message.lower() or "immediate" in user_message.lower(): return "Please seek immediate help from a healthcare professional." # Add user message to history conversation_history.append({ 'role': 'user', 'content': user_message }) # Get AI response try: response = ollama.chat( model=MODEL, messages=[ {'role': 'system', 'content': SYSTEM_PROMPT} ] + conversation_history, options=PARAMS ) # Extract answer answer = response['message']['content'] # Add to history conversation_history.append({ 'role': 'assistant', 'content': answer }) # 5: Add any post-processing here # Add disclaimer disclaimer = "\n\n" + "─"*50 + "\n**Disclaimer:** This is educational information only. Always consult qualified healthcare professionals for medical advice." return answer + disclaimer except Exception as e: return f"Error: {str(e)}\n\nMake sure Ollama is running and the model is downloaded."
def clear_conversation(): """Clear conversation history""" global conversation_history conversation_history = [] return "", "Conversation cleared! Start fresh."
# 6: Add your custom feature functions here
def switch_examples(mode): """Switch example prompts based on mode""" new_dataset = get_examples(mode) print ("Switching examples to:", new_dataset.samples) return new_dataset
def export_conversation(): """Export chat history to text file""" if not conversation_history: return "No conversation to export!" text = "" for msg in conversation_history: role = msg['role'].upper() content = msg['content'] text += f"{role}:\n{content}\n\n" + "─"*50 + "\n\n"
# Save to file with open("conversation_export.txt", "w") as f: f.write(text)
return "Exported to conversation_export.txt"
# Create a dictionary to hold the raw listsEXAMPLE_SAMPLES = { "patient": [ ["How should I manage my blood pressure medication schedule?"], ["Why did my doctor change my dosage?"], ["Is it normal to feel dizzy after starting this?"], ["What are the side effects of my current medications?"], ["Which medications should I take with food?"], ["What are the interactions between my medications?"], ], "doctor": [ ["What is the patient's current medication list?"], ["Can you provide a summary of the patient's recent medication schedule?"], ["What are the patient's concerns about their medications?"], ]}
def get_examples(mode): # Return the correct examples to the gradio component. return gr.Dataset(samples=EXAMPLE_SAMPLES[mode])
# =============================================# GRADIO INTERFACE# =============================================
# 7: Customize your interface designwith gr.Blocks(theme=gr.themes.Soft(), title="Medical Chatbot") as app: # Header gr.Markdown(f""" # Patient/Doctor Medication Chatbot ### Patients can ask questions about their medications and schedule. Healthcare professionals can get summaries of the patient's medication experience. **Domain:** Medication Management **Powered by:** {MODEL} via Ollama """) # Main interface with gr.Row(): with gr.Column(scale=2): # Input area question = gr.Textbox( label="💬 Your Question", placeholder="Ask anything about your medications...", lines=3 ) # Buttons with gr.Row(): submit_btn = gr.Button("🚀 Ask", variant="primary", size="lg") clear_btn = gr.Button("🗑️ Clear", size="lg") # 8: Add your custom controls here # Add button: export_btn = gr.Button("Export Conversation") export_status = gr.Textbox(label="Export Status") export_btn.click(export_conversation, outputs=export_status)
with gr.Row(): with gr.Column(scale=2): # A selector for patient or doctor mode. mode_selector = gr.Radio( choices=["patient", "doctor"], value="patient", label="Mode" ) with gr.Column(scale=3): # Response area response = gr.Textbox( label="🤖 AI Response", lines=15, interactive=False )
grExamples = gr.Examples( examples=EXAMPLE_SAMPLES[current_mode], inputs=question, label="💡 Try these examples:", cache_examples=False # Required for dynamic swapping )
mode_selector.change(switch_prompt, inputs=mode_selector) mode_selector.change(switch_examples, inputs=mode_selector, outputs=grExamples.dataset) # 10: Add an "About" section with gr.Accordion("ℹ️ About This Chatbot", open=False): gr.Markdown(""" ### About This chatbot is designed with two modes, patient and doctor, to assist patients and healthcare professionals with medication management. In patient mode, itt provides a patient information about medication schedules, side effects, interactions, and more based on their prompts. In doctor mode, it provides the doctor or healthcare professional a summary of what the patient has asked about regarding their medications. The chatbot will remember the conversation history to provide context-aware responses. ### Features - Feature 1: Answer patient questions about medications and remembers history. - Feature 2: Provide doctors with summaries of patient inquiries to help with medication management. - Feature 3: Suggests prompts depending on the mode selected (different prompts for doctors and patients). - Feature 4: Export conversation history for record-keeping or further analysis. ### Technical Details - **Model:** {model} - **Framework:** Ollama + Gradio - **Temperature:** {temp} - **Max Length:** {max_len} tokens ### Important Notes ⚠️ This chatbot is for educational purposes only. ⚠️ It is NOT a substitute for professional medical advice. ⚠️ Always consult qualified healthcare providers for medical concerns. ### Creator **Developed by:** Donnie Goodson **Course:** Medical AI **Date:** April 18, 2026 """.format( model=MODEL, temp=PARAMS['temperature'], max_len=PARAMS['num_predict'] )) # Connect buttons to functions submit_btn.click( fn=chat, inputs=question, outputs=response ) clear_btn.click( fn=clear_conversation, inputs=None, outputs=[question, response] )
# =============================================# LAUNCH# =============================================
if __name__ == "__main__": print("\n" + "="*60) print("LAUNCHING MEDICAL CHATBOT") print("="*60) print(f"\nModel: {MODEL}") print(f"Domain: Medication Management") print(f"Parameters: {PARAMS}") print("\nStarting server... Open the URL below in your browser.\n") app.launch( share=True, # Set to True to get public URL and False for local only )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467{ "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": [ "<div><iframe src=\"https://058deb7a179b2a769c.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "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}.gradio/certificate.pemAdded+31
README.md+54
app.pyAdded+314
chatBotOllama.ipynbAdded+467