|
|
from smolagents import CodeAgent, tool |
|
|
from smolagents.models import TransformersModel |
|
|
import datetime |
|
|
import pytz |
|
|
import yaml |
|
|
import random |
|
|
|
|
|
|
|
|
|
|
|
@tool |
|
|
def get_current_time() -> str: |
|
|
"""Get current local time. |
|
|
|
|
|
Returns: |
|
|
Current date and time |
|
|
""" |
|
|
try: |
|
|
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
|
|
return f"Текущее время: {current_time}" |
|
|
except Exception as e: |
|
|
return f"Ошибка получения времени: {str(e)}" |
|
|
|
|
|
@tool |
|
|
def get_current_time_in_timezone(timezone: str) -> str: |
|
|
"""Get current local time in specified timezone. |
|
|
|
|
|
Args: |
|
|
timezone: A valid timezone (e.g., 'America/New_York', 'Europe/Moscow') |
|
|
|
|
|
Returns: |
|
|
Current time in the specified timezone |
|
|
""" |
|
|
try: |
|
|
tz = pytz.timezone(timezone) |
|
|
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") |
|
|
return f"Текущее время в {timezone}: {local_time}" |
|
|
except Exception as e: |
|
|
return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}" |
|
|
|
|
|
@tool |
|
|
def how_are_you() -> str: |
|
|
"""Answer questions about how you are doing. |
|
|
|
|
|
Returns: |
|
|
Friendly response about current status |
|
|
""" |
|
|
responses = [ |
|
|
"У меня всё отлично! Готов помочь вам с любыми вопросами.", |
|
|
"Прекрасно себя чувствую! Что хотели бы узнать?", |
|
|
"Всё хорошо, спасибо! Чем могу быть полезен?", |
|
|
"Отлично! Готов к работе и жду ваших вопросов.", |
|
|
"Замечательно! Как ваши дела?" |
|
|
] |
|
|
return random.choice(responses) |
|
|
|
|
|
@tool |
|
|
def what_are_you_doing() -> str: |
|
|
"""Answer questions about what you are currently doing. |
|
|
|
|
|
Returns: |
|
|
Description of current activities |
|
|
""" |
|
|
responses = [ |
|
|
"Я общаюсь с вами и готов помочь с любыми вопросами!", |
|
|
"В данный момент я помогаю пользователям как ассистент.", |
|
|
"Я работаю здесь, чтобы отвечать на ваши вопросы!", |
|
|
"Сейчас я здесь, чтобы помочь вам! Чем могу быть полезен?", |
|
|
"Я анализирую ваш запрос и готовлю полезный ответ." |
|
|
] |
|
|
return random.choice(responses) |
|
|
|
|
|
@tool |
|
|
def calculate_math(expression: str) -> str: |
|
|
"""Calculate mathematical expressions safely. |
|
|
|
|
|
Args: |
|
|
expression: A mathematical expression (e.g., '2+2', '5*3/2') |
|
|
|
|
|
Returns: |
|
|
Result of the calculation |
|
|
""" |
|
|
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 get_day_of_week() -> str: |
|
|
"""Get current day of the week. |
|
|
|
|
|
Returns: |
|
|
Current day name in Russian |
|
|
""" |
|
|
days = { |
|
|
0: "понедельник", |
|
|
1: "вторник", |
|
|
2: "среда", |
|
|
3: "четверг", |
|
|
4: "пятница", |
|
|
5: "суббота", |
|
|
6: "воскресенье" |
|
|
} |
|
|
day_num = datetime.datetime.now().weekday() |
|
|
return f"Сегодня {days[day_num]}" |
|
|
|
|
|
@tool |
|
|
def get_date_info() -> str: |
|
|
"""Get current date information. |
|
|
|
|
|
Returns: |
|
|
Detailed date information in Russian |
|
|
""" |
|
|
now = datetime.datetime.now() |
|
|
months = { |
|
|
1: "января", 2: "февраля", 3: "марта", 4: "апреля", |
|
|
5: "мая", 6: "июня", 7: "июля", 8: "августа", |
|
|
9: "сентября", 10: "октября", 11: "ноября", 12: "декабря" |
|
|
} |
|
|
return f"Сегодня {now.day} {months[now.month]} {now.year} года" |
|
|
|
|
|
@tool |
|
|
def simple_weather_advice() -> str: |
|
|
"""Provide general weather advice based on season. |
|
|
|
|
|
Returns: |
|
|
Seasonal weather advice |
|
|
""" |
|
|
month = datetime.datetime.now().month |
|
|
if month in [12, 1, 2]: |
|
|
return "Сейчас зима - одевайтесь тепло!" |
|
|
elif month in [3, 4, 5]: |
|
|
return "Сейчас весна - погода переменчива, берите зонт!" |
|
|
elif month in [6, 7, 8]: |
|
|
return "Сейчас лето - отличная погода для прогулок!" |
|
|
else: |
|
|
return "Сейчас осень - не забудьте куртку!" |
|
|
|
|
|
@tool |
|
|
def count_characters(text: str) -> str: |
|
|
"""Count the number of characters in a text. |
|
|
|
|
|
Args: |
|
|
text: The text to count characters in |
|
|
|
|
|
Returns: |
|
|
Number of characters |
|
|
""" |
|
|
return f"В тексте {len(text)} символов" |
|
|
|
|
|
@tool |
|
|
def repeat_text(text: str, times: int) -> str: |
|
|
"""Repeat text specified number of times. |
|
|
|
|
|
Args: |
|
|
text: Text to repeat |
|
|
times: Number of times to repeat |
|
|
|
|
|
Returns: |
|
|
Repeated text |
|
|
""" |
|
|
if times <= 10: |
|
|
return (text + " ") * times |
|
|
else: |
|
|
return "Слишком много повторений! Максимум 10 раз." |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model = TransformersModel("microsoft/DialoGPT-small") |
|
|
|
|
|
|
|
|
agent = CodeAgent( |
|
|
model=model, |
|
|
tools=[ |
|
|
get_current_time, |
|
|
get_current_time_in_timezone, |
|
|
how_are_you, |
|
|
what_are_you_doing, |
|
|
calculate_math, |
|
|
get_day_of_week, |
|
|
get_date_info, |
|
|
simple_weather_advice, |
|
|
count_characters, |
|
|
repeat_text |
|
|
], |
|
|
max_steps=6, |
|
|
verbosity_level=1, |
|
|
grammar=None, |
|
|
planning_interval=None, |
|
|
name="LocalAssistant", |
|
|
description="Локальный ассистент для времени, дат и простых вычислений" |
|
|
) |
|
|
|
|
|
|
|
|
import gradio as gr |
|
|
|
|
|
def chat_with_agent(message, history): |
|
|
"""Функция для общения с агентом""" |
|
|
try: |
|
|
response = agent.run(message) |
|
|
return response |
|
|
except Exception as e: |
|
|
return f"Ошибка: {str(e)}" |
|
|
|
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("# 🎯 Local Assistant") |
|
|
gr.Markdown("Локальный ассистент для времени, дат и вычислений") |
|
|
|
|
|
chatbot = gr.Chatbot(height=400) |
|
|
msg = gr.Textbox( |
|
|
label="Ваш вопрос", |
|
|
placeholder="Спросите о времени, дате или сделайте вычисление...", |
|
|
lines=2 |
|
|
) |
|
|
clear_btn = gr.Button("Очистить чат") |
|
|
|
|
|
def respond(message, chat_history): |
|
|
bot_response = chat_with_agent(message, chat_history) |
|
|
chat_history.append((message, bot_response)) |
|
|
return "", chat_history |
|
|
|
|
|
msg.submit(respond, [msg, chatbot], [msg, chatbot]) |
|
|
clear_btn.click(lambda: None, None, chatbot, queue=False) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
print("🚀 Starting Local Assistant...") |
|
|
demo.launch(share=True) |