Merge copilot-llm: remote Copilot models for shots/report

This commit is contained in:
Stefano Zini
2026-11-03 16:56:45 +01:00
6 changed files with 62 additions and 25 deletions
+2 -3
View File
@@ -1,9 +1,8 @@
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow.""" """Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow."""
import json, os, re, shutil, subprocess import json, os, re, shutil, subprocess
import db, report import db, llama, report
TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe") TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
PROXY = "http://zproxy.idg.audi.vwg:9400"
SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.' SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.'
SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).' SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).'
KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$") KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$")
@@ -23,7 +22,7 @@ def _twg(*args, timeout=120):
except (OSError, ValueError): pass except (OSError, ValueError): pass
else: out = r.stdout if r.returncode == 0 else None else: out = r.stdout if r.returncode == 0 else None
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
env = {**env, "HTTPS_PROXY": PROXY, "HTTP_PROXY": PROXY} env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY}
def _run(name): def _run(name):
+50 -8
View File
@@ -1,4 +1,4 @@
import subprocess, time, urllib.request import json, sqlite3, ssl, subprocess, time, urllib.error, urllib.request
from pathlib import Path from pathlib import Path
HERE = Path(__file__).parent HERE = Path(__file__).parent
@@ -26,17 +26,57 @@ PORT = 18081
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082 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 _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
def available(): return [k for k, m in MODELS.items() if m[1].exists()] 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): def current(vision=True):
"""Model for shots (vision) or report/ask (text): GUI choice if on disk, else 4B for shots (VRAM-only, near-35B shots) """Model for shots (vision) or report/ask (text): GUI choice if available, else 4B for shots (VRAM-only, near-35B shots)
and the biggest model for reports (4B reports lose structure on long transcripts).""" 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 [""] 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 k = ks[0] if vision else ks[-1] # a single key (old format) applies to both
av = available() if k in available(vision): return k
if k in av: return k loc = _local()
if vision and "qwen4b" in av: return "qwen4b" if vision and "qwen4b" in loc: return "qwen4b"
return (av or ["qwen4b"])[0] 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 choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
@@ -46,6 +86,7 @@ def content(resp, what):
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split()) 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, " 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) 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"] return resp["choices"][0]["message"]["content"]
def up(port=PORT): def up(port=PORT):
@@ -63,6 +104,7 @@ def _spawn(args, port, log):
def start(vision=True, port=PORT, log="llama.log"): 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.""" """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)] _, model, mmproj, vargs, targs = MODELS[current(vision)]
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log) return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log)
+4 -6
View File
@@ -3,9 +3,7 @@ import base64, difflib, json, re, unicodedata, urllib.request
import db, llama import db, llama
from shots import CONTENT_KINDS from shots import CONTENT_KINDS
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
JIRA_BROWSE = "https://italdesign.atlassian.net/browse" JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b") TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. ' SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. ' 'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
@@ -52,18 +50,18 @@ def _strip_junk(o):
def chat(system, user, max_tokens, retries=2, think=False): def chat(system, user, max_tokens, retries=2, think=False):
"""think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast.""" """think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast."""
body = {"model": llama.current(False), "temperature": 0.2, "max_tokens": max_tokens + (THINK if think else 0), body = {"temperature": 0.2, "max_tokens": max_tokens + (THINK if think else 0),
"chat_template_kwargs": {"enable_thinking": think}, "response_format": {"type": "json_object"}, "chat_template_kwargs": {"enable_thinking": think}, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]} "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
for _ in range(retries): for _ in range(retries):
try: try:
try: try:
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800) r = llama.post(body, False, 1800)
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
if e.code != 400: raise if e.code != 400: raise
body.pop("response_format", None) body.pop("response_format", None)
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800) r = llama.post(body, False, 1800)
t = llama.content(json.load(r), f"report ({max_tokens} max)") t = llama.content(r, f"report ({max_tokens} max)")
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S) t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
d = _strip_junk(json.loads(t[t.find("{"):t.rfind("}") + 1])) d = _strip_junk(json.loads(t[t.find("{"):t.rfind("}") + 1]))
if isinstance(d, dict): return d if isinstance(d, dict): return d
+3 -3
View File
@@ -309,7 +309,7 @@ def status():
w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0 w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0
rs.append(d) rs.append(d)
return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE), return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE),
"llm": [llama.current(True), llama.current(False)], "llms": [[k, llama.MODELS[k][0]] for k in llama.available()]} "llm": [llama.current(True), llama.current(False)], "llms": [[[k, llama.label(k)] for k in llama.available(v)] for v in (True, False)]}
def fts(sql, q): def fts(sql, q):
@@ -505,7 +505,7 @@ addEventListener("dragleave",e=>{if(!e.relatedTarget)document.body.classList.rem
addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("drag");const f=e.dataTransfer.files[0];if(f)send(f)}); addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("drag");const f=e.dataTransfer.files[0];if(f)send(f)});
async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.busy;ab.title=j.busy?"pipeline in corso":""; async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.busy;ab.title=j.busy?"pipeline in corso":"";
const runp=j.recs.map(r=>r.prog).filter(p=>p&&p.pct!=null);document.title=runp.length?`${Math.round(runp[0].pct*100)}% · ${LBL[runp[0].step]} · Riunioni`:"Riunioni"; const runp=j.recs.map(r=>r.prog).filter(p=>p&&p.pct!=null);document.title=runp.length?`${Math.round(runp[0].pct*100)}% · ${LBL[runp[0].step]} · Riunioni`:"Riunioni";
for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "]])if(document.activeElement!==s){s.innerHTML=j.llms.map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.disabled=j.busy} for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "]])if(document.activeElement!==s){s.innerHTML=j.llms[i].map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.disabled=j.busy}
qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:""; qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:"";
document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value); document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value);
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>"; let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
@@ -604,7 +604,7 @@ class H(BaseHTTPRequestHandler):
self._send(b"") if run_all(f) else self._send("rielaborazione già in corso".encode(), 409) self._send(b"") if run_all(f) else self._send("rielaborazione già in corso".encode(), 409)
elif u.path == "/llm": elif u.path == "/llm":
ks = [q.get("shots"), q.get("report")] ks = [q.get("shots"), q.get("report")]
if not all(k in llama.available() for k in ks): return self._send(b"modello non installato", 400) if not (ks[0] in llama.available(True) and ks[1] in llama.available(False)): return self._send(b"modello non installato", 400)
if busy(): return self._send("pipeline in corso: cambia modello dopo".encode(), 409) if busy(): return self._send("pipeline in corso: cambia modello dopo".encode(), 409)
llama.choose(*ks); self._send() llama.choose(*ks); self._send()
elif u.path == "/speaker_map": elif u.path == "/speaker_map":
+2 -5
View File
@@ -2,8 +2,6 @@
import base64, collections, json, re, subprocess, urllib.error, urllib.request import base64, collections, json, re, subprocess, urllib.error, urllib.request
import db, llama import db, llama
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None} EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None}
CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"} CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"}
CROP_BOX = True CROP_BOX = True
@@ -39,13 +37,12 @@ EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def _ask(path, json_mode=True): def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode() img = base64.b64encode(path.read_bytes()).decode()
body = {"model": llama.current(True), "max_tokens": 1200, "temperature": 0.1, body = {"max_tokens": 1200, "temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": False}, "chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT}, "messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]} {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]}
if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"} if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"}
req = urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}) return llama.content(llama.post(body, True, 900), f"shot {path.name}")
return llama.content(json.load(_open(req, timeout=900)), f"shot {path.name}")
def read_shot(path): def read_shot(path):
+1
View File
@@ -0,0 +1 @@
listening http://127.0.0.1:18766/