Update app.py
Browse files
app.py
CHANGED
|
@@ -1,35 +1,94 @@
|
|
| 1 |
-
from smolagents import CodeAgent, tool
|
| 2 |
-
from smolagents.models import TransformersModel
|
| 3 |
import datetime
|
|
|
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
@tool
|
| 11 |
-
def
|
| 12 |
-
"""Get current
|
| 13 |
-
|
| 14 |
-
Returns:
|
| 15 |
-
Current date and time
|
| 16 |
-
"""
|
| 17 |
try:
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
-
return f"Ошибка
|
| 22 |
|
| 23 |
@tool
|
| 24 |
-
def
|
| 25 |
-
"""Get
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
tz = pytz.timezone(timezone)
|
| 35 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
@@ -37,48 +96,9 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 37 |
except Exception as e:
|
| 38 |
return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}"
|
| 39 |
|
| 40 |
-
@tool
|
| 41 |
-
def how_are_you() -> str:
|
| 42 |
-
"""Answer questions about how you are doing.
|
| 43 |
-
|
| 44 |
-
Returns:
|
| 45 |
-
Friendly response about current status
|
| 46 |
-
"""
|
| 47 |
-
responses = [
|
| 48 |
-
"У меня всё отлично! Готов помочь вам с любыми вопросами.",
|
| 49 |
-
"Прекрасно себя чувствую! Что хотели бы узнать?",
|
| 50 |
-
"Всё хорошо, спасибо! Чем могу быть полезен?",
|
| 51 |
-
"Отлично! Готов к работе и жду ваших вопросов.",
|
| 52 |
-
"Замечательно! Как ваши дела?"
|
| 53 |
-
]
|
| 54 |
-
return random.choice(responses)
|
| 55 |
-
|
| 56 |
-
@tool
|
| 57 |
-
def what_are_you_doing() -> str:
|
| 58 |
-
"""Answer questions about what you are currently doing.
|
| 59 |
-
|
| 60 |
-
Returns:
|
| 61 |
-
Description of current activities
|
| 62 |
-
"""
|
| 63 |
-
responses = [
|
| 64 |
-
"Я общаюсь с вами и готов помочь с любыми вопросами!",
|
| 65 |
-
"В данный момент я помогаю пользователям как ассистент.",
|
| 66 |
-
"Я работаю здесь, чтобы отвечать на ваши вопросы!",
|
| 67 |
-
"Сейчас я здесь, чтобы помочь вам! Чем могу быть полезен?",
|
| 68 |
-
"Я анализирую ваш запрос и готовлю полезный ответ."
|
| 69 |
-
]
|
| 70 |
-
return random.choice(responses)
|
| 71 |
-
|
| 72 |
@tool
|
| 73 |
def calculate_math(expression: str) -> str:
|
| 74 |
-
"""Calculate mathematical expressions safely.
|
| 75 |
-
|
| 76 |
-
Args:
|
| 77 |
-
expression: A mathematical expression (e.g., '2+2', '5*3/2')
|
| 78 |
-
|
| 79 |
-
Returns:
|
| 80 |
-
Result of the calculation
|
| 81 |
-
"""
|
| 82 |
try:
|
| 83 |
allowed_chars = set('0123456789+-*/.() ')
|
| 84 |
if all(c in allowed_chars for c in expression):
|
|
@@ -90,144 +110,45 @@ def calculate_math(expression: str) -> str:
|
|
| 90 |
return "Ошибка в выражении"
|
| 91 |
|
| 92 |
@tool
|
| 93 |
-
def
|
| 94 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
Current day name in Russian
|
| 98 |
-
"""
|
| 99 |
-
days = {
|
| 100 |
-
0: "понедельник",
|
| 101 |
-
1: "вторник",
|
| 102 |
-
2: "среда",
|
| 103 |
-
3: "четверг",
|
| 104 |
-
4: "пятница",
|
| 105 |
-
5: "суббота",
|
| 106 |
-
6: "воскресенье"
|
| 107 |
-
}
|
| 108 |
-
day_num = datetime.datetime.now().weekday()
|
| 109 |
-
return f"Сегодня {days[day_num]}"
|
| 110 |
|
| 111 |
-
|
| 112 |
-
def get_date_info() -> str:
|
| 113 |
-
"""Get current date information.
|
| 114 |
-
|
| 115 |
-
Returns:
|
| 116 |
-
Detailed date information in Russian
|
| 117 |
-
"""
|
| 118 |
-
now = datetime.datetime.now()
|
| 119 |
-
months = {
|
| 120 |
-
1: "января", 2: "февраля", 3: "марта", 4: "апреля",
|
| 121 |
-
5: "мая", 6: "июня", 7: "июля", 8: "августа",
|
| 122 |
-
9: "сентября", 10: "октября", 11: "ноября", 12: "декабря"
|
| 123 |
-
}
|
| 124 |
-
return f"Сегодня {now.day} {months[now.month]} {now.year} года"
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
"""
|
| 133 |
-
month = datetime.datetime.now().month
|
| 134 |
-
if month in [12, 1, 2]:
|
| 135 |
-
return "Сейчас зима - одевайтесь тепло!"
|
| 136 |
-
elif month in [3, 4, 5]:
|
| 137 |
-
return "Сейчас весна - погода переменчива, берите зонт!"
|
| 138 |
-
elif month in [6, 7, 8]:
|
| 139 |
-
return "Сейчас лето - отличная погода для прогулок!"
|
| 140 |
-
else:
|
| 141 |
-
return "Сейчас осень - не забудьте куртку!"
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
"""Count the number of characters in a text.
|
| 146 |
-
|
| 147 |
-
Args:
|
| 148 |
-
text: The text to count characters in
|
| 149 |
-
|
| 150 |
-
Returns:
|
| 151 |
-
Number of characters
|
| 152 |
-
"""
|
| 153 |
-
return f"В тексте {len(text)} символов"
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
Args:
|
| 160 |
-
text: Text to repeat
|
| 161 |
-
times: Number of times to repeat
|
| 162 |
-
|
| 163 |
-
Returns:
|
| 164 |
-
Repeated text
|
| 165 |
-
"""
|
| 166 |
-
if times <= 10:
|
| 167 |
-
return (text + " ") * times
|
| 168 |
-
else:
|
| 169 |
-
return "Слишком много повторений! Максимум 10 раз."
|
| 170 |
-
|
| 171 |
-
# 2. Создаем модель и агента
|
| 172 |
-
|
| 173 |
-
# Используем легкую локальную модель
|
| 174 |
-
model = TransformersModel("microsoft/DialoGPT-small")
|
| 175 |
-
|
| 176 |
-
# Создаем агента только с локальными инструментами
|
| 177 |
agent = CodeAgent(
|
| 178 |
model=model,
|
| 179 |
-
tools=[
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
how_are_you,
|
| 183 |
-
what_are_you_doing,
|
| 184 |
-
calculate_math,
|
| 185 |
-
get_day_of_week,
|
| 186 |
-
get_date_info,
|
| 187 |
-
simple_weather_advice,
|
| 188 |
-
count_characters,
|
| 189 |
-
repeat_text
|
| 190 |
-
],
|
| 191 |
-
max_steps=6,
|
| 192 |
-
verbosity_level=1,
|
| 193 |
grammar=None,
|
| 194 |
planning_interval=None,
|
| 195 |
-
name=
|
| 196 |
-
description=
|
|
|
|
| 197 |
)
|
| 198 |
|
| 199 |
-
|
| 200 |
-
import gradio as gr
|
| 201 |
-
|
| 202 |
-
def chat_with_agent(message, history):
|
| 203 |
-
"""Функция для общения с агентом"""
|
| 204 |
-
try:
|
| 205 |
-
response = agent.run(message)
|
| 206 |
-
return response
|
| 207 |
-
except Exception as e:
|
| 208 |
-
return f"Ошибка: {str(e)}"
|
| 209 |
-
|
| 210 |
-
# Создаем простой интерфейс
|
| 211 |
-
with gr.Blocks() as demo:
|
| 212 |
-
gr.Markdown("# 🎯 Local Assistant")
|
| 213 |
-
gr.Markdown("Локальный ассистент для времени, дат и вычислений")
|
| 214 |
-
|
| 215 |
-
chatbot = gr.Chatbot(height=400)
|
| 216 |
-
msg = gr.Textbox(
|
| 217 |
-
label="Ваш вопрос",
|
| 218 |
-
placeholder="Спросите о времени, дате или сделайте вычисление...",
|
| 219 |
-
lines=2
|
| 220 |
-
)
|
| 221 |
-
clear_btn = gr.Button("Очистить чат")
|
| 222 |
-
|
| 223 |
-
def respond(message, chat_history):
|
| 224 |
-
bot_response = chat_with_agent(message, chat_history)
|
| 225 |
-
chat_history.append((message, bot_response))
|
| 226 |
-
return "", chat_history
|
| 227 |
-
|
| 228 |
-
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 229 |
-
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
| 230 |
-
|
| 231 |
-
if __name__ == "__main__":
|
| 232 |
-
print("🚀 Starting Local Assistant...")
|
| 233 |
-
demo.launch(share=True)
|
|
|
|
| 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 |
+
# Инструменты (tools), используемые агентом:
|
| 14 |
+
# - web_search: поиск в интернете через DuckDuckGo
|
| 15 |
+
# - get_weather: получение текущей погоды для города
|
| 16 |
+
# - get_weather_detailed: подробный прогноз погоды
|
| 17 |
+
# - convert_fahrenheit_to_celsius: конвертация температуры
|
| 18 |
+
# - get_current_time_in_timezone: время в указанном часовом поясе
|
| 19 |
+
# - calculate_math: вычисление математических выражений
|
| 20 |
+
# - suggest_weather_sources: рекомендации источников погоды
|
| 21 |
+
# - final_answer: инструмент для финального ответа
|
| 22 |
|
| 23 |
+
@tool
|
| 24 |
+
def web_search(query: str) -> str:
|
| 25 |
+
"""Search the web for information using DuckDuckGo."""
|
| 26 |
+
try:
|
| 27 |
+
search_tool = DuckDuckGoSearchTool()
|
| 28 |
+
results = search_tool(query)
|
| 29 |
+
if not results or "No results found" in results:
|
| 30 |
+
return f"Поиск не дал результатов для запроса: '{query}'. Попробуйте другой запрос."
|
| 31 |
+
return f"**Результаты поиска по '{query}':**\n\n{results}"
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Ошибка поиска: {str(e)}"
|
| 34 |
|
| 35 |
@tool
|
| 36 |
+
def get_weather(city: str) -> str:
|
| 37 |
+
"""Get current weather for a city using reliable weather services."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
+
url = f"https://wttr.in/{city}?format=%C+%t+%h+%w&m&lang=ru"
|
| 40 |
+
response = requests.get(url, timeout=10)
|
| 41 |
+
|
| 42 |
+
if response.status_code == 200 and response.text.strip():
|
| 43 |
+
data = response.text.strip()
|
| 44 |
+
if '°F' in data:
|
| 45 |
+
data = data.replace('°F', '°C')
|
| 46 |
+
return f"Погода в {city}:\n{data}"
|
| 47 |
+
|
| 48 |
+
url2 = f"https://wttr.in/{city}?format=%C+%t+%h+%w+%P&m&lang=ru"
|
| 49 |
+
response2 = requests.get(url2, timeout=10)
|
| 50 |
+
|
| 51 |
+
if response2.status_code == 200 and response2.text.strip():
|
| 52 |
+
data = response2.text.strip()
|
| 53 |
+
if '°F' in data:
|
| 54 |
+
data = data.replace('°F', '°C')
|
| 55 |
+
return f"Погода в {city}:\n{data}"
|
| 56 |
+
|
| 57 |
+
return f"Данные о погоде в {city} временно недоступны. Попробуйте позже или проверьте на сайте gismeteo.ru"
|
| 58 |
+
|
| 59 |
except Exception as e:
|
| 60 |
+
return f"Ошибка при получении погоды: {str(e)}"
|
| 61 |
|
| 62 |
@tool
|
| 63 |
+
def get_weather_detailed(city: str) -> str:
|
| 64 |
+
"""Get detailed weather forecast for a city."""
|
| 65 |
+
try:
|
| 66 |
+
url = f"https://wttr.in/{city}?m&lang=ru"
|
| 67 |
+
response = requests.get(url, timeout=10)
|
| 68 |
|
| 69 |
+
if response.status_code == 200:
|
| 70 |
+
lines = response.text.split('\n')
|
| 71 |
+
short_forecast = '\n'.join(lines[:8])
|
| 72 |
+
short_forecast = short_forecast.replace('°F', '°C')
|
| 73 |
+
return f"Подробный прогноз для {city}:\n{short_forecast}"
|
| 74 |
+
else:
|
| 75 |
+
return f"Не удалось получить подробный прогноз для {city}"
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return f"Ошибка: {str(e)}"
|
| 79 |
+
|
| 80 |
+
@tool
|
| 81 |
+
def convert_fahrenheit_to_celsius(f_temp: float) -> str:
|
| 82 |
+
"""Convert Fahrenheit temperature to Celsius."""
|
| 83 |
+
try:
|
| 84 |
+
c_temp = (f_temp - 32) * 5/9
|
| 85 |
+
return f"{f_temp}°F = {c_temp:.1f}°C"
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return f"Ошибка конвертации: {str(e)}"
|
| 88 |
+
|
| 89 |
+
@tool
|
| 90 |
+
def get_current_time_in_timezone(timezone: str) -> str:
|
| 91 |
+
"""Get current local time in specified timezone."""
|
| 92 |
try:
|
| 93 |
tz = pytz.timezone(timezone)
|
| 94 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}"
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
@tool
|
| 100 |
def calculate_math(expression: str) -> str:
|
| 101 |
+
"""Calculate mathematical expressions safely."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
try:
|
| 103 |
allowed_chars = set('0123456789+-*/.() ')
|
| 104 |
if all(c in allowed_chars for c in expression):
|
|
|
|
| 110 |
return "Ошибка в выражении"
|
| 111 |
|
| 112 |
@tool
|
| 113 |
+
def suggest_weather_sources(city: str) -> str:
|
| 114 |
+
"""Suggest reliable weather sources for a city."""
|
| 115 |
+
sources = [
|
| 116 |
+
f"Gismeteo: https://www.gismeteo.ru/weather-{city.lower()}-4368/",
|
| 117 |
+
f"Yandex.Погода: https://yandex.ru/pogoda/{city.lower()}",
|
| 118 |
+
f"Weather.com: https://weather.com/weather/today/l/{city}",
|
| 119 |
+
f"AccuWeather: https://www.accuweather.com/ru/ru/{city.lower()}/weather-forecast"
|
| 120 |
+
]
|
| 121 |
|
| 122 |
+
return f"Надежные источники погоды для {city}:\n" + "\n".join(sources)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
final_answer = FinalAnswerTool()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
model = HfApiModel(
|
| 127 |
+
max_tokens=2096,
|
| 128 |
+
temperature=0.5,
|
| 129 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 130 |
+
custom_role_conversions=None,
|
| 131 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
with open("prompts.yaml", 'r') as stream:
|
| 134 |
+
prompt_templates = yaml.safe_load(stream)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
if "final_answer" not in prompt_templates:
|
| 137 |
+
prompt_templates["final_answer"] = {
|
| 138 |
+
"pre_messages": "Based on my research: ",
|
| 139 |
+
"post_messages": ""
|
| 140 |
+
}
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
agent = CodeAgent(
|
| 143 |
model=model,
|
| 144 |
+
tools=[final_answer, web_search, get_weather, get_weather_detailed, convert_fahrenheit_to_celsius, get_current_time_in_timezone, calculate_math, suggest_weather_sources],
|
| 145 |
+
max_steps=8,
|
| 146 |
+
verbosity_level=0,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
grammar=None,
|
| 148 |
planning_interval=None,
|
| 149 |
+
name=None,
|
| 150 |
+
description=None,
|
| 151 |
+
prompt_templates=prompt_templates
|
| 152 |
)
|
| 153 |
|
| 154 |
+
GradioUI(agent).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|