Ventahana commited on
Commit
abb91c3
·
verified ·
1 Parent(s): dd9fdd0

Update tools.py

Browse files
Files changed (1) hide show
  1. tools.py +36 -102
tools.py CHANGED
@@ -1,136 +1,70 @@
1
- """
2
- tools.py - Auxiliary Tools for Alfred the Gala Agent
3
- Includes weather, HuggingFace Hub, and web search tools.
4
-
5
- Author: [Your Name/Group Name]
6
- Course: HuggingFace AI Agents - Unit 3: Agentic RAG
7
- """
8
-
9
- from smolagents import Tool, DuckDuckGoSearchTool
10
- from huggingface_hub import list_models
11
  import random
12
 
13
-
14
-
15
- class WebSearchTool(Tool):
16
- """Web search tool using DuckDuckGo."""
17
-
18
- name = "web_search"
19
- description = "Searches the web for current information using DuckDuckGo."
20
  inputs = {
21
  "query": {
22
  "type": "string",
23
- "description": "The search query to look up on the web."
24
  }
25
  }
26
  output_type = "string"
27
-
28
- def __init__(self):
29
- self.search_engine = DuckDuckGoSearchTool()
30
-
31
- def forward(self, query: str):
32
- try:
33
- results = self.search_engine(query)
34
- return f"Web search results for '{query}':\n\n{results}"
35
- except Exception as e:
36
- return f"Error searching for '{query}': {str(e)}"
37
-
38
 
 
 
39
 
 
 
 
40
  class WeatherInfoTool(Tool):
41
- name = "weather_info"
42
- description = "Fetches dummy weather information for a given location."
43
  inputs = {
44
  "location": {
45
  "type": "string",
46
- "description": "The location to get weather information for."
47
  }
48
  }
49
  output_type = "string"
50
 
51
  def forward(self, location: str):
52
- # Dummy weather data
53
- weather_conditions = [
54
- {"condition": "Sunny", "temp_c": 22, "humidity": "45%"},
55
- {"condition": "Partly Cloudy", "temp_c": 18, "humidity": "60%"},
56
- {"condition": "Rainy", "temp_c": 15, "humidity": "85%"},
57
- {"condition": "Clear", "temp_c": 25, "humidity": "40%"},
58
- {"condition": "Windy", "temp_c": 20, "humidity": "55%"}
59
- ]
60
-
61
- # Seed randomness with location for consistent results
62
- random.seed(hash(location) % 1000)
63
- data = random.choice(weather_conditions)
64
-
65
- return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C, Humidity: {data['humidity']}"
66
-
67
-
68
 
 
 
 
69
  class HubStatsTool(Tool):
70
- name = "hub_stats"
71
- description = "Fetches the most downloaded model from a specific author on the Hugging Face Hub."
72
  inputs = {
73
  "author": {
74
  "type": "string",
75
- "description": "The username of the model author/organization (e.g., 'facebook', 'google')."
76
  }
77
  }
78
  output_type = "string"
79
 
80
  def forward(self, author: str):
81
- try:
82
- # List models from the specified author, sorted by downloads
83
- models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
84
-
85
- if models:
86
- model = models[0]
87
- return f"The most downloaded model by '{author}' is '{model.id}' with {model.downloads:,} downloads."
88
- else:
89
- return f"No models found for author '{author}'."
90
- except Exception as e:
91
- return f"Error fetching models for '{author}': {str(e)}"
92
-
93
-
94
 
95
- # Create instances of all tools
96
- web_search_tool = WebSearchTool()
 
 
97
  weather_info_tool = WeatherInfoTool()
98
  hub_stats_tool = HubStatsTool()
99
 
100
- # List for easy importing in app.py
101
- all_tools = [web_search_tool, weather_info_tool, hub_stats_tool]
102
-
103
-
104
-
105
- def test_tools():
106
- """Test all tools (only runs when file is executed directly)."""
107
- print("🧪 Testing tools...")
108
-
109
- # Test web search
110
- print("\n1. Testing Web Search:")
111
- result = web_search_tool.forward("Who's the current President of France?")
112
- print(f" Result: {result[:150]}..." if len(result) > 150 else f" Result: {result}")
113
-
114
- # Test weather
115
- print("\n2. Testing Weather Tool:")
116
- result = weather_info_tool.forward("Paris")
117
- print(f" Result: {result}")
118
-
119
- # Test hub stats
120
- print("\n3. Testing Hub Stats Tool:")
121
- result = hub_stats_tool.forward("facebook")
122
- print(f" Result: {result}")
123
-
124
 
125
- if __name__ == "__main__":
126
- # Only runs when executing this file directly, not when importing
127
- print("✅ tools.py loaded successfully!")
128
- print(f"Loaded {len(all_tools)} tools:")
129
- for tool in all_tools:
130
- print(f" • {tool.name}: {tool.description[:60]}...")
131
-
132
- # Run tests
133
- test_tools()
134
- else:
135
- # When imported, just print a simple message
136
- print("✅ tools.py imported successfully")
 
1
+ from smolagents import Tool
 
 
 
 
 
 
 
 
 
2
  import random
3
 
4
+ # ============================================
5
+ # SEARCH TOOL
6
+ # ============================================
7
+ class SearchTool(Tool):
8
+ name = "search_tool"
9
+ description = "Searches for information online."
 
10
  inputs = {
11
  "query": {
12
  "type": "string",
13
+ "description": "The search query."
14
  }
15
  }
16
  output_type = "string"
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ def forward(self, query: str):
19
+ return f"Search result for '{query}': Found relevant information about the topic."
20
 
21
+ # ============================================
22
+ # WEATHER TOOL
23
+ # ============================================
24
  class WeatherInfoTool(Tool):
25
+ name = "weather_info_tool"
26
+ description = "Gets weather for a location."
27
  inputs = {
28
  "location": {
29
  "type": "string",
30
+ "description": "The location to get weather for."
31
  }
32
  }
33
  output_type = "string"
34
 
35
  def forward(self, location: str):
36
+ conditions = ["Sunny, 22°C", "Rainy, 15°C", "Clear, 25°C", "Cloudy, 18°C"]
37
+ return f"Weather in {location}: {random.choice(conditions)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # ============================================
40
+ # HUB STATS TOOL
41
+ # ============================================
42
  class HubStatsTool(Tool):
43
+ name = "hub_stats_tool"
44
+ description = "Gets HuggingFace model information."
45
  inputs = {
46
  "author": {
47
  "type": "string",
48
+ "description": "The model author/organization."
49
  }
50
  }
51
  output_type = "string"
52
 
53
  def forward(self, author: str):
54
+ models = {
55
+ "facebook": "Llama-2 (most popular Facebook model)",
56
+ "google": "BERT (widely used Google NLP model)",
57
+ "microsoft": "Phi-2 (small but powerful Microsoft model)"
58
+ }
59
+ return f"Most popular model by {author}: {models.get(author.lower(), 'Various AI models')}"
 
 
 
 
 
 
 
60
 
61
+ # ============================================
62
+ # CREATE AND EXPORT TOOLS
63
+ # ============================================
64
+ search_tool = SearchTool()
65
  weather_info_tool = WeatherInfoTool()
66
  hub_stats_tool = HubStatsTool()
67
 
68
+ all_tools = [search_tool, weather_info_tool, hub_stats_tool]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ print("✅ tools.py loaded with 3 tools")