PharmaSafe / app.py
lukmanaj's picture
Update app.py
18c4235 verified
from mistralai import Mistral
import gradio as gr
import os
from datetime import datetime
api_key = os.environ["MISTRAL_API_KEY"]
model = "mistral-large-latest"
client = Mistral(api_key=api_key)
def interaction_check(prompt):
"""
Check for drug interactions and provide pharmacist guidance
"""
try:
# Input validation
if not prompt or prompt.strip() == "":
return "⚠️ Please enter your medications or questions about drug interactions."
if len(prompt.strip()) < 5:
return "⚠️ Please provide more details about your medications for a proper assessment."
# Enhanced system prompt with better instructions
system_prompt = f"""You are a knowledgeable pharmacist assistant specializing in drug interaction detection and medication safety.
Your responsibilities:
1. Analyze potential drug interactions from the user's medication list
2. Identify contraindications and warnings
3. Provide clear, actionable advice
4. Always recommend consulting with a licensed pharmacist or healthcare provider
5. Use appropriate medical terminology while remaining accessible
6. Structure your response clearly with sections if multiple interactions are found
Important guidelines:
- Always emphasize that this is preliminary guidance only
- Recommend professional consultation for all medication concerns
- Be specific about interaction severity (minor, moderate, major)
- Include timing recommendations when relevant
- Mention food interactions if applicable
- Note any special monitoring requirements
Format your response with clear sections and use emojis for visual clarity where appropriate."""
chat_response = client.chat.complete(
model=model,
messages=[
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": f"Please analyze the following for drug interactions: {prompt}",
},
],
temperature=0.1, # Lower temperature for more consistent medical advice
max_tokens=1000 # Ensure comprehensive responses
)
response = chat_response.choices[0].message.content
# Add disclaimer footer
disclaimer = "\n\n---\n⚠️ **IMPORTANT DISCLAIMER**: This information is for educational purposes only and should not replace professional medical advice. Always consult with a licensed pharmacist or healthcare provider before making any changes to your medications."
return response + disclaimer
except Exception as e:
error_msg = f"❌ **Error occurred**: {str(e)}\n\nPlease try again or contact support if the issue persists."
return error_msg
def clear_inputs():
"""Clear the input field"""
return ""
def get_example_interactions():
"""Return example drug interaction queries"""
examples = [
"I'm taking warfarin and my doctor prescribed ibuprofen for pain. Are there any interactions?",
"Can I take omeprazole with clopidogrel? I have both prescribed.",
"I'm on metformin for diabetes and want to know if it's safe with alcohol",
"Taking lisinopril and potassium supplements - any concerns?",
"I have simvastatin and clarithromycin prescribed together"
]
return examples
# Custom CSS for better styling
custom_css = """
#warning {
background-color: #667eea;
border: 1px solid #ffeaa7;
border-radius: 8px;
padding: 16px;
margin: 10px 0;
}
#main-container {
max-width: 900px;
margin: 0 auto;
}
.gradio-container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
#submit-btn {
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
border: none;
color: white;
font-weight: bold;
}
#clear-btn {
background-color: #6c757d;
border: none;
color: white;
}
"""
# Create the Gradio interface
with gr.Blocks(css=custom_css, title="πŸ’Š PharmaSafe - Drug Interaction Checker") as demo:
with gr.Column(elem_id="main-container"):
# Header
gr.Markdown(
"""
# πŸ’Š πŸ’Š PharmaSafe - Drug Interaction Checker
Get preliminary guidance on potential drug interactions and medication safety concerns.
This tool helps identify possible interactions between medications.
""",
elem_id="header"
)
# Warning notice
gr.Markdown(
"""
⚠️ **MEDICAL DISCLAIMER**: This tool provides educational information only.
Always consult with a licensed pharmacist, doctor, or healthcare provider
before making any decisions about your medications.
""",
elem_id="warning"
)
with gr.Row():
with gr.Column(scale=2):
# Input section
gr.Markdown("### Enter Your Medications or Questions")
medication_input = gr.Textbox(
label="Medications & Questions",
placeholder="Example: I'm taking warfarin and ibuprofen. Are there any interactions I should know about?",
lines=4,
max_lines=8
)
with gr.Row():
submit_btn = gr.Button("πŸ” Check Interactions", variant="primary", elem_id="submit-btn")
clear_btn = gr.Button("πŸ—‘οΈ Clear", elem_id="clear-btn")
with gr.Column(scale=1):
# Examples section
gr.Markdown("### Example Questions")
example_queries = get_example_interactions()
for i, example in enumerate(example_queries[:3]): # Show first 3 examples
gr.Markdown(f"**Example {i+1}:** {example}")
# Output section
gr.Markdown("### πŸ“‹ Analysis Results")
output_display = gr.Markdown(
value="Enter your medications above and click 'Check Interactions' to get started.",
elem_id="output"
)
# Usage tips
with gr.Accordion("πŸ’‘ Usage Tips", open=False):
gr.Markdown(
"""
**For best results:**
- List all medications you're taking (prescription and over-the-counter)
- Include dosages if known
- Mention any supplements or herbal products
- Be specific about your concerns
- Include timing of when you take each medication
**This tool can help with:**
- Drug-drug interactions
- Food-drug interactions
- Timing recommendations
- General medication safety concerns
**Remember:** Always verify with a healthcare professional!
"""
)
# Event handlers
submit_btn.click(
fn=interaction_check,
inputs=medication_input,
outputs=output_display
)
clear_btn.click(
fn=clear_inputs,
outputs=medication_input
)
medication_input.submit(
fn=interaction_check,
inputs=medication_input,
outputs=output_display
)
# Add footer with timestamp
footer_text = f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
if __name__ == "__main__":
demo.launch()