MADtoBAD commited on
Commit
0efc50e
·
verified ·
1 Parent(s): 87c390c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -112
app.py CHANGED
@@ -1,95 +1,11 @@
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
- url = f"https://wttr.in/{city}?format=%C+%t+%h+%w&m&lang=ru"
46
- response = requests.get(url, timeout=10)
47
-
48
- if response.status_code == 200 and response.text.strip():
49
- data = response.text.strip()
50
- if '°F' in data:
51
- data = data.replace('°F', '°C')
52
- return f"Погода в {city}:\n{data}"
53
-
54
- url2 = f"https://wttr.in/{city}?format=%C+%t+%h+%w+%P&m&lang=ru"
55
- response2 = requests.get(url2, timeout=10)
56
-
57
- if response2.status_code == 200 and response2.text.strip():
58
- data = response2.text.strip()
59
- if '°F' in data:
60
- data = data.replace('°F', '°C')
61
- return f"Погода в {city}:\n{data}"
62
-
63
- return f"Данные о погоде в {city} временно недоступны. Попробуйте позже или проверьте на сайте gismeteo.ru"
64
-
65
- except Exception as e:
66
- return f"Ошибка при получении погоды: {str(e)}"
67
-
68
- @tool
69
- def get_weather_detailed(city: str) -> str:
70
- """Get detailed weather forecast for a city.
71
-
72
- Args:
73
- city: The name of the city
74
-
75
- Returns:
76
- Detailed weather information in Celsius
77
- """
78
- try:
79
- url = f"https://wttr.in/{city}?m&lang=ru"
80
- response = requests.get(url, timeout=10)
81
-
82
- if response.status_code == 200:
83
- lines = response.text.split('\n')
84
- short_forecast = '\n'.join(lines[:8]) # Первые 8 строк
85
-
86
- short_forecast = short_forecast.replace('°F', '°C')
87
- return f"Подробный прогноз для {city}:\n{short_forecast}"
88
- else:
89
- return f"Не удалось получить подробный прогноз для {city}"
90
-
91
- except Exception as e:
92
- return f"Ошибка: {str(e)}"
93
 
94
  @tool
95
  def get_current_time() -> str:
@@ -146,9 +62,9 @@ def what_are_you_doing() -> str:
146
  Description of current activities
147
  """
148
  responses = [
149
- "Я общаюсь с вами и готов помочь с поиском информации!",
150
- "В данный момент я помогаю пользователям находить ответы на их вопросы.",
151
- "Я работаю ассистентом - ищу информацию в интернете, сообщаю о погоде и текущем времени.",
152
  "Сейчас я здесь, чтобы помочь вам! Чем могу быть полезен?",
153
  "Я анализирую ваш запрос и готовлю полезный ответ."
154
  ]
@@ -176,25 +92,57 @@ def calculate_math(expression: str) -> str:
176
  return "Ошибка в выражении"
177
 
178
  @tool
179
- def suggest_weather_sources(city: str) -> str:
180
- """Suggest reliable weather sources for a city.
181
 
182
- Args:
183
- city: The name of the city
184
-
185
  Returns:
186
- List of reliable weather sources
187
  """
188
- sources = [
189
- f"Gismeteo: https://www.gismeteo.ru/weather-{city.lower()}-4368/",
190
- f"Yandex.Погода: https://yandex.ru/pogoda/{city.lower()}",
191
- f"Weather.com: https://weather.com/weather/today/l/{city}",
192
- f"AccuWeather: https://www.accuweather.com/ru/ru/{city.lower()}/weather-forecast"
193
- ]
 
 
 
 
 
 
 
 
 
194
 
195
- return f"Надежные источники погоды для {city}:\n" + "\n".join(sources)
 
 
 
 
 
 
 
 
 
196
 
197
- # 2. остальные объекты
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  final_answer = FinalAnswerTool()
200
 
@@ -214,27 +162,26 @@ if "final_answer" not in prompt_templates:
214
  "post_messages": ""
215
  }
216
 
217
- # Создаем агента с новым именем и обновленными инструментами
218
  agent = CodeAgent(
219
  model=model,
220
  tools=[
221
  final_answer,
222
- web_search,
223
- get_weather,
224
- get_weather_detailed,
225
  get_current_time,
226
  get_current_time_in_timezone,
227
  how_are_you,
228
  what_are_you_doing,
229
- calculate_math,
230
- suggest_weather_sources
 
 
231
  ],
232
- max_steps=8,
233
  verbosity_level=1,
234
  grammar=None,
235
  planning_interval=None,
236
- name="WeatherTimeBot", # Новое имя агента
237
- description="Ассистент для поиска информации, прогноза погоды и определения времени",
238
  prompt_templates=prompt_templates
239
  )
240
 
 
1
+ from smolagents import CodeAgent, HfApiModel, tool
2
  import datetime
 
3
  import pytz
4
  import yaml
 
 
 
 
5
  from tools.final_answer import FinalAnswerTool
6
  from Gradio_UI import GradioUI
7
 
8
+ # 1. Локальные функции-инструменты (без интернета)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  @tool
11
  def get_current_time() -> str:
 
62
  Description of current activities
63
  """
