Local-LLM support so J.A.R.V.I.S. works offline without GROQ_TOKEN.
LLM multi-backend (crates/jarvis-core/src/llm/client.rs)
- LlmBackend enum {Groq, Ollama}. Both use OpenAI-compatible /v1/chat/completions
(Ollama exposes one natively at :11434/v1).
- LlmClient::from_env() now dispatches on JARVIS_LLM=groq|ollama. Auto-detect:
Groq if GROQ_TOKEN set, else Ollama.
- New helpers: LlmClient::groq() (was: from_env), LlmClient::ollama().
- Reqwest client now has a 60s timeout (was: unbounded — Groq freezes could hang).
- api_key skipped when empty (Ollama doesn't need auth).
- Defaults: OLLAMA_BASE_URL=http://localhost:11434/v1, OLLAMA_MODEL=qwen2.5:3b.
Override via OLLAMA_BASE_URL / OLLAMA_MODEL env.
- llm_fallback + llm_router log the active backend on init.
- Tests: 32/32 pass. Renamed `from_env_fails` → `groq_fails_when_token_missing`,
added `ollama_works_without_token`.
Daily briefing pack (resources/commands/daily_briefing/, 3 commands)
- setup.lua: "настрой утренний брифинг на 9:00" → adds a daily scheduled task
that runs now.lua via the scheduler's Lua-action support.
- now.lua: greeting + time + active profile + scheduled task count + memory recap
+ LLM motivational nudge. Voice-triggered ("утренний брифинг") works the same.
- off.lua: removes the scheduled task.
Pomodoro pack (resources/commands/pomodoro/, 2 commands)
- start.lua / stop.lua + tick.lua (re-scheduled by itself). State stored in
jarvis.state — phase alternates work (25 min) / break (5 min) until stop.
Currency conversion (resources/commands/currency/convert.lua)
- "сколько будет 1000 долларов в рублях" — fetches CBR daily rates from
cbr-xml-daily.ru, normalises by Nominal, prints both directions.
- Recognises USD/EUR/CNY/GBP/JPY/RUB by substring. Pluralises russian units.
Stocks pack (resources/commands/stocks/, 1 command)
- "сколько Сбер" → MOEX ISS /iss/engines/stock/markets/shares/securities/<TKR>.
- Mapping of 22 popular Russian tickers to common names (Сбер→SBER, Газпром→GAZP,
Лукойл→LKOH, Яндекс→YDEX, Т-банк→T, etc).
- Picks TQBR (main board) row, reports LAST + LASTTOPREVPRICE%.
Habit nudges (resources/commands/habit_nudge/, 4 commands)
- "напоминай мне пить воду" → every 2 hours
- "напоминай мне размяться" → every 50 minutes
- "напоминай отдыхать глазам" → every 20 minutes (20-20-20 rule)
- "отключи все привычки" → stops all three by id.
Translate clipboard (resources/commands/translate/clipboard.lua)
- "переведи буфер на английский" → grabs clipboard, sends to LLM, speaks first
sentence, replaces clipboard with full translation, fires notification.
Build: cargo build --release -p jarvis-app -p jarvis-gui both green. 32/32 tests.
To use Ollama:
1. Install + run Ollama (https://ollama.com).
2. `ollama pull qwen2.5:3b` (or any chat model).
3. Optional: `set JARVIS_LLM=ollama` (auto-picked if GROQ_TOKEN unset).
144 lines
4.4 KiB
Rust
144 lines
4.4 KiB
Rust
use once_cell::sync::OnceCell;
|
|
use parking_lot::Mutex;
|
|
|
|
use jarvis_core::config;
|
|
use jarvis_core::i18n;
|
|
use jarvis_core::ipc::{self, IpcEvent};
|
|
use jarvis_core::llm::{ChatMessage, ConversationHistory, LlmClient};
|
|
use jarvis_core::long_term_memory;
|
|
use jarvis_core::profiles;
|
|
use jarvis_core::tts::{self, SpeakOpts};
|
|
use jarvis_core::voices;
|
|
|
|
struct State {
|
|
client: LlmClient,
|
|
history: Mutex<ConversationHistory>,
|
|
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;
|
|
}
|
|
|
|
let client = match LlmClient::from_env() {
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
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);
|
|
let history = Mutex::new(ConversationHistory::new(prompt, config::LLM_DEFAULT_MAX_HISTORY));
|
|
|
|
info!("LLM fallback enabled (backend: {}, model: {}).", client.backend().name(), client.model());
|
|
Some(State {
|
|
client,
|
|
history,
|
|
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);
|
|
|
|
let snapshot: Vec<ChatMessage> = {
|
|
let mut h = state.history.lock();
|
|
h.push_user(prompt);
|
|
let mut snap = h.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 !snap.is_empty() && snap[0].role == "system" { 1 } else { 0 };
|
|
snap.insert(insert_at, ChatMessage::system(overlay));
|
|
}
|
|
|
|
snap
|
|
};
|
|
|
|
match state.client.complete(&snapshot, state.max_tokens) {
|
|
Ok(reply) => {
|
|
let reply = reply.trim().to_string();
|
|
info!("LLM reply: {}", reply);
|
|
state.history.lock().push_assistant(reply.clone());
|
|
ipc::send(IpcEvent::LlmReply { text: reply.clone() });
|
|
voices::play_ok();
|
|
speak_reply(&reply);
|
|
}
|
|
Err(e) => {
|
|
error!("LLM request failed: {}", e);
|
|
state.history.lock().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 std::env::var("JARVIS_LLM_TTS").as_deref() == Ok("false") {
|
|
return;
|
|
}
|
|
tts::speak(text, &SpeakOpts::lang("ru"));
|
|
}
|