1378 lines
54 KiB
Python
1378 lines
54 KiB
Python
import json
|
|
import re
|
|
import threading
|
|
import time
|
|
import tkinter as tk
|
|
|
|
import customtkinter as ctk
|
|
from tkinter import filedialog, messagebox
|
|
|
|
from .base import ViewBase
|
|
from ..theme import c, mono_font, ui_font
|
|
from ..components.controls import IconButton, IconCanvas, soft_scrollbar
|
|
from ..core.mcp.manager import MCPManager
|
|
|
|
|
|
class ReasoningBlock(ctk.CTkFrame):
|
|
"""Свёрнутый блок рассуждения модели; открывается по клику."""
|
|
|
|
def __init__(self, master, text: str, expanded: bool = False):
|
|
super().__init__(master, fg_color=c("card"), corner_radius=8,
|
|
border_width=1, border_color=c("border"))
|
|
self._text = str(text or "")
|
|
self._expanded = False
|
|
self._body = None
|
|
|
|
self.head = ctk.CTkFrame(self, fg_color="transparent", height=30)
|
|
self.head.pack(fill="x")
|
|
self.head.pack_propagate(False)
|
|
|
|
self.icon = IconCanvas(self.head, "chevron_right", 13,
|
|
c("text_faint"), c("card"))
|
|
self.icon.pack(side="left", padx=(10, 6), pady=7)
|
|
self.label = ctk.CTkLabel(self.head, text="Рассуждение",
|
|
font=ui_font(11), height=16,
|
|
text_color=c("text_faint"))
|
|
self.label.pack(side="left")
|
|
self.hint = ctk.CTkLabel(self.head, text="Показать",
|
|
font=ui_font(10), height=16,
|
|
text_color=c("text_faint"))
|
|
self.hint.pack(side="right", padx=(6, 10))
|
|
|
|
for widget in (self.head, self.icon, self.label, self.hint):
|
|
widget.bind("<Button-1>", lambda _e: self.toggle())
|
|
try:
|
|
widget.configure(cursor="hand2")
|
|
except Exception:
|
|
pass
|
|
widget.bind("<Enter>", lambda _e: self._hover(True), add="+")
|
|
widget.bind("<Leave>", lambda _e: self._hover(False), add="+")
|
|
|
|
if expanded:
|
|
self.open()
|
|
else:
|
|
self.close()
|
|
|
|
def _hover(self, on: bool):
|
|
try:
|
|
self.label.configure(text_color=(c("text") if on else c("text_faint")))
|
|
self.icon.set(color=(c("text_dim") if on else c("text_faint")))
|
|
self.hint.configure(text_color=(c("text_dim") if on else c("text_faint")))
|
|
except Exception:
|
|
pass
|
|
|
|
def _build_body(self):
|
|
if self._body is not None:
|
|
return
|
|
lines = self._text.count("\n") + 1
|
|
approx = max(lines, len(self._text) // 80 + 1)
|
|
height = max(52, min(260, approx * 17 + 12))
|
|
self._body = ctk.CTkTextbox(
|
|
self, height=height, wrap="word", font=ui_font(11),
|
|
fg_color="transparent", border_width=0,
|
|
text_color=c("text_dim"),
|
|
)
|
|
self._body.insert("1.0", self._text)
|
|
try:
|
|
self._body.configure(state="disabled")
|
|
except Exception:
|
|
pass
|
|
|
|
def open(self):
|
|
if self._expanded:
|
|
return
|
|
self._expanded = True
|
|
self._build_body()
|
|
try:
|
|
self._body.pack(fill="x", padx=10, pady=(0, 8))
|
|
self.icon.set_name("chevron_down")
|
|
self.hint.configure(text="Скрыть")
|
|
except Exception:
|
|
pass
|
|
|
|
def close(self):
|
|
if not self._expanded:
|
|
self.icon.set_name("chevron_right")
|
|
self.hint.configure(text="Показать")
|
|
return
|
|
self._expanded = False
|
|
try:
|
|
if self._body is not None:
|
|
self._body.pack_forget()
|
|
self.icon.set_name("chevron_right")
|
|
self.hint.configure(text="Показать")
|
|
except Exception:
|
|
pass
|
|
|
|
def toggle(self):
|
|
if self._expanded:
|
|
self.close()
|
|
else:
|
|
self.open()
|
|
|
|
|
|
class ChatView(ViewBase):
|
|
MAX_RENDER = 150
|
|
|
|
def __init__(self, master, **kwargs):
|
|
super().__init__(master, **kwargs)
|
|
self.title_text = "Чат"
|
|
self.configure(fg_color="transparent")
|
|
self._busy = False
|
|
self._labels = [] # [(CTkLabel, is_user), ...] — для пересчёта переноса строк
|
|
self._stream_label = None
|
|
self._stream_text = ""
|
|
self._typing_label = None
|
|
self._typing_job = None
|
|
self._typing_dots = 0
|
|
self._unloading = False
|
|
self._agent_mode = False
|
|
self._empty_box = None
|
|
try:
|
|
self.mcp = MCPManager(self.app)
|
|
except Exception:
|
|
self.mcp = None
|
|
self._column_pad = 24
|
|
self._column_max = 860
|
|
self._text_max = 680
|
|
|
|
# центральная колонка чата (не даём растягиваться на весь экран)
|
|
self.column = ctk.CTkFrame(self, fg_color="transparent", corner_radius=0)
|
|
self.column.pack(fill="both", expand=True, padx=self._column_pad, pady=0)
|
|
self.bind("<Configure>", self._on_view_resize)
|
|
|
|
# --- история сообщений ---
|
|
self.messages = ctk.CTkScrollableFrame(self.column, fg_color="transparent", corner_radius=0)
|
|
self.messages.pack(fill="both", expand=True, pady=(18, 8))
|
|
# add="+" обязателен: CTkScrollableFrame сам обновляет scrollregion
|
|
# по <Configure>, нельзя перетирать его собственный обработчик.
|
|
self.messages.bind("<Configure>", self._on_resize, add="+")
|
|
soft_scrollbar(self.messages, "content")
|
|
|
|
# --- строка над вводом: действия слева, контекст справа ---
|
|
meta_row = ctk.CTkFrame(self.column, fg_color="transparent")
|
|
meta_row.pack(fill="x", padx=2, pady=(0, 6))
|
|
|
|
self._ghost(meta_row, "Экспорт", self.export_chat, width=66).pack(side="left")
|
|
self._ghost(meta_row, "Очистить", self.clear_chat, width=72).pack(side="left", padx=(4, 0))
|
|
self._ghost(meta_row, "Параметры", self.open_generation_settings,
|
|
width=88).pack(side="left", padx=(4, 0))
|
|
|
|
self.agent_switch = ctk.CTkSwitch(
|
|
meta_row, text="Файлы", width=64, switch_width=28, switch_height=14,
|
|
font=ui_font(11), text_color=c("text_dim"),
|
|
command=self._toggle_agent,
|
|
)
|
|
self.agent_switch.pack(side="left", padx=(10, 0))
|
|
|
|
self.status_label = ctk.CTkLabel(meta_row, text="", font=ui_font(11), text_color=c("text_faint"), anchor="w")
|
|
self.status_label.pack(side="left", padx=(10, 0))
|
|
|
|
self.unload_btn = self._ghost(meta_row, "Выгрузить", self.unload_model, width=88)
|
|
self.unload_btn.pack(side="right", padx=(0, 10))
|
|
self.context_label = ctk.CTkLabel(meta_row, text="Контекст —", font=mono_font(10),
|
|
text_color=c("text_faint"))
|
|
self.context_label.pack(side="right")
|
|
self.context_meter = tk.Canvas(meta_row, width=44, height=6, bg=c("content"),
|
|
highlightthickness=0, bd=0)
|
|
self.context_meter.pack(side="right", padx=(0, 8))
|
|
self._set_context_meter(0.0, "text_faint")
|
|
|
|
# --- карточка ввода ---
|
|
card = ctk.CTkFrame(self.column, fg_color=c("input"), corner_radius=12, border_width=1, border_color=c("border"))
|
|
card.pack(fill="x", pady=(0, 16))
|
|
self.input_card = card
|
|
|
|
self.input_box = ctk.CTkTextbox(
|
|
card,
|
|
height=50,
|
|
corner_radius=8,
|
|
border_width=0,
|
|
fg_color="transparent",
|
|
text_color=c("text"),
|
|
font=ui_font(14),
|
|
wrap="word",
|
|
)
|
|
self.input_box.pack(fill="x", padx=8, pady=(6, 0))
|
|
self.input_box.bind("<Return>", self._on_enter)
|
|
self.input_box.bind("<KeyRelease>", self._update_placeholder)
|
|
try:
|
|
inner = self.input_box._textbox
|
|
inner.configure(insertbackground=c("text"), insertwidth=2, insertofftime=0)
|
|
inner.bind("<FocusIn>", lambda _e: card.configure(border_color=c("accent")))
|
|
inner.bind("<FocusOut>", lambda _e: card.configure(border_color=c("border")))
|
|
except Exception:
|
|
pass
|
|
|
|
self.placeholder = ctk.CTkLabel(
|
|
card,
|
|
text="Сообщение",
|
|
font=ui_font(14),
|
|
text_color=c("text_faint"),
|
|
)
|
|
self.placeholder.place(x=18, y=12)
|
|
self.placeholder.bind("<Button-1>", self._focus_input)
|
|
try:
|
|
inner = getattr(self.placeholder, "_label", None)
|
|
if inner is not None:
|
|
inner.bind("<Button-1>", self._focus_input)
|
|
inner.configure(cursor="xterm", takefocus=0)
|
|
except Exception:
|
|
pass
|
|
card.bind("<Button-1>", self._focus_input)
|
|
|
|
actions = ctk.CTkFrame(card, fg_color="transparent")
|
|
actions.pack(fill="x", padx=10, pady=(2, 6))
|
|
|
|
ctk.CTkLabel(
|
|
actions,
|
|
text="Enter — отправить · Shift+Enter — перенос",
|
|
font=ui_font(10),
|
|
text_color=c("text_faint"),
|
|
).pack(side="left")
|
|
|
|
self.send_btn = IconButton(
|
|
actions,
|
|
"arrow_up",
|
|
self.send_message,
|
|
size=34,
|
|
icon_size=17,
|
|
radius=8,
|
|
bg=c("action_bg"),
|
|
hover=c("action_hover"),
|
|
icon_color=c("action_fg"),
|
|
hover_icon_color=c("action_fg"),
|
|
)
|
|
self.send_btn.pack(side="right")
|
|
|
|
self.render_history()
|
|
self.update_context_indicator()
|
|
self._update_unload_btn()
|
|
self.after(1500, self._tick_context)
|
|
|
|
# ---------- helpers ----------
|
|
def _ghost(self, parent, text, command, width=72):
|
|
return ctk.CTkButton(
|
|
parent,
|
|
text=text,
|
|
command=command,
|
|
width=width,
|
|
height=26,
|
|
corner_radius=6,
|
|
fg_color="transparent",
|
|
hover_color=c("card_hover"),
|
|
font=ui_font(11),
|
|
text_color=c("text_dim"),
|
|
)
|
|
|
|
def _max_text_width(self):
|
|
try:
|
|
w = self.column.winfo_width()
|
|
except Exception:
|
|
w = 0
|
|
if w <= 10:
|
|
w = 680
|
|
return max(280, min(self._text_max, int(w * 0.92)))
|
|
|
|
def _on_view_resize(self, event=None):
|
|
# Держим колонку чата по центру и не даём ей растягиваться на весь экран.
|
|
try:
|
|
width = self.winfo_width()
|
|
except Exception:
|
|
return
|
|
pad = max(24, int((width - self._column_max) / 2))
|
|
if pad != self._column_pad:
|
|
self._column_pad = pad
|
|
try:
|
|
self.column.pack_configure(padx=(pad, pad))
|
|
except Exception:
|
|
pass
|
|
self._fit_empty()
|
|
self._on_resize()
|
|
|
|
def _on_resize(self, event=None):
|
|
wrap = self._max_text_width()
|
|
for label, is_user in self._labels:
|
|
try:
|
|
label.configure(wraplength=min(wrap, int(self._max_text_width() * 0.78)) if is_user else wrap)
|
|
except Exception:
|
|
pass
|
|
|
|
def _tick_context(self):
|
|
if not getattr(self, "_alive", True):
|
|
return
|
|
try:
|
|
if self.winfo_ismapped():
|
|
self.update_context_indicator()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.after(1500, self._tick_context)
|
|
except Exception:
|
|
pass
|
|
|
|
def _focus_input(self, event=None):
|
|
if self._busy:
|
|
return "break"
|
|
target = getattr(self.input_box, "_textbox", None) or self.input_box
|
|
try:
|
|
target.focus_force()
|
|
if hasattr(target, "mark_set"):
|
|
target.mark_set("insert", "end")
|
|
target.see("end")
|
|
except Exception:
|
|
pass
|
|
|
|
# Tk может вернуть фокус внутреннему Label после обработчика клика.
|
|
# Возвращаем его в поле ввода уже после завершения события.
|
|
def _again():
|
|
if self._busy:
|
|
return
|
|
try:
|
|
target.focus_force()
|
|
if hasattr(target, "mark_set"):
|
|
target.mark_set("insert", "end")
|
|
if hasattr(target, "configure"):
|
|
target.configure(insertbackground=c("text"), insertwidth=2,
|
|
insertofftime=0)
|
|
self.input_card.configure(border_color=c("accent"))
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.after(1, _again)
|
|
except Exception:
|
|
pass
|
|
return "break"
|
|
|
|
def _update_placeholder(self, event=None):
|
|
try:
|
|
empty = not self.input_box.get("1.0", "end").strip()
|
|
except Exception:
|
|
empty = True
|
|
try:
|
|
if empty:
|
|
self.placeholder.place(x=18, y=14)
|
|
self.placeholder.lift()
|
|
else:
|
|
self.placeholder.place_forget()
|
|
except Exception:
|
|
pass
|
|
|
|
def _update_unload_btn(self):
|
|
loaded = bool(self.app_state and self.app_state.model_loaded)
|
|
enabled = loaded and not self._busy and not self._unloading
|
|
try:
|
|
self.unload_btn.configure(
|
|
state=("normal" if enabled else "disabled"),
|
|
text_color=(c("text_dim") if enabled else c("text_faint")),
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
def _start_typing(self):
|
|
self._stop_typing()
|
|
self._typing_dots = 0
|
|
try:
|
|
self._typing_label = ctk.CTkLabel(
|
|
self._stream_parent, text="Печатает", font=ui_font(10),
|
|
text_color=c("text_faint"), anchor="w",
|
|
)
|
|
self._typing_label.pack(anchor="w", padx=2, pady=(0, 4))
|
|
self._typing_label.lift()
|
|
except Exception:
|
|
self._typing_label = None
|
|
return
|
|
self._animate_typing()
|
|
|
|
def _animate_typing(self):
|
|
if not getattr(self, "_alive", True) or self._typing_label is None:
|
|
return
|
|
try:
|
|
dots = "." * ((self._typing_dots % 3) + 1)
|
|
self._typing_label.configure(text="Печатает" + dots)
|
|
self._typing_dots += 1
|
|
self._typing_job = self.after(420, self._animate_typing)
|
|
except Exception:
|
|
pass
|
|
|
|
def _stop_typing(self):
|
|
job = self._typing_job
|
|
self._typing_job = None
|
|
if job is not None:
|
|
try:
|
|
self.after_cancel(job)
|
|
except Exception:
|
|
pass
|
|
label = self._typing_label
|
|
self._typing_label = None
|
|
if label is not None:
|
|
try:
|
|
label.destroy()
|
|
except Exception:
|
|
pass
|
|
|
|
def set_busy(self, busy: bool):
|
|
self._busy = busy
|
|
state = "disabled" if busy else "normal"
|
|
try:
|
|
self.input_box.configure(state=state)
|
|
self.send_btn.set_enabled(not busy)
|
|
except Exception:
|
|
pass
|
|
self.status_label.configure(text="Генерация…" if busy else "")
|
|
self._update_unload_btn()
|
|
|
|
def on_show(self):
|
|
self._update_unload_btn()
|
|
self._update_placeholder()
|
|
try:
|
|
if self.app_state is not None and not self.app_state.chat_history:
|
|
self.render_history()
|
|
elif getattr(self, "_empty_box", None) is not None:
|
|
self._remove_empty_state()
|
|
except Exception:
|
|
pass
|
|
|
|
def unload_model(self):
|
|
if self._busy:
|
|
self.status_label.configure(text="Сначала дождитесь завершения генерации")
|
|
return
|
|
if self._unloading or not (self.app_state and self.app_state.model_loaded):
|
|
return
|
|
self._unloading = True
|
|
self._update_unload_btn()
|
|
self.status_label.configure(text="Выгрузка модели…")
|
|
|
|
def task():
|
|
try:
|
|
ok = self.engine.unload_model() if self.engine else False
|
|
error = ""
|
|
except Exception as e:
|
|
ok, error = False, str(e)
|
|
self.ui(lambda: self._after_unload(ok, error))
|
|
|
|
threading.Thread(target=task, daemon=True).start()
|
|
|
|
def _after_unload(self, ok, error=""):
|
|
if not getattr(self, "_alive", True):
|
|
return
|
|
self._unloading = False
|
|
self._stop_typing()
|
|
if ok:
|
|
self.status_label.configure(text="Модель выгружена")
|
|
self.context_label.configure(text="Контекст —", text_color=c("text_faint"))
|
|
else:
|
|
self.status_label.configure(text=f"Не удалось выгрузить модель: {error}")
|
|
self._update_unload_btn()
|
|
try:
|
|
if not (self.app_state and self.app_state.chat_history):
|
|
self.render_history()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.app._update_status_bar()
|
|
self.app.sidebar.update_status(self.app_state, True)
|
|
except Exception:
|
|
pass
|
|
|
|
# ---------- оценка контекста ----------
|
|
def _estimate_text_tokens(self, text: str) -> int:
|
|
if not text:
|
|
return 0
|
|
return max(1, len(str(text)) // 4)
|
|
|
|
def _estimate_context_used(self):
|
|
if not self.app_state or not self.app_state.chat_history:
|
|
return 0
|
|
chars = 0
|
|
for msg in self.app_state.chat_history:
|
|
chars += len(str(msg.get("content", "")))
|
|
return max(0, chars // 4)
|
|
|
|
def _get_context_info(self):
|
|
"""Возвращает (used, limit, estimated). used/limit могут быть None."""
|
|
if not self.engine or not (self.app_state and self.app_state.model_loaded):
|
|
return None, None, False
|
|
used = limit = None
|
|
estimated = True
|
|
try:
|
|
used, limit, estimated = self.engine.context_info()
|
|
except Exception:
|
|
pass
|
|
if used is None:
|
|
used = self._estimate_context_used()
|
|
estimated = True
|
|
return used, limit, estimated
|
|
|
|
@staticmethod
|
|
def _fmt_tokens(value) -> str:
|
|
try:
|
|
value = int(value)
|
|
except Exception:
|
|
return "—"
|
|
if value >= 10000:
|
|
return f"{value / 1000:.0f}K"
|
|
if value >= 1000:
|
|
return f"{value / 1000:.1f}K"
|
|
return str(value)
|
|
|
|
def _set_context_meter(self, fraction: float, color_role: str = "accent"):
|
|
meter = getattr(self, "context_meter", None)
|
|
if meter is None:
|
|
return
|
|
try:
|
|
meter.delete("all")
|
|
width, height = 44, 6
|
|
meter.create_line(1, height / 2, width - 1, height / 2,
|
|
fill=c("border_strong"), width=2, capstyle="round")
|
|
frac = max(0.0, min(1.0, float(fraction or 0.0)))
|
|
if frac > 0.0:
|
|
meter.create_line(1, height / 2, 1 + (width - 2) * frac, height / 2,
|
|
fill=c(color_role), width=3, capstyle="round")
|
|
except Exception:
|
|
pass
|
|
|
|
def update_context_indicator(self, extra_text: str = ""):
|
|
if not hasattr(self, "context_label"):
|
|
return
|
|
|
|
if not self.engine or not (self.app_state and self.app_state.model_loaded):
|
|
self.context_label.configure(text="Контекст —", text_color=c("text_faint"))
|
|
try:
|
|
self.context_meter.pack_forget()
|
|
except Exception:
|
|
pass
|
|
return
|
|
|
|
try:
|
|
if not self.context_meter.winfo_ismapped():
|
|
self.context_meter.pack(side="right", padx=(0, 8))
|
|
except Exception:
|
|
pass
|
|
|
|
used, limit, estimated = self._get_context_info()
|
|
if used is None:
|
|
used = 0
|
|
|
|
extra = self._estimate_text_tokens(extra_text) if extra_text else 0
|
|
projected = used + extra
|
|
approx = "~" if (estimated or extra_text) else ""
|
|
|
|
if limit and limit > 0:
|
|
fraction = min(1.0, projected / float(limit))
|
|
warn = ""
|
|
if extra_text and extra > limit:
|
|
warn = " · больше контекста"
|
|
elif projected > limit:
|
|
warn = " · лимит"
|
|
role = ("danger" if projected >= limit
|
|
else ("warn" if projected >= limit * 0.9 else "text_dim"))
|
|
self.context_label.configure(
|
|
text=f"Контекст {approx}{self._fmt_tokens(projected)} / "
|
|
f"{self._fmt_tokens(limit)}{warn}",
|
|
text_color=c(role),
|
|
)
|
|
self._set_context_meter(fraction, role if role != "text_dim" else "accent")
|
|
else:
|
|
self.context_label.configure(
|
|
text=f"Контекст {approx}{self._fmt_tokens(projected)}",
|
|
text_color=c("text_faint"),
|
|
)
|
|
self._set_context_meter(0.0, "text_faint")
|
|
|
|
# ---------- рендер сообщений ----------
|
|
def _clear_messages(self):
|
|
for w in self.messages.winfo_children():
|
|
w.destroy()
|
|
self._labels = []
|
|
self._stream_label = None
|
|
self._stream_text = ""
|
|
self._typing_label = None
|
|
self._typing_job = None
|
|
self._typing_dots = 0
|
|
self._unloading = False
|
|
self._empty_box = None
|
|
try:
|
|
if getattr(self, "mcp", None) is not None:
|
|
self.mcp.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.mcp = MCPManager(self.app)
|
|
except Exception:
|
|
self.mcp = None
|
|
|
|
def _add_empty_state(self):
|
|
loaded = bool(self.app_state and self.app_state.model_loaded)
|
|
box = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
box.pack(fill="both", expand=True)
|
|
self._empty_box = box
|
|
content = ctk.CTkFrame(box, fg_color="transparent")
|
|
content.place(relx=0.5, rely=0.44, anchor="center")
|
|
ctk.CTkLabel(
|
|
content,
|
|
text="Локальная модель загружена" if loaded else "Модель не загружена",
|
|
font=ui_font(16), height=24,
|
|
text_color=c("text"),
|
|
).pack(anchor="center")
|
|
ctk.CTkLabel(
|
|
content,
|
|
text=("Задайте вопрос или попросите код" if loaded
|
|
else "Выберите GGUF в библиотеке моделей"),
|
|
font=ui_font(13), height=18,
|
|
text_color=c("text_dim"),
|
|
).pack(anchor="center", pady=(6, 0))
|
|
if not loaded:
|
|
actions = ctk.CTkFrame(content, fg_color="transparent")
|
|
actions.pack(anchor="center", pady=(16, 0))
|
|
ctk.CTkButton(
|
|
actions, text="Открыть библиотеку", width=156, height=34,
|
|
corner_radius=8, fg_color=c("action_bg"), hover_color=c("action_hover"),
|
|
font=ui_font(12), text_color=c("action_fg"),
|
|
command=lambda: self.app.switch_view("models") if self.app else None,
|
|
).pack(side="left")
|
|
ctk.CTkButton(
|
|
actions, text="Найти модель", width=124, height=34,
|
|
corner_radius=8, fg_color="transparent", hover_color=c("card_hover"),
|
|
font=ui_font(12), text_color=c("text_dim"),
|
|
command=lambda: self.app.switch_view("discover") if self.app else None,
|
|
).pack(side="left", padx=(8, 0))
|
|
self._fit_empty()
|
|
self.after(60, self._fit_empty)
|
|
|
|
def _fit_empty(self):
|
|
box = getattr(self, "_empty_box", None)
|
|
if box is None:
|
|
return
|
|
try:
|
|
height = int(self.messages._parent_canvas.winfo_height())
|
|
if height > 120:
|
|
box.configure(height=height)
|
|
except Exception:
|
|
pass
|
|
|
|
def _remove_empty_state(self):
|
|
box = getattr(self, "_empty_box", None)
|
|
self._empty_box = None
|
|
if box is not None:
|
|
try:
|
|
box.destroy()
|
|
except Exception:
|
|
pass
|
|
|
|
def _append_message(self, role: str, content: str, reasoning: str = ""):
|
|
is_user = role == "user"
|
|
wrap = self._max_text_width()
|
|
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 18))
|
|
|
|
if is_user:
|
|
bubble = ctk.CTkFrame(row, fg_color=c("user_bubble"), corner_radius=12, border_width=0)
|
|
bubble.pack(side="right", anchor="e")
|
|
label = ctk.CTkLabel(
|
|
bubble,
|
|
text=content,
|
|
justify="left",
|
|
anchor="w",
|
|
font=ui_font(14),
|
|
height=20,
|
|
text_color=c("user_text"),
|
|
wraplength=int(wrap * 0.72),
|
|
)
|
|
label.pack(padx=14, pady=10)
|
|
self._labels.append((label, True))
|
|
else:
|
|
bubble = ctk.CTkFrame(row, fg_color="transparent")
|
|
bubble.pack(side="left", fill="x", expand=True, anchor="w")
|
|
ctk.CTkLabel(bubble, text="Xenith", font=ui_font(11), height=16,
|
|
text_color=c("text_dim")).pack(
|
|
anchor="w", padx=2, pady=(0, 5)
|
|
)
|
|
if str(reasoning or "").strip():
|
|
ReasoningBlock(bubble, reasoning).pack(
|
|
anchor="w", fill="x", padx=2, pady=(0, 8))
|
|
self._render_assistant_body(bubble, content, wrap)
|
|
|
|
def _text_label(self, parent, text: str, wrap: int):
|
|
label = ctk.CTkLabel(
|
|
parent,
|
|
text=text,
|
|
justify="left",
|
|
anchor="w",
|
|
font=ui_font(14),
|
|
height=20,
|
|
text_color=c("text"),
|
|
wraplength=wrap,
|
|
)
|
|
label.pack(anchor="w", padx=2, pady=(0, 2))
|
|
self._labels.append((label, False))
|
|
return label
|
|
|
|
def _code_block(self, parent, code: str, language: str):
|
|
box = ctk.CTkFrame(parent, fg_color=c("code_bg"), corner_radius=10, border_width=1, border_color=c("border"))
|
|
box.pack(fill="x", anchor="w", padx=2, pady=(6, 8))
|
|
if language:
|
|
ctk.CTkLabel(box, text=language.lower(), font=mono_font(10), text_color=c("text_faint")).pack(
|
|
anchor="w", padx=12, pady=(8, 0)
|
|
)
|
|
label = ctk.CTkLabel(
|
|
box,
|
|
text=code,
|
|
justify="left",
|
|
anchor="w",
|
|
font=mono_font(11),
|
|
text_color=c("code_text"),
|
|
wraplength=max(240, self._max_text_width() - 40),
|
|
)
|
|
label.pack(anchor="w", padx=12, pady=(4 if language else 10, 10))
|
|
self._labels.append((label, False))
|
|
|
|
def _render_assistant_body(self, parent, content: str, wrap: int):
|
|
pattern = re.compile(r"```[ \t]*([A-Za-z0-9_+\-]*)\n(.*?)```", re.S)
|
|
pos = 0
|
|
found = False
|
|
for m in pattern.finditer(content):
|
|
before = content[pos:m.start()].strip("\n")
|
|
if before.strip():
|
|
self._text_label(parent, before, wrap)
|
|
self._code_block(parent, m.group(2).rstrip("\n"), m.group(1))
|
|
pos = m.end()
|
|
found = True
|
|
tail = content[pos:].strip("\n")
|
|
if tail.strip() or not found:
|
|
self._text_label(parent, tail if found else content, wrap)
|
|
self._scroll_bottom()
|
|
|
|
def _refresh_scrollregion(self):
|
|
try:
|
|
canvas = self.messages._parent_canvas
|
|
canvas.configure(scrollregion=canvas.bbox("all"))
|
|
except Exception:
|
|
pass
|
|
|
|
def _scroll_bottom(self, force=False):
|
|
def _do():
|
|
if not getattr(self, "_alive", True):
|
|
return
|
|
try:
|
|
canvas = self.messages._parent_canvas
|
|
canvas.configure(scrollregion=canvas.bbox("all"))
|
|
_first, last = canvas.yview()
|
|
# Не выдёргиваем пользователя наверх/вниз, если он сам
|
|
# прокрутил историю. Принудительно — только после отправки.
|
|
if force or last >= 0.985:
|
|
canvas.yview_moveto(1.0)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.after(10, _do)
|
|
except Exception:
|
|
pass
|
|
|
|
def append_to_box(self, text: str):
|
|
"""Совместимость со старым кодом."""
|
|
self._append_message("assistant", text)
|
|
|
|
def render_history(self):
|
|
self._clear_messages()
|
|
history = list(self.app_state.chat_history) if self.app_state else []
|
|
if not history:
|
|
self._add_empty_state()
|
|
else:
|
|
hidden = max(0, len(history) - self.MAX_RENDER)
|
|
if hidden:
|
|
history = history[-self.MAX_RENDER:]
|
|
ctk.CTkLabel(
|
|
self.messages,
|
|
text=f"Показаны последние {len(history)} сообщений из {len(history) + hidden}",
|
|
font=ui_font(11), text_color=c("text_faint"), anchor="w",
|
|
height=16,
|
|
).pack(anchor="w", padx=2, pady=(0, 12))
|
|
for msg in history:
|
|
role = msg.get("role", "assistant")
|
|
content = msg.get("content", "")
|
|
if role not in ("user", "assistant"):
|
|
content = f"{role}: {content}"
|
|
role = "assistant"
|
|
self._append_message(role, content, msg.get("reasoning") or "")
|
|
self.update_context_indicator()
|
|
self._update_unload_btn()
|
|
self._refresh_scrollregion()
|
|
self._scroll_bottom(force=True)
|
|
|
|
# ---------- действия ----------
|
|
def _on_enter(self, event=None):
|
|
# Shift+Enter — перенос строки (стандартное поведение Text), Enter — отправка.
|
|
if event is not None and (event.state & 0x0001):
|
|
return None
|
|
self.send_message()
|
|
return "break"
|
|
|
|
def export_chat(self):
|
|
if not self.app_state or not self.app_state.chat_history:
|
|
self.status_label.configure(text="Нет сообщений для экспорта")
|
|
return
|
|
path = filedialog.asksaveasfilename(
|
|
title="Экспорт чата",
|
|
defaultextension=".md",
|
|
filetypes=[("Markdown", "*.md"), ("Text", "*.txt"), ("JSON", "*.json"), ("All files", "*.*")],
|
|
initialfile=f"chat_{time.strftime('%Y%m%d_%H%M%S')}.md",
|
|
)
|
|
if not path:
|
|
return
|
|
try:
|
|
ext = path.lower().rsplit(".", 1)[-1] if "." in path else "md"
|
|
if ext == "json":
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
json.dump(self.app_state.chat_history, f, ensure_ascii=False, indent=2)
|
|
else:
|
|
lines = []
|
|
for msg in self.app_state.chat_history:
|
|
role = msg.get("role", "?")
|
|
content = msg.get("content", "")
|
|
if ext == "md":
|
|
title = "Вы" if role == "user" else ("Xenith" if role == "assistant" else role)
|
|
lines.append(f"## {title}\n\n{content}\n")
|
|
else:
|
|
prefix = "Вы" if role == "user" else ("Xenith" if role == "assistant" else role)
|
|
lines.append(f"{prefix}: {content}\n")
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
f.write("\n".join(lines).strip() + "\n")
|
|
self.app_state.log(f"Чат экспортирован: {path}")
|
|
self.status_label.configure(text=f"Экспортировано: {path}")
|
|
except Exception as e:
|
|
self.status_label.configure(text=f"Ошибка экспорта: {e}")
|
|
|
|
def clear_chat(self):
|
|
if self.app_state:
|
|
self.app_state.chat_history.clear()
|
|
self.app_state.log("Чат очищен")
|
|
if self.engine and hasattr(self.engine, "reset_chat"):
|
|
try:
|
|
self.engine.reset_chat()
|
|
except Exception:
|
|
pass
|
|
self.render_history()
|
|
self.set_busy(False)
|
|
self.update_context_indicator()
|
|
self._update_placeholder()
|
|
try:
|
|
self.input_box.focus_set()
|
|
except Exception:
|
|
pass
|
|
|
|
def send_message(self):
|
|
if self._busy:
|
|
return
|
|
|
|
text = self.input_box.get("1.0", "end").strip()
|
|
if not text:
|
|
return
|
|
if self.app_state is None:
|
|
return
|
|
if not self.app_state.model_loaded:
|
|
self.status_label.configure(text="Сначала загрузите модель")
|
|
return
|
|
|
|
# Не запускаем генерацию, пока идёт обучение/загрузка другой модели.
|
|
try:
|
|
if self.app is not None and self.app.any_busy(exclude=self):
|
|
self.status_label.configure(text="Дождитесь завершения обучения/загрузки модели")
|
|
return
|
|
except Exception:
|
|
pass
|
|
|
|
# Контроль контекста: не даём истории выйти за пределы лимита модели.
|
|
used, limit, _ = self._get_context_info()
|
|
if used is None:
|
|
used = self._estimate_context_used()
|
|
msg_tokens = self._estimate_text_tokens(text)
|
|
if limit and limit > 0:
|
|
if msg_tokens <= limit and (used + msg_tokens) > limit:
|
|
self.app_state.chat_history.clear()
|
|
if self.engine and hasattr(self.engine, "reset_chat"):
|
|
try:
|
|
self.engine.reset_chat()
|
|
except Exception:
|
|
pass
|
|
self.render_history()
|
|
self.status_label.configure(text="Контекст переполнен — история сброшена")
|
|
self.app_state.log("Контекст переполнен: история чата сброшена перед отправкой")
|
|
used = 0
|
|
elif msg_tokens > limit:
|
|
self.status_label.configure(text="Внимание: сообщение больше контекста модели")
|
|
|
|
self._remove_empty_state()
|
|
self.app_state.chat_history.append({"role": "user", "content": text})
|
|
self._append_message("user", text)
|
|
self._scroll_bottom(force=True)
|
|
self.input_box.delete("1.0", "end")
|
|
self._update_placeholder()
|
|
self.set_busy(True)
|
|
self.update_context_indicator()
|
|
self._append_assistant_shell()
|
|
|
|
params = dict(self.app_state.gen_params) if self.app_state.gen_params else {}
|
|
messages = list(self.app_state.chat_history)
|
|
|
|
# Переключатель «Файлы» — источник истины. После перерисовки истории
|
|
# флаг мог разойтись с положением свитча; синхронизируем перед отправкой.
|
|
try:
|
|
files_on = bool(self.agent_switch.get())
|
|
except Exception:
|
|
files_on = bool(getattr(self, "_agent_mode", False))
|
|
if files_on and (self.mcp is None or not self.mcp.enabled()):
|
|
files_on = False
|
|
try:
|
|
self.agent_switch.deselect()
|
|
self.status_label.configure(text="Файлы: укажите папки в настройках MCP")
|
|
except Exception:
|
|
pass
|
|
self._agent_mode = files_on
|
|
|
|
if self._agent_mode:
|
|
self._start_agent(messages, params)
|
|
return
|
|
|
|
def on_result(result_text: str):
|
|
reasoning = ""
|
|
try:
|
|
if self.engine is not None:
|
|
reasoning = self.engine.reasoning_text()
|
|
except Exception:
|
|
reasoning = ""
|
|
self.ui(lambda t=result_text, r=reasoning: self._on_result(t, r))
|
|
|
|
def on_token(piece: str):
|
|
self.ui(lambda p=piece: self._on_token(p))
|
|
|
|
if self.engine is None:
|
|
self._on_result("[ОШИБКА] Движок недоступен.")
|
|
return
|
|
|
|
try:
|
|
self.engine.chat(messages, params=params, on_result=on_result, on_token=on_token)
|
|
except Exception as e:
|
|
self.set_busy(False)
|
|
self.status_label.configure(text=f"[ОШИБКА] {e}")
|
|
|
|
def _append_assistant_shell(self):
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 18))
|
|
bubble = ctk.CTkFrame(row, fg_color="transparent")
|
|
bubble.pack(side="left", fill="x", expand=True, anchor="w")
|
|
ctk.CTkLabel(bubble, text="Xenith", font=ui_font(11),
|
|
text_color=c("text_dim")).pack(anchor="w", padx=2, pady=(0, 4))
|
|
self._stream_parent = bubble
|
|
label = ctk.CTkLabel(
|
|
bubble, text="", justify="left", anchor="w", font=ui_font(13),
|
|
text_color=c("text"), wraplength=self._max_text_width(),
|
|
)
|
|
label.pack(anchor="w", padx=2)
|
|
self._labels.append((label, False))
|
|
self._stream_label = label
|
|
self._stream_text = ""
|
|
self._start_typing()
|
|
self._scroll_bottom(force=True)
|
|
|
|
def _on_token(self, piece: str):
|
|
if not piece or self._stream_label is None:
|
|
return
|
|
if self._typing_label is not None:
|
|
self._stop_typing()
|
|
self._stream_text += str(piece)
|
|
try:
|
|
if self._stream_label.winfo_exists():
|
|
self._stream_label.configure(text=self._stream_text)
|
|
except Exception:
|
|
pass
|
|
self._scroll_bottom()
|
|
|
|
def open_generation_settings(self):
|
|
try:
|
|
self.app.open_generation_settings()
|
|
except Exception as e:
|
|
try:
|
|
self.status_label.configure(text=f"Не удалось открыть параметры: {e}")
|
|
except Exception:
|
|
pass
|
|
|
|
# ---------- агентный режим / MCP ----------
|
|
def _toggle_agent(self):
|
|
try:
|
|
on = bool(self.agent_switch.get())
|
|
except Exception:
|
|
on = False
|
|
if on and (self.mcp is None or not self.mcp.enabled()):
|
|
try:
|
|
self.agent_switch.deselect()
|
|
except Exception:
|
|
pass
|
|
self._agent_mode = False
|
|
self.status_label.configure(text="Укажите папки в настройках MCP")
|
|
try:
|
|
if self.app:
|
|
self.app.open_settings("mcp")
|
|
except Exception:
|
|
pass
|
|
return
|
|
self._agent_mode = on
|
|
self.status_label.configure(text="Файлы включены" if on else "")
|
|
|
|
def _parse_tool_call(self, text: str):
|
|
"""Достаёт объект вызова инструмента даже из вложенного JSON."""
|
|
raw = str(text or "")
|
|
if not raw:
|
|
return None
|
|
candidates = []
|
|
i = 0
|
|
length = min(len(raw), 200000)
|
|
while i < length:
|
|
if raw[i] != "{":
|
|
i += 1
|
|
continue
|
|
depth = 0
|
|
in_string = False
|
|
escaped = False
|
|
j = i
|
|
while j < length:
|
|
ch = raw[j]
|
|
if in_string:
|
|
if escaped:
|
|
escaped = False
|
|
elif ch == "\\":
|
|
escaped = True
|
|
elif ch == '"':
|
|
in_string = False
|
|
else:
|
|
if ch == '"':
|
|
in_string = True
|
|
elif ch == "{":
|
|
depth += 1
|
|
elif ch == "}":
|
|
depth -= 1
|
|
if depth == 0:
|
|
candidates.append(raw[i:j + 1])
|
|
i = j
|
|
break
|
|
j += 1
|
|
i += 1
|
|
|
|
for candidate in candidates:
|
|
try:
|
|
data = json.loads(candidate)
|
|
except Exception:
|
|
continue
|
|
if not isinstance(data, dict):
|
|
continue
|
|
name = data.get("tool") or data.get("name")
|
|
if not name:
|
|
continue
|
|
args = data.get("arguments")
|
|
if args is None:
|
|
args = data.get("args")
|
|
if isinstance(args, str):
|
|
try:
|
|
args = json.loads(args)
|
|
except Exception:
|
|
args = {}
|
|
if not isinstance(args, dict):
|
|
args = {}
|
|
return str(name), args
|
|
return None
|
|
|
|
def _append_tool_note(self, title: str, body: str = "", ok: bool = True):
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 8))
|
|
box = ctk.CTkFrame(row, fg_color=c("code_bg"), corner_radius=8,
|
|
border_width=1, border_color=c("border"))
|
|
box.pack(anchor="w", fill="x", padx=2)
|
|
ctk.CTkLabel(box, text=title, font=mono_font(10),
|
|
text_color=(c("text_dim") if ok else c("danger"))).pack(
|
|
anchor="w", padx=10, pady=(8, 2))
|
|
if body:
|
|
label = ctk.CTkLabel(
|
|
box, text=body, font=mono_font(10), justify="left", anchor="w",
|
|
text_color=(c("text_faint") if ok else c("danger")),
|
|
wraplength=max(240, self._max_text_width() - 36),
|
|
)
|
|
label.pack(anchor="w", padx=10, pady=(0, 8))
|
|
self._labels.append((label, False))
|
|
self._scroll_bottom()
|
|
|
|
def _ask_tool(self, name: str, args: dict) -> bool:
|
|
event = threading.Event()
|
|
box = {"ok": False}
|
|
|
|
def ask_ui():
|
|
try:
|
|
preview = json.dumps(args, ensure_ascii=False, indent=2)[:900]
|
|
box["ok"] = messagebox.askyesno(
|
|
"MCP: подтверждение",
|
|
f"Разрешить инструмент «{name}»?\n\n{preview}",
|
|
parent=self,
|
|
)
|
|
finally:
|
|
event.set()
|
|
|
|
try:
|
|
self.ui(ask_ui)
|
|
except Exception:
|
|
return False
|
|
event.wait(timeout=180)
|
|
return bool(box.get("ok"))
|
|
|
|
def _flatten_history(self, messages, limit=10):
|
|
lines = []
|
|
for m in messages[-limit:]:
|
|
role = m.get("role", "user")
|
|
content = str(m.get("content", ""))
|
|
who = "Пользователь" if role == "user" else ("Ассистент" if role == "assistant" else role)
|
|
lines.append(f"{who}: {content}")
|
|
return "\n".join(lines)
|
|
|
|
def _mcp_tool_schemas(self):
|
|
tools = []
|
|
for item in (self.mcp.list_tools() if self.mcp else []):
|
|
name = str(item.get("name") or "")
|
|
if not name:
|
|
continue
|
|
schema = item.get("inputSchema")
|
|
if not isinstance(schema, dict):
|
|
schema = {"type": "object", "properties": {}}
|
|
tools.append({
|
|
"type": "function",
|
|
"function": {
|
|
"name": name,
|
|
"description": str(item.get("description") or ""),
|
|
"parameters": schema,
|
|
},
|
|
})
|
|
return tools
|
|
|
|
def _agent_system_prompt(self, native: bool) -> str:
|
|
base = (getattr(self.app_state, "system_prompt", "") or "").strip()
|
|
roots = "\n".join(f"- {r}" for r in (self.mcp.roots() if self.mcp else []))
|
|
prefix = (base + "\n\n") if base else ""
|
|
if native:
|
|
body = (
|
|
"Ты — Xenith, локальный ассистент с доступом к файловым инструментам.\n"
|
|
"Когда пользователь просит создать, изменить, прочитать или найти файл, "
|
|
"вызывай подходящий инструмент через function call. Не выводи вызов инструмента текстом.\n"
|
|
f"Разрешённые папки:\n{roots}\n"
|
|
"Пути указывай абсолютными и внутри этих папок. Если файл уже существует и его нужно заменить, "
|
|
"передай overwrite: true. После выполнения инструмента коротко ответь пользователю. "
|
|
"Отвечай на языке последнего сообщения пользователя."
|
|
)
|
|
else:
|
|
body = (
|
|
"Ты — Xenith, локальный ассистент с доступом к файловым инструментам.\n"
|
|
+ self.mcp.tool_prompt() +
|
|
"\nНе описывай рассуждения. Если нужен инструмент — ответь ровно одним блоком tool "
|
|
"и дождись результата. Отвечай на языке последнего сообщения пользователя."
|
|
)
|
|
return prefix + body
|
|
|
|
def _agent_conversation(self, messages):
|
|
convo = [{"role": "system", "content": self._agent_system_prompt(True)}]
|
|
for msg in list(messages or [])[-14:]:
|
|
if not isinstance(msg, dict):
|
|
continue
|
|
role = str(msg.get("role") or "")
|
|
if role not in ("user", "assistant"):
|
|
continue
|
|
content = str(msg.get("content") or "").strip()
|
|
if content:
|
|
convo.append({"role": role, "content": content})
|
|
return convo
|
|
|
|
def _agent_gen_params(self, params):
|
|
out = dict(params or {})
|
|
try:
|
|
n = int(out.get("n") or 0)
|
|
except Exception:
|
|
n = 0
|
|
out["n"] = max(n, 1536)
|
|
return out
|
|
|
|
def _run_native_agent(self, messages, params, reasoning_out=None):
|
|
schemas = self._mcp_tool_schemas()
|
|
if not schemas:
|
|
raise RuntimeError("MCP не вернул инструменты")
|
|
convo = self._agent_conversation(messages)
|
|
last = ""
|
|
for step in range(4):
|
|
result = self.engine.chat_tools_sync(convo, schemas, params)
|
|
if not isinstance(result, dict):
|
|
raise RuntimeError("Движок вернул неверный ответ tools")
|
|
thought = str(result.get("reasoning") or "").strip()
|
|
if thought and reasoning_out is not None:
|
|
reasoning_out.append(thought)
|
|
calls = result.get("tool_calls") or []
|
|
content = str(result.get("content") or "").strip()
|
|
if not calls:
|
|
prompt_call = self._parse_tool_call(content)
|
|
if prompt_call:
|
|
calls = [{"name": prompt_call[0], "arguments": prompt_call[1]}]
|
|
else:
|
|
return content or last
|
|
results = []
|
|
for call in calls[:4]:
|
|
if not isinstance(call, dict):
|
|
continue
|
|
name = str(call.get("name") or call.get("tool") or "")
|
|
args = call.get("arguments") or call.get("args") or {}
|
|
if isinstance(args, str):
|
|
try:
|
|
args = json.loads(args)
|
|
except Exception:
|
|
args = {}
|
|
if not name or not isinstance(args, dict):
|
|
continue
|
|
self.ui(lambda n=name, a=args: self._append_tool_note(
|
|
f"tool: {n}", json.dumps(a, ensure_ascii=False)[:700], True))
|
|
ok, result_text = self.mcp.call_tool(name, args, ask=self._ask_tool)
|
|
preview = str(result_text)
|
|
if len(preview) > 1400:
|
|
preview = preview[:1400] + "…"
|
|
self.ui(lambda n=name, r=preview, o=ok: self._append_tool_note(
|
|
f"{'ok' if o else 'ошибка'}: {n}", r, o))
|
|
results.append((name, ok, str(result_text)))
|
|
if not results:
|
|
return content or last
|
|
notes = "\n\n".join(
|
|
f"Инструмент {name} ({'ok' if ok else 'ошибка'}):\n{text[:4000]}"
|
|
for name, ok, text in results
|
|
)
|
|
convo.append({"role": "assistant",
|
|
"content": content or "Использую инструменты."})
|
|
convo.append({"role": "user", "content":
|
|
"Результаты инструментов:\n" + notes +
|
|
"\n\nНе повторяй уже выполненный успешный вызов. "
|
|
"Продолжи ответ пользователю. Если инструмент больше не нужен — ответь обычным текстом."})
|
|
last = content or last
|
|
return last or "Готово."
|
|
|
|
def _run_prompt_agent(self, messages, params, reasoning_out=None):
|
|
prompt = (
|
|
self._agent_system_prompt(False) +
|
|
"\n\nДиалог:\n" + self._flatten_history(messages, limit=10) +
|
|
"\nАссистент:"
|
|
)
|
|
try:
|
|
allowed = {str(t.get("name") or "") for t in self.mcp.list_tools()}
|
|
except Exception:
|
|
allowed = set()
|
|
final = ""
|
|
for step in range(4):
|
|
out = self.engine.generate_sync(prompt, params)
|
|
try:
|
|
thought = self.engine.reasoning_text()
|
|
except Exception:
|
|
thought = ""
|
|
if thought.strip() and reasoning_out is not None:
|
|
reasoning_out.append(thought.strip())
|
|
call = self._parse_tool_call(out)
|
|
if not call:
|
|
return (out or "").strip()
|
|
name, args = call
|
|
if allowed and name not in allowed:
|
|
prompt += (
|
|
f"\n{out}\nОшибка: инструмент {name} не существует. "
|
|
"Используй только инструменты из списка выше.\n"
|
|
)
|
|
continue
|
|
self.ui(lambda n=name, a=args: self._append_tool_note(
|
|
f"tool: {n}", json.dumps(a, ensure_ascii=False)[:700], True))
|
|
ok, result = self.mcp.call_tool(name, args, ask=self._ask_tool)
|
|
preview = str(result)
|
|
if len(preview) > 1400:
|
|
preview = preview[:1400] + "…"
|
|
self.ui(lambda n=name, r=preview, o=ok: self._append_tool_note(
|
|
f"{'ok' if o else 'ошибка'}: {n}", r, o))
|
|
prompt += (
|
|
f"\n{out}\nРезультат инструмента {name}:\n{str(result)[:4000]}\n"
|
|
"Продолжи ответ пользователю. Если инструмент больше не нужен — ответь обычным текстом."
|
|
)
|
|
final = (out or "").strip()
|
|
return final or "Готово."
|
|
|
|
def _start_agent(self, messages, params):
|
|
if self.mcp is None or not self.mcp.enabled():
|
|
self._on_result("[ОШИБКА] MCP не настроен: укажите папки в настройках")
|
|
return
|
|
try:
|
|
self.mcp.list_tools()
|
|
except Exception as e:
|
|
self._on_result(f"[ОШИБКА] MCP: {e}")
|
|
return
|
|
agent_params = self._agent_gen_params(params)
|
|
|
|
def worker():
|
|
final = ""
|
|
reasoning_parts = []
|
|
try:
|
|
caps = self.engine.capabilities() if self.engine else None
|
|
if bool(getattr(caps, "tools", False)):
|
|
try:
|
|
final = self._run_native_agent(
|
|
messages, agent_params, reasoning_parts)
|
|
except Exception as e:
|
|
try:
|
|
self.app_state.log(f"[MCP] native tools: {e}")
|
|
except Exception:
|
|
pass
|
|
final = self._run_prompt_agent(
|
|
messages, agent_params, reasoning_parts)
|
|
else:
|
|
final = self._run_prompt_agent(
|
|
messages, agent_params, reasoning_parts)
|
|
except Exception as e:
|
|
final = f"[ОШИБКА] {e}"
|
|
reasoning = "\n\n".join(
|
|
part for part in reasoning_parts if str(part or "").strip())
|
|
self.ui(lambda t=final, r=reasoning: self._on_result(t, r))
|
|
|
|
threading.Thread(target=worker, daemon=True).start()
|
|
|
|
def destroy(self):
|
|
try:
|
|
if getattr(self, "mcp", None) is not None:
|
|
self.mcp.close()
|
|
except Exception:
|
|
pass
|
|
super().destroy()
|
|
|
|
def _on_result(self, result_text: str, reasoning: str = ""):
|
|
self._stop_typing()
|
|
reasoning = str(reasoning or "").strip()
|
|
if self.app_state is not None:
|
|
message = {"role": "assistant", "content": result_text}
|
|
if reasoning:
|
|
message["reasoning"] = reasoning
|
|
self.app_state.chat_history.append(message)
|
|
if self._stream_label is not None:
|
|
label = self._stream_label
|
|
self._stream_label = None
|
|
final = result_text or self._stream_text
|
|
try:
|
|
if reasoning and self._stream_parent is not None:
|
|
ReasoningBlock(self._stream_parent, reasoning).pack(
|
|
anchor="w", fill="x", padx=2, pady=(0, 8), before=label)
|
|
if label.winfo_exists():
|
|
label.configure(text=final)
|
|
except Exception:
|
|
pass
|
|
self._stream_text = ""
|
|
else:
|
|
self._append_message("assistant", result_text, reasoning)
|
|
self.set_busy(False)
|
|
self.update_context_indicator()
|
|
self._update_unload_btn()
|
|
self._scroll_bottom()
|
|
try:
|
|
self._focus_input()
|
|
except Exception:
|
|
pass
|