Files
Negotiation_daegu/eval/01_win_rate/run_split.py
T
민헌andClaude Fable 5.1 cb737b9a11 저장소 재편 — results/ 폐지, eval/<지표>/ 통합, 최저가 탐색 엔진 server/ 이동
- results/ 를 없애고 지표별 eval/<NN_지표>/ 에 측정 코드·result.json·detail.jsonl·실행 원본·provenance.md 를 모음 (요약은 eval/SUMMARY.md)
- 입력은 testdata/ 로 통일: 0_server_logs_frozen(동결본)·2_total_data(②)·8_items1000_master(⑧ 시험 데이터)
- ⑧ 은 입력 8_items1000_master.xlsx 1개 + 검수 완료 items1000.xlsx 1개만 남김 (실행 원본·캐시·모집단은 저장소 밖 보관)
- prism_core + capture_local → server/services/price_search (데모 API 와 측정 하네스가 같은 엔진 사용, sys.path 해킹 제거)
- 엔진 의존성(selectolax·Pillow·openpyxl) server/requirements.txt 로 통합, docker-compose 는 eval·testdata 만 마운트
- prism_core 주석·독스트링 1~2줄로 축약 (AST 동일성 검증)
- 데모 콘솔 최저가 검색 패널(PriceSearchPanel) 추가

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 11:34:07 +09:00

