clintonvanry commited on
Commit
e5d7c9f
·
verified ·
1 Parent(s): 40130ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -23
app.py CHANGED
@@ -9,8 +9,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 get_weather(city: str) -> str: # Fixed comment syntax and function name
13
- """A tool that retrieves the current weather for a city
14
 
15
  Args:
16
  city: the name of the city
@@ -19,43 +19,91 @@ def get_weather(city: str) -> str: # Fixed comment syntax and function name
19
  str: Weather information for the specified city, or error message
20
  """
21
  try:
22
- # Initialize the search tool correctly
23
  web_search_tool = DuckDuckGoSearchTool(max_results=3)
24
- web_search_tool.setup() # Call setup on the instance, not the class
25
 
26
  # Search for weather information
27
- search_query = f"current weather {city} temperature conditions"
28
  results = web_search_tool(search_query)
29
 
30
- # Extract and format weather information
31
- if results and len(results) > 0:
32
- # Assuming results is a list of search result objects with 'snippet' or 'body' attributes
33
- weather_info = ""
34
- for result in results[:2]: # Use top 2 results
35
- if hasattr(result, 'snippet'):
36
- weather_info += result.snippet + " "
37
- elif hasattr(result, 'body'):
38
- weather_info += result.body + " "
39
- elif isinstance(result, dict):
40
- weather_info += result.get('snippet', result.get('body', str(result))) + " "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- if weather_info.strip():
43
- return f"Weather in {city}: {weather_info.strip()}"
44
  else:
45
- return f"Weather information found for {city}, but couldn't extract details. Raw results: {str(results)}"
 
 
 
 
 
 
 
 
46
  else:
47
- return f"No weather information found for city '{city}'"
48
 
49
- except ImportError:
50
- return f"Error: DuckDuckGoSearchTool not available. Please install required dependencies."
51
  except AttributeError as e:
52
- return f"Error: Problem with search tool configuration: {str(e)}"
 
 
53
  except Exception as e:
54
  return f"Error fetching weather information for city '{city}': {str(e)}"
55
 
56
 
57
 
58
 
 
59
  @tool
60
  def get_current_time_in_timezone(timezone: str) -> str:
61
  """A tool that fetches the current local time in a specified timezone.
 
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
+ def get_weather_tool(city: str) -> str:
13
+ """A tool that retrieves the current weather for a city using DuckDuckGoSearchTool
14
 
15
  Args:
16
  city: the name of the city
 
19
  str: Weather information for the specified city, or error message
20
  """
21
  try:
22
+ # Create instance first, then call setup on the instance
23
  web_search_tool = DuckDuckGoSearchTool(max_results=3)
24
+ web_search_tool.setup() # Call setup on instance, not class
25
 
26
  # Search for weather information
27
+ search_query = f"current weather {city} temperature forecast"
28
  results = web_search_tool(search_query)
29
 
30
+ # Debug: Print raw results to understand the structure
31
+ print(f"Raw results type: {type(results)}")
32
+ print(f"Raw results: {results}")
33
+
34
+ # Process results based on different possible return types
35
+ if results:
36
+ weather_info = []
37
+
38
+ # Handle different result formats
39
+ if isinstance(results, list):
40
+ for i, result in enumerate(results[:3]): # Use top 3 results
41
+ print(f"Result {i}: {type(result)} - {result}")
42
+
43
+ if isinstance(result, dict):
44
+ # Handle dictionary results
45
+ text = result.get('snippet', result.get('body', result.get('content', '')))
46
+ title = result.get('title', '')
47
+ url = result.get('url', '')
48
+
49
+ # Combine title and text for better context
50
+ combined = f"{title} {text}".strip()
51
+
52
+ elif isinstance(result, str):
53
+ # Handle string results
54
+ combined = result
55
+
56
+ else:
57
+ # Handle object results with attributes
58
+ combined = ""
59
+ for attr in ['snippet', 'body', 'content', 'text', 'description']:
60
+ if hasattr(result, attr):
61
+ value = getattr(result, attr)
62
+ if value:
63
+ combined += f"{value} "
64
+
65
+ # Also try title
66
+ if hasattr(result, 'title'):
67
+ title = getattr(result, 'title')
68
+ if title:
69
+ combined = f"{title} {combined}"
70
+
71
+ # Filter for weather-related content
72
+ if combined and any(keyword in combined.lower() for keyword in
73
+ ['temperature', 'weather', '°f', '°c', 'degrees', 'sunny',
74
+ 'cloudy', 'rain', 'forecast', 'humidity', 'wind']):
75
+ weather_info.append(combined[:200]) # Limit length
76
+
77
+ elif isinstance(results, str):
78
+ # Handle single string result
79
+ weather_info = [results[:300]]
80
 
 
 
81
  else:
82
+ # Handle other result types
83
+ weather_info = [str(results)[:300]]
84
+
85
+ # Format final response
86
+ if weather_info:
87
+ return f"Weather in {city}: {' | '.join(weather_info)}"
88
+ else:
89
+ return f"Found search results for {city} but no clear weather information. Raw results: {str(results)[:200]}"
90
+
91
  else:
92
+ return f"No search results found for weather in {city}"
93
 
94
+ except ImportError as e:
95
+ return f"Error: DuckDuckGoSearchTool not available. Import error: {str(e)}"
96
  except AttributeError as e:
97
+ return f"Error: Problem with DuckDuckGoSearchTool setup or usage: {str(e)}"
98
+ except TypeError as e:
99
+ return f"Error: Incorrect parameters for DuckDuckGoSearchTool: {str(e)}"
100
  except Exception as e:
101
  return f"Error fetching weather information for city '{city}': {str(e)}"
102
 
103
 
104
 
105
 
106
+
107
  @tool
108
  def get_current_time_in_timezone(timezone: str) -> str:
109
  """A tool that fetches the current local time in a specified timezone.