Chinez-dev commited on
Commit
bf229b2
·
verified ·
1 Parent(s): 73db2ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -193
app.py CHANGED
@@ -1,167 +1,127 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- # @tool
12
- # def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- # #Keep this format for the description / args / args description but feel free to modify the tool
14
- # """A tool that does nothing yet
15
- # Args:
16
- # arg1: the first argument
17
- # arg2: the second argument
18
- # """
19
- # return "What magic will you build ?"
20
-
21
-
22
- def __init__(self):
23
- self.patient_data = {}
24
-
25
- @tool
26
- def collect_symptoms(patient_id: str, symptoms: str) -> str:
27
- """
28
- Nurse tool to collect symptoms and ask follow-up questions.
29
-
30
- Args:
31
- patient_id: Unique identifier for the patient.
32
- symptoms: Initial symptoms provided by the patient.
33
-
34
- Returns:
35
- Follow-up questions based on the symptoms.
36
- """
37
- try:
38
- if not patient_id or not symptoms:
39
- raise ValueError("Patient ID and symptoms must be provided.")
40
-
41
- self.patient_data[patient_id] = {"symptoms": symptoms, "additional_info": {}}
42
-
43
- questions = [
44
- "How long have you had these symptoms?",
45
- "Do you have any allergies?",
46
- "Are you taking any medications?",
47
- "Have you experienced these symptoms before?",
48
- "Have you had any recent illnesses?",
49
- "Have you noticed any other unusual changes?",
50
- "What is your medical history related to these symptoms?"
51
-
52
- ]
53
-
54
- return f"Nurse: I have noted the symptoms ({symptoms}). Here are follow-up questions:\n" + "\n".join(questions)
55
-
56
- except ValueError as e:
57
- return f"Error: {str(e)}"
58
- except Exception as e:
59
- return f"Unexpected Error: {str(e)}"
60
-
61
- @tool
62
- def diagnose_patient(patient_id: str) -> str:
63
- """
64
- Doctor tool to diagnose the patient based on symptoms.
65
-
66
- Args:
67
- patient_id: Unique identifier for the patient.
68
-
69
- Returns:
70
- Diagnosis and recommendations.
71
- """
72
- try:
73
- if patient_id not in CodeAgent.patient_data:
74
- raise ValueError("No symptoms found. Nurse must collect symptoms first.")
75
-
76
- symptoms = CodeAgent.patient_data[patient_id]["symptoms"]
77
- diagnosis = CodeAgent.fetch_diagnosis(symptoms)
78
- medication = CodeAgent.fetch_medication(symptoms)
79
- advice = CodeAgent.fetch_treatment_advice(symptoms)
80
-
81
- return (f"Doctor: Based on the symptoms: {symptoms},\n"
82
- f"Diagnosis: {diagnosis}\n"
83
- f"Medication: {medication}\n"
84
- f"Advice: {advice}")
85
-
86
- except ValueError as e:
87
- return f"Error: {str(e)}"
88
- except Exception as e:
89
- return f"Unexpected Error: {str(e)}"
90
-
91
-
92
- @tool
93
- def fetch_diagnosis(symptoms: str) -> str:
94
- """
95
- AI tool to retrieve a diagnosis based on symptoms.
96
-
97
- Args:
98
- symptoms: The symptoms provided by the patient.
99
-
100
- Returns:
101
- Detailed Diagnosis information.
102
- """
103
- search_query = f" A detailed medical diagnosis for this {symptoms}"
104
- return search_tool(search_query)
105
- try:
106
- if not symptoms:
107
- raise ValueError("Symptoms must be provided.")
108
-
109
- return f"AI Diagnosis: Potential cause of {symptoms} found."
110
-
111
- except ValueError as e:
112
- return f"Error: {str(e)}"
113
- except Exception as e:
114
- return f"Unexpected Error: {str(e)}"
115
-
116
- @tool
117
- def fetch_medication(symptoms: str) -> str:
118
- """
119
- AI tool to suggest medications based on symptoms.
120
-
121
- Args:
122
- symptoms: The symptoms provided by the patient.
123
-
124
- Returns:
125
- Suggested medication.
126
- """
127
- search_query = f" A detailed suggested medication for this {symptoms}"
128
- return search_tool(search_query)
129
- try:
130
- if not symptoms:
131
- raise ValueError("Symptoms must be provided.")
132
-
133
- return f"Suggested medication for {symptoms} found."
134
-
135
- except ValueError as e:
136
- return f"Error: {str(e)}"
137
- except Exception as e:
138
- return f"Unexpected Error: {str(e)}"
139
-
140
- @tool
141
- def fetch_treatment_advice(symptoms: str) -> str:
142
- """
143
- AI tool to provide treatment recommendations.
144
-
145
- Args:
146
- symptoms: The symptoms provided by the patient.
147
-
148
- Returns:
149
- Recommended treatment and advice.
150
- """
151
- search_query = f" A detailed recommended treatment and advice for this {symptoms}"
152
- return search_tool(search_query)
153
- try:
154
- if not symptoms:
155
- raise ValueError("Symptoms must be provided.")
156
-
157
- return f"Treatment advice for {symptoms} retrieved."
158
-
159
- except ValueError as e:
160
- return f"Error: {str(e)}"
161
- except Exception as e:
162
- return f"Unexpected Error: {str(e)}"
163
-
164
- search_tool = DuckDuckGoSearchTool()
165
 
