Wayne0102 commited on
Commit
c7f63b0
·
verified ·
1 Parent(s): 020f526

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -68
app.py CHANGED
@@ -1,69 +1,152 @@
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
- @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
- Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
- """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # 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:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
-
68
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
2
+ import datetime
3
+ import pytz
4
+ import yaml
5
+ from tools.final_answer import FinalAnswerTool
6
+ from Gradio_UI import GradioUI
7
+
8
+ # ==================== LOCATION 1: YOUR TOOLS ✨ ====================
9
+ # Existing tool from Unit 1
10
+ @tool
11
+ def get_current_time_in_timezone(timezone: str) -> str:
12
+ """A tool that fetches the current local time in a specified timezone.
13
+ Args:
14
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
15
+ """
16
+ try:
17
+ # Create timezone object
18
+ tz = pytz.timezone(timezone)
19
+ # Get current time in that timezone
20
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
21
+ return f"The current local time in {timezone} is: {local_time}"
22
+ except Exception as e:
23
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
24
+
25
+ # NEW TOOL 1: Tip Calculator
26
+ @tool
27
+ def calculate_tip(bill_amount: float, tip_percent: float) -> str:
28
+ """Calculate tip amount for a restaurant bill.
29
+ Args:
30
+ bill_amount: Total bill amount in dollars
31
+ tip_percent: Tip percentage (e.g., 15 for 15%)
32
+ """
33
+ try:
34
+ tip = bill_amount * (tip_percent / 100)
35
+ total = bill_amount + tip
36
+ return f"💰 Tip Amount: ${tip:.2f}\n💵 Total Bill: ${total:.2f}\n📊 Tip Percentage: {tip_percent}%"
37
+ except Exception as e:
38
+ return f"Error calculating tip: {str(e)}"
39
+
40
+ # ✨ NEW TOOL 2: Word Counter
41
+ @tool
42
+ def word_counter(text: str) -> str:
43
+ """Count words and characters in text.
44
+ Args:
45
+ text: The text to analyze
46
+ """
47
+ try:
48
+ words = len(text.split())
49
+ characters = len(text)
50
+ sentences = text.count('.') + text.count('!') + text.count('?')
51
+ return f"📝 Text Analysis:\n• Words: {words}\n• Characters: {characters}\n• Sentences: {sentences}"
52
+ except Exception as e:
53
+ return f"Error analyzing text: {str(e)}"
54
+
55
+ # ✨ NEW TOOL 3: BMI Calculator
56
+ @tool
57
+ def calculate_bmi(weight_kg: float, height_m: float) -> str:
58
+ """Calculate Body Mass Index (BMI).
59
+ Args:
60
+ weight_kg: Weight in kilograms
61
+ height_m: Height in meters
62
+ """
63
+ try:
64
+ bmi = weight_kg / (height_m ** 2)
65
+
66
+ if bmi < 18.5:
67
+ category = "Underweight"
68
+ elif 18.5 <= bmi < 25:
69
+ category = "Normal weight"
70
+ elif 25 <= bmi < 30:
71
+ category = "Overweight"
72
+ else:
73
+ category = "Obese"
74
+
75
+ return f"⚖️ BMI Result: {bmi:.1f}\n📋 Category: {category}"
76
+ except Exception as e:
77
+ return f"Error calculating BMI: {str(e)}"
78
+
79
+ # ✨ NEW TOOL 4: Currency Converter (Simulated)
80
+ @tool
81
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
82
+ """Convert currency between different types (simulated rates).
83
+ Args:
84
+ amount: Amount to convert
85
+ from_currency: Source currency (USD, EUR, JPY, etc.)
86
+ to_currency: Target currency (USD, EUR, JPY, etc.)
87
+ """
88
+ # Simulated exchange rates (for demo purposes)
89
+ rates = {
90
+ 'USD': 1.0,
91
+ 'EUR': 0.85,
92
+ 'JPY': 110.0,
93
+ 'GBP': 0.75,
94
+ 'CAD': 1.25,
95
+ 'AUD': 1.35,
96
+ 'INR': 75.0
97
+ }
98
+
99
+ try:
100
+ if from_currency.upper() not in rates or to_currency.upper() not in rates:
101
+ return f"❌ Currency not supported. Available: {', '.join(rates.keys())}"
102
+
103
+ rate = rates[to_currency.upper()] / rates[from_currency.upper()]
104
+ converted = amount * rate
105
+
106
+ return f"💱 Currency Conversion:\n{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()}\n📈 Exchange Rate: 1 {from_currency.upper()} = {rate:.4f} {to_currency.upper()}"
107
+ except Exception as e:
108
+ return f"Error converting currency: {str(e)}"
109
+
110
+ # ==================== ✨ AGENT SETUP ✨ ====================
111
+ final_answer = FinalAnswerTool()
112
+
113
+ # Load image generation tool from Hub
114
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
115
+
116
+ # Create model
117
+ model = InferenceClientModel(
118
+ max_tokens=2096,
119
+ temperature=0.5,
120
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
121
+ custom_role_conversions=None,
122
+ )
123
+
124
+ # Load system prompt from prompts.yaml file
125
+ with open("prompts.yaml", 'r') as stream:
126
+ prompt_templates = yaml.safe_load(stream)
127
+
128
+ # ==================== ✨ LOCATION 2: AGENT WITH ALL TOOLS ✨ ====================
129
+ # ✨ UPGRADED: Added 5 new tools and increased max_steps
130
+ agent = CodeAgent(
131
+ model=model,
132
+ tools=[
133
+ final_answer, # Required - DON'T REMOVE
134
+ DuckDuckGoSearchTool(), # Web search capability
135
+ image_generation_tool, # Image generation
136
+ get_current_time_in_timezone, # Existing time tool
137
+ calculate_tip, # ✨ NEW: Tip calculator
138
+ word_counter, # ✨ NEW: Word counter
139
+ calculate_bmi, # ✨ NEW: BMI calculator
140
+ convert_currency # ✨ NEW: Currency converter
141
+ ],
142
+ max_steps=10, # ✨ UPGRADED: Was 6, now 10
143
+ verbosity_level=2, # ✨ NEW: Shows detailed thinking
144
+ grammar=None,
145
+ planning_interval=None,
146
+ name="SuperAssistant Pro",
147
+ description="An enhanced AI agent with multiple useful tools",
148
+ prompt_templates=prompt_templates
149
+ )
150
+
151
+ # ==================== ✨ LAUNCH ✨ ====================
152
  GradioUI(agent).launch()