Files
Negotiation_daegu/eval/07_data_count/collect.py
T
민헌andClaude Opus 5 87aeda52a4 ⑦ 협상데이터 수집 완료(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>
2026-09-09 16:39:36 +09:00

144 lines
7.6 KiB
Python

#!/usr/bin/env python3
"""⑦ 협상 데이터 수집 — 협상 챗봇을 실행해 계약 기록을 이 폴더(data/contracts.jsonl)에 쌓는다.
협상 루프·상대 에이전트는 ①의 실행기(../01_win_rate/run.py)를 그대로 import 한다(코드 두 벌 금지).
케이스 1건 협상이 끝나면 엔진이 직접 적은 계약 레코드(server/data/contracts.jsonl)를 session_id 로
찾아 data/contracts.jsonl 에 이어 붙인다 — 데이터는 07 에 쌓이고, 기록의 주체는 여전히 엔진이다.
사용: python3 collect.py [--testset 7_testset_10272.json] [--limit 10272] [--opponent profiled]
[--prefix DATA] [--out-dir 수집_YYYYMMDD]
출력: data/contracts.jsonl 누적 계약 기록 (재실행 시 이미 있는 session_id 는 건너뜀 = 재개)
<out-dir>/detail.jsonl 케이스별 협상 상세 (라운드 흐름)
<out-dir>/meta.json 실행 조건·시작/종료·건수
"""
import argparse
import atexit
import json
import os
import sys
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).parent
sys.path.insert(0, str(HERE.parent / "01_win_rate"))
import run as harness # noqa: E402 — negotiate · LLMOpponent · ScriptedOpponent · QuotaExhausted
DATA_FILE = HERE / "data" / "contracts.jsonl"
def engine_log_path(arg: str | None) -> Path:
"""엔진 계약 로그 — 컨테이너(/app/data)와 로컬(../../server/data) 어느 쪽이든 찾는다."""
if arg:
return Path(arg)
for p in (Path("/app/data/contracts.jsonl"), HERE.parents[1] / "server" / "data" / "contracts.jsonl"):
if p.exists():
return p
raise SystemExit("엔진 계약 로그(contracts.jsonl)를 찾지 못했다 — --engine-log 로 지정")
def collected_ids(path: Path) -> set:
if not path.exists():
return set()
return {json.loads(l)["session_id"] for l in path.read_text(encoding="utf-8").splitlines() if l.strip()}
def new_records(log: Path, offset: int) -> tuple[list[dict], int]:
"""엔진 로그에서 offset 이후 줄만 읽는다 (파일 전체 재스캔 방지)."""
with open(log, "rb") as f:
f.seek(offset)
chunk = f.read()
rows = [json.loads(l) for l in chunk.decode("utf-8").splitlines() if l.strip()]
return rows, offset + len(chunk)
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
ap.add_argument("--testset", default="7_testset_10272.json")
ap.add_argument("--limit", type=int)
ap.add_argument("--case-range", default=None, help="예: 1:1000")
ap.add_argument("--opponent", default="llm", choices=["scripted", "llm", "profiled"],
help="llm=gpt-4o · profiled=gpt-4o 실측 보정 규칙 상대 · scripted=앵커 기준 단순 규칙")
ap.add_argument("--model", default="gpt-4o")
ap.add_argument("--url", default="http://127.0.0.1:3300/v1/nego/chat")
ap.add_argument("--prefix", default="DATA", help="session_id 접두 (① 측정의 EVAL 과 구분)")
ap.add_argument("--engine-log", default=None)
ap.add_argument("--out-dir", default=None, help="실행 로그 폴더 (기본: 수집_YYYYMMDD)")
ap.add_argument("--data-file", default=None, help="계약 기록 누적 파일 (기본 data/contracts.jsonl — 검증 실행은 따로 지정)")
args = ap.parse_args()
harness.SESSION_PREFIX = args.prefix
global DATA_FILE
if args.data_file:
DATA_FILE = Path(args.data_file)
engine_log = engine_log_path(args.engine_log)
cases = json.loads((harness.TESTDATA_DIR / args.testset).read_text(encoding="utf-8"))["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]
done = collected_ids(DATA_FILE)
todo = [c for c in cases if f"{args.prefix}-{c['id']}" not in done]
# 동시 실행 방지 — 두 프로세스가 같은 data/contracts.jsonl 에 붙으면 세션이 중복 기록된다
# (2026-09-09 실측: 중복 실행으로 266 세션 280줄 중복). 각자 자기 done 집합만 보기 때문에 막지 못한다.
lock = HERE / "data" / ".collect.lock"
lock.parent.mkdir(exist_ok=True)
if lock.exists():
raise SystemExit(f"이미 수집이 실행 중이다: {lock}\n 끝난 뒤에도 남아 있으면 파일을 지우고 다시 실행한다.")
lock.write_text(f"{datetime.now().isoformat()} pid={os.getpid()}\n", encoding="utf-8")
atexit.register(lambda: lock.exists() and lock.unlink())
out_dir = Path(args.out_dir) if args.out_dir else HERE / f"수집_{datetime.now():%Y%m%d}"
out_dir.mkdir(parents=True, exist_ok=True)
DATA_FILE.parent.mkdir(exist_ok=True)
detail_path = out_dir / "detail.jsonl"
meta = {"testset": args.testset, "opponent": args.opponent,
"model": args.model if args.opponent == "llm" else ("ProfiledOpponent(seed 20260909)" if args.opponent == "profiled" else "ScriptedOpponent"), "prefix": args.prefix,
"대상": len(cases), "이미수집_건너뜀": len(cases) - len(todo),
"시작": datetime.now().isoformat(), "종료": None, "협상": 0, "계약기록": 0, "오류": 0}
(out_dir / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"[수집] 대상 {len(cases)}건 · 이미 수집 {len(cases) - len(todo)}건 건너뜀 · 진행 {len(todo)}건 "
f"({args.opponent}{' ' + args.model if args.opponent == 'llm' else ''}) · 엔진 로그 {engine_log}", flush=True)
opponent = (harness.LLMOpponent(model=args.model) if args.opponent == "llm"
else harness.ProfiledOpponent() if args.opponent == "profiled"
else harness.ScriptedOpponent())
offset = engine_log.stat().st_size
for n, case in enumerate(todo, 1):
sid = f"{args.prefix}-{case['id']}"
try:
r = harness.negotiate(args.url, case, opponent)
except harness.QuotaExhausted as e:
print(f"\n[중단] {e} — 누적 {len(done)}건 보존, 충전 후 같은 명령으로 재개", flush=True)
break
except Exception as e:
meta["오류"] += 1
print(f"[{n}/{len(todo)}] {sid} 오류: {e}", flush=True)
continue
meta["협상"] += 1
with open(detail_path, "a", encoding="utf-8") as f:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
rows, offset = new_records(engine_log, offset)
mine = [x for x in rows if x.get("session_id") == sid]
if mine:
with open(DATA_FILE, "a", encoding="utf-8") as f:
for x in mine:
f.write(json.dumps(x, ensure_ascii=False) + "\n")
done.add(sid)
meta["계약기록"] += len(mine)
print(f"[{n}/{len(todo)}] {sid} {str(r.get('item_name') or '')[:14]:14s} "
f"{str(r.get('outcome')):6s} 최종가 {str(r.get('final_price')):>9s} "
f"{'계약기록 ✓' if mine else '기록 없음'} 누적 {len(done)}", flush=True)
if n % 50 == 0:
meta["종료"] = datetime.now().isoformat()
(out_dir / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
meta["종료"] = datetime.now().isoformat()
(out_dir / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"\n완료: 협상 {meta['협상']}건 · 계약기록 {meta['계약기록']}건 · 오류 {meta['오류']}건 · "
f"data/contracts.jsonl 누적 {len(done)}건 → python3 aggregate.py", flush=True)
if __name__ == "__main__":
main()