Files changed (1) hide show
  1. app.py +224 -23
app.py CHANGED
@@ -1,61 +1,263 @@
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,5 +267,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
+ Args:
19
+ query: The search query to look up
20
+ """
21
+ try:
22
+ search_tool = DuckDuckGoSearchTool()
23
+ results = search_tool(query)
24
+ return f"🔍 **Результаты поиска по '{query}':**\n\n{results}"
25
+ except Exception as e:
26
+ return f"❌ Ошибка поиска: {str(e)}"
27
+
28
  @tool
29
+ def get_weather(city: str) -> str:
30
+ """Get current weather for a city using wttr.in service.
 
31
  Args:
32
+ city: The name of the city to get weather for (e.g., 'Moscow', 'London')
 
33
  """
34
+ try:
35
+ # Используем wttr.in с метрической системой (Цельсий)
36
+ url = f"http://wttr.in/{city}?format=%C+%t+%h+%w+%P&lang=ru&m"
37
+ response = requests.get(url, timeout=10)
38
+
39
+ if response.status_code == 200:
40
+ data = response.text.strip()
41
+
42
+ # Парсим ответ wttr.in
43
+ parts = data.split(' ')
44
+ if len(parts) >= 4:
45
+ condition = parts[0] # Погодные условия
46
+ temperature = parts[1] # Температура
47
+ humidity = parts[2] # Влажность
48
+ wind = parts[3] # Ветер
49
+
50
+ return (f"🌤 Погода в {city}:\n"
51
+ f"🌡 {temperature}\n"
52
+ f"☁️ {condition}\n"ы
53
+ f"💧 Влажность: {humidity}\n"
54
+ f"💨 Ветер: {wind}")
55
+ else:
56
+ return f"Погода в {city}: {data}"
57
+ else:
58
+ return f"❌ Не удалось получить погоду для {city}"
59
+
60
+ except Exception as e:
61
+ return f"❌ Ошибка: {str(e)}"
62
 
63
  @tool
64
  def get_current_time_in_timezone(timezone: str) -> str:
65
  """A tool that fetches the current local time in a specified timezone.
66
  Args:
