my_agent / app.py
MADtoBAD's picture
Update app.py
0efc50e verified
raw
history blame
6.21 kB
from smolagents import CodeAgent, HfApiModel, tool
import datetime
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# 1. Локальные функции-инструменты (без интернета)
@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 = [
"У меня всё отлично! Готов помочь вам с любыми вопросами.",
"Прекрасно себя чувствую! Что хотели бы узнать?",
"Всё хорошо, спасибо! Чем могу быть полезен?",
"Отлично! Готов к работе и жду ваших вопросов.",
"Замечательно! Как ваши дела?"
]
import random
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 = [
"Я общаюсь с вами и готов помочь с любыми вопросами!",
"В данный момент я помогаю пользователям как ассистент.",
"Я работаю здесь, чтобы отвечать на ваши вопросы!",
"Сейчас я здесь, чтобы помочь вам! Чем могу быть полезен?",
"Я анализирую ваш запрос и готовлю полезный ответ."
]
import random
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 "Сейчас осень - не забудьте куртку!"
# 2. Остальные объекты
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
if "final_answer" not in prompt_templates:
prompt_templates["final_answer"] = {
"pre_messages": "Based on my research: ",
"post_messages": ""
}
# Создаем агента только с локальными инструментами
agent = CodeAgent(
model=model,
tools=[
final_answer,
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
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name="LocalAssistant", # Новое имя для локального агента
description="Локальный ассистент для времени, дат и простых вычислений",
prompt_templates=prompt_templates
)
GradioUI(agent).launch()