J.A.R.V.I.S-rust/crates/jarvis-app/src/llm_fallback.rs
Bossiara13 385bd5c8ce feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics
Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish
after restart. Plus P0.3 (long-standing roadmap item) and two new packs.

Persistent backend choice (crates/jarvis-core/src/db/structs.rs)
  - Settings struct gains llm_backend + tts_backend fields (both String,
    "" / "auto" = follow env/auto-detect).
  - set("llm_backend", "groq"|"ollama"|"auto") validates input.
  - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect.
  - llm::swap_to() now persists the choice via db::save_settings.
  - Voice swap "переключись на локальный" now survives restart.

Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs)
  - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton.
  - Helpers: init_history, history_push_user, history_push_assistant,
    history_snapshot, history_clear, history_pop_last_user, history_last_assistant.
  - llm_fallback migrated off its own Mutex<History> — now reads/writes shared.
  - ConversationHistory gains last_assistant() method.

New Lua APIs
  - jarvis.llm_reset()        → clear conversation turns (keeps system prompt).
  - jarvis.llm_last_reply()   → string or nil (last assistant message text).
  - jarvis.health()           → debug table {tts_backend, llm_backend, llm_model,
                                  active_profile, memory_facts, scheduled_tasks,
                                  language, voice, microphone, vosk_model,
                                  noise_suppression}. No secrets included.

New voice packs
  - resources/commands/llm_context/   (P0.3)
    * "сбрось контекст" / "забудь разговор"     → llm.reset
    * "повтори последнее" / "повтори ответ"     → llm.repeat (uses last_assistant)
  - resources/commands/quick_search/   (imba P1 item)
    * "найди в гугле <X>" / "загугли <X>"
    * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required).
      Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure
      LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer.
  - resources/commands/diagnostics/
    * "диагностика" / "доложи о себе" / "статус"
    * Reads jarvis.health() and speaks a one-line summary. Useful when
      debugging — user can read out their current state for a bug report.

Build: cargo build --release -p jarvis-app -p jarvis-gui green.
Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00

144 lines
4.5 KiB
Rust

use once_cell::sync::OnceCell;
use jarvis_core::config;
use jarvis_core::i18n;
use jarvis_core::ipc::{self, IpcEvent};
use jarvis_core::llm::{self, ChatMessage};
use jarvis_core::long_term_memory;
use jarvis_core::profiles;
use jarvis_core::tts::{self, SpeakOpts};
use jarvis_core::voices;
// State now only holds the max_tokens config — both the LLM client AND the
// conversation history live in `jarvis_core::llm::*` globals. This lets voice
// commands ("сбрось контекст", "повтори последнее") and Lua scripts share the
// same buffer instead of each module owning its own.
struct State {
max_tokens: u32,
}
static STATE: OnceCell<Option<State>> = OnceCell::new();
pub fn init() {
let _ = STATE.set(build_state());
}
fn build_state() -> Option<State> {
if !config::LLM_DEFAULT_ENABLED {
info!("LLM fallback disabled by config.");
return None;
}
// Initialise the shared global client (idempotent — fine if init was already called).
if let Err(e) = llm::init_global() {
warn!("LLM fallback disabled: {}. Set GROQ_TOKEN or run Ollama to enable.", e);
return None;
}
let lang = i18n::get_language();
let prompt = config::get_llm_system_prompt(&lang);
llm::init_history(prompt, config::LLM_DEFAULT_MAX_HISTORY);
info!("LLM fallback enabled (backend: {}).", llm::current_backend_name());
Some(State {
max_tokens: config::LLM_DEFAULT_MAX_TOKENS,
})
}
pub fn is_enabled() -> bool {
STATE.get().and_then(|s| s.as_ref()).is_some()
}
pub fn extract_prompt(text: &str) -> Option<String> {
let lang = i18n::get_language();
let triggers = config::get_llm_trigger_phrases(&lang);
let lowered = text.to_lowercase();
for trig in triggers {
if let Some(rest) = strip_trigger(&lowered, trig) {
let trimmed = rest.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
}
None
}
fn strip_trigger(text: &str, trigger: &str) -> Option<String> {
let t = text.trim_start();
if let Some(after) = t.strip_prefix(trigger) {
let next = after.chars().next();
if next.map_or(true, |c| !c.is_alphanumeric()) {
return Some(after.to_string());
}
}
None
}
pub fn handle(prompt: &str) {
let state = match STATE.get().and_then(|s| s.as_ref()) {
Some(s) => s,
None => {
warn!("LLM fallback called while disabled — ignoring.");
return;
}
};
info!("LLM prompt: {}", prompt);
llm::history_push_user(prompt);
let mut snapshot: Vec<ChatMessage> = llm::history_snapshot();
// Inject (a) profile personality (b) relevant long-term memory as a fresh
// system message right after the base prompt. Both are optional.
let profile = profiles::active();
let mut overlay = String::new();
if !profile.llm_personality.is_empty() {
overlay.push_str(&format!("Активный профиль: {} {}\nХарактер для ответа: {}\n",
profile.icon, profile.name, profile.llm_personality));
}
let mem_ctx = long_term_memory::build_context(prompt, 5);
if !mem_ctx.is_empty() {
overlay.push_str(&mem_ctx);
}
if !overlay.is_empty() {
// Insert after the base system prompt (index 0 typically), before user msgs.
let insert_at = if !snapshot.is_empty() && snapshot[0].role == "system" { 1 } else { 0 };
snapshot.insert(insert_at, ChatMessage::system(overlay));
}
let client = match llm::current() {
Some(c) => c,
None => {
warn!("LLM call but global client missing — ignoring.");
return;
}
};
match client.complete(&snapshot, state.max_tokens) {
Ok(reply) => {
let reply = reply.trim().to_string();
info!("LLM reply: {}", reply);
llm::history_push_assistant(reply.clone());
ipc::send(IpcEvent::LlmReply { text: reply.clone() });
voices::play_ok();
speak_reply(&reply);
}
Err(e) => {
error!("LLM request failed: {}", e);
llm::history_pop_last_user();
let err_text = config::LLM_FALLBACK_ERROR_RU.to_string();
ipc::send(IpcEvent::LlmReply { text: err_text.clone() });
voices::play_error();
speak_reply(&err_text);
}
}
}
fn speak_reply(text: &str) {
if !jarvis_core::runtime_config::llm_tts_enabled() {
return;
}
tts::speak(text, &SpeakOpts::lang("ru"));
}