Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화

This commit is contained in:
HyeongBaeYang committed 2026-06-17 11:10:03 +09:00
1 parent 212725e5f9
commit 951d6eab84
140 files changed
+6689 -214

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,66 @@
"""Q-Table — 이산 (state, action) 가치표 + 방문횟수 (우리 자체 numpy 구현).
클린룸: Q-learning(off-policy TD) 과 UCB 는 표준 알고리즘(아이디어)이고, 아래 구현은 우리 작성이다.
state_space_size x action_space_size 밀집 행렬. 차원은 TenantConfig 에서 산출된 값을 주입.
"""
from typing import List, Tuple
import numpy as np
class QTable:
def __init__(self, state_space_size: int, action_space_size: int,
learning_rate: float = 0.1, discount_factor: float = 0.95):
self.state_space_size = state_space_size
self.action_space_size = action_space_size
self.lr = learning_rate
self.gamma = discount_factor
self.q = np.zeros((state_space_size, action_space_size), dtype=float)
self.visits = np.zeros((state_space_size, action_space_size), dtype=np.int64)
# ---- 접근 ----------------------------------------------------------
def row(self, state_index: int) -> np.ndarray:
return self.q[state_index]
def visit_row(self, state_index: int) -> np.ndarray:
return self.visits[state_index]
def state_visits(self, state_index: int) -> int:
return int(self.visits[state_index].sum())
def best_action(self, state_index: int) -> int:
return int(np.argmax(self.q[state_index]))
# ---- 갱신 ----------------------------------------------------------
def mark_visit(self, state_index: int, action_id: int):
self.visits[state_index, action_id] += 1
def update(self, state_index: int, action_id: int, reward: float,
next_state_index: int = None, done: bool = False) -> float:
"""Q-learning 1-스텝 갱신. 반환: 갱신 후 Q[s,a].
target = reward + (0 if done/next 없음 else gamma * max_a' Q[s',a'])
Q[s,a] += lr * (target - Q[s,a])
"""
bootstrap = 0.0
if not done and next_state_index is not None:
bootstrap = self.gamma * float(np.max(self.q[next_state_index]))
td_target = reward + bootstrap
self.q[state_index, action_id] += self.lr * (td_target - self.q[state_index, action_id])
return float(self.q[state_index, action_id])
# ---- 직렬화 (희소: 0 아닌 셀만) ------------------------------------
def nonzero_cells(self) -> List[Tuple[int, int, float, int]]:
"""(state_index, action_id, q_value, visit_count) — q 또는 visit 가 0 이 아닌 셀."""
out = []
nz = np.argwhere((self.q != 0) | (self.visits != 0))
for s, a in nz:
out.append((int(s), int(a), float(self.q[s, a]), int(self.visits[s, a])))
return out
def load_cells(self, cells: List[Tuple[int, int, float, int]]):
for s, a, q, v in cells:
if 0 <= s < self.state_space_size and 0 <= a < self.action_space_size:
self.q[s, a] = q
self.visits[s, a] = v
@@ -0,0 +1,49 @@
"""NegotiationSnapshot — 한 협상 의사결정 시점의 관측치 (우리 자체 스키마).
이산 상태(state_index)와 연속 feature 가 한 곳에 공존한다. experience_logs.snapshot(JSON)에
저장되어 3개 알고리즘(Q-Table/LinUCB/Offline RL)이 같은 데이터를 공유한다(계획서 핵심통찰).
클린룸: 필드 구성은 우리 설계다. 상태 산출에 필요한 관측치 + reward 계산 입력을 담는다.
"""
from dataclasses import dataclass, asdict
from enum import Enum
from typing import Any, Dict, Optional
class NegotiationOutcome(str, Enum):
"""협상 라운드 결과 (reward 계산 입력)."""
ONGOING = "ongoing"
SUCCESS = "success"
FAILURE = "failure"
@dataclass
class NegotiationSnapshot:
# --- 이산 상태 산출 입력 ---
revenue_amount: float # 매출액(원)
distribution_code: str # 유통 구조 외부 코드 (테넌트 code_map 으로 해석)
partner_count: int # 파트너사 수
acceptance_ratio: float # 가격 수용률 (0~1)
input_price: float # 현재 제시/입력 가격
anchor_price: float # 앵커(시작) 가격
target_price: float # 목표 가격
# --- 시퀀스/보상 컨텍스트 ---
round_number: int = 0 # 협상 라운드(turn)
outcome: NegotiationOutcome = NegotiationOutcome.ONGOING
def to_dict(self) -> Dict[str, Any]:
d = asdict(self)
d["outcome"] = self.outcome.value
return d
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "NegotiationSnapshot":
d = dict(d)
outcome = d.get("outcome", NegotiationOutcome.ONGOING.value)
d["outcome"] = NegotiationOutcome(outcome) if not isinstance(outcome, NegotiationOutcome) else outcome
# 알 수 없는 키는 무시(스키마 진화 내성).
allowed = cls.__dataclass_fields__.keys()
return cls(**{k: v for k, v in d.items() if k in allowed})
@@ -0,0 +1,44 @@
"""이산 협상 State 모델 (우리 자체 구현, config 주입형).
Chat_server 의 state.py 는 임계값/가중치를 IntEnum 클래스변수로 박아 config 주입이 불가능했다.
여기서는 임계값/가중치/코드맵을 모두 TenantConfig.state(StateConfig)에서 주입받고,
State 는 차원 인덱스 튜플만 보유하는 순수 값객체로 둔다.
state_index 는 mixed-radix(혼합 진법) 인코딩으로 차원 곱 공간에 매핑한다 — 차원 개수가
회사마다 달라도 일반적으로 동작한다(기능적 방법).
"""
from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class State:
"""5개 이산 차원 인덱스. 각 인덱스는 해당 차원의 [0, dim) 범위."""
revenue_idx: int
distribution_idx: int
partner_idx: int
acceptance_idx: int
price_zone_idx: int
def to_tuple(self) -> tuple[int, int, int, int, int]:
return (self.revenue_idx, self.distribution_idx, self.partner_idx, self.acceptance_idx, self.price_zone_idx)
def encode_index(indices: List[int], dims: List[int]) -> int:
"""mixed-radix 인코딩: indices 를 dims 진법으로 단일 정수에 매핑.
idx = ((...(i0)*d1 + i1)*d2 + i2)...)*d_{n-1} + i_{n-1}
범위/차원 검증 포함 — 잘못된 입력은 즉시 실패(학습 차원 오염 방지).
"""
if len(indices) != len(dims):
raise ValueError(f"indices/dims length mismatch: {len(indices)} vs {len(dims)}")
idx = 0
for i, (val, dim) in enumerate(zip(indices, dims)):
if dim <= 0:
raise ValueError(f"dim[{i}] must be positive, got {dim}")
if not (0 <= val < dim):
raise ValueError(f"index[{i}]={val} out of range [0,{dim})")
idx = idx * dim + val
return idx