MallikarjunSonna commited on
Commit
3b9f904
·
verified ·
1 Parent(s): 6dee0c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -32
app.py CHANGED
@@ -1,71 +1,109 @@
1
  import datetime
 
2
  import pytz
3
  import yaml
4
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
5
  from tools.final_answer import FinalAnswerTool
6
  from Gradio_UI import GradioUI
7
 
8
- # Define the tool correctly with a properly formatted docstring
9
  @tool
10
  def get_current_time_in_timezone(timezone: str) -> str:
11
- """
12
- Fetches the current local time in a specified timezone.
13
-
14
  Args:
15
- timezone (str): The timezone string (e.g., 'America/New_York', 'Asia/Kolkata').
16
-
17
- Returns:
18
- str: The current local time in the specified timezone.
19
  """
20
  try:
21
  tz = pytz.timezone(timezone)
22
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
23
  return f"The current local time in {timezone} is: {local_time}"
24
- except pytz.UnknownTimeZoneError:
25
- return f"Error: Invalid timezone '{timezone}'. Please use a valid timezone."
26
  except Exception as e:
27
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
28
 
29
- # Load final answer tool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  final_answer = FinalAnswerTool()
31
 
32
- # Define the model
33
  model = HfApiModel(
34
  max_tokens=2096,
35
  temperature=0.5,
36
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
37
  custom_role_conversions=None,
38
  )
39
 
40
- # Load Hugging Face's image generation tool
41
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
42
-
43
- # Load prompt templates from YAML
44
- try:
45
- with open("prompts.yaml", 'r') as stream:
46
- prompt_templates = yaml.safe_load(stream)
47
- except FileNotFoundError:
48
- prompt_templates = {}
49
- print("Warning: prompts.yaml not found. Using empty prompt templates.")
50
 
51
- # Create the Agent with properly defined tools
52
  agent = CodeAgent(
53
  model=model,
54
  tools=[
55
  final_answer,
56
- DuckDuckGoSearchTool(),
57
  get_current_time_in_timezone,
58
- image_generation_tool
 
 
 
59
  ],
60
  max_steps=6,
61
  verbosity_level=1,
62
  grammar=None,
63
  planning_interval=None,
64
- name="My First SmolAgent",
65
- description="An AI assistant capable of searching, fetching time, and generating images.",
66
- prompt_templates=prompt_templates
67
  )
68
 
69
- # Launch UI
70
- if __name__ == "__main__":
71
- GradioUI(agent).launch()
 
1
  import datetime
2
+ import requests
3
  import pytz
4
  import yaml
5
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
 
9
+ # 1. Tool: Get Current Time in Any Timezone
10
  @tool
11
  def get_current_time_in_timezone(timezone: str) -> str:
12
+ """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
  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
+ # 2. Tool: Get Current Weather Data (Requires OpenWeatherMap API)
24
+ @tool
25
+ def get_weather(city: str) -> str:
26
+ """Fetches current weather information for a specified city.
27
+ Args:
28
+ city: The name of the city (e.g., 'New York').
29
+ """
30
+ api_key = "YOUR_OPENWEATHER_API_KEY" # Replace with your OpenWeather API key
31
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
32
+
33
+ try:
34
+ response = requests.get(url).json()
35
+ if response["cod"] != 200:
36
+ return f"Error: {response['message']}"
37
+
38
+ temp = response["main"]["temp"]
39
+ weather_desc = response["weather"][0]["description"]
40
+ return f"The current weather in {city} is {weather_desc} with a temperature of {temp}°C."
41
+ except Exception as e:
42
+ return f"Error fetching weather data: {str(e)}"
43
+
44
+ # 3. Tool: Currency Exchange Converter
45
+ @tool
46
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
47
+ """Converts currency from one type to another using real-time exchange rates.
48
+ Args:
49
+ amount: The amount to convert.
50
+ from_currency: The source currency code (e.g., 'USD').
51
+ to_currency: The target currency code (e.g., 'INR').
52
+ """
53
+ api_key = "YOUR_EXCHANGERATE_API_KEY" # Replace with a valid API key from ExchangeRate API
54
+ url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/{from_currency}"
55
+
56
+ try:
57
+ response = requests.get(url).json()
58
+ if "conversion_rates" not in response:
59
+ return f"Error: Unable to fetch exchange rates."
60
+
61
+ rate = response["conversion_rates"].get(to_currency, None)
62
+ if rate is None:
63
+ return f"Error: Unsupported currency code."
64
+
65
+ converted_amount = round(amount * rate, 2)
66
+ return f"{amount} {from_currency} is equal to {converted_amount} {to_currency}."
67
+ except Exception as e:
68
+ return f"Error fetching exchange rates: {str(e)}"
69
+
70
+ # Load Hugging Face Text-to-Image Tool
71
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
72
+
73
+ # Load Final Answer Tool
74
  final_answer = FinalAnswerTool()
75
 
76
+ # Initialize Model
77
  model = HfApiModel(
78
  max_tokens=2096,
79
  temperature=0.5,
80
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
81
  custom_role_conversions=None,
82
  )
83
 
84
+ # Load Prompt Templates
85
+ with open("prompts.yaml", "r") as stream:
86
+ prompt_templates = yaml.safe_load(stream)
 
 
 
 
 
 
 
87
 
88
+ # Create Agent with Additional Tools
89
  agent = CodeAgent(
90
  model=model,
91
  tools=[
92
  final_answer,
 
93
  get_current_time_in_timezone,
94
+ get_weather,
95
+ convert_currency,
96
+ DuckDuckGoSearchTool(),
97
+ image_generation_tool,
98
  ],
99
  max_steps=6,
100
  verbosity_level=1,
101
  grammar=None,
102
  planning_interval=None,
103
+ name=None,
104
+ description=None,
105
+ prompt_templates=prompt_templates,
106
  )
107
 
108
+ # Launch Gradio UI
109
+ GradioUI(agent).launch()