⑦ 협상데이터 수집 완료(10,272건 PASS) + 저장소를 입력·코드·최종 결과만 남기게 정리
⑦ 협상데이터 수집 - collect.py 추가 — ①의 협상 실행기를 재사용해 챗봇을 돌리고 계약 기록을 data/contracts.jsonl 에 축적 (재실행 시 수집분 건너뜀, data/.collect.lock 으로 동시 실행 차단) - run.py 에 ProfiledOpponent 추가 — gpt-4o 실측 409건 분포로 보정한 규칙 기반 공급사(프로파일 4종, seed 고정) 검증: 같은 409 케이스에서 첫 제안·양보폭·합의가·협상률 일치, 카드 수락과 목표 달성은 6~7%p 보수적 - 시뮬레이터 상대로 10,272건 수집 → 목표 10,000건 PASS - aggregate.py 간소화 — result.json 은 최종 집계·목표 건수·판정 3개만. 계획서 평가방법이 기간 환산을 규정하지 않으므로 연환산 제거, 건수는 고유 session_id 수로 집계 저장소 정리 - 각 eval/<지표>/ 에 측정 코드·result.json·provenance.md 와 최종 데이터 산출물만 남김 - 실행 원본·로그·중간 산출물은 NEGO_DOCS/_archive_20260909_*/ 로 이동 (provenance 가 위치를 가리킨다) - 삭제: description.md, testdata/testset_100.json(파일럿 미사용), testdata/validate_dataset.py(미참조), ⑨ 본측정 폴더 내 중복 6개, 서버 로그 동결본 - .gitignore 에 재생성되는 중간 산출물 등록 - provenance 8종을 정의·원천·명령·결과 중심으로 재작성 (364줄 → 240줄) - 재현 검증: ⑦⑧② 집계기 재실행 시 동일 수치 자체측정 8종 전부 PASS — ① 85.67% ② 76.29% ③ 5.877% ⑥ p95 31.65ms ⑦ 10,272건 ⑧ 96.1% ⑨ 99.71% ⑩ 98.23% Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
af12ba44db
commit
87aeda52a4
66 files changed
+339859
-55777
No files matched your search
+88
-5
@@ -8,7 +8,7 @@ NEGO_AGENT 서버(:3300 /v1/nego/chat)를 상대로, 공급사 역할 에이전
|
||||
run.py 공급사 에이전트(scripted|llm) + 협상 루프 + 집계
|
||||
|
||||
사용:
|
||||
python run.py --testset testset_100.json --limit 3 # scripted (결정적, API 키 불필요)
|
||||
python run.py --testset testset_300.json --limit 3 # scripted (결정적, API 키 불필요)
|
||||
python run.py --testset testset_300.json --opponent llm # GPT-4o 상대 (OPENAI_API_KEY, seed 고정)
|
||||
|
||||
출력:
|
||||
@@ -23,7 +23,9 @@ NEGO_AGENT 서버(:3300 /v1/nego/chat)를 상대로, 공급사 역할 에이전
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
@@ -32,6 +34,8 @@ 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():
|
||||
@@ -156,6 +160,81 @@ class LLMOpponent:
|
||||
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:
|
||||
@@ -174,7 +253,7 @@ def build_card_data(case: dict, price, anchor_v) -> dict:
|
||||
|
||||
|
||||
def negotiate(url: str, case: dict, opponent, profiling: bool = False) -> dict:
|
||||
session_id = f"EVAL-{case['id']}"
|
||||
session_id = f"{SESSION_PREFIX}-{case['id']}"
|
||||
base = {
|
||||
"rq_type": "재협상", "session_id": session_id,
|
||||
"item_price": case.get("item_price") or case.get("revenue"),
|
||||
@@ -269,7 +348,7 @@ 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("--opponent", default="scripted", choices=["scripted", "llm", "profiled"])
|
||||
ap.add_argument("--testset", default="testset_300.json",
|
||||
help="testdata/ 안의 케이스셋 파일명")
|
||||
ap.add_argument("--target-rate", type=float, default=70.0, help="① 목표 성공률(%%)")
|
||||
@@ -285,7 +364,11 @@ def main():
|
||||
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]
|
||||
@@ -306,8 +389,8 @@ def main():
|
||||
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()
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user