Spaces:
Sleeping
Sleeping
File size: 5,999 Bytes
c1bc991 b8c4827 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 c1bc991 fcd9088 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# agents/drug_info_agent.py
"""
Drug Information Agent - Handles drug-related queries using Generative AI.
"""
import re
class DrugInfoAgent:
def __init__(self, gemini_model=None):
"""
Initializes the agent with the Gemini model.
Args:
gemini_model: An instance of the Gemini model client.
"""
self.model = gemini_model
def _extract_drug_name(self, query: str) -> str:
"""A simple helper to extract the drug name from the user's query."""
# Remove common phrases used to request drug information
patterns = [
r"tell me about",
r"what is",
r"information on",
r"info on",
r"about the drug",
r"about"
]
drug_name = query.lower()
for p in patterns:
drug_name = re.sub(p, "", drug_name)
# Clean up any extra whitespace
return drug_name.strip().title() # Capitalize for better recognition
def process_query(self, query: str, file_context: str = "", chat_history: list = None):
if not self.model:
return {
'message': "π The pharmacy database is offline! The Gemini API key is missing.",
'agent_used': 'drug_info', 'status': 'error_no_api_key'
}
drug_name = self._extract_drug_name(query)
history_for_prompt = ""
if chat_history:
for turn in chat_history:
role = "User" if turn['role'] == 'user' else "AI"
if turn.get('parts'):
history_for_prompt += f"{role}: {turn['parts'][0]}\n"
prompt = f"""You are a cautious AI Pharmacist Tutor providing educational information for a B.Pharmacy student.
**CRITICAL SAFETY INSTRUCTION:** START EVERY RESPONSE with this disclaimer: "β οΈ **Disclaimer:** This information is for educational purposes ONLY and is not a substitute for professional medical advice."
CONVERSATION HISTORY:
{history_for_prompt}
CURRENT QUESTION:
User: {query}
Based on the CURRENT QUESTION and conversation history, provide a structured summary for the drug mentioned. Include: Therapeutic Class, Mechanism of Action (MOA), Common Indications, Common Side Effects, and Important Warnings. DO NOT provide specific dosages.
"""
try:
response = self.model.generate_content(prompt)
return {'message': response.text, 'agent_used': 'drug_info', 'status': 'success'}
except Exception as e:
print(f"Drug Info Agent Error: {e}")
return {'message': f"Sorry, I couldn't access the drug database. Error: {e}", 'agent_used': 'drug_info', 'status': 'error_api_call'}
# def process_query(self, query: str, file_context: str = "", chat_history: list = None):
# """
# Processes a query to retrieve information about a specific drug.
# Args:
# query (str): The user's full query (e.g., "Tell me about Metformin").
# file_context (str): Optional context from uploaded files.
# Returns:
# dict: A dictionary containing the response message and agent metadata.
# """
# # Fallback response if the AI model is not configured
# if not self.model:
# return {
# 'message': "π **Drug Information Agent**\n\nThe pharmacy database is offline! The Gemini API key is missing, so I can't look up drug information. Please configure the API key to enable this feature.",
# 'agent_type': 'drug_info',
# 'status': 'error_no_api_key'
# }
# drug_name = self._extract_drug_name(query)
# if not drug_name:
# return {
# 'message': "Please tell me which drug you want to know about! For example, try 'info on Paracetamol'.",
# 'agent_type': 'drug_info',
# 'status': 'error_no_topic'
# }
# # Construct a specialized, safety-conscious prompt for the Gemini model
# prompt = f"""
# You are a highly knowledgeable and cautious AI Pharmacist Tutor. Your primary role is to provide accurate drug information for a B.Pharmacy student in India for EDUCATIONAL PURPOSES ONLY.
# **CRITICAL SAFETY INSTRUCTION:**
# START EVERY RESPONSE with the following disclaimer, exactly as written:
# "β οΈ **Disclaimer:** This information is for educational purposes ONLY and is not a substitute for professional medical advice. Always consult a qualified healthcare provider."
# **Task:**
# Provide a structured summary for the drug: **{drug_name}**
# **Information to Include:**
# 1. **Therapeutic Class:** What family of drugs does it belong to?
# 2. **Mechanism of Action (MOA):** How does it work in the body? Explain simply.
# 3. **Common Indications:** What is it typically used for?
# 4. **Common Side Effects:** List a few of the most common side effects.
# 5. **Important Contraindications/Warnings:** Who should not take this drug or be cautious?
# 6. **Common Dosage Forms:** What forms is it available in (e.g., Tablets, Syrup, Injection)? DO NOT provide specific dosages like mg or frequency.
# **Format:**
# Use clear headings (like "π¬ Mechanism of Action") and bullet points for readability. Use relevant emojis.
# """
# try:
# # Generate content using the AI model
# ai_response = self.model.generate_content(prompt, chat_history)
# return {
# 'message': ai_response.text,
# 'agent_used': 'drug_info',
# 'status': 'success'
# }
# except Exception as e:
# print(f"Drug Info Agent Error: {e}")
# return {
# 'message': f"I'm sorry, I couldn't access the drug database at the moment. An error occurred: {str(e)}",
# 'agent_type': 'drug_info',
# 'status': 'error_api_call'
# } |