Files
Negotiation_daegu/eval/10_persona/negotiation.py
T
민헌andClaude Opus 5 50016ebd06 ③⑩ 단독측정 정본 반영 + 테스트데이터 지표별 명명 + ⑩ 실행기 경로 정리
③⑩ 을 09-10 단독측정으로 교체 (지표별 독립 실행기 negotiation.py, gpt-4o 1종 300건)
  ③ 5.877 → 5.784% · ⑩ 98.23 → 98.36% (253세션 1,086매칭)
  ①의 협상 기록 재집계 방식은 aggregate.py 보조 경로로 유지

run-eval.sh ⑩ 경로를 ③ 과 같은 단독측정으로 교체 (M10_REAGG=1 이면 옛 재집계)
eval/10_persona/aggregate.py
  - --out 추가 — 시험 실행이 정본 result.json·detail.jsonl 을 덮지 않게
  - 세션 대응 키를 기록의 session_id 우선으로 (EVAL-case_id 하드코딩 시
    EVAL10-* 기록이 ①의 옛 로그와 잘못 짝지어져 오답을 냈다. ① 기록은 폴백 동작 동일)

testdata 명명 규칙 <지표번호>_data_<이름>, 둘 이상이 쓰면 00_ (공용)
  testset_300 → 00_data_testset_300 · product_names → 00_data_product_names
  2_total_data → 02_data_total · 7_testset_10272 → 07_data_testset_10272
  8_items1000_master → 08_data_items1000_master
  생성기·룰(.py)은 번호 없음. 끝난 측정의 기록에는 옛 이름이 남아 있어
  testdata/README.md 에 옛↔새 대응표를 둔다

eval/SUMMARY.md 를 정본 수치와 일치시킴
③ 100건 파일럿 실행원본은 저장소 밖 _archive_20260910_실행원본/ 으로 이동

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

