초기 커밋 — 협상 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
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,63 @@
|
||||
"""Q-Table 모델 — 추론 전용 (학습 경로는 이 프로젝트에서 제외)."""
|
||||
|
||||
import numpy as np
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class QTable:
|
||||
"""
|
||||
Q-Table은 추상적인 action_id만 다루며,
|
||||
실제 협상 카드(card_id)는 ActionCardMapper에서 매핑한다.
|
||||
"""
|
||||
|
||||
def __init__(self, state_space_size: int, action_space_size: int):
|
||||
self.state_space_size = state_space_size
|
||||
self.action_space_size = action_space_size
|
||||
self.q_values = np.zeros((state_space_size, action_space_size))
|
||||
|
||||
def get_q_value(self, state_index: int, action_id: int) -> float:
|
||||
self._validate_indices(state_index, action_id)
|
||||
return float(self.q_values[state_index, action_id])
|
||||
|
||||
def get_q_values_for_state(self, state_index: int) -> np.ndarray:
|
||||
self._validate_state(state_index)
|
||||
return self.q_values[state_index, :].copy()
|
||||
|
||||
def get_best_action(self, state_index: int) -> int:
|
||||
self._validate_state(state_index)
|
||||
return int(np.argmax(self.q_values[state_index, :]))
|
||||
|
||||
def to_dict(self) -> Dict:
|
||||
return {
|
||||
"state_space_size": self.state_space_size,
|
||||
"action_space_size": self.action_space_size,
|
||||
"q_values": self.q_values.tolist(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict) -> "QTable":
|
||||
q_table = cls(
|
||||
state_space_size=data["state_space_size"],
|
||||
action_space_size=data["action_space_size"],
|
||||
)
|
||||
q_table.q_values = np.array(data["q_values"])
|
||||
return q_table
|
||||
|
||||
def _validate_state(self, state_index: int):
|
||||
if state_index < 0 or state_index >= self.state_space_size:
|
||||
raise ValueError(
|
||||
f"state_index {state_index} out of range [0, {self.state_space_size})"
|
||||
)
|
||||
|
||||
def _validate_indices(self, state_index: int, action_id: int):
|
||||
self._validate_state(state_index)
|
||||
if action_id < 0 or action_id >= self.action_space_size:
|
||||
raise ValueError(
|
||||
f"action_id {action_id} out of range [0, {self.action_space_size})"
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"QTable(state_space_size={self.state_space_size}, "
|
||||
f"action_space_size={self.action_space_size})"
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""카드 선택기 — State → action_id → card_id 추론."""
|
||||
|
||||
import logging
|
||||
from typing import Dict, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from services.cards.mapper import ActionCardMapper
|
||||
from services.policy.q_table import QTable
|
||||
from services.policy.state import State
|
||||
from services.policy.ucb import UCBPolicy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CardSelector:
|
||||
"""
|
||||
Q_Table은 추상적인 action_id만 반환하고,
|
||||
ActionCardMapper를 통해 구체적인 card_id로 변환한다.
|
||||
"""
|
||||
|
||||
def __init__(self, q_table: QTable, policy: UCBPolicy,
|
||||
action_card_mapper: ActionCardMapper):
|
||||
self.q_table = q_table
|
||||
self.policy = policy
|
||||
self.action_card_mapper = action_card_mapper
|
||||
|
||||
def execute(
|
||||
self,
|
||||
state: State,
|
||||
use_policy: bool = True,
|
||||
excluded_actions: Optional[list] = None,
|
||||
) -> Dict:
|
||||
"""
|
||||
현재 상태에서 최적의 협상 카드 선택.
|
||||
|
||||
Args:
|
||||
use_policy: True면 UCB 정책(방문수 증가 + 에피소드 중복 방지),
|
||||
False면 순수 Q-value argmax (학습 격리 — 신규견적 등)
|
||||
excluded_actions: 선택에서 제외할 action_id 리스트
|
||||
"""
|
||||
state_index = state.to_index()
|
||||
q_values = self.q_table.get_q_values_for_state(state_index)
|
||||
|
||||
available_mask = None
|
||||
if excluded_actions is not None:
|
||||
action_space_size = len(q_values)
|
||||
available_mask = np.ones(action_space_size, dtype=int)
|
||||
for action_id in excluded_actions:
|
||||
if 0 <= action_id < action_space_size:
|
||||
available_mask[action_id] = 0
|
||||
logger.info(f"[CardSelector] excluded actions: {excluded_actions}")
|
||||
|
||||
if use_policy:
|
||||
action_id = self.policy.select_action(
|
||||
state_index, q_values, available_mask=available_mask
|
||||
)
|
||||
else:
|
||||
if available_mask is not None:
|
||||
masked_q = q_values.copy()
|
||||
masked_q[available_mask == 0] = -np.inf
|
||||
action_id = int(np.argmax(masked_q))
|
||||
if masked_q[action_id] == -np.inf:
|
||||
action_id = None
|
||||
else:
|
||||
action_id = self.q_table.get_best_action(state_index)
|
||||
|
||||
if action_id is None:
|
||||
return {
|
||||
"action_id": None,
|
||||
"card_id": None,
|
||||
"q_value": None,
|
||||
"state_index": state_index,
|
||||
"message": "No available actions (all actions used in this episode)",
|
||||
}
|
||||
|
||||
card_id = self.action_card_mapper.get_card_id(action_id)
|
||||
if card_id is None:
|
||||
return {
|
||||
"action_id": action_id,
|
||||
"card_id": None,
|
||||
"q_value": float(q_values[action_id]),
|
||||
"state_index": state_index,
|
||||
"visit_count": 0,
|
||||
"message": f"action_id {action_id} has no card mapping",
|
||||
}
|
||||
|
||||
q_value = self.q_table.get_q_value(state_index, action_id)
|
||||
|
||||
# 학습 격리 경로는 정책을 거치지 않으므로 정책 통계가 무의미 → None
|
||||
if use_policy:
|
||||
visit_count = self.policy.visit_table.get_action_count(state_index, action_id)
|
||||
selection_info = self.policy._last_selection_info
|
||||
else:
|
||||
visit_count = None
|
||||
selection_info = {}
|
||||
|
||||
return {
|
||||
"action_id": action_id,
|
||||
"card_id": card_id,
|
||||
"q_value": float(q_value),
|
||||
"state_index": state_index,
|
||||
"visit_count": visit_count,
|
||||
"visit_count_at_selection": selection_info.get("visit_count"),
|
||||
"total_visits_at_selection": selection_info.get("total_visits"),
|
||||
"ucb_score_at_selection": selection_info.get("ucb_score"),
|
||||
}
|
||||
|
||||
def reset_episode(self):
|
||||
"""협상 세션 종료/시작 시 정책 초기화"""
|
||||
self.policy.reset_episode()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""협상 스냅샷 → Q-Table State 변환."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from services.policy.state import (
|
||||
AcceptanceRate,
|
||||
DistributionStructure,
|
||||
InputPriceZone,
|
||||
PartnerType,
|
||||
RevenueRange,
|
||||
State,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NegotiationSnapshot:
|
||||
"""협상 스냅샷 — 실제 비즈니스 데이터"""
|
||||
|
||||
revenue_amount: float # 매출액 (원)
|
||||
distribution_code: str # "M" 제조 / "W" 총판 / "R" 유통
|
||||
partner_count: int
|
||||
anchor_price: float
|
||||
target_price: float
|
||||
input_price: float
|
||||
acceptance_ratio: Optional[float] = None # 0~1, 없으면 initial_price로 계산
|
||||
initial_price: Optional[float] = None
|
||||
|
||||
|
||||
def build_state(snapshot: NegotiationSnapshot) -> State:
|
||||
revenue_range = RevenueRange.from_amount(snapshot.revenue_amount)
|
||||
distribution = DistributionStructure.from_code(snapshot.distribution_code)
|
||||
partner_type = PartnerType.from_count(snapshot.partner_count)
|
||||
|
||||
if snapshot.acceptance_ratio is not None:
|
||||
acceptance_rate = AcceptanceRate.from_ratio(snapshot.acceptance_ratio)
|
||||
elif snapshot.initial_price is not None:
|
||||
if snapshot.initial_price <= 0:
|
||||
raise ValueError("initial_price must be positive")
|
||||
ratio = (snapshot.initial_price - snapshot.input_price) / snapshot.initial_price
|
||||
acceptance_rate = AcceptanceRate.from_ratio(ratio)
|
||||
else:
|
||||
raise ValueError("Either acceptance_ratio or initial_price must be provided")
|
||||
|
||||
input_price_zone = InputPriceZone.from_prices(
|
||||
input_price=snapshot.input_price,
|
||||
anchor_price=snapshot.anchor_price,
|
||||
target_price=snapshot.target_price,
|
||||
)
|
||||
|
||||
return State(
|
||||
revenue_range=revenue_range,
|
||||
distribution=distribution,
|
||||
partner_type=partner_type,
|
||||
acceptance_rate=acceptance_rate,
|
||||
input_price_zone=input_price_zone,
|
||||
)
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Q-Learning State 표현 (162 states = 3×3×3×3×2)."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import IntEnum
|
||||
from typing import List
|
||||
|
||||
_REVENUE_DESCRIPTIONS = ("Low (≤1,000만원)", "Mid (1,000~3,000만원)", "High (>3,000만원)")
|
||||
_DISTRIBUTION_DESCRIPTIONS = ("제조", "총판", "유통")
|
||||
_PARTNER_DESCRIPTIONS = ("Single (단독)", "Multiple (다수)", "None (없음)")
|
||||
_ACCEPTANCE_DESCRIPTIONS = ("Low (<3%)", "Mid (3~9%)", "High (>9%)")
|
||||
_PRICE_ZONE_DESCRIPTIONS = ("PZ1 (A≤P≤T)", "PZ2 (P>T)")
|
||||
|
||||
|
||||
class RevenueRange(IntEnum):
|
||||
"""매출액 가격구간"""
|
||||
|
||||
LOW = 0 # ≤ 1,000만원
|
||||
MID = 1 # 1,000만원 ~ 3,000만원
|
||||
HIGH = 2 # > 3,000만원
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _REVENUE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_amount(cls, amount: float) -> "RevenueRange":
|
||||
if amount <= 10_000_000:
|
||||
return cls.LOW
|
||||
elif amount <= 30_000_000:
|
||||
return cls.MID
|
||||
return cls.HIGH
|
||||
|
||||
|
||||
class DistributionStructure(IntEnum):
|
||||
"""유통 구조"""
|
||||
|
||||
MANUFACTURER = 0 # 제조 (M)
|
||||
WHOLESALER = 1 # 총판 (W)
|
||||
RETAILER = 2 # 유통 (R)
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _DISTRIBUTION_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_code(cls, code: str) -> "DistributionStructure":
|
||||
normalized = (code or "").strip().upper()
|
||||
mapping = {"M": cls.MANUFACTURER, "W": cls.WHOLESALER, "R": cls.RETAILER}
|
||||
if normalized not in mapping:
|
||||
raise ValueError(f"unknown distribution code: {code}")
|
||||
return mapping[normalized]
|
||||
|
||||
|
||||
class PartnerType(IntEnum):
|
||||
"""파트너사 종류"""
|
||||
|
||||
SINGLE = 0 # 단독
|
||||
MULTIPLE = 1 # 다수
|
||||
NONE = 2 # 없음
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _PARTNER_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_count(cls, count: int) -> "PartnerType":
|
||||
if count == 0:
|
||||
return cls.NONE
|
||||
elif count == 1:
|
||||
return cls.SINGLE
|
||||
return cls.MULTIPLE
|
||||
|
||||
|
||||
class AcceptanceRate(IntEnum):
|
||||
"""가격 수용률 구간"""
|
||||
|
||||
LOW = 0 # < 3%
|
||||
MID = 1 # 3% ~ 9%
|
||||
HIGH = 2 # > 9%
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _ACCEPTANCE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_ratio(cls, ratio: float) -> "AcceptanceRate":
|
||||
if ratio < 0.03:
|
||||
return cls.LOW
|
||||
elif ratio <= 0.09:
|
||||
return cls.MID
|
||||
return cls.HIGH
|
||||
|
||||
|
||||
class InputPriceZone(IntEnum):
|
||||
"""입력 금액 구간"""
|
||||
|
||||
PZ1 = 0 # A ≤ P ≤ T
|
||||
PZ2 = 1 # P > T
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _PRICE_ZONE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_prices(cls, input_price: float, anchor_price: float,
|
||||
target_price: float) -> "InputPriceZone":
|
||||
if anchor_price <= 0 or target_price <= 0:
|
||||
raise ValueError("anchor_price and target_price must be positive")
|
||||
if anchor_price > target_price:
|
||||
raise ValueError("anchor_price must not exceed target_price")
|
||||
if anchor_price <= input_price <= target_price:
|
||||
return cls.PZ1
|
||||
return cls.PZ2
|
||||
|
||||
|
||||
@dataclass
|
||||
class State:
|
||||
"""State = (매출구간, 유통구조, 파트너, 수용률, 가격구간) — 3×3×3×3×2 = 162"""
|
||||
|
||||
revenue_range: RevenueRange
|
||||
distribution: DistributionStructure
|
||||
partner_type: PartnerType
|
||||
acceptance_rate: AcceptanceRate
|
||||
input_price_zone: InputPriceZone
|
||||
|
||||
def to_array(self) -> List[int]:
|
||||
return [
|
||||
self.revenue_range.value,
|
||||
self.distribution.value,
|
||||
self.partner_type.value,
|
||||
self.acceptance_rate.value,
|
||||
self.input_price_zone.value,
|
||||
]
|
||||
|
||||
def to_index(self) -> int:
|
||||
"""State를 1차원 인덱스(0~161)로 변환"""
|
||||
return (
|
||||
self.revenue_range.value * 54
|
||||
+ self.distribution.value * 18
|
||||
+ self.partner_type.value * 6
|
||||
+ self.acceptance_rate.value * 2
|
||||
+ self.input_price_zone.value
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_index(cls, index: int) -> "State":
|
||||
if index < 0 or index >= 162:
|
||||
raise ValueError(f"index {index} out of range [0, 162)")
|
||||
revenue_value, remainder = divmod(index, 54)
|
||||
dist_value, remainder = divmod(remainder, 18)
|
||||
partner_value, remainder = divmod(remainder, 6)
|
||||
accept_value, pricezone_value = divmod(remainder, 2)
|
||||
return cls(
|
||||
revenue_range=RevenueRange(revenue_value),
|
||||
distribution=DistributionStructure(dist_value),
|
||||
partner_type=PartnerType(partner_value),
|
||||
acceptance_rate=AcceptanceRate(accept_value),
|
||||
input_price_zone=InputPriceZone(pricezone_value),
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return (
|
||||
f"State("
|
||||
f"revenue={self.revenue_range.description}, "
|
||||
f"distribution={self.distribution.description}, "
|
||||
f"partner={self.partner_type.description}, "
|
||||
f"acceptance={self.acceptance_rate.description}, "
|
||||
f"price_zone={self.input_price_zone.description})"
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""UCB 액션 선택 정책 — 에피소드 내 카드 중복 방지 포함."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from services.policy.visit_table import VisitTable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UCBPolicy:
|
||||
"""Upper Confidence Bound policy with per-episode action masking.
|
||||
|
||||
UCB = Q(s,a) + c * sqrt(ln(N(s)) / N(s,a))
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
visit_table: VisitTable,
|
||||
exploration_constant: float = float(np.sqrt(2.0)),
|
||||
epsilon: float = 1e-6,
|
||||
rng: Optional[np.random.Generator] = None,
|
||||
) -> None:
|
||||
self.visit_table = visit_table
|
||||
self.action_space_size = visit_table.action_space_size
|
||||
self.exploration_constant = exploration_constant
|
||||
self.epsilon = epsilon
|
||||
self._rng = rng or np.random.default_rng()
|
||||
self._episode_actions: set[int] = set()
|
||||
self._last_selection_info: dict = {}
|
||||
|
||||
def select_action(
|
||||
self,
|
||||
state_index: int,
|
||||
q_values: np.ndarray,
|
||||
available_mask: Optional[np.ndarray] = None,
|
||||
) -> Optional[int]:
|
||||
mask = self._prepare_mask(available_mask)
|
||||
if not mask.any():
|
||||
self.reset_episode()
|
||||
mask = self._prepare_mask(available_mask)
|
||||
if not mask.any():
|
||||
return None
|
||||
|
||||
counts = self.visit_table.get_state_counts(state_index)
|
||||
masked_counts = np.where(mask, counts, 0)
|
||||
total = max(masked_counts.sum(), 1)
|
||||
|
||||
# N(s,a)=0인 액션은 epsilon으로 대체 → UCB 보너스가 매우 커져 자연스럽게 우선 선택
|
||||
denom = np.where(counts > 0, counts.astype(float), self.epsilon)
|
||||
bonus = self.exploration_constant * np.sqrt(np.log(total + 1.0) / denom)
|
||||
scores = q_values + bonus
|
||||
scores[~mask] = -np.inf
|
||||
action = int(np.argmax(scores))
|
||||
|
||||
self._last_selection_info = {
|
||||
"visit_count": int(counts[action]),
|
||||
"total_visits": int(total),
|
||||
"ucb_score": float(scores[action]),
|
||||
}
|
||||
|
||||
logger.info(
|
||||
f"[UCB Policy - State {state_index}] "
|
||||
f"q={[f'{q:.3f}' for q in q_values]} visits={counts.tolist()} "
|
||||
f"mask={mask.astype(int).tolist()} => action {action}"
|
||||
)
|
||||
|
||||
self.visit_table.increment(state_index, action)
|
||||
self._episode_actions.add(action)
|
||||
return action
|
||||
|
||||
def reset_episode(self) -> None:
|
||||
"""에피소드(협상 세션) 내 사용된 액션 기록 초기화 — 세션 경계마다 호출할 것"""
|
||||
self._episode_actions.clear()
|
||||
|
||||
def get_action_mask(self) -> np.ndarray:
|
||||
mask = np.ones(self.action_space_size, dtype=int)
|
||||
for action in self._episode_actions:
|
||||
mask[action] = 0
|
||||
return mask
|
||||
|
||||
def _prepare_mask(self, available_mask: Optional[np.ndarray]) -> np.ndarray:
|
||||
if available_mask is None:
|
||||
mask = np.ones(self.action_space_size, dtype=bool)
|
||||
else:
|
||||
mask = np.asarray(available_mask, dtype=bool).copy()
|
||||
for action in self._episode_actions:
|
||||
mask[action] = False
|
||||
return mask
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Visit (N) table — UCB 정책의 방문 횟수 추적."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisitTable:
|
||||
state_space_size: int
|
||||
action_space_size: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._counts = np.zeros(
|
||||
(self.state_space_size, self.action_space_size), dtype=np.int64
|
||||
)
|
||||
|
||||
def increment(self, state_index: int, action_id: int, count: int = 1) -> None:
|
||||
self._validate_indices(state_index, action_id)
|
||||
if count < 0:
|
||||
raise ValueError("count must be non-negative")
|
||||
self._counts[state_index, action_id] += count
|
||||
|
||||
def get_action_count(self, state_index: int, action_id: int) -> int:
|
||||
self._validate_indices(state_index, action_id)
|
||||
return int(self._counts[state_index, action_id])
|
||||
|
||||
def get_state_counts(self, state_index: int) -> np.ndarray:
|
||||
self._validate_state(state_index)
|
||||
return self._counts[state_index, :].copy()
|
||||
|
||||
def total_visits(self, state_index: int) -> int:
|
||||
self._validate_state(state_index)
|
||||
return int(self._counts[state_index, :].sum())
|
||||
|
||||
def reset_state(self, state_index: int) -> None:
|
||||
self._validate_state(state_index)
|
||||
self._counts[state_index, :] = 0
|
||||
|
||||
def to_dict(self) -> Dict:
|
||||
return {
|
||||
"state_space_size": self.state_space_size,
|
||||
"action_space_size": self.action_space_size,
|
||||
"counts": self._counts.tolist(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict) -> "VisitTable":
|
||||
table = cls(
|
||||
state_space_size=data["state_space_size"],
|
||||
action_space_size=data["action_space_size"],
|
||||
)
|
||||
table._counts = np.array(data["counts"], dtype=np.int64)
|
||||
return table
|
||||
|
||||
def _validate_state(self, state_index: int) -> None:
|
||||
if state_index < 0 or state_index >= self.state_space_size:
|
||||
raise ValueError(
|
||||
f"state_index {state_index} out of range [0, {self.state_space_size})"
|
||||
)
|
||||
|
||||
def _validate_indices(self, state_index: int, action_id: int) -> None:
|
||||
self._validate_state(state_index)
|
||||
if action_id < 0 or action_id >= self.action_space_size:
|
||||
raise ValueError(
|
||||
f"action_id {action_id} out of range [0, {self.action_space_size})"
|
||||
)
|
||||
Reference in new issue
Block a user