64
  responses = [
65
+ "Я общаюсь с вами и готов помочь с любыми вопросами!",
66
+ "В данный момент я помогаю пользователям как ассистент.",
67
+ "Я работаю здесь, чтобы отвечать на ваши вопросы!",
68
  "Сейчас я здесь, чтобы помочь вам! Чем могу быть полезен?",
69
  "Я анализирую ваш запрос и готовлю полезный ответ."
70
  ]
 
92
  return "Ошибка в выражении"
93
 
94
  @tool
95
+ def get_day_of_week() -> str:
96
+ """Get current day of the week.
97
 
 
 
 
98
  Returns:
99
+ Current day name in Russian
100
  """
101
+ days = {
102
+ 0: "понедельник",
103
+ 1: "вторник",
104
+ 2: "среда",
105
+ 3: "четверг",
106
+ 4: "пятница",
107
+ 5: "суббота",
108
+ 6: "воскресенье"
109
+ }
110
+ day_num = datetime.datetime.now().weekday()
111
+ return f"Сегодня {days[day_num]}"
112
+
113
+ @tool
114
+ def get_date_info() -> str:
115
+ """Get current date information.
116
 
117
+ Returns:
118
+ Detailed date information in Russian
119
+ """
120
+ now = datetime.datetime.now()
121
+ months = {
122
+ 1: "января", 2: "февраля", 3: "марта", 4: "апреля",
123
+ 5: "мая", 6: "июня", 7: "июля", 8: "августа",
124
+ 9: "сентября", 10: "октября", 11: "ноября", 12: "декабря"
125
+ }
126
+ return f"Сегодня {now.day} {months[now.month]} {now.year} года"
127
 
128
+ @tool
129
+ def simple_weather_advice() -> str:
130
+ """Provide general weather advice based on season.
131
+
132
+ Returns:
133
+ Seasonal weather advice
134
+ """
135
+ month = datetime.datetime.now().month
136
+ if month in [12, 1, 2]:
137
+ return "Сейчас зима - одевайтесь тепло!"
138
+ elif month in [3, 4, 5]:
139
+ return "Сейчас весна - погода переменчива, берите зонт!"
140
+ elif month in [6, 7, 8]:
141
+ return "Сейчас лето - отличная погода для прогулок!"
142
+ else:
143
+ return "Сейчас осень - не забудьте куртку!"
144
+
145
+ # 2. Остальные объекты
146
 
147
  final_answer = FinalAnswerTool()
148
 
 
162
  "post_messages": ""
163
  }
164
 
165
+ # Создаем агента только с локальными инструментами
166
  agent = CodeAgent(
167
  model=model,
168
  tools=[
169
  final_answer,
 
 
 
170
  get_current_time,
171
  get_current_time_in_timezone,
172
  how_are_you,
173
  what_are_you_doing,
174
+ calculate_math,
175
+ get_day_of_week,
176
+ get_date_info,
177
+ simple_weather_advice
178
  ],
179
+ max_steps=6,
180
  verbosity_level=1,
181
  grammar=None,
182
  planning_interval=None,
183
+ name="LocalAssistant", # Новое имя для локального агента
184
+ description="Локальный ассистент для времени, дат и простых вычислений",
185
  prompt_templates=prompt_templates
186
  )
187