"""협상 오케스트레이터 — 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()