Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-06-07 15:24:51 +03:00
1 parent f35f861987
commit 6699c074ac
7 files changed
+1008 -215

No files matched your search

+269 -26
View File
@@ -1,7 +1,20 @@
"""
Ollama LLM client for MARK XL.
Replaces Google Gemini API with local Ollama inference.
All modules that previously used google.generativeai import from here.
Local LLM client for MARK XL.
Supports two backends — selected via "llm_provider" in config/api_keys.json:
"llm_provider": "ollama" (default)
Uses Ollama's native /api/chat endpoint.
Download: https://ollama.com
Default port: 11434
"llm_provider": "openai"
Uses any OpenAI-compatible server: LM Studio, Jan, LocalAI,
llama.cpp server, vLLM, etc.
LM Studio download: https://lmstudio.ai (default port: 1234)
Set "llm_url": "http://localhost:1234" in config.
Note: tool-calling support depends on the model; use a model that
supports function/tool calls (e.g. Qwen2.5, Llama-3.1, Mistral).
"""
import json
import re
@@ -27,11 +40,18 @@ BASE_DIR = get_base_dir()
CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
_DEFAULTS = {
"llm_url": "http://localhost:11434",
"llm_model": "llama3.2",
"llm_url": "http://localhost:11434",
"llm_model": "llama3.2",
"llm_provider": "ollama", # "ollama" | "openai"
}
def get_llm_provider() -> str:
"""Returns 'ollama' or 'openai' (covers LM Studio, LocalAI, Jan, etc.)."""
raw = _load_config().get("llm_provider", "ollama").strip().lower()
return "openai" if raw in ("openai", "lmstudio", "localai", "jan", "llamacpp") else "ollama"
def _load_config() -> dict:
try:
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
@@ -41,12 +61,33 @@ def _load_config() -> dict:
def ensure_ollama_running(timeout: int = 15) -> bool:
"""
Ping Ollama; if it's not responding, launch 'ollama serve' in the background
and wait up to `timeout` seconds for it to become ready.
Returns True if Ollama is available, False otherwise.
For Ollama: ping /api/tags; auto-launch 'ollama serve' if not running.
For OpenAI-compatible providers: just ping /v1/models (server must be started manually).
Returns True if the LLM server is reachable.
"""
url, _ = get_llm_settings()
health = f"{url}/api/tags"
url, _ = get_llm_settings()
provider = get_llm_provider()
if provider == "openai":
# OpenAI-compatible servers (LM Studio, LocalAI, etc.) must be started
# by the user — we just check if they're reachable.
health = f"{url}/v1/models"
try:
ok = requests.get(health, timeout=5).status_code == 200
if ok:
print(f"[LLM] OpenAI-compatible server reachable at {url}")
else:
print(f"[LLM] Server at {url} returned non-200. Is it running?")
return ok
except Exception as e:
print(
f"[LLM] Cannot reach OpenAI-compatible server at {url}.\n"
" Make sure LM Studio / LocalAI / Jan is running and the server is started."
)
return False
# ── Ollama ──────────────────────────────────────────────────────────────
health = f"{url}/api/tags"
def _is_up() -> bool:
try:
@@ -81,25 +122,62 @@ def ensure_ollama_running(timeout: int = 15) -> bool:
return False
def warmup_model() -> bool:
def warmup_model(system_prompt: str | None = None) -> bool:
"""
Pre-load the model into Ollama memory so the first real request is instant.
Sends a minimal 1-token request with keep_alive=-1.
Returns True on success, False if warmup failed (non-fatal).
Pre-load the model AND prime Ollama's KV prefix cache.
Why the system_prompt matters
─────────────────────────────
Ollama caches the KV attention state of the prompt prefix across requests.
If warmup includes the same system prompt that real requests will use, Ollama
evaluates those tokens ONCE at startup. Every subsequent request only needs
to evaluate the small delta (user message ± time context) instead of the full
300-500 token system prompt → drops first-token latency from ~17 s to <1 s.
Pass the *static* part of the system prompt (the JARVIS protocol text, without
timestamps or per-minute context) so the prefix stays valid across calls.
"""
url, model = get_llm_settings()
print(f"[LLM] Warming up '{model}'…")
provider = get_llm_provider()
print(f"[LLM] Warming up '{model}' ({provider})…")
messages: list[dict] = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": "hi"})
if provider == "openai":
# OpenAI-compatible: just fire a minimal request to ensure the model is loaded.
# No keep_alive or KV-cache priming available — server manages this internally.
payload = {
"model": model,
"messages": messages,
"stream": False,
"max_tokens": 1,
}
try:
resp = requests.post(f"{url}/v1/chat/completions", json=payload, timeout=180)
resp.raise_for_status()
print(f"[LLM] '{model}' ready (OpenAI-compatible server).")
return True
except Exception as e:
print(f"[LLM] Warmup failed (non-fatal): {e}")
return False
# ── Ollama ──────────────────────────────────────────────────────────────
payload = {
"model": model,
"messages": [{"role": "user", "content": "hi"}],
"messages": messages,
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 1},
# num_gpu:99 → push ALL transformer layers to GPU (Ollama caps at available)
# This is safe even without a GPU — Ollama silently ignores if n_gpu_layers=0
"options": {"num_predict": 1, "num_gpu": 99},
}
try:
resp = requests.post(f"{url}/api/chat", json=payload, timeout=120)
resp = requests.post(f"{url}/api/chat", json=payload, timeout=180)
resp.raise_for_status()
print(f"[LLM] '{model}' loaded and ready.")
print(f"[LLM] '{model}' loaded and KV cache primed.")
return True
except Exception as e:
print(f"[LLM] Warmup failed (non-fatal): {e}")
@@ -120,20 +198,61 @@ def call_llm(
timeout: int = 120,
) -> dict:
"""
Chat request to Ollama (with optional tool declarations).
Non-streaming chat request. Routes to Ollama or OpenAI-compatible backend.
Returns:
{"content": str, "tool_calls": list}
"""
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
provider = get_llm_provider()
payload: dict = {
if provider == "openai":
endpoint = f"{url}/v1/chat/completions"
payload: dict = {
"model": model,
"messages": messages,
"stream": False,
"max_tokens": 300,
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
choice = resp.json().get("choices", [{}])[0]
msg = choice.get("message", {})
# OpenAI tool_calls format → normalise to Ollama-style
raw_tc = msg.get("tool_calls") or []
tc_list = [
{
"id": t.get("id", ""),
"function": {
"name": t["function"]["name"],
"arguments": (
json.loads(t["function"]["arguments"])
if isinstance(t["function"].get("arguments"), str)
else t["function"].get("arguments", {})
),
},
}
for t in raw_tc
]
return {
"content": (msg.get("content") or "").strip(),
"tool_calls": tc_list,
}
except Exception as e:
raise RuntimeError(f"OpenAI-compatible LLM call failed: {e}")
# ── Ollama ──────────────────────────────────────────────────────────────
endpoint = f"{url}/api/chat"
payload = {
"model": model,
"messages": messages,
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 600},
"options": {"num_predict": 300, "num_gpu": 99},
}
if tools:
payload["tools"] = tools
@@ -216,21 +335,142 @@ def call_llm_text(
raise RuntimeError(f"LLM text call failed: {e}")
def _stream_openai(
messages: list,
tools: list | None,
timeout: int,
) -> Generator[dict, None, None]:
"""
Streaming backend for OpenAI-compatible servers (LM Studio, LocalAI, Jan…).
Parses Server-Sent Events (SSE) and accumulates streaming tool-call fragments
so the output format is identical to the Ollama backend.
"""
url, model = get_llm_settings()
endpoint = f"{url}/v1/chat/completions"
payload: dict = {
"model": model,
"messages": messages,
"stream": True,
"max_tokens": 300,
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
try:
with requests.post(endpoint, json=payload, timeout=timeout, stream=True) as resp:
resp.raise_for_status()
full_content = ""
buf = ""
# tool_call fragments: index → {"id", "function": {"name", "arguments"}}
tc_fragments: dict[int, dict] = {}
for raw in resp.iter_lines():
if not raw:
continue
# SSE lines look like: b"data: {...}" or b"data: [DONE]"
line = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
try:
chunk = json.loads(data)
except json.JSONDecodeError:
continue
choice = chunk.get("choices", [{}])[0]
delta = choice.get("delta", {})
text = delta.get("content") or ""
full_content += text
buf += text
# Accumulate sentence boundaries for streaming TTS
while True:
m = _SENT_END.search(buf)
if not m:
break
sentence = buf[: m.start() + 1].strip()
buf = buf[m.end():]
if sentence:
yield {"type": "sentence", "text": sentence}
# Accumulate streaming tool-call fragments
for tc in (delta.get("tool_calls") or []):
idx = tc.get("index", 0)
if idx not in tc_fragments:
tc_fragments[idx] = {"id": "", "function": {"name": "", "arguments": ""}}
frag = tc_fragments[idx]
frag["id"] = frag["id"] or tc.get("id", "")
fn = tc.get("function", {})
frag["function"]["name"] += fn.get("name") or ""
frag["function"]["arguments"] += fn.get("arguments") or ""
finish = choice.get("finish_reason")
if finish in ("stop", "tool_calls", "length"):
break
# Flush any trailing content
if buf.strip():
yield {"type": "sentence", "text": buf.strip()}
# Parse accumulated tool-call argument strings → dicts
tool_calls: list = []
for idx in sorted(tc_fragments):
frag = tc_fragments[idx]
args = frag["function"]["arguments"]
try:
args = json.loads(args)
except Exception:
pass # leave as raw string; _execute_tool handles it
tool_calls.append({
"id": frag["id"],
"function": {"name": frag["function"]["name"], "arguments": args},
})
yield {
"type": "done",
"content": full_content.strip(),
"tool_calls": tool_calls,
}
except requests.exceptions.ConnectionError:
raise RuntimeError(
f"Cannot reach OpenAI-compatible server at {url}.\n"
"Make sure LM Studio / LocalAI / Jan is running and the server is started."
)
except requests.exceptions.Timeout:
raise RuntimeError("OpenAI-compatible stream timed out.")
except requests.exceptions.HTTPError as e:
raise RuntimeError(f"OpenAI-compatible HTTP error: {e.response.status_code}")
except Exception as e:
raise RuntimeError(f"OpenAI-compatible stream failed: {e}")
def call_llm_stream(
messages: list,
tools: list | None = None,
timeout: int = 120,
) -> Generator[dict, None, None]:
"""
Streaming chat request to Ollama.
Streaming chat request. Routes to Ollama or OpenAI-compatible backend.
Yields:
{"type": "sentence", "text": str} — each complete sentence as it arrives
{"type": "done", "content": str, "tool_calls": list} — when stream ends
Sentences are split on [.!?] + whitespace so TTS can start immediately.
Tool calls (if any) always appear in the final "done" event with empty content.
Tool calls always appear in the final "done" event.
"""
provider = get_llm_provider()
if provider == "openai":
yield from _stream_openai(messages, tools, timeout)
return
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
@@ -239,7 +479,8 @@ def call_llm_stream(
"messages": messages,
"stream": True,
"keep_alive": -1,
"options": {"num_predict": 600},
# num_gpu:99 pushes all layers to GPU; num_thread removed (Ollama auto-tunes).
"options": {"num_predict": 300, "num_gpu": 99},
}
if tools:
payload["tools"] = tools
@@ -261,6 +502,7 @@ def call_llm_stream(
msg = chunk.get("message", {})
delta = msg.get("content") or ""
full_content += delta
buf += delta
@@ -281,6 +523,7 @@ def call_llm_stream(
if chunk.get("done"):
if buf.strip():
yield {"type": "sentence", "text": buf.strip()}
yield {
"type": "done",
"content": full_content.strip(),