166
  @tool
167
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -170,45 +130,53 @@ def get_current_time_in_timezone(timezone: str) -> str:
170
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
171
  """
172
  try:
173
- # Create timezone object
174
  tz = pytz.timezone(timezone)
175
- # Get current time in that timezone
176
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
177
  return f"The current local time in {timezone} is: {local_time}"
178
  except Exception as e:
179
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
180
 
181
-
182
- final_answer = FinalAnswerTool()
183
-
184
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
185
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
186
-
187
- model = HfApiModel(
188
- max_tokens=2096,
189
- temperature=0.5,
190
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
191
- custom_role_conversions=None,
192
- )
193
-
194
-
195
- # Import tool from Hub
196
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
197
-
198
- with open("prompts.yaml", 'r') as stream:
199
- prompt_templates = yaml.safe_load(stream)
200
-
201
- agent = CodeAgent(
202
- model=model,
203
- tools=[final_answer, collect_symptoms, diagnose_patient, get_current_time_in_timezone], ## add your tools here (don't remove final answer)
204
- max_steps=6,
205
- verbosity_level=1,
206
- grammar=None,
207
- planning_interval=None,
208
- name="MedicalDoctor",
209
- description="A tool that simulates the roles of a medical doctor and a nurse in gathering symptoms, diagnosing, and providing recommendations",
210
- prompt_templates=prompt_templates
211
- )
212
-
213
-
214
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
7
  from Gradio_UI import GradioUI
8
 
9
+ class MedicalAgent:
10
+ def __init__(self):
11
+ self.patient_data = {}
12
+ self.search_tool = DuckDuckGoSearchTool()
13
+
14
+ @tool
15
+ def collect_symptoms(self, patient_id: str, symptoms: str) -> str:
16
+ """
17
+ Nurse tool to collect symptoms and ask follow-up questions.
18
+ Args:
19
+ patient_id: Unique identifier for the patient.
20
+ symptoms: Initial symptoms provided by the patient.
21
+ Returns:
22
+ Follow-up questions based on the symptoms.
23
+ """
24
+ try:
25
+ if not patient_id or not symptoms:
26
+ raise ValueError("Patient ID and symptoms must be provided.")
27
+
28
+ self.patient_data[patient_id] = {"symptoms": symptoms, "additional_info": {}}
29
+
30
+ questions = [
31
+ "How long have you had these symptoms?",
32
+ "Do you have any allergies?",
33
+ "Are you taking any medications?",
34
+ "Have you experienced these symptoms before?",
35
+ "Have you had any recent illnesses?",
36
+ "Have you noticed any other unusual changes?",
37
+ "What is your medical history related to these symptoms?"
38
+ ]
39
+
40
+ return f"Nurse: I have noted the symptoms ({symptoms}). Here are follow-up questions:\n" + "\n".join(questions)
41
+
42
+ except ValueError as e:
43
+ return f"Error: {str(e)}"
44
+ except Exception as e:
45
+ return f"Unexpected Error: {str(e)}"
46
+
47
+ @tool
48
+ def diagnose_patient(self, patient_id: str) -> str:
49
+ """
50
+ Doctor tool to diagnose the patient based on symptoms.
51
+ Args:
52
+ patient_id: Unique identifier for the patient.
53
+ Returns:
54
+ Diagnosis and recommendations.
55
+ """
56
+ try:
57
+ if patient_id not in self.patient_data:
58
+ raise ValueError("No symptoms found. Nurse must collect symptoms first.")
59
+
60
+ symptoms = self.patient_data[patient_id]["symptoms"]
61
+ diagnosis = self.fetch_diagnosis(symptoms)
62
+ medication = self.fetch_medication(symptoms)
63
+ advice = self.fetch_treatment_advice(symptoms)
64
+
65
+ return (f"Doctor: Based on the symptoms: {symptoms},\n"
66
+ f"Diagnosis: {diagnosis}\n"
67
+ f"Medication: {medication}\n"
68
+ f"Advice: {advice}")
69
+
70
+ except ValueError as e:
71
+ return f"Error: {str(e)}"
72
+ except Exception as e:
73
+ return f"Unexpected Error: {str(e)}"
74
+
75
+ @tool
76
+ def fetch_diagnosis(self, symptoms: str) -> str:
77
+ """
78
+ AI tool to retrieve a diagnosis based on symptoms.
79
+ Args:
80
+ symptoms: The symptoms provided by the patient.
81
+ Returns:
82
+ Detailed Diagnosis information.
83
+ """
84
+ try:
85
+ if not symptoms:
86
+ raise ValueError("Symptoms must be provided.")
87
+ search_query = f"A detailed medical diagnosis for these symptoms: {symptoms}"
88
+ return self.search_tool(search_query)
89
+ except Exception as e:
90
+ return f"Error fetching diagnosis: {str(e)}"
91
+
92
+ @tool
93
+ def fetch_medication(self, symptoms: str) -> str:
94
+ """
95
+ AI tool to suggest medications based on symptoms.
96
+ Args:
97
+ symptoms: The symptoms provided by the patient.
98
+ Returns:
99
+ Suggested medication.
100
+ """
101
+ try:
102
+ if not symptoms:
103
+ raise ValueError("Symptoms must be provided.")
104
+ search_query = f"Recommended medications for these symptoms: {symptoms}"
105
+ return self.search_tool(search_query)
106
+ except Exception as e:
107
+ return f"Error fetching medication: {str(e)}"
108
+
109
+ @tool
110
+ def fetch_treatment_advice(self, symptoms: str) -> str:
111
+ """
112
+ AI tool to provide treatment recommendations.
113
+ Args:
114
+ symptoms: The symptoms provided by the patient.
115
+ Returns:
116
+ Recommended treatment and advice.
117
+ """
118
+ try:
119
+ if not symptoms:
120
+ raise ValueError("Symptoms must be provided.")
121
+ search_query = f"Treatment advice and recommendations for these symptoms: {symptoms}"
122
+ return self.search_tool(search_query)
123
+ except Exception as e:
124
+ return f"Error fetching treatment advice: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  @tool
127
  def get_current_time_in_timezone(timezone: str) -> str:
 
130
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
131
  """