67
+ timezone: A string representing a valid timezone (e.g., 'America/New_York')
68
  """
69
  try:
 
70
  tz = pytz.timezone(timezone)
 
71
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
72
  return f"The current local time in {timezone} is: {local_time}"
73
  except Exception as e:
74
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
75
 
76
+ @tool
77
+ def generate_image(prompt: str) -> str:
78
+ """Generate an image from text prompt and save it.
79
+ Args:
80
+ prompt: Text description of the image to generate
81
+ """
82
+ try:
83
+ image = image_generation_tool(prompt=prompt)
84
+
85
+ # Создаем папку для изображений если её нет
86
+ os.makedirs("images", exist_ok=True)
87
+
88
+ # Сохраняем в папку images
89
+ import time
90
+ filename = f"image_{int(time.time())}.png"
91
+ filepath = f"images/{filename}"
92
+ image.save(filepath)
93
+
94
+ return f"🎨 **Изображение сгенерировано!**\n\n" \
95
+ f"**Запрос:** {prompt}\n" \
96
+ f"**Файл:** `{filepath}`\n\n" \
97
+ f"📁 Изображение сохранено в папке 'images/'"
98
+
99
+ except Exception as e:
100
+ return f"❌ Ошибка генерации: {str(e)}"
101
 
102
+ @tool
103
+ def calculate_math(expression: str) -> str:
104
+ """Calculate mathematical expressions safely.
105
+ Args:
106
+ expression: A mathematical expression to calculate (e.g., '2+2', '5*3/2')
107
+ """
108
+ try:
109
+ # Безопасные математические операции
110
+ allowed_chars = set('0123456789+-*/.() ')
111
+ if all(c in allowed_chars for c in expression):
112
+ result = eval(expression)
113
+ return f"🧮 Результат: {result}"
114
+ else:
115
+ return "❌ Используй��е только цифры и +-*/.()"
116
+ except:
117
+ return "❌ Ошибка в выражении"
118
+
119
+
120
+ @tool
121
+ def coin_flip() -> str:
122
+ """Flip a coin and get heads or tails."""
123
+ import random
124
+ result = random.choice(["орел", "решка"])
125
+ return f"🪙"решка"])
126
+ return f"🪙 Результат броска: **{result}**"
127
 
128
+ @tool
129
+ def generate_password(length: int = 12) -> str:
130
+ """Generate a secure random password.
131
+ Args:
132
+ length: The length of the password (default: 12)
133
+ """
134
+ import string
135
+ import random
136
+ characters = string.ascii_letters + string.digits + "!@#$%"
137
+ password = ''.join(random.choice(characters) for _ in range(length))
138
+ return f"🔐 Сгенерированный пароль: `{password}`"
139
+
140
+ @tool
141
+ def advice_by_category(category: str = "random") -> str:
142
+ """Get advice by specific category.
143
+ Args:
144
+ category: Advice category ('motivation', 'health', 'work', 'relationships', 'random', 'personal development')
145
+ """
146
+ advice_categories = {
147
+ 'motivation': [
148
+ "Ты сильнее, чем думаешь 💪",
149
+ "Каждый эксперт когда-то был новичком 🌱",
150
+ "Не смотри на других - соревнуйся с собой вчерашним 🏆",
151
+ "Дыши глубоко в стрессовых ситуациях 🧘",
152
+ "Помни: все временно, и это тоже пройдет 🌈",
153
+ "Прими то, что не можешь изменить 🌊",
154
+ "Найди время для тишины каждый день 🤫",
155
+ ],
156
+ 'health': [
157
+ "Прогулка на свежем воздухе творит чудеса 🌳",
158
+ "Слушай свое тело - оно мудрее любого доктора 👂",
159
+ "Здоровье - главное богатство 💎",
160
+ "Пей больше воды 💧",
161
+ "Двигайся каждый день 🏃‍♂️",
162
+ "Высыпайся - сон это суперсила 😴",
163
+ "Ешь больше овощей и фруктов 🍎",
164
+ ],
165
+ 'work': [
166
+ "Делай зарядку с утра 🐸",
167
+ "Учись делегировать 🤲",
168
+ "Баланс работы и отдыха - ключ к успеху ⚖️",
169
+ "Инвестируй в свои знания 💼",
170
+ "Откладывай хотя бы 10% от дохода 💰",
171
+ "Учись говорить 'нет' когда нужно 🚫",
172
+ "Цени свой труд и время ⭐",
173
+ ],
174
+ 'relationships': [
175
+ "Искренний комплимент может изменить чей-то день 🌈",
176
+ "Слушай чтобы понять, а не чтобы ответить 💭",
177
+ "Прощение освобождает в первую очередь тебя 🕊️",
178
+ "Будь добрым к себе и другим 💖",
179
+ "Цени моменты - они уникальны 🌟",
180
+ "Говори 'спасибо' чаще 🙏",
181
+ "Слушай больше, чем говоришь 👂"
182
+ ],
183
+ 'personal development': [
184
+ "Выходи из зоны комфорта каждый день 🚪",
185
+ "Учись новому навыку каждый месяц 🎓",
186
+ "Рефлексируй над своим днем 📝",
187
+ "Ставь реалистичные цели 🎯",
188
+ ],
189
+ }
190
+
191
+ import random
192
+
193
+ if category == 'random' or category not in advice_categories:
194
+ all_advice = [advice for category_list in advice_categories.values() for advice in category_list]
195
+ return f"💡 Совет: {random.choice(all_advice)}"
196
+ else:
197
+ return f"💡 {category.title()} совет: {random.choice(advice_categories[category])}"
198
+
199
+ @tool
200
+ def calculate_age(birth_year: int) -> str:
201
+ """Calculate current age based on birth year.
202
+ Args:
203
+ birth_year: The year of birth
204
+ """
205
+ from datetime import datetime
206
+ current_year = datetime.now().year
207
+ age = current_year - birth_year
208
+
209
+ if age < 0:
210
+ return "❌ Год рождения не может быть в будущем!"
211
+ elif age == 0:
212
+ return "👶 0 лет! Новое начало! 🎉"
213
+ elif age < 13:
214
+ return f"🎂 {age} лет! Детство - прекрасная пора! 🌈"
215
+ elif age < 20:
216
+ return f"🎂 {age} лет! Юность полна возможностей! 🚀"
217
+ elif age < 30:
218
+ return f"🎂 {age} лет! Молодость и энергия! ⚡"
219
+ elif age < 40:
220
+ return f"🎂 {age} лет! Опыт и уверенность! 💼"
221
+ elif age < 50:
222
+ return f"🎂 {age} лет! Расцвет сил и мудрости! 🌟"
223
+ elif age < 60:
224
+ return f"🎂 {age} лет! Золотой возраст! 🏆"
225
+ elif age < 120:
226
+ return f"🎂 {age} лет! Богатый жизненный опыт! 📚"
227
+ else:
228
+ return f"🎂 {age} лет! Легендарное долголетие! 🎊"
229
+
230
+
231
+
232
+
233
+ # 2. ТОЛЬКО ПОСЛЕ ВСЕХ ФУНКЦИЙ создаем остальные объекты
234
+
235
+ final_answer = FinalAnswerTool()
236
 
237
  model = HfApiModel(
238
+ max_tokens=2096,
239
+ temperature=0.5,
240
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
241
+ custom_role_conversions=None,
242
  )
243
 
244
+ # Загрузка инструмента генерации изображений
 
245
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
246
 
247
  with open("prompts.yaml", 'r') as stream:
248
  prompt_templates = yaml.safe_load(stream)
249
+
250
+ # Добавляем проверку для final_answer
251
+ if "final_answer" not in prompt_templates:
252
+ prompt_templates["final_answer"] = {
253
+ "pre_messages": "Based on my research: ",
254
+ "post_messages": ""
255
+ }
256
 
257
+ # 3. Теперь используем функции в списке инструментов
258
  agent = CodeAgent(
259
  model=model,
260
+ tools=[final_answer, web_search, generate_image, get_current_time_in_timezone, get_weather, calculate_math, coin_flip, generate_password, advice_by_category, calculate_age],
261
  max_steps=6,
262
  verbosity_level=1,
263
  grammar=None,
 
267
  prompt_templates=prompt_templates
268
  )
269
 
 
270
  GradioUI(agent).launch()