droid22 commited on
Commit
05da41f
·
verified ·
1 Parent(s): 2c13f20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -29
app.py CHANGED
@@ -1,24 +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 custom_duckduckgo_search(query: str) -> str:
13
  """A tool that performs a web search using DuckDuckGo to find current information.
14
  Args:
15
  query: The search query string to look up on the web.
16
  """
17
- base_search_tool = DuckDuckGoSearchTool()
18
  try:
19
- # Call the underlying smolagents search tool
20
- result = base_search_tool(query)
21
- return str(result)
22
  except Exception as e:
23
  return f"Error performing search: {str(e)}"
24
 
@@ -29,45 +28,95 @@ def get_current_time_in_timezone(timezone: str) -> str:
29
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
30
  """
31
  try:
32
- # Create timezone object
33
  tz = pytz.timezone(timezone)
34
- # Get current time in that timezone
35
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
36
  return f"The current local time in {timezone} is: {local_time}"
37
  except Exception as e:
38
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # 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:
44
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
45
 
 
46
  model = HfApiModel(
47
- max_tokens=2096,
48
- temperature=0.5,
49
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
50
- custom_role_conversions=None,
51
  )
52
 
53
-
54
- # Import tool from Hub
55
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
56
 
57
- with open("prompts.yaml", 'r') as stream:
58
- prompt_templates = yaml.safe_load(stream)
59
-
 
 
 
 
 
 
 
 
 
 
 
60
  agent = CodeAgent(
61
  model=model,
62
- tools=[final_answer, custom_duckduckgo_search, get_current_time_in_timezone], ## add your tools here (don't remove final answer)
63
- max_steps=50,
64
  verbosity_level=1,
65
  grammar=None,
66
  planning_interval=None,
67
- name=None,
68
- description=None,
69
- prompt_templates=prompt_templates
70
  )
71
 
72
-
73
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
 
 
 
5
  from Gradio_UI import GradioUI
6
 
7
+ # ==========================================
8
+ # 1. DEFINE YOUR TOOLS
9
+ # ==========================================
10
+
11
+ base_search_tool = DuckDuckGoSearchTool()
12
+
13
  @tool
14
  def custom_duckduckgo_search(query: str) -> str:
15
  """A tool that performs a web search using DuckDuckGo to find current information.
16
  Args:
17
  query: The search query string to look up on the web.
18
  """
 
19
  try:
20
+ return str(base_search_tool(query))
 
 
21
  except Exception as e:
22
  return f"Error performing search: {str(e)}"
23
 
 
28
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
29
  """
30
  try:
 
31
  tz = pytz.timezone(timezone)
 
32
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
33
  return f"The current local time in {timezone} is: {local_time}"
34
  except Exception as e:
35
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
36
 
37
+ @tool
38
+ def get_weather(location: str) -> str:
39
+ """A tool that fetches the current weather for a given city or location.
40
+ Args:
41
+ location: The name of the city (e.g., 'Tokyo', 'New York', 'Paris').
42
+ """
43
+ try:
44
+ # Step 1: Get latitude and longitude
45
+ geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1"
46
+ geo_data = requests.get(geo_url).json()
47
+ if "results" not in geo_data:
48
+ return f"Could not find coordinates for {location}."
49
+
50
+ lat = geo_data["results"][0]["latitude"]
51
+ lon = geo_data["results"][0]["longitude"]
52
+
53
+ # Step 2: Fetch the weather using the coordinates
54
+ weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
55
+ weather_data = requests.get(weather_url).json()
56
+
57
+ current = weather_data["current_weather"]
58
+ temp = current["temperature"]
59
+ wind = current["windspeed"]
60
+
61
+ return f"The current weather in {location} is {temp}°C with wind speeds of {wind} km/h."
62
+ except Exception as e:
63
+ return f"Error fetching weather: {str(e)}"
64
 
65
+ @tool
66
+ def get_crypto_price(crypto_id: str) -> str:
67
+ """Fetches the current live price of a cryptocurrency in USD.
68
+ Args:
69
+ crypto_id: The full CoinGecko ID of the coin (e.g., 'bitcoin', 'ethereum', 'dogecoin').
70
+ """
71
+ try:
72
+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto_id}&vs_currencies=usd"
73
+ response = requests.get(url).json()
74
+ if crypto_id.lower() in response:
75
+ price = response[crypto_id.lower()]["usd"]
76
+ return f"The current price of {crypto_id.capitalize()} is ${price} USD."
77
+ else:
78
+ return f"Could not find price for '{crypto_id}'. Make sure to use the full name (e.g., 'bitcoin' not 'BTC')."
79
+ except Exception as e:
80
+ return f"Error fetching price: {str(e)}"
81
 
82
+ # ==========================================
83
+ # 2. SETUP MODEL AND EXTERNAL TOOLS
84
+ # ==========================================
85
 
86
+ # Initialize the model
87
  model = HfApiModel(
88
+ max_tokens=2096,
89
+ temperature=0.5,
90
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
 
91
  )
92
 
93
+ # Load the image generation tool from Hugging Face Hub
 
94
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
95
 
96
+ # ==========================================
97
+ # 3. CONFIGURE AND LAUNCH THE AGENT
98
+ # ==========================================
99
+
100
+ # Compile all our tools into a single list
101
+ my_tools = [
102
+ custom_duckduckgo_search,
103
+ get_current_time_in_timezone,
104
+ get_weather,
105
+ get_crypto_price,
106
+ image_generation_tool
107
+ ]
108
+
109
+ # Note: Removed `prompt_templates` here to use the built-in, error-free defaults
110
  agent = CodeAgent(
111
  model=model,
112
+ tools=my_tools,
113
+ max_steps=10, # Bumped up to 10 to give the agent more room to think!
114
  verbosity_level=1,
115
  grammar=None,
116
  planning_interval=None,
117
+ name="Super_Analyst",
118
+ description="An agent capable of checking weather, stock prices, web searching, and drawing images."
 
119
  )
120
 
121
+ # Launch the UI
122
  GradioUI(agent).launch()