Wayne0102 commited on
Commit
8fba84e
·
verified ·
1 Parent(s): c7f63b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -80
app.py CHANGED
@@ -1,11 +1,11 @@
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:
@@ -14,15 +14,13 @@ def get_current_time_in_timezone(timezone: str) -> str:
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.
@@ -33,11 +31,11 @@ def calculate_tip(bill_amount: float, tip_percent: float) -> str:
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.
@@ -46,13 +44,12 @@ def word_counter(text: str) -> str:
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).
@@ -62,91 +59,44 @@ def calculate_bmi(weight_kg: float, height_m: float) -> str:
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()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, 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
+ # ==================== YOUR TOOLS ====================
9
  # Existing tool from Unit 1
10
  @tool
11
  def get_current_time_in_timezone(timezone: str) -> str:
 
14
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
15
  """
16
  try:
 
17
  tz = pytz.timezone(timezone)
 
18
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
19
  return f"The current local time in {timezone} is: {local_time}"
20
  except Exception as e:
21
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
22
 
23
+ # NEW TOOL 1: Tip Calculator
24
  @tool
25
  def calculate_tip(bill_amount: float, tip_percent: float) -> str:
26
  """Calculate tip amount for a restaurant bill.
 
31
  try:
32
  tip = bill_amount * (tip_percent / 100)
33
  total = bill_amount + tip
34
+ return f"💰 Tip: ${tip:.2f}, Total: ${total:.2f} ({tip_percent}%)"
35
  except Exception as e:
36
+ return f"Error: {str(e)}"
37
 
38
+ # NEW TOOL 2: Word Counter
39
  @tool
40
  def word_counter(text: str) -> str:
41
  """Count words and characters in text.
 
44
  """
45
  try:
46
  words = len(text.split())
47
+ chars = len(text)
48
+ return f"📝 Words: {words}, Characters: {chars}"
 
49
  except Exception as e:
50
+ return f"Error: {str(e)}"
51
 
52
+ # NEW TOOL 3: BMI Calculator
53
  @tool
54
  def calculate_bmi(weight_kg: float, height_m: float) -> str:
55
  """Calculate Body Mass Index (BMI).
 
59
  """
60
  try:
61
  bmi = weight_kg / (height_m ** 2)
 
62
  if bmi < 18.5:
63
+ cat = "Underweight"
64
  elif 18.5 <= bmi < 25:
65
+ cat = "Normal"
66
  elif 25 <= bmi < 30:
67
+ cat = "Overweight"
68
  else:
69
+ cat = "Obese"
70
+ return f"⚖️ BMI: {bmi:.1f} ({cat})"
 
71
  except Exception as e:
72
+ return f"Error: {str(e)}"
73
 
74
+ # ==================== AGENT SETUP ====================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  final_answer = FinalAnswerTool()
76
 
77
  # Load image generation tool from Hub
78
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
79
 
80
+ # Load system prompt
 
 
 
 
 
 
 
 
81
  with open("prompts.yaml", 'r') as stream:
82
  prompt_templates = yaml.safe_load(stream)
83
 
84
+ # ==================== CREATE AGENT ====================
85
+ # SIMPLIFIED: Use default model instead of InferenceClientModel
86
  agent = CodeAgent(
 
87
  tools=[
88
+ final_answer, # Required
89
+ DuckDuckGoSearchTool(), # Search
90
+ image_generation_tool, # Images
91
+ get_current_time_in_timezone, # Time
92
+ calculate_tip, # NEW
93
+ word_counter, # NEW
94
+ calculate_bmi # NEW
 
95
  ],
96
+ max_steps=8, # Increased
97
+ verbosity_level=1, # Show thinking
 
 
 
 
98
  prompt_templates=prompt_templates
99
  )
100
 
101
+ # ==================== LAUNCH ====================
102
  GradioUI(agent).launch()