Files
Negotiation_daegu/server/services/negotiation/orchestrator.py
T
민헌andClaude Fable 5 dfb9ad6e66 초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117)
- frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시)
- eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋
- results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256)
  ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99
- docker-compose.yml + run.sh: backend+frontend 일괄 기동

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
2026-08-31 13:09:52 +09:00

92 lines
3.1 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.
"""협상 오케스트레이터 — Q-Table·정책·카드 저장소를 조립해 카드를 선택한다.
Q-Table은 resources/policy/q_table.json (휴리스틱 초기값)에서 로드한다. DB 없음.
"""
import json
import logging
from common.paths import RESOURCES_DIR
from services.cards.mapper import ActionCardMapper
from services.cards.repository import CardScriptRepository
from services.policy.q_table import QTable
from services.policy.selector import CardSelector
from services.policy.state import State
from services.policy.ucb import UCBPolicy
from services.policy.visit_table import VisitTable
logger = logging.getLogger(__name__)
STATE_SPACE_SIZE = 162
class NegotiationOrchestrator:
def __init__(self):
self.mapper = ActionCardMapper()
self.script_repo = CardScriptRepository()
self.action_space_size = self.mapper.get_action_space_size()
self.q_table = self._load_q_table()
self.visit_table = VisitTable(
state_space_size=STATE_SPACE_SIZE,
action_space_size=self.action_space_size,
)
self.policy = UCBPolicy(visit_table=self.visit_table)
self.selector = CardSelector(
q_table=self.q_table,
policy=self.policy,
action_card_mapper=self.mapper,
)
def _load_q_table(self) -> QTable:
q_json = RESOURCES_DIR / "policy" / "q_table.json"
if q_json.exists():
with open(q_json, "r", encoding="utf-8") as f:
q_table = QTable.from_dict(json.load(f))
logger.info(f"Q-Table 로드: {q_json} "
f"({q_table.state_space_size}×{q_table.action_space_size})")
return q_table
logger.warning("q_table.json 없음 — 빈 Q-Table로 기동")
return QTable(
state_space_size=STATE_SPACE_SIZE,
action_space_size=self.action_space_size,
)
def select_card(self, state: State, excluded_cards: list = None,
isolate_learning: bool = False) -> dict:
"""
Args:
excluded_cards: 제외할 card_id 리스트
isolate_learning: True면 UCB 격리(방문수 미증가, argmax) — 신규견적 등
"""
logger.info(f"[Input State] {state}")
excluded_actions = []
if excluded_cards:
for card_id in excluded_cards:
action_id = self.mapper.get_action_id(card_id)
if action_id is not None:
excluded_actions.append(action_id)
result = self.selector.execute(
state,
use_policy=not isolate_learning,
excluded_actions=excluded_actions,
)
if result.get("card_id"):
card = self.script_repo.find_by_id(result["card_id"])
if card:
result["card_name"] = card.get("card_name")
result["script"] = card.get("script")
else:
result["script"] = "Script not found in repository."
return result
def reset_episode(self):
"""협상 세션 경계에서 정책의 에피소드 상태 초기화"""
self.selector.reset_episode()