132
  try:
 
133
  tz = pytz.timezone(timezone)
 
134
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
135
  return f"The current local time in {timezone} is: {local_time}"
136
  except Exception as e:
137
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
138
 
139
+ def initialize_agent():
140
+ try:
141
+ with open("prompts.yaml", 'r') as stream:
142
+ prompt_templates = yaml.safe_load(stream)
143
+ except FileNotFoundError:
144
+ print("Warning: prompts.yaml not found. Using default templates.")
145
+ prompt_templates = {}
146
+
147
+ final_answer = FinalAnswerTool()
148
+ medical_agent = MedicalAgent()
149
+
150
+ # If the primary model is overloaded, uncomment the following alternative endpoint
151
+ model_id = 'https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
152
+ model = HfApiModel(
153
+ max_tokens=2096,
154
+ temperature=0.5,
155
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
156
+ custom_role_conversions=None,
157
+ )
158
+
159
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
160
+
161
+ agent = CodeAgent(
162
+ model=model,
163
+ tools=[
164
+ final_answer,
165
+ medical_agent.collect_symptoms,
166
+ medical_agent.diagnose_patient,
167
+ get_current_time_in_timezone
168
+ ],
169
+ max_steps=6,
170
+ verbosity_level=1,
171
+ grammar=None,
172
+ planning_interval=None,
173
+ name="MedicalDoctor",
174
+ description="A tool that simulates the roles of a medical doctor and a nurse in gathering symptoms, diagnosing, and providing recommendations",
175
+ prompt_templates=prompt_templates
176
+ )
177
+
178
+ return agent
179
+
180
+ if __name__ == "__main__":
181
+ agent = initialize_agent()
182
+ GradioUI(agent).launch()