115 lines
7.9 KiB
Python
115 lines
7.9 KiB
Python
import json, sqlite3, ssl, subprocess, time, urllib.error, urllib.request
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).parent
|
|
SERVER = HERE / "bin" / "llama-server.exe"
|
|
MD = HERE / "models"
|
|
CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>"
|
|
# Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02.
|
|
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
|
|
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
|
|
# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch))
|
|
MODELS = {
|
|
# MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention
|
|
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
|
|
"qwen35b": ("Qwen3.6 35B-A3B (RAM)", MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf",
|
|
["--mmproj-offload", *_IMG, "--cpu-moe", "-ngl", "30", "-c", "16384", *_Q],
|
|
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", "--reasoning-budget", "1024", *_Q]),
|
|
# Hybrid attention -> 16k KV is only ~0.3 GB. Q4_K_S: best boxes/entities vs IQ4_XS/Q4_K_M/UD-Q4_K_XL on 8 sample shots.
|
|
# Vision: encoder on GPU, FFN of the last 13/32 layers in RAM to make room: shot 36 -> 22 s (CPU encoder was ~19 s/image),
|
|
# gen only 30 -> 25 tok/s; 12 is the limit (10 OOMs), 13 leaves margin. Text: everything on GPU.
|
|
"qwen4b": ("Qwen3.5 4B (VRAM)", MD / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf", MD / "qwen3.5-4b" / "mmproj-BF16.gguf",
|
|
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q],
|
|
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]),
|
|
}
|
|
PORT = 18081
|
|
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
|
|
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
|
|
|
|
PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, Copilot)
|
|
OMP_DB = Path.home() / ".omp" / "agent" / "agent.db" # omp stores the github-copilot OAuth login here
|
|
# key -> (label, Copilot model id, vision). Vision=False: report/docs/memory/ask only (BYOK italdesign/ models reject images).
|
|
REMOTE = {
|
|
"cp-haiku": ("Claude Haiku 5.5 (Copilot, crediti)", "claude-haiku-5.5", True),
|
|
"cp-kimi": ("Kimi K2.5 (italdesign BYOK)", "italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5", False),
|
|
"cp-deepseek": ("DeepSeek V3.2 (italdesign BYOK)", "italdesign/Bedrock_Mantle/deepseek.v3.2", False),
|
|
"cp-sonnet": ("Claude Sonnet 5.5 (Copilot, crediti)", "claude-sonnet-5.5", False),
|
|
"cp-gemini": ("Gemini 3.8 Flash (Copilot, crediti)", "gemini-3.8-flash", False),
|
|
}
|
|
_HDR = {"Editor-Version": "vscode/1.107.1", "Editor-Plugin-Version": "copilot-chat/0.26.7", "Copilot-Integration-Id": "copilot-developer-cli"}
|
|
_ctx = ssl.create_default_context(); _ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT # corp TLS proxy CA lacks critical basicConstraints
|
|
_ropen = urllib.request.build_opener(urllib.request.ProxyHandler({"https": PROXY}), urllib.request.HTTPSHandler(context=_ctx)).open
|
|
|
|
def _local(): return [k for k, m in MODELS.items() if m[1].exists()]
|
|
def available(vision=True): return _local() + [k for k, r in REMOTE.items() if r[2] or not vision]
|
|
def label(k): return (MODELS.get(k) or REMOTE[k])[0]
|
|
|
|
def current(vision=True):
|
|
"""Model for shots (vision) or report/ask (text): GUI choice if available, else 4B for shots (VRAM-only, near-35B shots)
|
|
and the biggest local model for reports (4B reports lose structure on long transcripts). Never falls back to remote."""
|
|
ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""]
|
|
k = ks[0] if vision else ks[-1] # a single key (old format) applies to both
|
|
if k in available(vision): return k
|
|
loc = _local()
|
|
if vision and "qwen4b" in loc: return "qwen4b"
|
|
return (loc or ["qwen4b"])[0]
|
|
|
|
def _copilot():
|
|
"""(token, api base) of omp's github-copilot login."""
|
|
try:
|
|
c = sqlite3.connect(f"file:{OMP_DB.as_posix()}?mode=ro", uri=True)
|
|
try: row = c.execute("SELECT data FROM auth_credentials WHERE provider='github-copilot' AND disabled_cause IS NULL ORDER BY id DESC LIMIT 1").fetchone()
|
|
finally: c.close()
|
|
except sqlite3.Error as e: raise RuntimeError(f"omp agent.db non leggibile ({OMP_DB}): {e}") from e
|
|
if not row: raise RuntimeError("nessun login github-copilot in omp: esegui /login github-copilot in omp")
|
|
d = json.loads(row[0]); return d["access"], d.get("apiEndpoint") or "https://api.githubcopilot.com"
|
|
|
|
def post(body, vision, timeout):
|
|
"""Chat completion on llama-server, or on GitHub Copilot when the GUI picked a REMOTE model."""
|
|
k = current(vision); r = REMOTE.get(k)
|
|
if not r:
|
|
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k}).encode(), {"Content-Type": "application/json"})
|
|
return json.load(_open(req, timeout=timeout))
|
|
tok, base = _copilot()
|
|
body = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1]}
|
|
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR, **({"Copilot-Vision-Request": "true"} if vision else {})}
|
|
try: return json.load(_ropen(urllib.request.Request(base + "/chat/completions", json.dumps(body).encode(), h), timeout=timeout))
|
|
except urllib.error.HTTPError as e:
|
|
if e.code == 400: raise # callers retry 400 without response_format
|
|
raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
|
|
|
|
def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
|
|
|
|
def content(resp, what):
|
|
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints)."""
|
|
t = resp.get("timings") or {}
|
|
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split())
|
|
if t: print(f"llm {what}: prompt {t.get('prompt_n', 0)} tok @ {t.get('prompt_per_second', 0):.0f} t/s, "
|
|
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s" + (f" (thinking ~{think} words)" if think else ""), flush=True)
|
|
elif resp.get("usage"): print(f"llm {what}: prompt {resp['usage'].get('prompt_tokens', 0)} tok, gen {resp['usage'].get('completion_tokens', 0)} tok (Copilot)", flush=True)
|
|
return resp["choices"][0]["message"]["content"]
|
|
|
|
def up(port=PORT):
|
|
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True
|
|
except Exception: return False
|
|
|
|
def _spawn(args, port, log):
|
|
if up(port): return None
|
|
p = subprocess.Popen([str(SERVER), *args, "--port", str(port)], stdout=open(log, "w"), stderr=subprocess.STDOUT)
|
|
for _ in range(600):
|
|
if up(port): return p
|
|
assert p.poll() is None, f"llama-server died, see {log}"
|
|
time.sleep(2)
|
|
raise TimeoutError("llama-server not ready")
|
|
|
|
def start(vision=True, port=PORT, log="llama.log"):
|
|
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
|
|
if current(vision) in REMOTE: return None
|
|
_, model, mmproj, vargs, targs = MODELS[current(vision)]
|
|
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log)
|
|
|
|
def start_embed(log="embed.log"):
|
|
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
|
|
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
|
|
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
|