File size: 7,683 Bytes
7663d57 87c390c 7663d57 87c390c 0efc50e 87c390c 0efc50e 87c390c b016b2b 87c390c 52b0c91 87c390c 0efc50e de90e17 87c390c 0efc50e 87c390c 0efc50e 3bcc4b6 0efc50e 87c390c 0efc50e 7663d57 87c390c 7663d57 87c390c 7663d57 87c390c 7663d57 87c390c 0efc50e 87c390c 0efc50e 7663d57 87c390c 0efc50e 87c390c 7663d57 87c390c 7663d57 |
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 |
from smolagents import CodeAgent, tool
from smolagents.models import TransformersModel
import datetime
import pytz
import yaml
import random
# 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 = [
"У меня всё отлично! Готов помочь вам с любыми вопросами.",
"Прекрасно себя чувствую! Что хотели бы узнать?",
"Всё хорошо, спасибо! Чем могу быть полезен?",
"Отлично! Готов к работе и жду ваших вопросов.",
"Замечательно! Как ваши дела?"
]
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 раз."
# 2. Создаем модель и агента
# Используем легкую локальную модель
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="Локальный ассистент для времени, дат и простых вычислений"
)
# 3. Простой интерфейс Gradio (если нет Gradio_UI)
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) |