File size: 10,932 Bytes
f7f4564
9b5b26a
 
 
c19d193
f7f4564
 
 
 
6aae614
9b5b26a
 
f7f4564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
f7f4564
 
9b5b26a
f7f4564
9b5b26a
f7f4564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
 
f7f4564
9b5b26a
 
 
 
 
 
 
8c01ffb
f7f4564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
f7f4564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
f7f4564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
e121372
f7f4564
 
 
 
13d500a
8c01ffb
f7f4564
9b5b26a
8c01ffb
861422e
 
f7f4564
 
 
 
 
 
 
9b5b26a
f7f4564
8c01ffb
8fe992b
f7f4564
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
8c01ffb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
from smolagents import CodeAgent, HfApiModel, load_tool, tool, DuckDuckGoSearchTool
import datetime
import requests
import pytz
import yaml
import base64
import os
import io
from PIL import Image
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# 1. Сначала определяем ВСЕ функции-инструменты

@tool
def web_search(query: str) -> str:
    """Search the web for information using DuckDuckGo.
    Args:
        query: The search query to look up
    """
    try:
        search_tool = DuckDuckGoSearchTool()
        results = search_tool(query)
        return f"🔍 **Результаты поиска по '{query}':**\n\n{results}"
    except Exception as e:
        return f"❌ Ошибка поиска: {str(e)}"

