teethbot commited on
Commit
cd463a6
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -24
app.py CHANGED
@@ -1,24 +1,62 @@
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:
@@ -33,37 +71,91 @@ def get_current_time_in_timezone(timezone: str) -> str:
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, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import json
7
  from tools.final_answer import FinalAnswerTool
 
8
  from Gradio_UI import GradioUI
9
 
10
+ # Weather API Tool
11
+ def get_weather(location: str) -> str:
12
+ """A tool that fetches current weather for a specified location.
 
 
13
  Args:
14
+ location: A string representing a city or location (e.g., 'New York', 'London, UK').
 
15
  """
16
+ try:
17
+ # Using open-meteo API which doesn't require API key
18
+ # First get coordinates
19
+ geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1"
20
+ geocoding_response = requests.get(geocoding_url)
21
+ geocoding_data = geocoding_response.json()
22
+
23
+ if not geocoding_data.get("results"):
24
+ return f"Could not find location: {location}"
25
+
26
+ lat = geocoding_data["results"][0]["latitude"]
27
+ lon = geocoding_data["results"][0]["longitude"]
28
+ city_name = geocoding_data["results"][0]["name"]
29
+
30
+ # Now get weather
31
+ weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current=temperature_2m,wind_speed_10m,relative_humidity_2m,precipitation,weather_code"
32
+ weather_response = requests.get(weather_url)
33
+ weather_data = weather_response.json()
34
+
35
+ current = weather_data["current"]
36
+ temperature = current["temperature_2m"]
37
+ wind_speed = current["wind_speed_10m"]
38
+ humidity = current["relative_humidity_2m"]
39
+ precipitation = current["precipitation"]
40
+
41
+ # Weather code to text mapping
42
+ weather_codes = {
43
+ 0: "Clear sky",
44
+ 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45
+ 45: "Fog", 48: "Depositing rime fog",
46
+ 51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
47
+ 61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
48
+ 71: "Slight snow fall", 73: "Moderate snow fall", 75: "Heavy snow fall",
49
+ 80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers",
50
+ 95: "Thunderstorm", 96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail"
51
+ }
52
+
53
+ weather_description = weather_codes.get(current["weather_code"], "Unknown")
54
+
55
+ return f"Current weather in {city_name}: {weather_description}, {temperature}°C, {wind_speed}km/h wind, {humidity}% humidity, {precipitation}mm precipitation"
56
+
57
+ except Exception as e:
58
+ return f"Error fetching weather for '{location}': {str(e)}"
59
 
 
60
  def get_current_time_in_timezone(timezone: str) -> str:
61
  """A tool that fetches the current local time in a specified timezone.
62
  Args:
 
71
  except Exception as e:
72
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
73
 
74
+ def currency_converter(amount: float, from_currency: str, to_currency: str) -> str:
75
+ """A tool that converts an amount from one currency to another using latest exchange rates.
76
+ Args:
77
+ amount: The amount to convert
78
+ from_currency: The source currency code (e.g., 'USD')
79
+ to_currency: The target currency code (e.g., 'EUR')
80
+ """
81
+ try:
82
+ # Using ExchangeRate API
83
+ url = f"https://open.er-api.com/v6/latest/{from_currency.upper()}"
84
+ response = requests.get(url)
85
+ data = response.json()
86
+
87
+ if data["result"] != "success":
88
+ return f"Error: Could not fetch exchange rates for {from_currency}"
89
+
90
+ if to_currency.upper() not in data["rates"]:
91
+ return f"Error: Target currency {to_currency} not found"
92
+
93
+ rate = data["rates"][to_currency.upper()]
94
+ converted_amount = amount * rate
95
+
96
+ return f"{amount} {from_currency.upper()} = {converted_amount:.2f} {to_currency.upper()} (Rate: 1 {from_currency.upper()} = {rate} {to_currency.upper()})"
97
+
98
+ except Exception as e:
99
+ return f"Error converting currency: {str(e)}"
100
 
101
+ def stock_price_lookup(ticker: str) -> str:
102
+ """A tool that looks up the latest stock price for a given ticker symbol.
103
+ Args:
104
+ ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
105
+ """
106
+ try:
107
+ # Using Alpha Vantage API (free tier, limited to 25 requests per day)
108
+ # Note: In a production environment, you'd want to use a proper API key
109
+ url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey=demo"
110
+ response = requests.get(url)
111
+ data = response.json()
112
+
113
+ if "Global Quote" not in data or not data["Global Quote"]:
114
+ return f"Could not find data for ticker: {ticker}"
115
+
116
+ quote = data["Global Quote"]
117
+ price = quote.get("05. price", "N/A")
118
+ change = quote.get("09. change", "N/A")
119
+ change_percent = quote.get("10. change percent", "N/A")
120
+
121
+ return f"{ticker} current price: ${price} (Change: {change} / {change_percent})"
122
+
123
+ except Exception as e:
124
+ return f"Error looking up stock price for '{ticker}': {str(e)}"
125
 
126
+ final_answer = FinalAnswerTool()
127
  model = HfApiModel(
128
+ max_tokens=2096,
129
+ temperature=0.5,
130
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
131
+ custom_role_conversions=None,
132
  )
133
 
 
134
  # Import tool from Hub
135
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
136
+ search_tool = DuckDuckGoSearchTool()
137
 
138
  with open("prompts.yaml", 'r') as stream:
139
  prompt_templates = yaml.safe_load(stream)
140
 
141
  agent = CodeAgent(
142
  model=model,
143
+ tools=[
144
+ final_answer,
145
+ get_current_time_in_timezone,
146
+ get_weather,
147
+ currency_converter,
148
+ stock_price_lookup,
149
+ image_generation_tool,
150
+ search_tool
151
+ ],
152
  max_steps=6,
153
  verbosity_level=1,
154
  grammar=None,
155
  planning_interval=None,
156
+ name="DataAssistant",
157
+ description="A helpful assistant that can search the web, check time zones, weather, financial data, and generate images.",
158
  prompt_templates=prompt_templates
159
  )
160
 
 
161
  GradioUI(agent).launch()