samuelolubukun commited on
Commit
bffcf77
·
verified ·
1 Parent(s): 89e867e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -14
app.py CHANGED
@@ -1,17 +1,23 @@
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
@@ -33,29 +39,94 @@ 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,
@@ -65,5 +136,4 @@ agent = CodeAgent(
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
  from tools.final_answer import FinalAnswerTool
7
 
8
+ # Add imports for the new weather tool
9
+ import openmeteo_requests
10
+ import requests_cache
11
+ from retry_requests import retry
12
+ import pandas as pd
13
+
14
  from Gradio_UI import GradioUI
15
 
16
+ # Below is an example of a tool that does nothing. Amaze us with your creativity!
17
  @tool
18
+ def my_custom_tool(arg1: str, arg2: int) -> str:
19
+ # Keep this format for the description / args / args description but feel free to modify the tool
20
+ """A tool that does nothing yet
21
  Args:
22
  arg1: the first argument
23
  arg2: the second argument
 
39
  except Exception as e:
40
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
41
 
42
+ # A new tool to get weather forecast using Open-Meteo
43
+ @tool
44
+ def get_weather_forecast(city: str) -> str:
45
+ """Fetches the hourly temperature forecast for a specified city.
46
+
47
+ Args:
48
+ city: The name of the city (e.g., 'London', 'New York').
49
+ """
50
+ try:
51
+ # Set up the Open-Meteo API client with cache and retry on error
52
+ cache_session = requests_cache.CachedSession('.cache', expire_after=3600)
53
+ retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
54
+ openmeteo = openmeteo_requests.Client(session=retry_session)
55
+
56
+ # First, use the Open-Meteo Geocoding API to get coordinates for the city
57
+ geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&language=en&format=json"
58
+ geocoding_response = requests.get(geocoding_url)
59
+ geocoding_response.raise_for_status()
60
+ geocoding_data = geocoding_response.json()
61
+
62
+ if not geocoding_data.get('results'):
63
+ return f"Error: Could not find coordinates for city '{city}'."
64
+
65
+ result = geocoding_data['results'][0]
66
+ latitude = result['latitude']
67
+ longitude = result['longitude']
68
+
69
+ # Next, use the weather API to get the forecast with the new coordinates
70
+ url = "https://api.open-meteo.com/v1/forecast"
71
+ params = {
72
+ "latitude": latitude,
73
+ "longitude": longitude,
74
+ "hourly": ["temperature_2m"],
75
+ }
76
+
77
+ responses = openmeteo.weather_api(url, params=params)
78
+ response = responses[0]
79
+
80
+ hourly = response.Hourly()
81
+ hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy()
82
+
83
+ # Create a pandas DataFrame for better presentation
84
+ hourly_data = {
85
+ "date": pd.date_range(
86
+ start=pd.to_datetime(hourly.Time(), unit="s", utc=True),
87
+ end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True),
88
+ freq=pd.Timedelta(seconds=hourly.Interval()),
89
+ inclusive="left"
90
+ ),
91
+ "temperature_2m": hourly_temperature_2m
92
+ }
93
+ hourly_dataframe = pd.DataFrame(data=hourly_data)
94
+
95
+ # Format the output for the agent
96
+ forecast_summary = f"Hourly temperature forecast for {city} ({latitude}°N, {longitude}°E):\n"
97
+ for index, row in hourly_dataframe.iterrows():
98
+ forecast_summary += f"- Time {row['date'].strftime('%Y-%m-%d %H:%M')}: {row['temperature_2m']}°C\n"
99
+
100
+ return forecast_summary
101
+
102
+ except requests.exceptions.RequestException as e:
103
+ return f"An error occurred while fetching data: {str(e)}"
104
+ except Exception as e:
105
+ return f"An unexpected error occurred: {str(e)}"
106
+
107
 
108
  final_answer = FinalAnswerTool()
109
 
110
  # 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:
111
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
112
 
113
  model = HfApiModel(
114
+ max_tokens=2096,
115
+ temperature=0.5,
116
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # it is possible that this model may be overloaded
117
+ custom_role_conversions=None,
118
  )
119
 
 
120
  # Import tool from Hub
121
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
122
+ duckduckgo_search = DuckDuckGoSearchTool()
123
 
124
  with open("prompts.yaml", 'r') as stream:
125
  prompt_templates = yaml.safe_load(stream)
126
+
127
  agent = CodeAgent(
128
  model=model,
129
+ tools=[final_answer, duckduckgo_search, image_generation_tool, get_weather_forecast], # Added the new weather tool
130
  max_steps=6,
131
  verbosity_level=1,
132
  grammar=None,
 
136
  prompt_templates=prompt_templates
137
  )
138
 
 
139
  GradioUI(agent).launch()