scripts/ab-replay.py: 실제 /api/chat에 같은 질문을 모델별로 흘려 비교(세션·일별로그 정리 포함)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7e07b31b2b
commit
5835709022
1 file changed
+129
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
실제 홈클로(/api/chat, 도구 85개·실제 시스템 프롬프트·가드 전부 적용)에 같은 질문을 모델별로 흘려 비교한다.
|
||||
질문은 실사용 로그에서 뽑은 읽기 전용(부작용 없는) 질문만 쓴다.
|
||||
|
||||
- 로그인: papa 계정(메모리 파일의 자격증명 사용, 출력하지 않음) → 세션 토큰
|
||||
- 각 질문은 새 세션(ab_<모델>_<번호>)에서 실행하고 끝나면 세션 파일을 지운다
|
||||
- 일별 메모리 로그(memory/YYYY-MM-DD.md)에 쌓인 시험 흔적은 시험 전 상태로 되돌린다(그 사이 다른 기록이 끼면 그대로 둠)
|
||||
|
||||
사용: python3 scripts/ab-replay.py --models gemma4:31b-cloud,glm-5.3-flash:cloud --out ab.json
|
||||
"""
|
||||
import argparse, json, os, re, sys, time, glob, datetime, urllib.request, concurrent.futures as cf
|
||||
|
||||
BASE = "http://localhost:18789"
|
||||
USER = "papa"
|
||||
CRED_FILE = "/home/kim/.claude/projects/-srv-homeclaw/memory/project_papa_credentials.md"
|
||||
USER_DIR = "/srv/homeclaw/.smallclaw/users/papa"
|
||||
|
||||
QUESTIONS = [
|
||||
("날씨", "내일 구미 날씨 어때?"),
|
||||
("미세먼지", "오늘 서울 미세먼지"),
|
||||
("강수량", "구미 지금까지 강수량"),
|
||||
("강수량2", "경남 주요지역 누적 강수량"),
|
||||
("GPU비교", "4080이 5060 보다 얼마나 빠르지?"),
|
||||
("맛집", "구미 송정동의 파스타 전문점"),
|
||||
("논문", "치면열구전색의 치아우식 예방 효과에 대한 논문 결과 있어?"),
|
||||
("역사", "수메르 문명에 관한 최근 시각"),
|
||||
("시사", "마두로 미국에 잡혀가지 않았나?"),
|
||||
("경제수치", "미국 총 국채 규모는 얼마야?"),
|
||||
("제품성능", "DGX Spark 128GB에 젬마 dense 모델 돌리면 속도가 어느 정도 되지?"),
|
||||
("뉴스", "오늘 미국 증시 뉴스"),
|
||||
("지도", "인천 미추홀구 지도"),
|
||||
("과학(무도구)", "엔트로피와 해밀토니안은 어떤 관계이지?"),
|
||||
("상식(무도구)", "샴 고양이는 털이 적은가?"),
|
||||
("계산", "1000에서 2000 사이의 소수를 모두 찾아서 개수를 알려줘"),
|
||||
]
|
||||
|
||||
CJK = re.compile(r"[-ヿ一-鿿]")
|
||||
|
||||
|
||||
def login():
|
||||
# 비밀번호는 환경변수 HC_PASSWORD 우선(터미널에서 직접 넘김). 없으면 메모리 파일의 값을 시도한다.
|
||||
pw = os.environ.get("HC_PASSWORD")
|
||||
if not pw:
|
||||
txt = open(CRED_FILE, encoding="utf-8").read()
|
||||
pw = re.search(r"password\s*=\s*(\S+)", txt).group(1)
|
||||
req = urllib.request.Request(BASE + "/api/auth/login", json.dumps({"username": USER, "password": pw}).encode(),
|
||||
{"Content-Type": "application/json"})
|
||||
data = json.loads(urllib.request.urlopen(req, timeout=20).read())
|
||||
return data.get("token") or data.get("sessionToken")
|
||||
|
||||
|
||||
def chat_once(token, model, sid, message, timeout=240):
|
||||
body = json.dumps({"message": message, "sessionId": sid, "model": model}).encode()
|
||||
req = urllib.request.Request(BASE + "/api/chat", body,
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + token})
|
||||
t0 = time.time()
|
||||
tools, reply, tokens, err = [], "", "", None
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
ev = None
|
||||
for raw in r:
|
||||
line = raw.decode("utf-8", "replace").rstrip("\n")
|
||||
if line.startswith("event:"):
|
||||
ev = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
try:
|
||||
d = json.loads(line[5:].strip())
|
||||
except Exception:
|
||||
continue
|
||||
if ev == "tool_result" and d.get("action") and not d.get("synthetic"):
|
||||
tools.append(d["action"])
|
||||
elif ev == "token":
|
||||
tokens += d.get("text", "")
|
||||
elif ev == "done":
|
||||
reply = d.get("reply") or ""
|
||||
elif ev == "error":
|
||||
err = str(d.get("message") or d)[:150]
|
||||
except Exception as e:
|
||||
err = f"{type(e).__name__}: {str(e)[:100]}"
|
||||
return {"tools": tools, "reply": reply or tokens, "sec": round(time.time() - t0, 1), "error": err}
|
||||
|
||||
|
||||
def run_model(token, model, tag):
|
||||
out = []
|
||||
for i, (label, q) in enumerate(QUESTIONS):
|
||||
sid = f"ab_{tag}_{i}"
|
||||
r = chat_once(token, model, sid, q)
|
||||
r.update(label=label, q=q, model=model, sid=sid,
|
||||
cjk=bool(CJK.search(r["reply"])), chars=len(r["reply"]))
|
||||
out.append(r)
|
||||
print(f"[{tag}] {label}: {r['sec']}s tools={len(r['tools'])} chars={r['chars']} {r['error'] or ''}", flush=True)
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--models", default="gemma4:31b-cloud,glm-5.3-flash:cloud,kimi-k3:cloud,kimi-k2.6:cloud")
|
||||
ap.add_argument("--out", default="ab.json")
|
||||
a = ap.parse_args()
|
||||
models = [m for m in a.models.split(",") if m]
|
||||
|
||||
today = datetime.datetime.utcnow().strftime("%Y-%m-%d")
|
||||
daily = os.path.join(USER_DIR, "workspace", "memory", today + ".md")
|
||||
before = open(daily, "rb").read() if os.path.exists(daily) else None
|
||||
|
||||
token = login()
|
||||
if not token:
|
||||
sys.exit("login failed")
|
||||
results = []
|
||||
try:
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futs = [ex.submit(run_model, token, m, re.sub(r"\W", "", m.split(":")[0])) for m in models]
|
||||
for f in futs:
|
||||
results += f.result()
|
||||
finally:
|
||||
for p in glob.glob(os.path.join(USER_DIR, "**", "ab_*.json"), recursive=True):
|
||||
try: os.remove(p)
|
||||
except OSError: pass
|
||||
if before is not None and os.path.exists(daily):
|
||||
now = open(daily, "rb").read()
|
||||
if now.startswith(before):
|
||||
open(daily, "wb").write(before)
|
||||
json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1)
|
||||
print("saved", a.out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user