158 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""① 본측정 오케스트레이터 — OpenAI 3종 분할 측정.
계획서 목표 근거("LLM 협상 시뮬레이션 상위 세 개 모델 평균")에 맞춰 케이스를
3개 모델에 블록 분할(모델당 100건, 총 300건 — 2026-08-28 축소 결정)하고,
모델별 결과 + 3모델 통합을 집계한다.
※ 블록 분할 이유: 테스트셋이 27개 조합(유통×파트너×매출) 순환 구조라 교차 분할(id%3)을
쓰면 모델당 9개 조합만 배정된다. 연속 블록 333건이면 27조합이 각 ~12회씩 온전히 돈다.
사용:
python run_split.py # 새 측정 (본측정_YYYYMMDD/ 폴더 생성)
python run_split.py --resume --dir 본측정_20260828 # 중단 지점부터 재개
기록:
<폴더>/detail_<모델>.jsonl 건별 상세 (케이스마다 즉시 append — 중단 안전)
<폴더>/log_<모델>.txt 진행 로그 (25건마다 중간집계 포함, tail -f 가능)
<폴더>/result_<모델>.json 모델별 집계
<폴더>/result.json 3모델 통합 (모델별 breakdown + 가중평균 + ①③ 판정)
<폴더>/meta.json 측정 조건 (모델·분할·seed·시작/종료 시각)
"""
import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).parent
# 축소 설계 (2026-08-28 사용자 결정): 모델당 100건 × 3 = 총 300건
# 연속 블록 100건이면 27조합(유통×파트너×매출)이 각 3~4회씩 돌아 모델별 커버리지 유지
MODELS = [
("gpt-4o", "1:100"),
("gpt-4.1", "101:200"),
("gpt-4o-mini", "201:300"),
]
TESTSET = "testset_300.json"
TARGET_RATE, TARGET_REDUCTION = 70.0, 3.0
def run_model(model: str, case_range: str, out_dir: Path, resume: bool) -> int:
tag = model.replace(".", "_")
log_path = out_dir / f"log_{tag}.txt"
cmd = [sys.executable, str(HERE / "run.py"),
"--opponent", "llm", "--model", model,
"--testset", TESTSET, "--case-range", case_range,
"--out-dir", str(out_dir), "--tag", tag]
if resume:
cmd.append("--resume")
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} ({case_range}) 시작 → {log_path.name}",
flush=True)
with open(log_path, "a", encoding="utf-8") as log:
log.write(f"\n===== {datetime.now().isoformat()} {model} {case_range} =====\n")
log.flush()
rc = subprocess.call(cmd, stdout=log, stderr=subprocess.STDOUT)
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} 종료 (rc={rc})", flush=True)
return rc
def aggregate(out_dir: Path) -> dict:
per_model, all_details = {}, []
for model, case_range in MODELS:
tag = model.replace(".", "_")
detail_path = out_dir / f"detail_{tag}.jsonl"
rows = []
if detail_path.exists():
rows = [json.loads(x) for x in
detail_path.read_text(encoding="utf-8").splitlines() if x.strip()]
all_details.extend(rows)
n = len(rows)
s = sum(1 for r in rows if r.get("success"))
reds = [r["reduction_pct"] for r in rows if r.get("reduction_pct") is not None]
per_model[model] = {
"case_range": case_range, "n": n, "success": s,
"win_rate_pct": round(100 * s / n, 2) if n else None,
"avg_reduction_pct": round(sum(reds) / len(reds), 3) if reds else None,
"상품가_이하": sum(1 for r in rows if r.get("success_product")),
"앵커가_합의": sum(1 for r in rows if r.get("success_engine")),
}
total = len(all_details)
success = sum(1 for r in all_details if r.get("success"))
reds = [r["reduction_pct"] for r in all_details if r.get("reduction_pct") is not None]
rate = round(100 * success / total, 2) if total else 0.0
avg_red = round(sum(reds) / len(reds), 3) if reds else 0.0
model_rates = [m["win_rate_pct"] for m in per_model.values() if m["win_rate_pct"] is not None]
return {
"설계": "OpenAI 상위 3종 분할 측정 — 계획서 근거 '상위 세 개 모델 평균'(arxiv 2402.05863) 대응",
"testset": TESTSET, "seed": 20260828, "profiling": False,
"모델별": per_model,
"지표①_협상성공률": {
"판정기준": "목표가 이하 제안 확보",
"total": total, "success": success,
"win_rate_pct_통합": rate,
"win_rate_pct_3모델단순평균": round(sum(model_rates) / len(model_rates), 2)
if len(model_rates) == len(MODELS) else None,
"target_pct": TARGET_RATE,
"verdict": "PASS" if rate >= TARGET_RATE else "FAIL",
"참고지표": {
"상품가_이하_확보(계획서 기준: 손해 없는 협상)":
sum(1 for r in all_details if r.get("success_product")),
"앵커가_도달_합의":
sum(1 for r in all_details if r.get("success_engine")),
},
},
"지표③_평균가격협상률": {
"산식": "협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균",
"합의건수": len(reds), "avg_reduction_pct": avg_red,
"target_pct": TARGET_REDUCTION,
"verdict": "PASS" if avg_red >= TARGET_REDUCTION else "FAIL",
},
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dir", default=None, help="측정 폴더 (기본: 본측정_YYYYMMDD)")
ap.add_argument("--resume", action="store_true")
args = ap.parse_args()
out_dir = HERE / (args.dir or f"본측정_{datetime.now().strftime('%Y%m%d')}")
out_dir.mkdir(parents=True, exist_ok=True)
meta_path = out_dir / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {
"설계": "OpenAI 3종 블록 분할 — 모델당 100건 (1~100/101~200/201~300)",
"models": dict(MODELS), "testset": TESTSET, "seed": 20260828,
"profiling": False, "시작": datetime.now().isoformat(),
}
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
for model, case_range in MODELS:
rc = run_model(model, case_range, out_dir, resume=args.resume)
# 모델 하나 끝날 때마다 통합 결과 갱신 (중간에도 result.json이 항상 최신)
result = aggregate(out_dir)
(out_dir / "result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
if rc == 3: # 크레딧 소진 — 다음 모델로 넘어가지 않고 전체 중단
print("[중단] OpenAI 크레딧 소진 — 충전 후 `python3 run_split.py "
f"--dir {out_dir.name} --resume` 로 재개", flush=True)
raise SystemExit(3)
meta["종료"] = datetime.now().isoformat()
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
result = aggregate(out_dir)
print()
print(json.dumps({"모델별": result["모델별"],
"①": result["지표①_협상성공률"]["win_rate_pct_통합"],
"③": result["지표③_평균가격협상률"]["avg_reduction_pct"]},
ensure_ascii=False, indent=1))
if __name__ == "__main__":
main()