121 lines
5.8 KiB
Python
121 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Kernprüfung Block A und B (#1263): läuft auf dem Entwicklungsrechner gegen die Testinstanz auf srv04.
|
|
|
|
Voraussetzung: remote.sh prepare und start, Tunnel `ssh -f -N -L 18100:127.0.0.1:18100 srv04`.
|
|
Aufruf: block_ab.py ERGEBNIS.jsonl [Modell ...] Schreibt je Modell eine Zeile; keine Antworttexte, kein Key.
|
|
"""
|
|
import json, subprocess, sys, time, urllib.request
|
|
import openai
|
|
|
|
BASE = "http://127.0.0.1:18100"
|
|
|
|
def ssh(cmd):
|
|
return subprocess.run(["ssh", "-o", "BatchMode=yes", "srv04", cmd], capture_output=True, text=True, timeout=60).stdout.strip()
|
|
|
|
KEY = ssh("cat /tmp/nexus-kern/key")
|
|
client = openai.OpenAI(base_url=BASE + "/v1", api_key=KEY, max_retries=0, timeout=600)
|
|
|
|
def gpu():
|
|
out = ssh("nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits; free -m | awk '/^Mem/{print $7}'")
|
|
*g, ram = [int(x) for x in out.split()]
|
|
return {"gpu_mib": g, "ram_frei_mb": ram}
|
|
|
|
def instances():
|
|
req = urllib.request.Request(BASE + "/gateway/v1/status", headers={"Authorization": "Bearer " + KEY})
|
|
return json.load(urllib.request.urlopen(req, timeout=30))["scheduler"]["instances"]
|
|
|
|
def probe(fn):
|
|
t = time.time()
|
|
try:
|
|
r = fn()
|
|
return {"ok": True, "s": round(time.time() - t, 1), **(r or {})}
|
|
except openai.APIStatusError as e:
|
|
return {"ok": False, "s": round(time.time() - t, 1), "status": e.status_code, "code": e.code, "meldung": str(e.message)[:300]}
|
|
except Exception as e:
|
|
return {"ok": False, "s": round(time.time() - t, 1), "fehler": f"{type(e).__name__}: {e}"[:300]}
|
|
|
|
TOOLS = [{"type": "function", "function": {"name": "wetter", "description": "Liefert das Wetter einer Stadt.",
|
|
"parameters": {"type": "object", "properties": {"stadt": {"type": "string"}}, "required": ["stadt"]}}}]
|
|
FRAGE = [{"role": "user", "content": "Wie ist das Wetter in Bremen? Benutze das Werkzeug."}]
|
|
|
|
def chat(m, **kw):
|
|
def run():
|
|
r = client.chat.completions.create(model=m, messages=[{"role": "user", "content": "Nenne eine Farbe."}], max_tokens=200, **kw)
|
|
c = r.choices[0]
|
|
return {"ende": c.finish_reason, "zeichen": len(c.message.content or ""), "usage": bool(r.usage and r.usage.total_tokens), "modell_ok": r.model == m}
|
|
return run
|
|
|
|
def stream(m):
|
|
def run():
|
|
n, ende = 0, None
|
|
for p in client.chat.completions.create(model=m, messages=[{"role": "user", "content": "Zähle bis fünf."}], max_tokens=200, stream=True):
|
|
n += 1
|
|
if p.choices and p.choices[0].finish_reason: ende = p.choices[0].finish_reason
|
|
return {"stuecke": n, "ende": ende}
|
|
return run
|
|
|
|
def tools(m):
|
|
def run():
|
|
r = client.chat.completions.create(model=m, messages=FRAGE, tools=TOOLS, max_tokens=600)
|
|
msg = r.choices[0].message
|
|
if not msg.tool_calls:
|
|
return {"werkzeug": False, "ende": r.choices[0].finish_reason}
|
|
tc = msg.tool_calls[0]
|
|
args = json.loads(tc.function.arguments)
|
|
folge = client.chat.completions.create(model=m, tools=TOOLS, max_tokens=600, messages=FRAGE + [
|
|
{"role": "assistant", "content": msg.content, "tool_calls": [t.model_dump() for t in msg.tool_calls]},
|
|
*[{"role": "tool", "tool_call_id": t.id, "content": "17 Grad, Regen"} for t in msg.tool_calls]])
|
|
return {"werkzeug": True, "name": tc.function.name, "args_ok": "stadt" in args, "folge_nutzt_ergebnis": "17" in (folge.choices[0].message.content or "")}
|
|
return run
|
|
|
|
def tools_stream(m):
|
|
def run():
|
|
name, args, ende = "", "", None
|
|
for p in client.chat.completions.create(model=m, messages=FRAGE, tools=TOOLS, max_tokens=600, stream=True):
|
|
if not p.choices: continue
|
|
for t in p.choices[0].delta.tool_calls or []:
|
|
name += (t.function.name or "") if t.function else ""
|
|
args += (t.function.arguments or "") if t.function else ""
|
|
ende = p.choices[0].finish_reason or ende
|
|
if args: json.loads(args)
|
|
return {"werkzeug": bool(name), "name": name, "ende": ende}
|
|
return run
|
|
|
|
def embed(m):
|
|
def run():
|
|
r = client.embeddings.create(model=m, input=["Hallo", "Welt"])
|
|
return {"vektoren": len(r.data), "dim": len(r.data[0].embedding)}
|
|
return run
|
|
|
|
def main():
|
|
out, wanted = sys.argv[1], sys.argv[2:]
|
|
models = sorted(x.id for x in client.models.list())
|
|
with open(out, "a") as f:
|
|
def emit(d):
|
|
f.write(json.dumps(d, ensure_ascii=False) + "\n"); f.flush(); print(json.dumps(d, ensure_ascii=False), flush=True)
|
|
emit({"fall": "allgemein", "modelle": len(models), "instanzen": len(instances()), **gpu(),
|
|
"unbekannt": probe(chat("gibt-es-nicht")),
|
|
"falscher_key": probe(lambda: openai.OpenAI(base_url=BASE + "/v1", api_key="falsch", max_retries=0).models.list() and None),
|
|
"instanzen_danach": len(instances())})
|
|
for m in wanted or models:
|
|
d = {"modell": m, "vorher": gpu()}
|
|
if m == "bge-m3":
|
|
d["kalt"] = probe(embed(m)); d["geladen"] = gpu()
|
|
else:
|
|
d["kalt"] = probe(chat(m)); d["geladen"] = gpu()
|
|
if d["kalt"]["ok"]:
|
|
d["stream"] = probe(stream(m))
|
|
d["werkzeug"] = probe(tools(m))
|
|
d["werkzeug_stream"] = probe(tools_stream(m))
|
|
d["falscher_parameter"] = probe(chat(m, temperature=-5))
|
|
d["warm"] = probe(chat(m))
|
|
d["instanzen_geladen"] = [{k: i.get(k) for k in ("model", "state", "vram_mb", "gpus")} for i in instances()]
|
|
t = time.time()
|
|
while instances() and time.time() - t < 150:
|
|
time.sleep(5)
|
|
time.sleep(3)
|
|
d["entladen"] = {"s": round(time.time() - t), "instanzen": len(instances()), **gpu()}
|
|
emit(d)
|
|
|
|
main()
|