@tool
def get_weather(city: str) -> str:
    """Get current weather for a city using wttr.in service.
    Args:
        city: The name of the city to get weather for (e.g., 'Moscow', 'London')
    """
    try:
        # Используем wttr.in с метрической системой (Цельсий)
        url = f"http://wttr.in/{city}?format=%C+%t+%h+%w+%P&lang=ru&m"
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            data = response.text.strip()
            
            # Парсим ответ wttr.in
            parts = data.split(' ')
            if len(parts) >= 4:
                condition = parts[0]  # Погодные условия
                temperature = parts[1]  # Температура
                humidity = parts[2]    # Влажность
                wind = parts[3]        # Ветер
                
                return (f"🌤 Погода в {city}:\n"
                       f"🌡 {temperature}\n"
                       f"☁️ {condition}\n"ы
                       f"💧 Влажность: {humidity}\n"
                       f"💨 Ветер: {wind}")
            else:
                return f"Погода в {city}: {data}"
        else:
            return f"❌ Не удалось получить погоду для {city}"
            
    except Exception as e:
        return f"❌ Ошибка: {str(e)}"

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York')
    """
    try:
        tz = pytz.timezone(timezone)
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"

@tool
def generate_image(prompt: str) -> str:
    """Generate an image from text prompt and save it.
    Args:
        prompt: Text description of the image to generate
    """
    try:
        image = image_generation_tool(prompt=prompt)
        
        # Создаем папку для изображений если её нет
        os.makedirs("images", exist_ok=True)
        
        # Сохраняем в папку images
        import time
        filename = f"image_{int(time.time())}.png"
        filepath = f"images/{filename}"
        image.save(filepath)
        
        return f"🎨 **Изображение сгенерировано!**\n\n" \
               f"**Запрос:** {prompt}\n" \
               f"**Файл:** `{filepath}`\n\n" \
               f"📁 Изображение сохранено в папке 'images/'"
               
    except Exception as e:
        return f"❌ Ошибка генерации: {str(e)}"

@tool
def calculate_math(expression: str) -> str:
    """Calculate mathematical expressions safely.
    Args:
        expression: A mathematical expression to calculate (e.g., '2+2', '5*3/2')
    """
    try:
        # Безопасные математические операции
        allowed_chars = set('0123456789+-*/.() ')
        if all(c in allowed_chars for c in expression):
            result = eval(expression)
            return f"🧮 Результат: {result}"
        else:
            return "❌ Используйте только цифры и +-*/.()"
    except:
        return "❌ Ошибка в выражении"


@tool
def coin_flip() -> str:
    """Flip a coin and get heads or tails."""
    import random
    result = random.choice(["орел", "решка"])
    return f"🪙"решка"])
    return f"🪙 Результат броска: **{result}**"

@tool
def generate_password(length: int = 12) -> str:
    """Generate a secure random password.
    Args:
        length: The length of the password (default: 12)
    """
    import string
    import random
    characters = string.ascii_letters + string.digits + "!@#$%"
    password = ''.join(random.choice(characters) for _ in range(length))
    return f"🔐 Сгенерированный пароль: `{password}`"

@tool
def advice_by_category(category: str = "random") -> str:
    """Get advice by specific category.
    Args:
        category: Advice category ('motivation', 'health', 'work', 'relationships', 'random', 'personal development')
    """
    advice_categories = {
        'motivation': [
            "Ты сильнее, чем думаешь 💪",
            "Каждый эксперт когда-то был новичком 🌱",
            "Не смотри на других - соревнуйся с собой вчерашним 🏆",
            "Дыши глубоко в стрессовых ситуациях 🧘",
            "Помни: все временно, и это тоже пройдет 🌈",
            "Прими то, что не можешь изменить 🌊",
            "Найди время для тишины каждый день 🤫",
        ],
        'health': [
            "Прогулка на свежем воздухе творит чудеса 🌳",
            "Слушай свое тело - оно мудрее любого доктора 👂",
            "Здоровье - главное богатство 💎",
            "Пей больше воды 💧",
            "Двигайся каждый день 🏃‍♂️",
            "Высыпайся - сон это суперсила 😴",
            "Ешь больше овощей и фруктов 🍎",
        ],
        'work': [
            "Делай зарядку с утра 🐸",
            "Учись делегировать 🤲",
            "Баланс работы и отдыха - ключ к успеху ⚖️",
            "Инвестируй в свои знания 💼",
            "Откладывай хотя бы 10% от дохода 💰",
            "Учись говорить 'нет' когда нужно 🚫",
            "Цени свой труд и время ⭐",
        ],
        'relationships': [
            "Искренний комплимент может изменить чей-то день 🌈",
            "Слушай чтобы понять, а не чтобы ответить 💭",
            "Прощение освобождает в первую очередь тебя 🕊️",
            "Будь добрым к себе и другим 💖",
            "Цени моменты - они уникальны 🌟",
            "Говори 'спасибо' чаще 🙏",
            "Слушай больше, чем говоришь 👂"
        ],
        'personal development': [
            "Выходи из зоны комфорта каждый день 🚪",
            "Учись новому навыку каждый месяц 🎓",
            "Рефлексируй над своим днем 📝",
            "Ставь реалистичные цели 🎯",
        ],
    }
    
    import random
    
    if category == 'random' or category not in advice_categories:
        all_advice = [advice for category_list in advice_categories.values() for advice in category_list]
        return f"💡 Совет: {random.choice(all_advice)}"
    else:
        return f"💡 {category.title()} совет: {random.choice(advice_categories[category])}"

@tool
def calculate_age(birth_year: int) -> str:
    """Calculate current age based on birth year.
    Args:
        birth_year: The year of birth
    """
    from datetime import datetime
    current_year = datetime.now().year
    age = current_year - birth_year
    
    if age < 0:
        return "❌ Год рождения не может быть в будущем!"
    elif age == 0:
        return "👶 0 лет! Новое начало! 🎉"
    elif age < 13:
        return f"🎂 {age} лет! Детство - прекрасная пора! 🌈"
    elif age < 20:
        return f"🎂 {age} лет! Юность полна возможностей! 🚀"
    elif age < 30:
        return f"🎂 {age} лет! Молодость и энергия! ⚡"
    elif age < 40:
        return f"🎂 {age} лет! Опыт и уверенность! 💼"
    elif age < 50:
        return f"🎂 {age} лет! Расцвет сил и мудрости! 🌟"
    elif age < 60:
        return f"🎂 {age} лет! Золотой возраст! 🏆"
    elif age < 120:
        return f"🎂 {age} лет! Богатый жизненный опыт! 📚"
    else:
        return f"🎂 {age} лет! Легендарное долголетие! 🎊"




# 2. ТОЛЬКО ПОСЛЕ ВСЕХ ФУНКЦИЙ создаем остальные объекты

final_answer = FinalAnswerTool()

model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

# Загрузка инструмента генерации изображений
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)

# Добавляем проверку для final_answer
if "final_answer" not in prompt_templates:
    prompt_templates["final_answer"] = {
        "pre_messages": "Based on my research: ",
        "post_messages": ""
    }
    
# 3. Теперь используем функции в списке инструментов
agent = CodeAgent(
    model=model,
    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],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)

GradioUI(agent).launch()