Files
Negotiation_daegu/eval/01_win_rate/run.py
T
민헌andClaude Opus 5 f59ee53689 ① 실행 출력에서 ③ 표시 제거 — 정본이 아닌 값이 요약에 섞이지 않게
③은 2026-09-10 부터 eval/03_price_reduction/ 의 단독 측정이 정본이다.
①의 실행기는 가격 인하율을 부산물로 계속 계산해 result.json 에 남기지만,
화면 요약에 함께 찍히면 ③ 정본처럼 읽힌다.

run.py      요약 배너 제목을 "① 협상 성공률 — 평가 요약" 로, ③ 줄 삭제
            25건마다 찍던 중간집계에서도 ③ 제거
            독스트링에 ③ 정본 위치를 명시
run_split.py 3모델 종료 출력에서 ③ 제거

집계 로직과 result.json 스키마는 그대로다(화면 출력만 정리).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 13:14:01 +09:00

515 lines
27 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""① 협상 성공률 — 독립 실행 평가기.
NEGO_AGENT 서버(:3300 /v1/nego/chat)를 상대로, 공급사 역할 에이전트가 자동 협상을 수행한다.
구성:
../../testdata/*_data_testset_*.json 합성 케이스셋 (generate_testset.py 산출)
run.py 공급사 에이전트(scripted|llm) + 협상 루프 + 집계
사용:
python run.py --testset 00_data_testset_300.json --limit 3 # scripted (결정적, API 키 불필요)
python run.py --testset 00_data_testset_300.json --opponent llm # GPT-4o 상대 (OPENAI_API_KEY, seed 고정)
출력:
detail.jsonl 건별 상세 (라운드별 step/가격 흐름 포함)
result.json 집계 — ① 성공률(목표 70%). 가격 인하율도 부산물로 함께 기록되지만
③의 정본은 eval/03_price_reduction/ 의 단독 측정분이다
판정:
① 주판정 = 목표가 이하 제안 확보 (협상 과정에서 target 이하 제안을 받아냄)
참고: 상품가 이하 확보(손해 없는 협상) / 앵커가 도달 협상완료(엔진 룰)
"""
import argparse
import json
import math
import os
import random
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
# 세션 접두 — EVAL(①③ 측정) / 그 외(⑦ 데이터 수집 등). contracts.jsonl 에서 용도를 가르는 키.
SESSION_PREFIX = "EVAL"
# 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"))
class ProfiledOpponent:
"""gpt-4o 공급사 409건(2026-09-09 수집) 분포로 보정한 규칙 기반 공급사 — 상황 프로파일 4종.
정보 조건은 LLMOpponent 와 같다(기존 공급가·원가 하한 0.90 만 앎). 케이스 id seed → 결정적.
실측 핵심: 엔진이 가격을 6~7번 묻지만 상대는 그중 0~3번만 양보하고 나머지는 같은 가격을 유지한다."""
# (이름, 배정 비율, 첫 제안 중앙/편차, 양보 횟수, 1라운드 양보 중앙, 1% 카드 수락 확률) — 실측 분포
PROFILES = [
("즉시수용", 0.11, 0.975, 0.010, 0, 0.000, 0.85),
("표준", 0.59, 0.983, 0.010, 1, 0.032, 0.82),
("버티기", 0.27, 0.989, 0.008, 2, 0.022, 0.60),
("장기", 0.03, 0.998, 0.004, 3, 0.015, 0.75),
]
RESERVE_RATIO, DECAY, SEED = 0.90, 0.8, 20260909 # 양보율은 회차마다 0.8배로 점감(실측 2.5→2.0→1.1%)
MAX_PROMPTS = 6 # 엔진이 가격을 묻는 횟수(실측 75% 가 6회)
CONC_SIGMA = 0.55 # 양보 폭 lognormal 산포(실측 Q1/Q3 = 중앙값의 0.65/1.6배)
FLOOR_JUMP = 0.07 # 마지막 양보에서 하한(0.90)까지 직행하는 비율(실측 하한 도달 9.8%)
FOLLOW_ANCHOR = 0.25 # 챗봇이 앵커 카드로 언급한 매입가를 그대로 수용하는 비율(실측 앵커가 ±0.5% 제안 22%)
_ANCHOR_RE = re.compile(r"매입 가격은 ([\d,]+)원")
def __init__(self, reserve_ratio: float = 0.90, seed: int = SEED):
self.RESERVE_RATIO, self.SEED, self._state = reserve_ratio, seed, {}
def _state_for(self, case: dict) -> dict:
key = case["id"]
if key not in self._state:
rng = random.Random(f"{self.SEED}:{key}")
u, acc = rng.random(), 0.0
prof = self.PROFILES[-1]
for pr in self.PROFILES:
acc += pr[1]
if u < acc:
prof = pr
break
name, _, f_med, f_sd, n_conc, c_med, p_acc = prof
# 양보가 일어나는 프롬프트 번호(2 이상)를 seed 로 고른다 — 나머지 프롬프트는 가격 유지
slots = sorted(rng.sample(range(2, self.MAX_PROMPTS + 1), n_conc)) if n_conc else []
self._state[key] = {
"profile": name, "slots": slots,
"first": min(1.0, max(0.95, rng.gauss(f_med, f_sd))),
"conc": min(0.12, max(0.005, c_med * math.exp(rng.gauss(0, self.CONC_SIGMA)))) if c_med else 0.0,
"floor_jump": n_conc > 0 and rng.random() < self.FLOOR_JUMP,
"follow_anchor": n_conc > 0 and rng.random() < self.FOLLOW_ANCHOR,
"accept": rng.random() < p_acc, "k": 0, "n_conc": 0}
return self._state[key]
def next_price(self, case: dict, prev_offer, script: str = "") -> int:
st = self._state_for(case)
base = float(case.get("item_price") or case.get("revenue"))
reserve = base * self.RESERVE_RATIO
st["k"] += 1
if prev_offer is None:
return int(max(base * st["first"], reserve))
if st["follow_anchor"] and st["n_conc"] < len(st["slots"]):
m = self._ANCHOR_RE.search(script or "")
if m: # 챗봇이 제시한 유통 매입가를 그대로 수용
ask = int(m.group(1).replace(",", ""))
if reserve <= ask < prev_offer:
st["n_conc"] += 1
st["follow_anchor"] = False
return ask
if st["k"] not in st["slots"]:
return int(prev_offer) # 유지
conc = st["conc"] * (self.DECAY ** st["n_conc"])
st["n_conc"] += 1
if st["floor_jump"] and st["n_conc"] == len(st["slots"]):
return int(reserve) # 마지막 양보: 하한 직행
return int(max(prev_offer * (1 - conc), reserve))
def decide_accept(self, case: dict, prev_offer, script: str = "") -> bool:
st = self._state_for(case)
base = float(case.get("item_price") or case.get("revenue"))
if prev_offer is None:
return False
return st["accept"] and int(prev_offer) * 0.99 >= base * self.RESERVE_RATIO
# ---- 협상 루프 -------------------------------------------------------------
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"{SESSION_PREFIX}-{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:3300/v1/nego/chat")
ap.add_argument("--opponent", default="scripted", choices=["scripted", "llm", "profiled"])
ap.add_argument("--testset", default="00_data_testset_300.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")
ap.add_argument("--session-prefix", default="EVAL",
help="session_id 접두 (기본 EVAL). ⑦ 수집 실행은 COLLECT 등으로 구분")
args = ap.parse_args()
global SESSION_PREFIX
SESSION_PREFIX = args.session_prefix
# [사전 점검] 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 ProfiledOpponent() if args.opponent == "profiled" 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"))
print(f"--- 중간집계 [{_dt.now().strftime('%H:%M:%S')}] {len(results)}건: "
f"① {round(100 * _s / len(results), 2)}% ---", 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 - 4))
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_msg:.1f}건")
print(f" 산출물 : result{suffix}.json · {detail_path.name}")
print("=" * W)
if __name__ == "__main__":
main()