Files
Negotiation_daegu/eval/01_win_rate/run.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

436 lines
22 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/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_300.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:3300/v1/nego/chat")
ap.add_argument("--opponent", default="scripted", choices=["scripted", "llm"])
ap.add_argument("--testset", default="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")
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()