#!/usr/bin/env python3 """③ 평균 가격 협상률 — 단독 실행 측정기. NEGO_AGENT 서버(:3300 /v1/nego/chat)를 상대로, 공급사 역할 에이전트(모델 1종)가 자동 협상을 수행하고 그 결과에서 가격 협상률을 산출한다. 다른 지표의 코드를 호출하지 않는 독립 실행 파일이다. 산식: 건별 협상률 = (기존 공급가 − 최종 합의가) / 기존 공급가 × 100 협상완료(합의) 건의 **단순 평균**(건별 비율의 평균). 목표 3%. 계획서 평가방법 "협상 성공 품목의 품목별 공급가를 낮춘 비율" 대응. 사용: python negotiation.py # gpt-4o · 100건 python negotiation.py --model gpt-4.1 --n 50 python negotiation.py --opponent scripted # API 키 없이 결정적 상대로 사전 확인 python negotiation.py --n 3 --out-dir /tmp/x # 정본을 건드리지 않는 시험 실행 python negotiation.py --resume --dir 단독측정_20260910 출력: //detail_<태그>.jsonl 건별 상세 (라운드별 제안가·최종 합의가·협상률) //meta.json 측정 조건 (모델·건수·seed·시작/종료) /data/reduction_all.csv 건별 원자료 (기존공급가·합의가·협상률) /data/reduction_all_meta.json 산식·분포 /result.json 건수 + 평균 협상률 + PASS/FAIL ( 기본값 = 이 스크립트 폴더 = 정본. --out-dir 로 옮기면 정본이 보존된다) """ import argparse import csv import json import os import re import statistics import sys import time import urllib.error import urllib.request 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 = "EVAL03" # ①(EVAL)·⑦(COLLECT)의 세션과 구분한다 FORMULA = "건별 가격 협상률 = (기존 공급가 − 최종 합의가) ÷ 기존 공급가 × 100, 협상완료 건의 단순 평균" # 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 이하 도달. 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)는 프롬프트에 넣지 않는다. 상대 하한(원가) = 기존 공급가 × 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, model: str = "gpt-4o", reserve_ratio: float = 0.90): self.MODEL = model self.reserve_ratio = reserve_ratio def _ask(self, prompt: str) -> dict: """LLM 호출 — 일시 오류(429/5xx·말포맷 JSON)는 지수 백오프 재시도, 크레딧 소진(insufficient_quota)은 QuotaExhausted 로 즉시 중단.""" 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: """와일드카드(1% 추가 인하 등) 수락 여부를 공급사 입장에서 판단.""" 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"{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 prev_price = case.get("item_price") or case.get("revenue") # ③ 가격 협상률: 협상완료 합의 건만 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) prices = [rd["req_price"] for rd in rounds if rd.get("req_price") is not None] if accepted_1pct and final_price is not None: prices.append(final_price) return {"case_id": case["id"], "quotation_number": case.get("quotation_number"), "item_name": case.get("item_name"), "prev_price": prev_price, "target": case.get("target"), "anchor": case.get("anchor"), "initial_offer": initial, "lowest_offer": min(prices) if prices else None, "accepted_1pct": accepted_1pct, "final_price": final_price, "agreed": reached_done and final_price is not None, "reduction_pct": reduction_pct, "outcome": rounds[-1]["res_step"] if rounds else None, "n_messages": len(rounds), "rounds": rounds} # ---- 집계 ------------------------------------------------------------------- def aggregate(results: list, out_root: Path, source_desc: str, target: float) -> dict: """건별 결과 → CSV·분포 메타·result.json""" agreed = [r for r in results if r.get("reduction_pct") is not None] if not agreed: sys.exit("합의(협상완료) 건이 없습니다 — 집계할 수 없습니다.") reds = [r["reduction_pct"] for r in agreed] avg = round(sum(reds) / len(reds), 3) data_dir = out_root / "data" data_dir.mkdir(parents=True, exist_ok=True) with open(data_dir / "reduction_all.csv", "w", encoding="utf-8-sig", newline="") as f: w = csv.writer(f) w.writerow(["case_id", "견적번호", "품목명", "기존공급가", "최종합의가", "협상률_pct"]) for r in agreed: w.writerow([r["case_id"], r.get("quotation_number"), r.get("item_name"), r["prev_price"], r["final_price"], r["reduction_pct"]]) (data_dir / "reduction_all_meta.json").write_text(json.dumps({ "출처": source_desc, "산식": FORMULA, "분포_pct": {"최소": min(reds), "중앙값": round(statistics.median(reds), 3), "최대": max(reds), "표준편차": round(statistics.pstdev(reds), 3)}, }, ensure_ascii=False, indent=1), encoding="utf-8") result = { "전체 건수": len(results), "합의 건수": len(agreed), "미합의 건수": len(results) - len(agreed), "평균가격협상률_pct": avg, "산식": FORMULA, "목표_pct": target, "verdict": "PASS" if avg >= target else "FAIL", "상세": "data/reduction_all_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=100, help="협상 케이스 수 (기본 100)") 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("--dir", default=None, help="협상 기록 폴더명 (기본 단독측정_YYYYMMDD)") ap.add_argument("--out-dir", default=None, help="산출 위치 (기본: 이 스크립트 폴더 = 정본). 시험 실행은 다른 경로를 준다") ap.add_argument("--target", type=float, default=3.0, help="목표 협상률(%%)") ap.add_argument("--llm-reserve-ratio", type=float, default=0.90) ap.add_argument("--profiling", action="store_true", help="N-profiling(LLM 톤 재작성) 활성 상태로 측정 (기본 off)") 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 && python3 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] 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" # 재개: 기존 detail 에서 정상 완료 건은 스킵, '오류' 건은 버리고 재측정 results = [] if args.resume and detail_path.exists(): keep = [] for line in detail_path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue r = json.loads(line) if not str(r.get("outcome", "")).startswith("오류"): keep.append(r) results = keep 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}" f"{' · ' + args.case_range if args.case_range else ''}) · profiling {'on' if args.profiling else 'off'}") print(f" 협상 기록 : {detail_path}") 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"], "quotation_number": case.get("quotation_number"), "item_name": case.get("item_name"), "prev_price": case.get("item_price") or case.get("revenue"), "final_price": None, "agreed": False, "reduction_pct": None, "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") red = r.get("reduction_pct") mark = f"{red:>6.3f}%" if red is not None else " 미합의" print(f"[{i:3d}/{len(cases)}] {str(r.get('item_name'))[:18]:20s} " f"{str(r.get('outcome')):8s} 최종가 {str(r.get('final_price')):>10s} " f"/ 기존가 {str(r.get('prev_price')):>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']}") if len(results) % 25 == 0: _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"--- 중간집계 [{datetime.now():%H:%M:%S}] {len(results)}건: ③ {_avg}% ---", 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, "testset": args.testset, "케이스": args.case_range or f"1:{args.n}", "profiling": args.profiling, "url": args.url, "목표_pct": args.target, "시작": started.isoformat(), "종료": datetime.now().isoformat(), }, ensure_ascii=False, indent=1), encoding="utf-8") result = aggregate(results, out_root, f"{run_dir.name}/{detail_path.name} — 전체 {len(results)}건", args.target) print() print("=" * W) print(" ③ 평균 가격 협상률 — 단독 측정 요약".center(W - 8)) print("=" * W) print(f" 시험 일시 : {started:%Y-%m-%d %H:%M:%S}") print(f" 상대 에이전트 : {args.model + ' (seed 고정)' if args.opponent == 'llm' else 'scripted'}") print(f" 케이스 : {result['전체 건수']}건 ({args.testset}) · profiling {'on' if args.profiling else 'off'}") print(f" ③ 평균 협상률 : {result['평균가격협상률_pct']} % (목표 {args.target} %) → " f"{result['verdict']} [합의 {result['합의 건수']} / 미합의 {result['미합의 건수']}]") print(f" 산출물 : {out_root}/result.json · data/reduction_all.csv") print(f" {detail_path}") print("=" * W) sys.exit(0 if result["verdict"] == "PASS" else 1) if __name__ == "__main__": main()