File size: 10,249 Bytes
9b5b26a
 
 
 
c19d193
6aae614
cc76b16
9b5b26a
0e91305
 
8ea231c
7d033ed
6e8b049
 
0e91305
 
d369e9c
 
9b5b26a
5df72d6
21b9656
 
 
 
 
 
 
 
 
 
676be67
21b9656
 
 
9b5b26a
21b9656
 
 
9b5b26a
21b9656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e91305
21b9656
 
 
 
 
 
0e91305
 
 
 
 
 
 
 
 
21b9656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e91305
 
 
 
 
 
 
 
 
9b5b26a
0e91305
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
74fad09
8c01ffb
6aae614
e121372
bf6d34c
 
b1a95bc
fe328e0
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
07bd4e6
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
9b5b26a
8c01ffb
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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()