Naimahmed's picture
Update app.py
6e8b049 verified
Raw History Blame Contribute Delete
10.2 kB
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import os
from Gradio_UI import GradioUI
#from huggingface_hub import login
#login(token = os.getenv('HF_TOKEN'))
# Below is an example of a tool that does nothing. Amaze us with your creativity !
#@tool
#def my_cutom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
# #Keep this format for the description / args / args description but feel free to modify the tool
# """A tool that does nothing yet
# Args:
# arg1: the first argument
# arg2: the second argument
# """
# return "What magic will you build ?"
@tool
def my_custom_tool(question: str) -> str:
"""
A tool that acts like a cardiologist to answer questions about heart conditions.
Args:
question: A string representing the question about heart conditions.
Returns:
A string with detailed information about the condition, including heart rate range, symptoms, causes, treatments, prevention tips, and risk factors.
"""
# Define the conditions and their details
conditions = {
"tachycardia": {
"heart_rate_range": "> 100 beats per minute (bpm)",
"description": "Tachycardia is a condition where the heart beats faster than normal while at rest.",
"symptoms": "Palpitations, shortness of breath, chest pain, dizziness, or fainting.",
"causes": "Stress, exercise, fever, anemia, hyperthyroidism, or underlying heart conditions.",
"treatment": "Treatment depends on the cause. Options include medications, catheter ablation, or implantable devices like pacemakers.",
"prevention": "Manage stress, avoid stimulants like caffeine, and treat underlying conditions.",
"risk_factors": "High blood pressure, smoking, diabetes, or a family history of heart disease.",
"resource_link": "https://www.heart.org/en/health-topics/arrhythmia/about-arrhythmia/tachycardia"
},
"bradycardia": {
"heart_rate_range": "< 60 beats per minute (bpm)",
"description": "Bradycardia is a condition where the heart beats slower than normal while at rest.",
"symptoms": "Fatigue, dizziness, shortness of breath, chest pain, or fainting.",
"causes": "Aging, heart disease, hypothyroidism, electrolyte imbalances, or certain medications.",
"treatment": "Treatment may include adjusting medications, treating underlying conditions, or implanting a pacemaker.",
"prevention": "Regular exercise, a healthy diet, and avoiding excessive alcohol.",
"risk_factors": "Aging, heart disease, or certain medications like beta-blockers.",
"resource_link": "https://www.heart.org/en/health-topics/arrhythmia/about-arrhythmia/bradycardia"
},
"atrial fibrillation": {
"heart_rate_range": "Irregular and often rapid heart rate",
"description": "Atrial fibrillation (AFib) is an irregular and often rapid heart rhythm that can lead to blood clots, stroke, or heart failure.",
"symptoms": "Palpitations, fatigue, shortness of breath, dizziness, or chest pain.",
"causes": "High blood pressure, heart disease, obesity, alcohol use, or hyperthyroidism.",
"treatment": "Treatment includes rate control, rhythm control, blood thinners, or procedures like catheter ablation.",
"prevention": "Control blood pressure, maintain a healthy weight, and limit alcohol intake.",
"risk_factors": "High blood pressure, diabetes, obesity, or a family history of AFib.",
"resource_link": "https://www.heart.org/en/health-topics/atrial-fibrillation"
},
"ventricular tachycardia": {
"heart_rate_range": "> 100 beats per minute (bpm)",
"description": "Ventricular tachycardia (VT) is a fast heart rhythm originating from the ventricles, which can be life-threatening.",
"symptoms": "Palpitations, dizziness, fainting, or cardiac arrest.",
"causes": "Heart disease, electrolyte imbalances, or previous heart attacks.",
"treatment": "Immediate treatment may include CPR, defibrillation, or medications. Long-term treatment may involve an implantable cardioverter-defibrillator (ICD).",
"prevention": "Manage heart disease, avoid triggers like stress, and follow a heart-healthy lifestyle.",
"risk_factors": "Previous heart attacks, heart disease, or genetic conditions.",
"resource_link": "https://www.heart.org/en/health-topics/arrhythmia/about-arrhythmia/ventricular-tachycardia"
},
"heart attack": {
"heart_rate_range": "Varies (often irregular during an attack)",
"description": "A heart attack (myocardial infarction) occurs when blood flow to the heart is blocked, damaging the heart muscle.",
"symptoms": "Chest pain, shortness of breath, nausea, cold sweat, or pain radiating to the arm or jaw.",
"causes": "Coronary artery disease, blood clots, or plaque buildup in the arteries.",
"treatment": "Immediate treatment includes aspirin, nitroglycerin, and emergency procedures like angioplasty or stenting. Long-term treatment involves lifestyle changes and medications.",
"prevention": "Quit smoking, eat a heart-healthy diet, exercise regularly, and manage stress.",
"risk_factors": "High cholesterol, high blood pressure, smoking, diabetes, or a family history of heart disease.",
"resource_link": "https://www.heart.org/en/health-topics/heart-attack"
},
"heart failure": {
"heart_rate_range": "Varies (often elevated)",
"description": "Heart failure occurs when the heart cannot pump enough blood to meet the body's needs.",
"symptoms": "Shortness of breath, fatigue, swelling in the legs, rapid weight gain, or persistent coughing.",
"causes": "Coronary artery disease, high blood pressure, diabetes, or previous heart attacks.",
"treatment": "Treatment includes medications, lifestyle changes, or devices like pacemakers.",
"prevention": "Control blood pressure, manage diabetes, and maintain a healthy weight.",
"risk_factors": "High blood pressure, diabetes, obesity, or a history of heart disease.",
"resource_link": "https://www.heart.org/en/health-topics/heart-failure"
}
}
# Normalize the question to lowercase for easier matching
question = question.lower()
# Determine which condition is being asked about
condition = None
for key in conditions:
if key in question:
condition = key
break
# If no condition is found, use Hugging Face QA model to handle complex questions
if not condition and context:
try:
# Use the QA pipeline to answer the question based on the context
result = qa_pipeline(question=question, context=context)
return f"Answer: {result['answer']} (Confidence: {result['score']:.2f})"
except Exception as e:
return f"Sorry, I couldn't process your question. Error: {str(e)}"
# If no condition is found, return a default response
if not condition:
return (
"I can answer questions about the following heart conditions:\n"
"- Tachycardia\n"
"- Bradycardia\n"
"- Atrial fibrillation\n"
"- Ventricular tachycardia\n"
"- Heart attack\n"
"- Heart failure\n"
"Please ask about one of these conditions."
)
# Fetch the details for the condition
details = conditions.get(condition, {})
if not details:
return "Sorry, I couldn't find information about that condition."
# Return the detailed response
return (
f"For {condition}:\n"
f"- Heart Rate Range: {details['heart_rate_range']}\n"
f"- Description: {details['description']}\n"
f"- Symptoms: {details['symptoms']}\n"
f"- Causes: {details['causes']}\n"
f"- Treatment: {details['treatment']}\n"
f"- Prevention: {details['prevention']}\n"
f"- Risk Factors: {details['risk_factors']}\n"
f"- Learn More: {details['resource_link']}"
)
# Add follow-up suggestions
if not follow_up:
response += (
"\n\nWould you like to know more about:\n"
f"- Symptoms of {condition}?\n"
f"- Treatment options for {condition}?\n"
f"- Prevention tips for {condition}?"
)
return response
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
#HF_TOKEN = os.environ['HF_TOKEN']
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer,image_generation_tool,my_custom_tool], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()