Files changed (1) hide show
  1. app.py +162 -27
app.py CHANGED
@@ -1,62 +1,198 @@
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,
62
  planning_interval=None,
@@ -65,5 +201,4 @@ agent = CodeAgent(
65
  prompt_templates=prompt_templates
66
  )
67
 
68
-
69
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool, DuckDuckGoSearchTool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import base64
7
+ import os
8
+ import io
9
+ from PIL import Image
10
  from tools.final_answer import FinalAnswerTool
 
11
  from Gradio_UI import GradioUI
12
 
13
+ # 1. функции-инструменты
14
+
15
  @tool
16
+ def web_search(query: str) -> str:
17
+ """Search the web for information using DuckDuckGo.
18
+
19
  Args:
20
+ query: The search query to look up
21
+
22
+ Returns:
23
+ Search results from DuckDuckGo
24
  """
25
+ try:
26
+ search_tool = DuckDuckGoSearchTool()
27
+ results = search_tool(query)
28
+ if not results or "No results found" in results:
29
+ return f"Поиск не дал результатов для запроса: '{query}'. Попробуйте другой запрос."
30
+ return f"Результаты поиска по '{query}':\n\n{results}"
31
+ except Exception as e:
32
+ return f"Ошибка поиска: {str(e)}"
33
+
34
+ @tool
35
+ def get_weather(city: str) -> str:
36
+ """Get current weather for a city using reliable weather services.
37
+
38
+ Args:
39
+ city: The name of the city to get weather for (e.g., 'Moscow', 'London')
40
+
41
+ Returns:
42
+ Current weather information in Celsius
43
+ """
44
+ try:
45
+
46
+ url = f"https://wttr.in/{city}?format=%C+%t+%h+%w&m&lang=ru"
47
+ response = requests.get(url, timeout=10)
48
+
49
+ if response.status_code == 200 and response.text.strip():
50
+ data = response.text.strip()
51
+
52
+ if '°F' in data:
53
+ data = data.replace('°F', '°C')
54
+ return f"Погода в {city}:\n{data}"
55
+
56
+ url2 = f"https://wttr.in/{city}?format=%C+%t+%h+%w+%P&m&lang=ru"
57
+ response2 = requests.get(url2, timeout=10)
58
+
59
+ if response2.status_code == 200 and response2.text.strip():
60
+ data = response2.text.strip()
61
+ if '°F' in data:
62
+ data = data.replace('°F', '°C')
63
+ return f"Погода в {city}:\n{data}"
64
+
65
+ return f"Данные о погоде в {city} временно недоступны. Попробуйте позже или проверьте на сайте gismeteo.ru"
66
+
67
+ except Exception as e:
68
+ return f"Ошибка при получении погоды: {str(e)}"
69
+
70
+ @tool
71
+ def get_weather_detailed(city: str) -> str:
72
+ """Get detailed weather forecast for a city.
73
+
74
+ Args:
75
+ city: The name of the city
76
+
77
+ Returns:
78
+ Detailed weather information in Celsius
79
+ """
80
+ try:
81
+
82
+ url = f"https://wttr.in/{city}?m&lang=ru"
83
+ response = requests.get(url, timeout=10)
84
+
85
+ if response.status_code == 200:
86
+
87
+ lines = response.text.split('\n')
88
+ short_forecast = '\n'.join(lines[:8]) # Первые 8 строк
89
+
90
+ short_forecast = short_forecast.replace('°F', '°C')
91
+ return f"Подробный прогноз для {city}:\n{short_forecast}"
92
+ else:
93
+ return f"Не удалось получить подробный прогноз для {city}"
94
+
95
+ except Exception as e:
96
+ return f"Ошибка: {str(e)}"
97
+
98
+ @tool
99
+ def convert_fahrenheit_to_celsius(f_temp: float) -> str:
100
+ """Convert Fahrenheit temperature to Celsius.
101
+
102
+ Args:
103
+ f_temp: Temperature in Fahrenheit
104
+
105
+ Returns:
106
+ Temperature in Celsius
107
+ """
108
+ try:
109
+ c_temp = (f_temp - 32) * 5/9
110
+ return f"{f_temp}°F = {c_temp:.1f}°C"
111
+ except Exception as e:
112
+ return f"Ошибка конвертации: {str(e)}"
113
 
114
  @tool
115
  def get_current_time_in_timezone(timezone: str) -> str:
116
+ """Get current local time in specified timezone.
117
+
118
  Args:
119
+ timezone: A valid timezone (e.g., 'America/New_York', 'Europe/Moscow')
120
+
121
+ Returns:
122
+ Current time in the specified timezone
123
  """
124
  try:
 
125
  tz = pytz.timezone(timezone)
 
126
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
127
+ return f"Текущее врем�� в {timezone}: {local_time}"
128
  except Exception as e:
129
+ return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}"
130
+ @tool
131
+ def calculate_math(expression: str) -> str:
132
+ """Calculate mathematical expressions safely.
133
+
134
+ Args:
135
+ expression: A mathematical expression (e.g., '2+2', '5*3/2')
136
+
137
+ Returns:
138
+ Result of the calculation
139
+ """
140
+ try:
141
+
142
+ allowed_chars = set('0123456789+-*/.() ')
143
+ if all(c in allowed_chars for c in expression):
144
+ result = eval(expression)
145
+ return f"Результат: {result}"
146
+ else:
147
+ return "Используйте только цифры и +-*/.()"
148
+ except:
149
+ return "Ошибка в выражении"
150
 
151
+ @tool
152
+ def suggest_weather_sources(city: str) -> str:
153
+ """Suggest reliable weather sources for a city.
154
+
155
+ Args:
156
+ city: The name of the city
157
+
158
+ Returns:
159
+ List of reliable weather sources
160
+ """
161
+ sources = [
162
+ f"Gismeteo: https://www.gismeteo.ru/weather-{city.lower()}-4368/",
163
+ f"Yandex.Погода: https://yandex.ru/pogoda/{city.lower()}",
164
+ f"Weather.com: https://weather.com/weather/today/l/{city}",
165
+ f"AccuWeather: https://www.accuweather.com/ru/ru/{city.lower()}/weather-forecast"
166
+ ]
167
+
168
+ return f"Надежные источники погоды для {city}:\n" + "\n".join(sources)
169
 
170
+ # 2. остальные объекты
171
 
172
+ final_answer = FinalAnswerTool()
 
173
 
174
  model = HfApiModel(
175
+ max_tokens=2096,
176
+ temperature=0.5,
177
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
178
+ custom_role_conversions=None,
179
  )
180
 
 
 
181
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
182
 
183
  with open("prompts.yaml", 'r') as stream:
184
  prompt_templates = yaml.safe_load(stream)
185
+
186
+ if "final_answer" not in prompt_templates:
187
+ prompt_templates["final_answer"] = {
188
+ "pre_messages": "Based on my research: ",
189
+ "post_messages": ""
190
+ }
191
 
192
  agent = CodeAgent(
193
  model=model,
194
+ tools=[final_answer, web_search, get_weather, get_weather_detailed, convert_fahrenheit_to_celsius, get_current_time_in_timezone, calculate_math, suggest_weather_sources],
195
+ max_steps=8,
196
  verbosity_level=1,
197
  grammar=None,
198
  planning_interval=None,
 
201
  prompt_templates=prompt_templates
202
  )
203
 
 
204
  GradioUI(agent).launch()