mugwaneza commited on
Commit
b7558d3
·
verified ·
1 Parent(s): 86bd5dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -52
app.py CHANGED
@@ -1,61 +1,45 @@
 
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
2
- from smolagents.models import HuggingFaceLLM # unified model class in latest versions
3
  import datetime
4
- import requests
5
  import pytz
6
  import yaml
7
- from tools.final_answer import FinalAnswerTool
8
 
 
9
  import openmeteo_requests
10
  import pandas as pd
11
  import requests_cache
12
  from retry_requests import retry
13
 
 
14
  from Gradio_UI import GradioUI
15
 
16
 
17
- # ===== Custom Tools =====
18
-
19
  @tool
20
- def hourly_temperature(latitude: float, longitude: float) -> str:
21
- """Fetch hourly temperature from Open-Meteo API for a given location.
22
- Args:
23
- latitude: Latitude of the location.
24
- longitude: Longitude of the location.
25
- """
26
- try:
27
- cache_session = requests_cache.CachedSession('.cache', expire_after=3600)
28
- retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
29
- openmeteo = openmeteo_requests.Client(session=retry_session)
30
-
31
- url = "https://api.open-meteo.com/v1/forecast"
32
- params = {
33
- "latitude": latitude,
34
- "longitude": longitude,
35
- "hourly": "temperature_2m",
36
- }
37
- responses = openmeteo.weather_api(url, params=params)
38
- response = responses[0]
39
-
40
- hourly = response.Hourly()
41
- hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy()
42
- timestamps = pd.to_datetime(hourly.Time(), unit="s")
43
-
44
- data = pd.DataFrame({
45
- "time": timestamps,
46
- "temperature_2m": hourly_temperature_2m
47
- })
48
-
49
- latest_temp = data.iloc[-1]["temperature_2m"]
50
- return f"The latest recorded temperature at ({latitude}, {longitude}) is {latest_temp:.1f}°C."
51
-
52
- except Exception as e:
53
- return f"Error fetching weather data: {str(e)}"
54
-
55
-
56
  @tool
57
  def get_current_time_in_timezone(timezone: str) -> str:
58
- """Fetch the current local time in a specified timezone."""
59
  try:
60
  tz = pytz.timezone(timezone)
61
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
@@ -64,32 +48,46 @@ def get_current_time_in_timezone(timezone: str) -> str:
64
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
65
 
66
 
67
- # ===== Model and Agent Setup =====
68
-
69
  final_answer = FinalAnswerTool()
70
 
 
 
71
  model = HuggingFaceLLM(
72
- model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
73
  temperature=0.5,
74
- max_new_tokens=2048
 
75
  )
76
 
 
 
77
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
78
 
 
 
79
  with open("prompts.yaml", "r") as stream:
80
  prompt_templates = yaml.safe_load(stream)
81
 
 
 
82
  agent = CodeAgent(
83
  model=model,
84
- tools=[final_answer, hourly_temperature, get_current_time_in_timezone, image_generation_tool],
85
  max_steps=6,
86
  verbosity_level=1,
 
 
 
 
87
  prompt_templates=prompt_templates
88
  )
89
 
90
 
91
- # ===== Run the Agent =====
92
- if __name__ == "__main__":
93
- print(hourly_temperature(-1.95, 30.05))
94
- print(get_current_time_in_timezone("Africa/Kigali"))
95
- GradioUI(agent).launch()
 
 
 
1
+ # app.py
2
  from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
3
+ from smolagents.models import HuggingFaceLLM # unified model class in latest versions
4
  import datetime
 
5
  import pytz
6
  import yaml
 
7
 
8
+ # Weather-related imports
9
  import openmeteo_requests
10
  import pandas as pd
11
  import requests_cache
12
  from retry_requests import retry
13
 
14
+ from tools.final_answer import FinalAnswerTool
15
  from Gradio_UI import GradioUI
16
 
17
 
18
+ # Example tool: fetch hourly temperature from Open-Meteo API
 
19
  @tool
20
+ def hourly_temperature(lat: float, lon: float) -> pd.Series:
21
+ """Fetch hourly temperature for given latitude and longitude."""
22
+ cache_session = requests_cache.CachedSession('.cache', expire_after=3600)
23
+ retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
24
+ client = openmeteo_requests.Client(session=retry_session)
25
+
26
+ url = "https://api.open-meteo.com/v1/forecast"
27
+ params = {
28
+ "latitude": lat,
29
+ "longitude": lon,
30
+ "hourly": "temperature_2m",
31
+ }
32
+ response = client.weather_api(url, params=params)
33
+ hourly_data = response.Hourly()
34
+ temp_series = hourly_data.Variables(0).ValuesAsNumpy()
35
+
36
+ return pd.Series(temp_series, name="temperature_2m")
37
+
38
+
39
+ # Tool: get current time in timezone
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  @tool
41
  def get_current_time_in_timezone(timezone: str) -> str:
42
+ """Return current time in the specified timezone."""
43
  try:
44
  tz = pytz.timezone(timezone)
45
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
 
48
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
49
 
50
 
51
+ # Final answer tool
 
52
  final_answer = FinalAnswerTool()
53
 
54
+
55
+ # HuggingFace LLM model
56
  model = HuggingFaceLLM(
57
+ max_tokens=2096,
58
  temperature=0.5,
59
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # can switch to another HF endpoint if overloaded
60
+ custom_role_conversions=None,
61
  )
62
 
63
+
64
+ # Load a remote tool from HuggingFace Hub
65
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
66
 
67
+
68
+ # Load prompt templates
69
  with open("prompts.yaml", "r") as stream:
70
  prompt_templates = yaml.safe_load(stream)
71
 
72
+
73
+ # Create the agent
74
  agent = CodeAgent(
75
  model=model,
76
+ tools=[final_answer, hourly_temperature, get_current_time_in_timezone],
77
  max_steps=6,
78
  verbosity_level=1,
79
+ grammar=None,
80
+ planning_interval=None,
81
+ name=None,
82
+ description=None,
83
  prompt_templates=prompt_templates
84
  )
85
 
86
 
87
+ # Example calls (optional, can remove in prod)
88
+ hourly_temperature(32.9, 15)
89
+ get_current_time_in_timezone("Africa/Kigali")
90
+
91
+
92
+ # Launch the Gradio UI
93
+ GradioUI(agent).launch()