tool-bench: Anthropic·Gemini(OpenAI 호환) 어댑터, HTTP 오류 표시
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
396eaea309
commit
b0dbdc5f50
1 file changed
+89
-11
+89
-11
@@ -12,7 +12,7 @@
|
||||
|
||||
사용: python3 scripts/tool-bench.py [--models a,b,c] [--out file.json] [--endpoint http://localhost:11434]
|
||||
"""
|
||||
import argparse, json, re, sys, time, urllib.request, concurrent.futures as cf
|
||||
import argparse, json, os, re, sys, time, urllib.error, urllib.request, concurrent.futures as cf
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"gemma4:31b-cloud", "kimi-k3:cloud", "glm-5.3:cloud", "glm-5.3-flash:cloud",
|
||||
@@ -108,14 +108,84 @@ CASES = [
|
||||
final=lambda t: ("121932631112635269" in t.replace(",", ""), "정확한 값 인용")),
|
||||
]
|
||||
|
||||
def chat(endpoint, model, messages, timeout=150):
|
||||
body = {"model": model, "messages": messages, "tools": TOOLS, "stream": False,
|
||||
"options": {"temperature": 0}}
|
||||
req = urllib.request.Request(endpoint + "/api/chat", json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
t = time.time()
|
||||
def _post(url, body, headers, timeout):
|
||||
req = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json", **headers})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
data = json.loads(r.read())
|
||||
return data.get("message") or {}, time.time() - t
|
||||
return json.loads(r.read())
|
||||
|
||||
def _chat_ollama(endpoint, model, messages, timeout):
|
||||
data = _post(endpoint + "/api/chat", {"model": model, "messages": messages, "tools": TOOLS, "stream": False,
|
||||
"options": {"temperature": 0}}, {}, timeout)
|
||||
return data.get("message") or {}
|
||||
|
||||
def _chat_anthropic(model, messages, timeout):
|
||||
"""Ollama식 메시지 목록을 Anthropic Messages API 형식으로 바꿔 호출하고, 결과를 Ollama식으로 되돌린다."""
|
||||
key = os.environ["ANTHROPIC_API_KEY"]
|
||||
system = "".join(m["content"] for m in messages if m["role"] == "system")
|
||||
out, pending = [], []
|
||||
def flush():
|
||||
if pending:
|
||||
out.append({"role": "user", "content": list(pending)}); pending.clear()
|
||||
for m in messages:
|
||||
if m["role"] == "system":
|
||||
continue
|
||||
if m["role"] == "tool":
|
||||
pending.append({"type": "tool_result", "tool_use_id": m.get("tool_call_id") or "", "content": m["content"]})
|
||||
continue
|
||||
flush()
|
||||
if m["role"] == "assistant" and m.get("tool_calls"):
|
||||
blocks = ([{"type": "text", "text": m["content"]}] if m.get("content") else [])
|
||||
for tc in m["tool_calls"]:
|
||||
blocks.append({"type": "tool_use", "id": tc.get("id") or "", "name": tc["function"]["name"],
|
||||
"input": tc["function"].get("arguments") or {}})
|
||||
out.append({"role": "assistant", "content": blocks})
|
||||
else:
|
||||
out.append({"role": m["role"], "content": m["content"] or "."})
|
||||
flush()
|
||||
tools = [{"name": t["function"]["name"], "description": t["function"]["description"],
|
||||
"input_schema": t["function"]["parameters"]} for t in TOOLS]
|
||||
data = _post("https://api.anthropic.com/v1/messages",
|
||||
{"model": model, "max_tokens": 1024, "temperature": 0, "system": system, "messages": out, "tools": tools},
|
||||
{"x-api-key": key, "anthropic-version": "2023-06-01"}, timeout)
|
||||
text = "".join(b.get("text", "") for b in data.get("content", []) if b.get("type") == "text")
|
||||
tcs = [{"id": b["id"], "function": {"name": b["name"], "arguments": b.get("input") or {}}}
|
||||
for b in data.get("content", []) if b.get("type") == "tool_use"]
|
||||
return {"content": text, "tool_calls": tcs}
|
||||
|
||||
def _chat_openai_compat(base, key, model, messages, timeout):
|
||||
msgs = []
|
||||
for m in messages:
|
||||
if m["role"] == "tool":
|
||||
msgs.append({"role": "tool", "tool_call_id": m.get("tool_call_id") or "", "content": m["content"]})
|
||||
elif m["role"] == "assistant" and m.get("tool_calls"):
|
||||
msgs.append({"role": "assistant", "content": m.get("content") or None, "tool_calls": [
|
||||
{"id": tc.get("id") or "", "type": "function",
|
||||
"function": {"name": tc["function"]["name"], "arguments": json.dumps(tc["function"].get("arguments") or {}, ensure_ascii=False)}}
|
||||
for tc in m["tool_calls"]]})
|
||||
else:
|
||||
msgs.append({"role": m["role"], "content": m["content"]})
|
||||
data = _post(base + "/chat/completions", {"model": model, "messages": msgs, "tools": TOOLS, "temperature": 0},
|
||||
{"Authorization": "Bearer " + key}, timeout)
|
||||
msg = data["choices"][0]["message"]
|
||||
tcs = []
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
args = tc["function"].get("arguments") or "{}"
|
||||
try: args = json.loads(args) if isinstance(args, str) else args
|
||||
except Exception: args = {"_raw": args}
|
||||
tcs.append({"id": tc.get("id") or "", "function": {"name": tc["function"]["name"], "arguments": args}})
|
||||
return {"content": msg.get("content") or "", "tool_calls": tcs}
|
||||
|
||||
def chat(endpoint, model, messages, timeout=150):
|
||||
"""model 표기: 'anthropic:claude-...' / 'google:gemini-...' / 그 외는 Ollama."""
|
||||
t = time.time()
|
||||
if model.startswith("anthropic:"):
|
||||
msg = _chat_anthropic(model.split(":", 1)[1], messages, timeout)
|
||||
elif model.startswith("google:"):
|
||||
msg = _chat_openai_compat("https://generativelanguage.googleapis.com/v1beta/openai", os.environ["GEMINI_API_KEY"],
|
||||
model.split(":", 1)[1], messages, timeout)
|
||||
else:
|
||||
msg = _chat_ollama(endpoint, model, messages, timeout)
|
||||
return msg, time.time() - t
|
||||
|
||||
def run_model(endpoint, model, repeat=1):
|
||||
res, lat = [], []
|
||||
@@ -137,7 +207,7 @@ def run_model(endpoint, model, repeat=1):
|
||||
msgs.append({"role": "assistant", "content": cur.get("content") or "", "tool_calls": tcs})
|
||||
for x in tcs:
|
||||
nm = x["function"]["name"]; called.add(nm)
|
||||
msgs.append({"role": "tool", "tool_name": nm, "content": results.get(nm, "OK")})
|
||||
msgs.append({"role": "tool", "tool_name": nm, "tool_call_id": x.get("id") or "", "content": results.get(nm, "OK")})
|
||||
cur, dtn = chat(endpoint, model, msgs); lat.append(dtn)
|
||||
called |= {n for n, _ in calls(cur)}
|
||||
text = cur.get("content") or ""
|
||||
@@ -147,12 +217,18 @@ def run_model(endpoint, model, repeat=1):
|
||||
row["note"] += f" | 최종: {note2} " + ("✓" if ok2 else "✗")
|
||||
row["final_text"] = text[:200]
|
||||
row["ok"] = bool(ok)
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read()[:160].decode("utf-8", "replace").replace("\n", " ")
|
||||
row["note"] = f"오류: HTTP {e.code} {body}"
|
||||
except Exception as e:
|
||||
row["note"] = f"오류: {str(e)[:80]}"
|
||||
res.append(row)
|
||||
return {"model": model, "score": sum(r["ok"] for r in res), "total": len(res),
|
||||
"avg_s": round(sum(lat) / len(lat), 1) if lat else None, "rows": res}
|
||||
|
||||
def _short(m):
|
||||
return m.replace('anthropic:', '').replace('google:', '').split(':')[0].replace('claude-', '')[:9]
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--models", default=",".join(DEFAULT_MODELS))
|
||||
@@ -168,13 +244,15 @@ def main():
|
||||
for f in cf.as_completed(futs):
|
||||
r = f.result(); results.append(r)
|
||||
print(f"[done] {r['model']}: {r['score']}/{r['total']} 평균 {r['avg_s']}s", flush=True)
|
||||
errs = {x['note'] for x in r['rows'] if x['note'].startswith('오류')}
|
||||
if errs: print(f" 오류 예: {sorted(errs)[0]}", flush=True)
|
||||
results.sort(key=lambda r: (-r["score"], r["avg_s"] or 999))
|
||||
print("\n=== 순위 ===")
|
||||
for r in results:
|
||||
print(f"{r['score']:>2}/{r['total']} {r['avg_s']:>5}s {r['model']}")
|
||||
print(f"{r['score']:>2}/{r['total']} {str(r['avg_s']) + 's':>6} {r['model']}" + (f" ⚠ {r['rows'][0]['note']}" if r['score'] == 0 else ""))
|
||||
ids = [c["id"] for c in CASES]
|
||||
print("\n=== 케이스별 (통과/시도) ===")
|
||||
print("케이스".ljust(22) + " ".join(r["model"].split(":")[0][:9].ljust(9) for r in results))
|
||||
print("케이스".ljust(22) + " ".join(_short(r["model"]).ljust(9) for r in results))
|
||||
for cid in ids:
|
||||
cells = []
|
||||
for r in results:
|
||||
|
||||
Reference in new issue
Block a user