feat: контекст диалога с ИИ агентом
Изменения: - UserState.ai_chat_history — хранение истории диалога - handle_ai_task() передаёт историю в Qwen Code - История ограничена 20 последними сообщениями - Команда /ai clear — очистка истории - Исправлена кнопка меню (убран лишний импорт) Теперь ИИ помнит контекст диалога в рамках сессии Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
parent
77417c7db9
commit
a41556a2d6
29
bot.py
29
bot.py
|
|
@ -299,6 +299,7 @@ class UserState:
|
||||||
current_server: str = "local" # Имя текущего сервера
|
current_server: str = "local" # Имя текущего сервера
|
||||||
editing_server: Optional[str] = None # Имя сервера, который редактируем
|
editing_server: Optional[str] = None # Имя сервера, который редактируем
|
||||||
ai_chat_mode: bool = False # Режим чата с ИИ агентом
|
ai_chat_mode: bool = False # Режим чата с ИИ агентом
|
||||||
|
ai_chat_history: List[str] = field(default_factory=list) # История диалога с ИИ
|
||||||
|
|
||||||
|
|
||||||
class StateManager:
|
class StateManager:
|
||||||
|
|
@ -779,7 +780,6 @@ class MenuBuilder:
|
||||||
|
|
||||||
# Для главного меню — динамически меняем кнопку ИИ
|
# Для главного меню — динамически меняем кнопку ИИ
|
||||||
if menu_name == "main" and user_id:
|
if menu_name == "main" and user_id:
|
||||||
from bot import state_manager
|
|
||||||
state = state_manager.get(user_id)
|
state = state_manager.get(user_id)
|
||||||
ai_status = "✅" if state.ai_chat_mode else "❌"
|
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):
|
async def handle_ai_task(update: Update, text: str):
|
||||||
"""Обработка задачи для ИИ агента."""
|
"""Обработка задачи для ИИ агента."""
|
||||||
user_id = update.effective_user.id
|
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")
|
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):
|
def on_oauth_url(url: str):
|
||||||
pass # OAuth обрабатывается автоматически
|
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()
|
full_output = "".join(output_buffer).strip()
|
||||||
|
|
@ -1801,6 +1813,10 @@ async def handle_ai_task(update: Update, text: str):
|
||||||
if not full_output:
|
if not full_output:
|
||||||
full_output = result
|
full_output = result
|
||||||
|
|
||||||
|
# Добавляем ответ ИИ в историю
|
||||||
|
if full_output:
|
||||||
|
state.ai_chat_history.append(f"Assistant: {full_output[:500]}") # Ограничиваем длину
|
||||||
|
|
||||||
if len(full_output) > 4000:
|
if len(full_output) > 4000:
|
||||||
full_output = full_output[:4000] + "\n... (вывод обрезан)"
|
full_output = full_output[:4000] + "\n... (вывод обрезан)"
|
||||||
|
|
||||||
|
|
@ -2741,7 +2757,8 @@ async def ai_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
"`/ai найди баги в этом коде`\n\n"
|
"`/ai найди баги в этом коде`\n\n"
|
||||||
"Команды:\n"
|
"Команды:\n"
|
||||||
"`/ai status` — статус сессии\n"
|
"`/ai status` — статус сессии\n"
|
||||||
"`/ai stop` — завершить сессию",
|
"`/ai stop` — завершить сессию\n"
|
||||||
|
"`/ai clear` — очистить историю диалога",
|
||||||
parse_mode="Markdown"
|
parse_mode="Markdown"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
@ -2766,6 +2783,12 @@ async def ai_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
await update.message.reply_text("✅ Сессия Qwen Code завершена")
|
await update.message.reply_text("✅ Сессия Qwen Code завершена")
|
||||||
return
|
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")
|
status_msg = await update.message.reply_text("⏳ 🤖 Думаю...", parse_mode="Markdown")
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue