cjb97 commited on
Commit
bd6d853
·
1 Parent(s): ea40075

Fix tool compatibility with smolagents 1.9.2 by creating proper Tool classes

Browse files
Files changed (4) hide show
  1. app.py +8 -33
  2. tools/__init__.py +3 -1
  3. tools/search.py +52 -0
  4. tools/weather.py +38 -0
app.py CHANGED
@@ -1,38 +1,13 @@
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
- # Weather tool to get current weather information
11
- def get_weather(location: str) -> str:
12
- """A tool that fetches the current weather for a specified location.
13
- Args:
14
- location: A string representing a city or location (e.g., 'New York', 'Paris, France').
15
- """
16
- try:
17
- # Using OpenWeatherMap API with a free tier (limited requests)
18
- api_key = "1ae035abc608d0e1095a5472dc989299" # OpenWeatherMap API key
19
- url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
20
-
21
- response = requests.get(url)
22
- data = response.json()
23
-
24
- if response.status_code == 200:
25
- temp = data["main"]["temp"]
26
- weather = data["weather"][0]["description"]
27
- humidity = data["main"]["humidity"]
28
- wind_speed = data["wind"]["speed"]
29
- return f"The current weather in {location} is {temp}°C with {weather}. Humidity: {humidity}%, Wind speed: {wind_speed} m/s."
30
- else:
31
- return f"Error fetching weather for {location}: {data.get('message', 'Unknown error')}"
32
- except Exception as e:
33
- return f"Error fetching weather for {location}: {str(e)}"
34
-
35
  final_answer = FinalAnswerTool()
 
 
 
36
  model = HfApiModel(
37
  max_tokens=2096,
38
  temperature=0.5,
@@ -48,8 +23,8 @@ agent = CodeAgent(
48
  model=model,
49
  tools=[
50
  final_answer,
51
- DuckDuckGoSearchTool(),
52
- get_weather
53
  ],
54
  max_steps=6,
55
  verbosity_level=1,
 
1
+ from smolagents import CodeAgent, HfApiModel
 
 
 
2
  import yaml
3
+ from tools import FinalAnswerTool, WeatherTool, DuckDuckGoSearchTool
 
4
  from Gradio_UI import GradioUI
5
 
6
+ # Initialize our tools
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  final_answer = FinalAnswerTool()
8
+ weather_tool = WeatherTool()
9
+ search_tool = DuckDuckGoSearchTool()
10
+
11
  model = HfApiModel(
12
  max_tokens=2096,
13
  temperature=0.5,
 
23
  model=model,
24
  tools=[
25
  final_answer,
26
+ search_tool,
27
+ weather_tool
28
  ],
29
  max_steps=6,
30
  verbosity_level=1,
tools/__init__.py CHANGED
@@ -1,5 +1,7 @@
1
  """Tools for the agent."""
2
 
3
  from .final_answer import FinalAnswerTool
 
 
4
 
5
- __all__ = ["FinalAnswerTool"]
 
1
  """Tools for the agent."""
2
 
3
  from .final_answer import FinalAnswerTool
4
+ from .weather import WeatherTool
5
+ from .search import DuckDuckGoSearchTool
6
 
7
+ __all__ = ["FinalAnswerTool", "WeatherTool", "DuckDuckGoSearchTool"]
tools/search.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents.tools import Tool
2
+ import requests
3
+ from typing import Any, List, Dict, Optional
4
+ import json
5
+
6
+ class DuckDuckGoSearchTool(Tool):
7
+ """Tool for searching the web using DuckDuckGo."""
8
+
9
+ name = "duck_duck_go_search"
10
+ description = "Search the web for information using DuckDuckGo."
11
+
12
+ def __call__(self, query: str) -> str:
13
+ """
14
+ Search the web for information using DuckDuckGo.
15
+
16
+ Args:
17
+ query: A string representing the search query.
18
+
19
+ Returns:
20
+ A string with the search results.
21
+ """
22
+ try:
23
+ # Using the DuckDuckGo API
24
+ url = "https://api.duckduckgo.com/"
25
+ params = {
26
+ 'q': query,
27
+ 'format': 'json',
28
+ 'no_html': 1,
29
+ 'skip_disambig': 1
30
+ }
31
+
32
+ response = requests.get(url, params=params)
33
+ data = response.json()
34
+
35
+ results = []
36
+
37
+ # Add the abstract if available
38
+ if data.get('Abstract'):
39
+ results.append(f"Abstract: {data['Abstract']}")
40
+
41
+ # Add related topics
42
+ if data.get('RelatedTopics'):
43
+ for i, topic in enumerate(data['RelatedTopics'][:5]): # Limit to 5 topics
44
+ if 'Text' in topic:
45
+ results.append(f"Result {i+1}: {topic['Text']}")
46
+
47
+ if not results:
48
+ return f"No results found for query: {query}"
49
+
50
+ return "\n\n".join(results)
51
+ except Exception as e:
52
+ return f"Error searching for {query}: {str(e)}"
tools/weather.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents.tools import Tool
2
+ import requests
3
+ from typing import Any, Optional
4
+
5
+ class WeatherTool(Tool):
6
+ """Tool for getting weather information for a location."""
7
+
8
+ name = "get_weather"
9
+ description = "Get the current weather for a specified location."
10
+
11
+ def __call__(self, location: str) -> str:
12
+ """
13
+ Get the current weather for a specified location.
14
+
15
+ Args:
16
+ location: A string representing a city or location (e.g., 'New York', 'Paris, France').
17
+
18
+ Returns:
19
+ A string with the current weather information.
20
+ """
21
+ try:
22
+ # Using OpenWeatherMap API with a free tier (limited requests)
23
+ api_key = "1ae035abc608d0e1095a5472dc989299" # OpenWeatherMap API key
24
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
25
+
26
+ response = requests.get(url)
27
+ data = response.json()
28
+
29
+ if response.status_code == 200:
30
+ temp = data["main"]["temp"]
31
+ weather = data["weather"][0]["description"]
32
+ humidity = data["main"]["humidity"]
33
+ wind_speed = data["wind"]["speed"]
34
+ return f"The current weather in {location} is {temp}°C with {weather}. Humidity: {humidity}%, Wind speed: {wind_speed} m/s."
35
+ else:
36
+ return f"Error fetching weather for {location}: {data.get('message', 'Unknown error')}"
37
+ except Exception as e:
38
+ return f"Error fetching weather for {location}: {str(e)}"