SaraM2727 commited on
Commit
d15dc03
·
verified ·
1 Parent(s): 4d81a6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -119
app.py CHANGED
@@ -1,153 +1,61 @@
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
- from Gradio_UI import GradioUI
8
 
9
- # Tool: Fetch current time in a given timezone
10
 
 
11
  @tool
12
- def get_current_time_in_timezone(timezone: str) -> str:
 
 
 
 
 
13
  """
14
- Fetches the current local time in a specified timezone.
15
 
 
 
 
16
  Args:
17
- timezone (str): A string representing a valid timezone (e.g., 'America/New_York').
18
-
19
- Returns:
20
- str: The current time in the given timezone.
21
  """
22
  try:
 
23
  tz = pytz.timezone(timezone)
 
24
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
25
  return f"The current local time in {timezone} is: {local_time}"
26
  except Exception as e:
27
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
28
 
29
- # Tool: Fetch real-time weather for a given location
30
- @tool
31
- def get_weather(city: str) -> str:
32
- """
33
- Fetches the current weather for a given city.
34
-
35
- Args:
36
- city (str): The name of the city for which to fetch the weather.
37
-
38
- Returns:
39
- str: Weather description and temperature.
40
- """
41
- api_url = f"https://wttr.in/{city}?format=%C+%t"
42
- response = requests.get(api_url)
43
- if response.status_code == 200:
44
- return response.text
45
- return "Unable to retrieve weather information."
46
-
47
-
48
- # Tool: Fetch currency exchange rate
49
- @tool
50
- def get_exchange_rate(base_currency: str, target_currency: str) -> str:
51
- """
52
- Fetches the exchange rate between two currencies.
53
-
54
- Args:
55
- base_currency (str): The currency to convert from.
56
- target_currency (str): The currency to convert to.
57
-
58
- Returns:
59
- str: Exchange rate information.
60
- """
61
- url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
62
- response = requests.get(url)
63
- if response.status_code == 200:
64
- data = response.json()
65
- rate = data['rates'].get(target_currency, "N/A")
66
- return f"1 {base_currency} = {rate} {target_currency}"
67
- return "Exchange rate information not available."
68
-
69
- # Tool: Fetch Wikipedia summary
70
- @tool
71
- def get_wikipedia_summary(query: str) -> str:
72
- """
73
- Fetches a short summary from Wikipedia.
74
-
75
- Args:
76
- query (str): The topic to search on Wikipedia.
77
-
78
- Returns:
79
- str: Summary of the topic.
80
- """
81
- url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}"
82
- response = requests.get(url)
83
- if response.status_code == 200:
84
- return response.json().get("extract", "No summary available.")
85
- return "Wikipedia summary not found."
86
-
87
- # Tool: Fetch latest news headlines
88
- @tool
89
- def get_latest_news() -> str:
90
- """
91
- Fetches the latest news headlines.
92
-
93
- Returns:
94
- str: Top 5 latest news headlines.
95
- """
96
- url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_NEWSAPI_KEY"
97
- response = requests.get(url)
98
- if response.status_code == 200:
99
- articles = response.json().get("articles", [])[:5]
100
- return "\n".join([f"{i+1}. {article['title']}" for i, article in enumerate(articles)])
101
- return "Unable to retrieve news."
102
-
103
- # Tool: Fetch stock price for a given company symbol
104
- @tool
105
- def get_stock_price(symbol: str) -> str:
106
- """
107
- Fetches the latest stock price for a given company symbol.
108
-
109
- Args:
110
- symbol (str): The stock ticker symbol.
111
-
112
- Returns:
113
- str: The latest stock price.
114
- """
115
- url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=YOUR_FINNHUB_API_KEY"
116
- response = requests.get(url)
117
- if response.status_code == 200:
118
- data = response.json()
119
- return f"Stock price of {symbol}: ${data.get('c', 'N/A')}"
120
- return "Stock information not available."
121
 
122
  final_answer = FinalAnswerTool()
123
 
124
- # Hugging Face model setup
 
 
125
  model = HfApiModel(
126
- max_tokens=2096,
127
- temperature=0.5,
128
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
129
- custom_role_conversions=None,
130
  )
131
 
132
- # Load image generation tool from Hugging Face
 
133
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
134
 
135
  with open("prompts.yaml", 'r') as stream:
136
  prompt_templates = yaml.safe_load(stream)
137
 
138
- # Creating the AI agent
139
  agent = CodeAgent(
140
  model=model,
141
- tools=[
142
- final_answer,
143
- get_current_time_in_timezone,
144
- get_weather,
145
- get_exchange_rate,
146
- get_wikipedia_summary,
147
- get_latest_news,
148
- get_stock_price,
149
- image_generation_tool,
150
- ],
151
  max_steps=6,
152
  verbosity_level=1,
153
  grammar=None,
@@ -157,5 +65,5 @@ agent = CodeAgent(
157
  prompt_templates=prompt_templates
158
  )
159
 
160
- # Launch Gradio UI for interaction
161
  GradioUI(agent).launch()
 
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 my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
+ #Keep this format for the description / args / args description but feel free to modify the tool
14
+ """A tool that does nothing yet
15
+ Args:
16
+ arg1: the first argument
17
+ arg2: the second argument
18
  """
19
+ return "What magic will you build ?"
20
 
21
+ @tool
22
+ def get_current_time_in_timezone(timezone: str) -> str:
23
+ """A tool that fetches the current local time in a specified timezone.
24
  Args:
25
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
26
  """
27
  try:
28
+ # Create timezone object
29
  tz = pytz.timezone(timezone)
30
+ # Get current time in that timezone
31
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
  return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  final_answer = FinalAnswerTool()
38
 
39
+ # 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:
40
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
+
42
  model = HfApiModel(
43
+ max_tokens=2096,
44
+ temperature=0.5,
45
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
+ custom_role_conversions=None,
47
  )
48
 
49
+
50
+ # Import tool from Hub
51
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
55
 
 
56
  agent = CodeAgent(
57
  model=model,
58
+ tools=[final_answer], ## add your tools here (don't remove final answer)
 
 
 
 
 
 
 
 
 
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
 
65
  prompt_templates=prompt_templates
66
  )
67
 
68
+
69
  GradioUI(agent).launch()