511 lines
25 KiB
Python
Executable File
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)를 상대로 공급사 역할 에이전트(모델 1종)가 자동 협상을
수행하고, 그 가격 궤적에서 산출한 **실제 긴장도**를 서버가 실시간으로 남긴 **예측 긴장도**와
세션·라운드 단위로 대응시켜 정확도를 낸다. 다른 지표의 코드를 호출하지 않는 독립 실행 파일이다.
산식 (계획서 원문):
정확도 = (1 − mean(세션별 mean(|실제 긴장도 − 예측 긴장도|))) × 100. 목표 96%
- 실제 (사후, 가격 기록에서 산출) = clip((제안가 − 목표가) / (초기 제안가 − 목표가), 0~1)
- 예측 (서버 실시간 계측) = 지표점수(1~99)에서 역산한 긴장도 추정치.
이 수치가 페르소나(단호한 압박형 / 균형 협상형 / 우호적 마무리형) 선택에 실제로 쓰인다.
대응: (session_id, iteration) — 서버 로그의 persona 필드 보유 행만, 중복 키는 최신 우선.
사용:
python negotiation.py # gpt-4o · 300건
python negotiation.py --model gpt-4.1 --n 50
python negotiation.py --opponent scripted --n 3 # API 키 없이 결정적 상대로 사전 확인
python negotiation.py --n 3 --out-dir /tmp/x # 정본을 건드리지 않는 시험 실행
python negotiation.py --resume --dir 단독측정_YYYYMMDD
출력:
<out>/<dir>/detail_<태그>.jsonl 협상 기록 (라운드별 제안가·목표가·초기 제안가)
<out>/<dir>/meta.json 측정 조건
<out>/detail.jsonl 라운드별 예측·실제·오차·적용 페르소나
<out>/data/persona_meta.json 산식·정의·표본 추림·페르소나 분포
<out>/result.json 세션 수 + 정확도 + PASS/FAIL
(<out> 기본값 = 이 스크립트 폴더 = 정본. --out-dir 로 옮기면 정본이 보존된다)
"""
import argparse
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from collections import Counter
from datetime import datetime
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
SESSION_PREFIX = "EVAL10" # ①(EVAL)·③(EVAL03)·⑦(COLLECT) 세션과 구분한다
ACCURACY_FORMULA = "1 − mean(세션별 mean(|실제 긴장도 − 예측 긴장도|)) — 계획서 원문 산식 (시나리오=세션)"
# 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 default_tension_log() -> Path:
"""컨테이너(/app/data)와 로컬(server/data) 어느 쪽에서 돌려도 서버 로그를 찾는다."""
for p in (Path("/app/data/tension_log.jsonl"),
HERE.parent.parent / "server" / "data" / "tension_log.jsonl"):
if p.exists():
return p
return HERE.parent.parent / "server" / "data" / "tension_log.jsonl"
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% 양보. API 키 없이 파이프라인을 확인할 때 쓴다."""
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:
if prev_offer is None:
return False
reserve = float(case["anchor"]) * self.reserve_ratio
return int(prev_offer) * 0.99 >= reserve
class LLMOpponent:
"""OpenAI 모델 1종에 공급사 영업 담당자 역할을 부여한다.
구매측 내부가(target/anchor)는 프롬프트에 넣지 않는다 (정보 비대칭 현실화)."""
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, model: str = "gpt-4o", reserve_ratio: float = 0.90):
self.MODEL = model
self.reserve_ratio = reserve_ratio
def _ask(self, prompt: str) -> dict:
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:
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:
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 = 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
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":
user_input = "예" if opponent.decide_accept(case, offer, res["script"]) else "아니오"
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
return {"case_id": case["id"], "session_id": session_id,
"quotation_number": case.get("quotation_number"),
"item_name": case.get("item_name"),
"target": case.get("target"), "anchor": case.get("anchor"),
"initial_offer": initial, "final_price": final_price,
"agreed": reached_done and final_price is not None,
"outcome": rounds[-1]["res_step"] if rounds else None,
"n_messages": len(rounds), "rounds": rounds}
# ---- 긴장도 대응·집계 -------------------------------------------------------
def clip01(v: float) -> float:
return max(0.0, min(1.0, v))
def load_predicted(path: Path) -> dict:
"""(session_id, iteration) → {predicted, persona, indicator}.
persona 필드를 가진 신형 행만 쓰고, 중복 키는 최신 우선."""
pred = {}
if not path.exists():
return pred
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
if "persona" not in r: # 구형(잠정 산식 시절) 행 제외
continue
pred[(r["session_id"], r["iteration"])] = r
return pred
def actual_entries(row: dict):
"""협상 기록 한 건에서 (iteration, 실제 긴장도) 재구성 —
동적 스텝 진입(res_step == '가격협상') 시점의 제안가 기준."""
target, initial = row.get("target"), row.get("initial_offer")
if not target or not initial or float(initial) <= float(target):
return None # 긴장도 정의 불가 (초기 제안가 ≤ 목표가)
out, k = [], 0
for rd in row.get("rounds", []):
if rd.get("res_step") == "가격협상" and rd.get("req_price") is not None:
out.append((k, clip01((float(rd["req_price"]) - float(target))
/ (float(initial) - float(target)))))
k += 1
return out
def aggregate(results: list, tension_log: Path, out_root: Path,
source_desc: str, target: float) -> dict:
pred = load_predicted(tension_log)
session_diffs, persona_counter = {}, Counter()
matched = missing = undefined_sessions = 0
detail_out = []
for row in results:
if str(row.get("outcome", "")).startswith("오류"):
continue
entries = actual_entries(row)
if entries is None:
undefined_sessions += 1
continue
session = row["session_id"]
for k, actual in entries:
p = pred.get((session, k))
if p is None:
missing += 1
continue
matched += 1
diff = abs(p["predicted"] - actual)
session_diffs.setdefault(session, []).append(diff)
persona_counter[p["persona"]] += 1
detail_out.append({"session_id": session, "iteration": k,
"predicted": p["predicted"], "actual": round(actual, 4),
"diff": round(diff, 4), "indicator": p.get("indicator"),
"persona": p["persona"]})
if not session_diffs:
sys.exit("예측 긴장도와 대응된 라운드가 없습니다 — 서버 로그 경로를 확인하세요: "
f"{tension_log}")
session_means = {s: sum(d) / len(d) for s, d in session_diffs.items()}
overall = sum(session_means.values()) / len(session_means)
accuracy_pct = round(100 * (1 - overall), 2)
verdict = "PASS" if accuracy_pct >= target else "FAIL"
out_root.mkdir(parents=True, exist_ok=True)
data_dir = out_root / "data"
data_dir.mkdir(exist_ok=True)
(data_dir / "persona_meta.json").write_text(json.dumps({
"출처": source_desc,
"산식": ACCURACY_FORMULA,
"예측": "서버 실시간: 지표점수(1~99)→긴장도 역산 추정치 (페르소나 적용에 사용된 수치)",
"실제": "사후: clip((제안가−목표가)/(초기제안가−목표가)) — 협상 기록의 가격 궤적 기준",
"서버로그": str(tension_log),
"표본추림": {"집계_세션": len(session_means), "매칭_라운드": matched,
"미매칭_라운드": missing,
"제외_정의불가_세션(초기제안가≤목표가)": undefined_sessions},
"페르소나_적용분포": dict(persona_counter),
"평균오차": round(overall, 4),
"목표_pct": target,
"verdict": verdict,
}, ensure_ascii=False, indent=1), encoding="utf-8")
with open(out_root / "detail.jsonl", "w", encoding="utf-8") as f:
for r in detail_out:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
result = {
"협상 건수": len(results),
"집계 세션": len(session_means),
"제외_정의불가_세션": undefined_sessions,
"제외사유": "초기 제안가 ≤ 목표가 — 긴장도 분모(초기 제안가 − 목표가)가 0 이하라 정의 불가",
"오류 건수": sum(1 for r in results if str(r.get("outcome", "")).startswith("오류")),
"매칭 라운드": matched,
"미매칭 라운드": missing,
"평균오차": round(overall, 4),
"산식": ACCURACY_FORMULA,
"페르소나_적용분포": dict(persona_counter),
"페르소나정확도_pct": accuracy_pct,
"목표_pct": target,
"verdict": verdict,
"상세": "data/persona_meta.json",
}
(out_root / "result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
return result
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
ap.add_argument("--model", default="gpt-4o", help="공급사 역할 LLM 1종 (기본 gpt-4o)")
ap.add_argument("--opponent", default="llm", choices=["llm", "scripted"],
help="상대 에이전트 (기본 llm — scripted 는 API 키 없이 도는 결정적 상대)")
ap.add_argument("--n", type=int, default=300, help="협상 케이스 수 (기본 300)")
ap.add_argument("--case-range", default=None,
help="케이스 id 범위 'START:END' — 지정하면 --n 보다 우선한다")
ap.add_argument("--testset", default="00_data_testset_300.json", help="testdata/ 안의 케이스셋 파일명")
ap.add_argument("--url", default="http://127.0.0.1:3300/v1/nego/chat")
ap.add_argument("--tension-log", default=None,
help="서버 예측 긴장도 로그 (기본: /app/data 또는 server/data 자동 탐색)")
ap.add_argument("--dir", default=None, help="협상 기록 폴더명 (기본 단독측정_YYYYMMDD)")
ap.add_argument("--out-dir", default=None,
help="산출 위치 (기본: 이 스크립트 폴더 = 정본). 시험 실행은 다른 경로를 준다")
ap.add_argument("--target", type=float, default=96.0, help="목표 정확도(%%)")
ap.add_argument("--llm-reserve-ratio", type=float, default=0.90)
ap.add_argument("--profiling", action="store_true")
ap.add_argument("--resume", action="store_true",
help="기존 협상 기록의 완료 case_id 는 스킵하고 이어서 측정")
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}")
tension_log = Path(args.tension_log) if args.tension_log else default_tension_log()
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]
else:
cases = cases[: args.n]
opponent = (LLMOpponent(args.model, args.llm_reserve_ratio) if args.opponent == "llm"
else ScriptedOpponent())
tag = args.model.replace(".", "_") if args.opponent == "llm" else args.opponent
out_root = Path(args.out_dir) if args.out_dir else HERE
run_dir = out_root / (args.dir or f"단독측정_{datetime.now():%Y%m%d}")
run_dir.mkdir(parents=True, exist_ok=True)
detail_path = run_dir / f"detail_{tag}.jsonl"
results = []
if args.resume and detail_path.exists():
results = [json.loads(l) for l in detail_path.read_text(encoding="utf-8").splitlines()
if l.strip() and not str(json.loads(l).get("outcome", "")).startswith("오류")]
done = {r["case_id"] for r in results}
cases = [c for c in cases if c["id"] not in done]
detail_path.write_text(
"".join(json.dumps(r, ensure_ascii=False) + "\n" for r in results), encoding="utf-8")
print(f"[재개] 완료 {len(results)}건 유지 · 남은 {len(cases)}건 측정", flush=True)
else:
detail_path.write_text("", encoding="utf-8")
started = datetime.now()
W = 66
print("=" * W)
print(" ⑩ 실시간 페르소나 정확도 — 단독 측정")
print(f" 상대 에이전트 : {args.model + ' (seed 고정)' if args.opponent == 'llm' else 'scripted (결정적 양보 스케줄)'}")
print(f" 케이스 : {len(cases)}건 ({args.testset}) · profiling {'on' if args.profiling else 'off'}")
print(f" 협상 기록 : {detail_path}")
print(f" 서버 로그 : {tension_log}")
print(f" 집계 산출 : {out_root}")
print("=" * W, flush=True)
for i, case in enumerate(cases, 1):
try:
r = negotiate(args.url, case, opponent, args.profiling)
except QuotaExhausted as e:
print(f"\n[중단] {e}", flush=True)
break
except Exception as e:
r = {"case_id": case["id"], "session_id": f"{SESSION_PREFIX}-{case['id']}",
"item_name": case.get("item_name"), "target": case.get("target"),
"initial_offer": None, "final_price": None, "agreed": False,
"outcome": f"오류: {e}", "n_messages": 0, "rounds": []}
results.append(r)
with open(detail_path, "a", encoding="utf-8") as f:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
n_price = sum(1 for rd in r.get("rounds", []) if rd.get("res_step") == "가격협상"
and rd.get("req_price") is not None)
print(f"[{i:3d}/{len(cases)}] {str(r.get('item_name'))[:18]:20s} "
f"{str(r.get('outcome')):8s} 가격라운드 {n_price:2d} "
f"초기제안 {str(r.get('initial_offer')):>10s} / 목표 {str(r.get('target')):>10s}", flush=True)
if len(results) % 25 == 0:
print(f"--- 진행 [{datetime.now():%H:%M:%S}] {len(results)}건 ---", flush=True)
(run_dir / "meta.json").write_text(json.dumps({
"설계": "⑩ 단독 측정 — 모델 1종으로 협상을 직접 수행하고 긴장도를 대응·집계 (다른 지표 코드 비의존)",
"opponent": args.opponent,
"model": args.model if args.opponent == "llm" else None,
"seed": LLMOpponent.SEED if args.opponent == "llm" else None,
"session_prefix": SESSION_PREFIX,
"testset": args.testset,
"케이스": args.case_range or f"1:{args.n}",
"profiling": args.profiling,
"url": args.url,
"tension_log": str(tension_log),
"목표_pct": args.target,
"시작": started.isoformat(),
"종료": datetime.now().isoformat(),
}, ensure_ascii=False, indent=1), encoding="utf-8")
print("\n--- 긴장도 대응·집계 ---", flush=True)
result = aggregate(results, tension_log, out_root,
f"{run_dir.name}/{detail_path.name} — 전체 {len(results)}건", args.target)
print()
print("=" * W)
print(" ⑩ 실시간 페르소나 정확도 — 단독 측정 요약".center(W - 10))
print("=" * W)
print(f" 시험 일시 : {started:%Y-%m-%d %H:%M:%S}")
print(f" 상대 에이전트 : {args.model + ' (seed 고정)' if args.opponent == 'llm' else 'scripted'}")
print(f" 협상 케이스 : {len(results)}건 ({args.testset}) · profiling {'on' if args.profiling else 'off'}")
print(f" ⑩ 페르소나 정확도: {result['페르소나정확도_pct']} % (목표 {args.target} %) → "
f"{result['verdict']} [집계 세션 {result['집계 세션']} · 매칭 라운드 {result['매칭 라운드']}]")
print(f" 제외 : {result['제외_정의불가_세션']}건 (초기 제안가 ≤ 목표가 — 긴장도 정의 불가) · "
f"오류 {result['오류 건수']}건 · 미매칭 라운드 {result['미매칭 라운드']}")
print(f" 평균 오차 : {result['평균오차']}")
print(f" 산출물 : {out_root}/result.json · detail.jsonl · data/persona_meta.json")
print(f" {detail_path}")
print("=" * W)
sys.exit(0 if result["verdict"] == "PASS" else 1)
if __name__ == "__main__":
main()