From a41556a2d61f04bcb68423cdc0be001fe7d5c9fe Mon Sep 17 00:00:00 2001 From: mirivlad Date: Tue, 24 Feb 2026 04:37:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=BA?= =?UTF-8?q?=D1=81=D1=82=20=D0=B4=D0=B8=D0=B0=D0=BB=D0=BE=D0=B3=D0=B0=20?= =?UTF-8?q?=D1=81=20=D0=98=D0=98=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Изменения: - UserState.ai_chat_history — хранение истории диалога - handle_ai_task() передаёт историю в Qwen Code - История ограничена 20 последними сообщениями - Команда /ai clear — очистка истории - Исправлена кнопка меню (убран лишний импорт) Теперь ИИ помнит контекст диалога в рамках сессии Co-authored-by: Qwen-Coder --- bot.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index ff64376..0f2b7cd 100644 --- a/bot.py +++ b/bot.py @@ -299,6 +299,7 @@ class UserState: current_server: str = "local" # Имя текущего сервера editing_server: Optional[str] = None # Имя сервера, который редактируем ai_chat_mode: bool = False # Режим чата с ИИ агентом + ai_chat_history: List[str] = field(default_factory=list) # История диалога с ИИ class StateManager: @@ -779,7 +780,6 @@ class MenuBuilder: # Для главного меню — динамически меняем кнопку ИИ if menu_name == "main" and user_id: - from bot import state_manager state = state_manager.get(user_id) ai_status = "✅" if state.ai_chat_mode else "❌" @@ -1780,6 +1780,14 @@ async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE async def handle_ai_task(update: Update, text: str): """Обработка задачи для ИИ агента.""" user_id = update.effective_user.id + state = state_manager.get(user_id) + + # Добавляем сообщение пользователя в историю + state.ai_chat_history.append(f"User: {text}") + + # Ограничиваем историю последними 20 сообщениями + if len(state.ai_chat_history) > 20: + state.ai_chat_history = state.ai_chat_history[-20:] # Отправляем статус status_msg = await update.message.reply_text("⏳ 🤖 Думаю...", parse_mode="Markdown") @@ -1792,8 +1800,12 @@ async def handle_ai_task(update: Update, text: str): def on_oauth_url(url: str): pass # OAuth обрабатывается автоматически + # Формируем контекст с историей + history_context = "\n".join(state.ai_chat_history) + full_task = f"Previous conversation:\n{history_context}\n\nCurrent request: {text}" + # Выполняем задачу - result = await qwen_manager.run_task(user_id, text, on_output, on_oauth_url) + result = await qwen_manager.run_task(user_id, full_task, on_output, on_oauth_url) # Показываем результат full_output = "".join(output_buffer).strip() @@ -1801,6 +1813,10 @@ async def handle_ai_task(update: Update, text: str): if not full_output: full_output = result + # Добавляем ответ ИИ в историю + if full_output: + state.ai_chat_history.append(f"Assistant: {full_output[:500]}") # Ограничиваем длину + if len(full_output) > 4000: full_output = full_output[:4000] + "\n... (вывод обрезан)" @@ -2741,7 +2757,8 @@ async def ai_command(update: Update, context: ContextTypes.DEFAULT_TYPE): "`/ai найди баги в этом коде`\n\n" "Команды:\n" "`/ai status` — статус сессии\n" - "`/ai stop` — завершить сессию", + "`/ai stop` — завершить сессию\n" + "`/ai clear` — очистить историю диалога", parse_mode="Markdown" ) return @@ -2766,6 +2783,12 @@ async def ai_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("✅ Сессия Qwen Code завершена") return + if task == "clear": + state = state_manager.get(user_id) + state.ai_chat_history.clear() + await update.message.reply_text("✅ История диалога с ИИ очищена") + return + # Отправляем задачу в ИИ status_msg = await update.message.reply_text("⏳ 🤖 Думаю...", parse_mode="Markdown")