File size: 6,209 Bytes
0efc50e 87c390c 0efc50e 87c390c 0efc50e 87c390c b016b2b 87c390c 52b0c91 87c390c 0efc50e de90e17 87c390c 0efc50e 87c390c 0efc50e 3bcc4b6 0efc50e 87c390c 0efc50e 87c390c 3bcc4b6 0efc50e 87c390c 0efc50e 87c390c 0efc50e 87c390c 0efc50e 87c390c |
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 |
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() |