초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙

- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117)
- frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시)
- eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋
- results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256)
  ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99
- docker-compose.yml + run.sh: backend+frontend 일괄 기동

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
민헌andClaude Fable 5 committed 2026-08-31 13:09:52 +09:00
commit dfb9ad6e66
268 files changed
+164241

No files matched your search

+435
View File
@@ -0,0 +1,435 @@
#!/usr/bin/env python3
"""①③ 협상 성공률 · 평균 가격 협상률 — 독립 실행 평가기.
NEGO_AGENT 서버(:53117 /v1/nego/chat)를 상대로, 공급사 역할 에이전트가 자동 협상을 수행한다.
구성:
../../testdata/testset_*.json 합성 케이스셋 (generate_testset.py 산출)
run.py 공급사 에이전트(scripted|llm) + 협상 루프 + 집계
사용:
python run.py --testset testset_100.json --limit 3 # scripted (결정적, API 키 불필요)
python run.py --testset testset_1000.json --opponent llm # GPT-4o 상대 (OPENAI_API_KEY, seed 고정)
출력:
detail.jsonl 건별 상세 (라운드별 step/가격 흐름 포함)
result.json 집계 — ① 성공률(목표 70%) + ③ 평균 가격 협상률(목표 3%)
판정:
① 주판정 = 목표가 이하 제안 확보 (협상 과정에서 target 이하 제안을 받아냄)
참고: 상품가 이하 확보(손해 없는 협상) / 앵커가 도달 협상완료(엔진 룰)
③ = 성공(협상완료) 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균 (%)
"""
import argparse
import json
import os
import re
import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
TESTDATA_DIR = HERE.parent.parent / "testdata"
SERVER_CONFIG = HERE.parent.parent / "server" / "config.toml"
MAX_MESSAGES = 40
# OPENAI_API_KEY: 환경변수 → server/config.toml 순
if "OPENAI_API_KEY" not in os.environ and SERVER_CONFIG.exists():
m = re.search(r'^api_key\s*=\s*"([^"]+)"', SERVER_CONFIG.read_text(encoding="utf-8"),
re.MULTILINE)
if m and m.group(1):
os.environ["OPENAI_API_KEY"] = m.group(1)
def post(url: str, body: dict, headers: dict | None = None) -> dict:
req = urllib.request.Request(url, json.dumps(body).encode(),
{"Content-Type": "application/json", **(headers or {})})
with urllib.request.urlopen(req, timeout=120) as r:
return json.loads(r.read())
class QuotaExhausted(RuntimeError):
"""OpenAI 크레딧 소진 — 재시도 무의미, 측정 전체를 중단해야 한다."""
# ---- 공급사 역할 상대 에이전트 --------------------------------------------
class ScriptedOpponent:
"""결정적 양보 스케줄 (앵커 기준): anchor×1.10 에서 시작, 매 라운드 하한선(anchor×0.99)
방향으로 90% 양보 → 3번째 제안에서 anchor 이하 도달."""
def __init__(self, start_ratio: float = 1.10, concession: float = 0.90,
reserve_ratio: float = 0.99):
self.start_ratio, self.concession, self.reserve_ratio = \
start_ratio, concession, reserve_ratio
def next_price(self, case: dict, prev_offer, script: str = "") -> int:
anchor = float(case["anchor"])
reserve = anchor * self.reserve_ratio
if prev_offer is None:
return int(anchor * self.start_ratio)
return int(max(prev_offer - (prev_offer - reserve) * self.concession, reserve))
def decide_accept(self, case: dict, prev_offer, script: str = "") -> bool:
"""1% 추가 인하 제안 수락 여부: 인하가가 하한선 이상이면 수락 (결정적)."""
if prev_offer is None:
return False
reserve = float(case["anchor"]) * self.reserve_ratio
return int(prev_offer) * 0.99 >= reserve
class LLMOpponent:
"""GPT-4o 공급사 역할. 정보 비대칭 현실화: 구매측 내부가(target/anchor)는 비공개.
상대 하한(원가) = 기존 공급가 × reserve_ratio (기본 0.90 — 공급사 마진 여유 가정)."""
TEMP, SEED = 0.0, 20260828
PROMPT = ("당신은 B2B 공급사 영업 담당자다. 이 품목의 작년 공급가는 {base}원이고, "
"당신의 원가 하한선은 {reserve}원이다 (이 아래로 팔면 손해).\n"
"구매사(MD 챗봇)의 마지막 발화: {script}\n"
"규칙: 하한선 위에서 가능한 높은 공급가를 제시하되, 상대가 계속 인하를 요구하면 "
"라운드마다 단계적으로 양보하라. 합의가 안 되면 거래가 무산되므로 3라운드 이후에는 "
"하한선 근처까지 양보를 검토하라. 직전 제안보다 높은 가격은 제시하지 마라.\n"
"JSON만: {{\"price\": <정수>}}")
ACCEPT_PROMPT = ("당신은 B2B 공급사 영업 담당자다. 이 품목의 작년 공급가는 {base}원이고, "
"당신의 원가 하한선은 {reserve}원이다 (이 아래로 팔면 손해).\n"
"당신의 현재 제안가는 {offer}원이다.\n"
"구매사(MD 챗봇)의 마지막 발화: {script}\n"
"구매사가 위 발화에서 제시한 조건(추가 인하 등)을 수락할지 결정하라. "
"수락하면 즉시 계약이 확정되고, 거절하면 협상이 이대로 종료될 수 있다. "
"하한선 아래로 손해를 보면서 수락하지는 마라.\n"
"JSON만: {{\"accept\": true|false}}")
def __init__(self, reserve_ratio: float = 0.90, model: str = "gpt-4o"):
self.reserve_ratio = reserve_ratio
self.MODEL = model
def _ask(self, prompt: str) -> dict:
"""LLM 호출 — 일시 오류(429/5xx·말포맷 JSON)는 지수 백오프 재시도,
크레딧 소진(insufficient_quota)은 QuotaExhausted로 즉시 중단."""
import time
import urllib.error
body = {"model": self.MODEL, "temperature": self.TEMP, "seed": self.SEED,
"response_format": {"type": "json_object"},
"messages": [{"role": "user", "content": prompt}]}
last_err = None
for attempt in range(5):
try:
r = post("https://api.openai.com/v1/chat/completions", body,
{"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"})
return json.loads(r["choices"][0]["message"]["content"])
except urllib.error.HTTPError as e:
err_body = e.read().decode(errors="replace")
if "insufficient_quota" in err_body or "credit_balance_exhausted" in err_body:
raise QuotaExhausted("OpenAI 크레딧 소진 — 충전 후 --resume으로 재개")
if e.code in (429, 500, 502, 503):
wait = min(2 ** attempt * 2, 30)
print(f" [재시도 {attempt + 1}/5] HTTP {e.code} — {wait}초 대기", flush=True)
time.sleep(wait)
last_err = e
continue
raise
except (json.JSONDecodeError, KeyError, ValueError) as e:
# 모델이 말포맷 JSON을 낸 경우 — 재시도
print(f" [재시도 {attempt + 1}/5] 응답 파싱 실패: {str(e)[:60]}", flush=True)
last_err = e
continue
raise last_err
def next_price(self, case: dict, prev_offer, script: str = "") -> int:
base = case.get("item_price") or case.get("revenue")
reserve = int(float(base) * self.reserve_ratio)
out = self._ask(self.PROMPT.format(base=int(float(base)), reserve=reserve,
script=script[:500]))
price = int(out["price"])
if prev_offer is not None:
price = min(price, int(prev_offer)) # 비단조(가격 인상) 방지
return max(price, reserve)
def decide_accept(self, case: dict, prev_offer, script: str = "") -> bool:
"""와일드카드(1% 추가 인하 등) 수락 여부를 GPT-4o가 공급사 입장에서 판단."""
base = case.get("item_price") or case.get("revenue")
reserve = int(float(base) * self.reserve_ratio)
out = self._ask(self.ACCEPT_PROMPT.format(
base=int(float(base)), reserve=reserve,
offer=int(prev_offer) if prev_offer else 0, script=script[:500]))
return bool(out.get("accept"))
# ---- 협상 루프 -------------------------------------------------------------
def build_card_data(case: dict, price, anchor_v) -> dict:
"""케이스 합성 card_data + 기능정의서 산식의 동적 값.
- 경쟁사가격반영 = 100(1 − 앵커/입력가), 최소 1
- 인터넷최저가: 케이스 값 우선, 없으면 목표가 대체"""
card_data = dict(case.get("card_data") or {})
card_data["anchoring_price"] = int(anchor_v) if anchor_v else None
card_data.setdefault("internet_min_price",
int(case["target"]) if case.get("target") else None)
card_data.setdefault("alternative_supplier_count", 2)
if price and anchor_v and float(price) > 0:
card_data["competitor_price_diff"] = round(
max(100 * (1 - float(anchor_v) / float(price)), 1), 1)
return card_data
def negotiate(url: str, case: dict, opponent, profiling: bool = False) -> dict:
session_id = f"EVAL-{case['id']}"
base = {
"rq_type": "재협상", "session_id": session_id,
"item_price": case.get("item_price") or case.get("revenue"),
"revenue": case.get("revenue"), "dist": case.get("dist"),
"partners_yn": case.get("partners_yn"), "partners": case.get("partners", 0),
"anchor": case.get("anchor"), "target": case.get("target"),
"profiling": profiling,
}
index, step = 0, "시작"
user_input = price = initial = None
iteration, offer = 0, None
rounds, final_price, reached_done = [], None, False
accepted_1pct = False
anchor_v = case.get("anchor")
for _ in range(MAX_MESSAGES):
body = {**base, "index": index, "step": step, "user_input": user_input,
"input": price, "initial": initial, "iteration": iteration,
"card_data": build_card_data(case, price, anchor_v)}
res = post(url, body)
meta = res.get("chat_metadata") or {}
rounds.append({"req_step": step, "req_input": user_input, "req_price": price,
"res_step": res["step"], "input_mode": res["next_input_mode"],
"res_price": meta.get("price"),
"script_head": res["script"][:80].replace("\n", " ")})
if res["step"] == "협상완료":
reached_done, final_price = True, meta.get("price") or price
if res["chat_end"]:
break
step, index = res["step"], res["index"]
mode = res["next_input_mode"]
user_input = None
if mode == "confirm":
user_input = "확인"
elif mode == "yes_no":
if step == "wild_card_1pct":
# 1% 추가 인하 제안: 수락 여부는 공급사(상대)가 결정
ok = opponent.decide_accept(case, offer, res["script"])
user_input = "예" if ok else "아니오"
accepted_1pct = accepted_1pct or ok
else:
user_input = "예"
elif mode == "price":
offer = opponent.next_price(case, offer, res["script"])
if initial is None:
initial = offer
else:
iteration += 1
price = offer
# 세션 종료 — UCB 에피소드 초기화 (다음 케이스와 격리)
try:
post(url.replace("/chat", "/session/invalidate"),
{"session_id": session_id, "reason": "평가 케이스 종료"})
except Exception:
pass
# 판정
prices = [rd["req_price"] for rd in rounds if rd.get("req_price") is not None]
# 1% 카드 수락 시 합의가(= 직전 제안가 × 0.99)는 상대가 동의한 제안가로 판정에 포함
if accepted_1pct and final_price is not None:
prices.append(final_price)
lowest = min(prices) if prices else None
prev_price = case.get("item_price") or case.get("revenue")
success_target = bool(lowest is not None and case.get("target") is not None
and float(lowest) <= float(case["target"]))
success_product = bool(lowest is not None and prev_price is not None
and float(lowest) <= float(prev_price))
success_engine = bool(reached_done and final_price is not None
and float(final_price) <= float(case["target"]))
# ③ 가격 협상률: 협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가
reduction_pct = None
if reached_done and final_price is not None and prev_price:
reduction_pct = round(100 * (float(prev_price) - float(final_price))
/ float(prev_price), 3)
return {"case_id": case["id"], "quotation_number": case.get("quotation_number"),
"item_name": case.get("item_name"),
"success": success_target, "success_target": success_target,
"success_product": success_product, "success_engine": success_engine,
"lowest_offer": lowest, "prev_price": prev_price,
"accepted_1pct": accepted_1pct,
"target": case.get("target"), "anchor": case.get("anchor"),
"initial_offer": initial, "final_price": final_price,
"reduction_pct": reduction_pct,
"outcome": rounds[-1]["res_step"] if rounds else None,
"n_messages": len(rounds), "rounds": rounds}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int)
ap.add_argument("--url", default="http://127.0.0.1:53117/v1/nego/chat")
ap.add_argument("--opponent", default="scripted", choices=["scripted", "llm"])
ap.add_argument("--testset", default="testset_1000.json",
help="testdata/ 안의 케이스셋 파일명")
ap.add_argument("--target-rate", type=float, default=70.0, help="① 목표 성공률(%%)")
ap.add_argument("--target-reduction", type=float, default=3.0, help="③ 목표 협상률(%%)")
ap.add_argument("--profiling", action="store_true",
help="N-profiling(LLM 톤 재작성) 활성 상태로 측정 (기본 off)")
ap.add_argument("--llm-reserve-ratio", type=float, default=0.90)
ap.add_argument("--model", default="gpt-4o", help="LLM 상대 모델 (opponent=llm일 때)")
ap.add_argument("--case-range", default=None,
help="케이스 id 범위 'START:END' (양끝 포함, 예: 1:333) — 분할 측정용")
ap.add_argument("--out-dir", default=None, help="산출물 폴더 (기본: 스크립트 폴더)")
ap.add_argument("--tag", default=None, help="산출물 접미사 → detail_{tag}.jsonl, result_{tag}.json")
ap.add_argument("--resume", action="store_true",
help="기존 detail의 완료 case_id는 스킵하고 이어서 측정")
ap.add_argument("--verbose", "-v", action="store_true")
args = ap.parse_args()
# [사전 점검] NEGO_AGENT 서버 응답 확인
base_url = args.url.split("/v1/")[0]
try:
with urllib.request.urlopen(base_url + "/health", timeout=5) as r:
body = r.read().decode(errors="replace")
if "NEGO_AGENT" not in body:
raise SystemExit(f"[사전 점검 실패] {base_url}/health 가 NEGO_AGENT 서버가 아닙니다: {body[:120]}")
except SystemExit:
raise
except Exception as e:
raise SystemExit(f"[사전 점검 실패] 서버({base_url}) 연결 불가: {e}\n"
f"→ cd server && .venv/bin/python web_main.py")
data = json.loads((TESTDATA_DIR / args.testset).read_text(encoding="utf-8"))
cases = data["cases"]
if args.case_range:
lo, hi = (int(x) for x in args.case_range.split(":"))
cases = [c for c in cases if lo <= c["id"] <= hi]
cases = cases[: args.limit]
opponent = LLMOpponent(args.llm_reserve_ratio, model=args.model) \
if args.opponent == "llm" else ScriptedOpponent()
out_dir = Path(args.out_dir) if args.out_dir else HERE
out_dir.mkdir(parents=True, exist_ok=True)
suffix = f"_{args.tag}" if args.tag else ""
detail_path = out_dir / f"detail{suffix}.jsonl"
# 재개: 기존 detail에서 정상 완료 건은 스킵, '오류' 건은 버리고 재측정
done_ids, results = set(), []
if args.resume and detail_path.exists():
dropped = 0
for line in detail_path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
if str(r.get("outcome", "")).startswith("오류"):
dropped += 1
continue
done_ids.add(r["case_id"])
results.append(r)
# 오류 행 제거본으로 파일 재작성 (이후 append로 이어짐)
detail_path.write_text(
"".join(json.dumps(r, ensure_ascii=False) + "\n" for r in results),
encoding="utf-8")
print(f"[재개] 정상 완료 {len(done_ids)}건 스킵, 오류 {dropped}건 재측정 포함 "
f"남은 {len(cases) - len(done_ids)}건 진행")
else:
detail_path.write_text("", encoding="utf-8")
from datetime import datetime as _dt
for case in cases:
if case["id"] in done_ids:
continue
try:
r = negotiate(args.url, case, opponent, profiling=args.profiling)
except QuotaExhausted as e:
# 크레딧 소진: 이 케이스는 기록하지 않고 측정 전체 중단 (충전 후 --resume)
print(f"\n[중단] {e} — 완료 {len(results)}건은 보존됨", flush=True)
raise SystemExit(3)
except Exception as e:
r = {"case_id": case["id"], "quotation_number": case.get("quotation_number"),
"success": False, "outcome": f"오류: {e}", "rounds": []}
results.append(r)
with open(detail_path, "a", encoding="utf-8") as f:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
mark = "✅ 성공" if r["success"] else "❌ 실패"
print(f"[{len(results):3d}/{len(cases)}] {str(r.get('item_name') or '')[:16]:16s} "
f"{str(r.get('outcome')):8s} 최종가 {str(r.get('final_price')):>10s} "
f"/ 목표 {str(r.get('target')):>10s} {mark}", flush=True)
if args.verbose:
for rd in r.get("rounds", []):
if rd.get("req_price") is not None or rd["res_step"] in ("협상완료", "협상실패"):
print(f" {rd['req_step']:14s} 제안 {str(rd.get('req_price')):>10s} → {rd['res_step']}")
# 25건마다 중간 집계
if len(results) % 25 == 0:
_s = sum(1 for x in results if x.get("success"))
_reds = [x["reduction_pct"] for x in results if x.get("reduction_pct") is not None]
_avg = round(sum(_reds) / len(_reds), 3) if _reds else 0.0
print(f"--- 중간집계 [{_dt.now().strftime('%H:%M:%S')}] {len(results)}건: "
f"① {round(100 * _s / len(results), 2)}% · ③ {_avg}% ---", flush=True)
# 집계
total = len(results)
success = sum(1 for r in results if r["success"])
success_prod = sum(1 for r in results if r.get("success_product"))
success_eng = sum(1 for r in results if r.get("success_engine"))
rate = round(100 * success / total, 2) if total else 0.0
reductions = [r["reduction_pct"] for r in results if r.get("reduction_pct") is not None]
avg_reduction = round(sum(reductions) / len(reductions), 3) if reductions else 0.0
out = {
"opponent": args.opponent, "testset": args.testset, "profiling": args.profiling,
"total": total,
"지표①_협상성공률": {
"판정기준": "목표가 이하 제안 확보",
"success": success, "win_rate_pct": rate,
"target_pct": args.target_rate,
"verdict": "PASS" if rate >= args.target_rate else "FAIL",
"참고지표": {
"상품가_이하_확보": {"success": success_prod,
"rate_pct": round(100 * success_prod / total, 2) if total else 0.0,
"기준": "기존 공급가 유지·인하 = 손해 없는 협상"},
"앵커가_도달_합의": {"success": success_eng,
"rate_pct": round(100 * success_eng / total, 2) if total else 0.0,
"기준": "앵커가 도달 협상완료 (엔진 룰)"},
},
},
"지표③_평균가격협상률": {
"산식": "협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균",
"합의건수": len(reductions), "avg_reduction_pct": avg_reduction,
"target_pct": args.target_reduction,
"verdict": "PASS" if avg_reduction >= args.target_reduction else "FAIL",
},
"detail_file": detail_path.name,
}
if args.opponent == "llm":
out["model"] = args.model
out["seed"] = LLMOpponent.SEED
if args.case_range:
out["case_range"] = args.case_range
(out_dir / f"result{suffix}.json").write_text(
json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
from datetime import datetime
avg_msg = sum(r.get("n_messages", 0) for r in results) / total if total else 0
W = 66
print()
print("=" * W)
print(" ①③ 협상 성공률 · 평균 가격 협상률 — 평가 요약".center(W - 12))
print("=" * W)
print(f" 시험 일시 : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f" 상대 에이전트 : " + ("scripted (결정적 양보 스케줄)" if args.opponent == "scripted"
else f"{args.model} (seed 고정)"))
print(f" 케이스 : {total}건 ({args.testset}) · profiling {'on' if args.profiling else 'off'}")
print(f" ① 협상 성공률 : {rate} % (목표 {args.target_rate} %) → "
f"{out['지표①_협상성공률']['verdict']} [성공 {success} / 실패 {total - success}]")
print(f" 참고: 상품가 이하 {success_prod}건 / 앵커가 합의 {success_eng}건")
print(f" ③ 평균 협상률 : {avg_reduction} % (목표 {args.target_reduction} %) → "
f"{out['지표③_평균가격협상률']['verdict']} [합의 {len(reductions)}건 기준]")
print(f" 평균 메시지 : {avg_msg:.1f}건")
print(f" 산출물 : result{suffix}.json · {detail_path.name}")
print("=" * W)
if __name__ == "__main__":
main()
+157
View File
@@ -0,0 +1,157 @@
#!/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_1000.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()