Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화
This commit is contained in:
1 parent
212725e5f9
commit
951d6eab84
140 files changed
+6689
-214
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,56 @@
|
||||
"""ActionCardMapper — action_id ↔ card_id 매핑 (config 주입형).
|
||||
|
||||
Chat_server 의 매퍼는 JSON 파일에 결합돼 있었다. 여기서는 TenantConfig.action_mapping
|
||||
(ActionMappingConfig)에서 주입받아 테넌트별로 다른 카드셋을 지원한다.
|
||||
|
||||
PoC 는 카드 매핑을 고정한다(action_space_size ↔ Q-Table 차원 정합성 리스크 회피, 계획서).
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from tenancy.config import ActionMappingConfig
|
||||
|
||||
|
||||
class ActionCardMapper:
|
||||
def __init__(self, config: ActionMappingConfig):
|
||||
self._config = config
|
||||
self._action_to_card: Dict[int, str] = {}
|
||||
self._card_to_action: Dict[str, int] = {}
|
||||
self._rebuild()
|
||||
|
||||
def _rebuild(self):
|
||||
self._action_to_card = {int(a): c for a, c in self._config.action_to_card.items()}
|
||||
self._card_to_action = {c: a for a, c in self._action_to_card.items()}
|
||||
|
||||
def reload(self, config: ActionMappingConfig):
|
||||
"""카드 동기화/테넌트 reload 시 매핑 교체 (P6)."""
|
||||
self._config = config
|
||||
self._rebuild()
|
||||
|
||||
@property
|
||||
def action_space_size(self) -> int:
|
||||
return len(self._action_to_card)
|
||||
|
||||
def get_card_id(self, action_id: int) -> Optional[str]:
|
||||
return self._action_to_card.get(action_id)
|
||||
|
||||
def get_action_id(self, card_id: str) -> Optional[int]:
|
||||
return self._card_to_action.get(card_id)
|
||||
|
||||
def action_ids(self) -> List[int]:
|
||||
return sorted(self._action_to_card.keys())
|
||||
|
||||
def available_mask(self, used_action_ids: Optional[set] = None) -> np.ndarray:
|
||||
"""중복 방지 마스킹: 이미 사용한 action 은 False. 정책 select 시 곱해 제외한다.
|
||||
|
||||
길이 = action_space_size, dtype=bool. used_action_ids 가 None 이면 전부 True.
|
||||
"""
|
||||
n = self.action_space_size
|
||||
mask = np.ones(n, dtype=bool)
|
||||
if used_action_ids:
|
||||
for a in used_action_ids:
|
||||
if 0 <= a < n:
|
||||
mask[a] = False
|
||||
return mask
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,184 @@
|
||||
"""ChatEngine — 대화 step 전이 엔진 (동기 순수 로직, P7 슬라이스).
|
||||
|
||||
Chat_server 의 step 체계(서비스안내→담당자확인→협상품목안내→가격협상→협상완료/실패→협상종료)와
|
||||
조건 분기(check_wildcard_entry/price_match/iteration_limit)·와일드카드 진입을 우리 구현으로 재작성.
|
||||
|
||||
DB/정책(카드선택·학습)은 여기 두지 않는다 — ChatService(async)가 StepView 의 신호를 보고 처리한다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
|
||||
MAX_ROUNDS = 3
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatSession:
|
||||
session_id: str
|
||||
tenant_id: str
|
||||
company_id: str
|
||||
rq_type: str = "재협상"
|
||||
step: str = "시작"
|
||||
context: Dict[str, Any] = field(default_factory=dict)
|
||||
used_action_ids: set = field(default_factory=set)
|
||||
action_space_size: int = 0 # 카드 소진 판정용 (ChatService 가 주입)
|
||||
ended: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class StepView:
|
||||
step: str
|
||||
script: str
|
||||
input_mode: str
|
||||
input_options: List[str]
|
||||
chat_end: bool
|
||||
client_step: Optional[str] = None
|
||||
needs_card_selection: bool = False # 가격협상(에이전트 카운터) → UCB 카드선택+학습
|
||||
outcome: Optional[str] = None # 협상완료="success" / 협상실패="failure" → 종료보상
|
||||
wildcard: Optional[str] = None # 발동한 와일드카드 key
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
class ChatEngine:
|
||||
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
|
||||
self.repo = scripts_repo
|
||||
self.rq_type = rq_type
|
||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
||||
self.step_map = scripts_repo.client_step_mapping()
|
||||
|
||||
# ---- public --------------------------------------------------------
|
||||
def start(self, session: ChatSession) -> StepView:
|
||||
first = self._default_next(self.scripts.get("시작", {})) or "서비스안내"
|
||||
return self._render(session, first)
|
||||
|
||||
def advance(self, session: ChatSession, user_input: Optional[str]) -> StepView:
|
||||
if session.ended:
|
||||
return self._error(session, "협상이 종료되었습니다. 새 협상을 시작하세요.")
|
||||
node = self.scripts.get(session.step, {})
|
||||
mode = node.get("next_input_mode", "null")
|
||||
|
||||
if mode in _PRICE_MODES:
|
||||
try:
|
||||
price = float(str(user_input).replace(",", ""))
|
||||
except (TypeError, ValueError):
|
||||
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
||||
session.context["input_price"] = price
|
||||
session.context["round"] = session.context.get("round", 0) + 1
|
||||
nxt = self._default_next(node)
|
||||
elif mode in _CHOICE_MODES:
|
||||
nxt = self._choice_next(node, user_input, session)
|
||||
else:
|
||||
nxt = self._default_next(node)
|
||||
|
||||
nxt = self._resolve(nxt, session)
|
||||
return self._render(session, nxt)
|
||||
|
||||
# ---- transition ----------------------------------------------------
|
||||
def _default_next(self, node: dict) -> Optional[str]:
|
||||
ns = node.get("next_step")
|
||||
if isinstance(ns, dict):
|
||||
return ns.get("default") or next(iter(ns.values()), None)
|
||||
return ns
|
||||
|
||||
def _choice_next(self, node: dict, choice: Optional[str], session: ChatSession):
|
||||
ns = node.get("next_step") or {}
|
||||
if not isinstance(ns, dict):
|
||||
return ns
|
||||
val = ns.get(choice)
|
||||
if val is None:
|
||||
val = ns.get("default") or next(iter(ns.values()), None)
|
||||
return val
|
||||
|
||||
def _resolve(self, nxt, session: ChatSession) -> Optional[str]:
|
||||
"""조건 리스트 평가 + 가격협상_와일드 가상스텝 → 실제 와일드카드 key 로 해석."""
|
||||
if isinstance(nxt, list):
|
||||
nxt = self._eval_conditions(nxt, session)
|
||||
if nxt == "가격협상_와일드":
|
||||
nxt = self._pick_wildcard(session)
|
||||
return nxt
|
||||
|
||||
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
|
||||
"""KT 구매자 관점 조건 평가.
|
||||
- 협력사 제시가 ≤ anchor → 우선협상(협상완료).
|
||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||
"""
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
cards_used = len(session.used_action_ids)
|
||||
cards_total = session.action_space_size or 0
|
||||
for c in conds:
|
||||
cond = c.get("condition")
|
||||
ok = False
|
||||
if cond == "check_wildcard_entry":
|
||||
ok = (not ctx.get("wildcard_used")) and anchor < price <= anchor * 1.05
|
||||
elif cond == "check_is_supplier_type_c":
|
||||
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
||||
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
||||
ok = anchor > 0 and price <= anchor
|
||||
elif cond == "check_iteration_limit": # = 카드 소진
|
||||
ok = cards_total > 0 and cards_used >= cards_total
|
||||
elif cond == "default":
|
||||
ok = True
|
||||
if ok:
|
||||
return c.get("next")
|
||||
return "가격협상"
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가 살짝 초과 구간에서 인하 압박 카드 선택.
|
||||
- 앵커가에 아주 근접(≤ anchor*1.02): 1% 인하 요청(wild_card_1pct) → 앵커가 이하로 유도.
|
||||
- 그 외: 목표 매입가 맞춰달라(wild_card_budget).
|
||||
"""
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
ctx["wildcard_used"] = True
|
||||
if anchor > 0 and price <= anchor * 1.02:
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
||||
return "wild_card_1pct"
|
||||
return "wild_card_budget"
|
||||
|
||||
# ---- render --------------------------------------------------------
|
||||
def _vars(self, session: ChatSession) -> Dict[str, Any]:
|
||||
ctx = session.context
|
||||
out = {}
|
||||
if "input_price" in ctx:
|
||||
out["input_price"] = int(ctx["input_price"])
|
||||
if "target_price" in ctx:
|
||||
out["target"] = int(ctx["target_price"])
|
||||
if "offer_1pct" in ctx:
|
||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||
return out
|
||||
|
||||
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
|
||||
if not step_key or step_key not in self.scripts:
|
||||
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
|
||||
node = self.scripts[step_key]
|
||||
session.step = step_key
|
||||
session.ended = bool(node.get("chat_end"))
|
||||
outcome = "success" if step_key == "협상완료" else "failure" if step_key == "협상실패" else None
|
||||
return StepView(
|
||||
step=step_key,
|
||||
script=self.repo.format_script(node.get("script", ""), self._vars(session)),
|
||||
input_mode=node.get("next_input_mode", "null"),
|
||||
input_options=node.get("input_options", []),
|
||||
chat_end=bool(node.get("chat_end")),
|
||||
client_step=self.step_map.get(step_key, step_key),
|
||||
needs_card_selection=(step_key == "가격협상"),
|
||||
outcome=outcome,
|
||||
wildcard=step_key if step_key.startswith("wild_card_") else None,
|
||||
)
|
||||
|
||||
def _error(self, session: ChatSession, msg: str) -> StepView:
|
||||
node = self.scripts.get(session.step, {})
|
||||
return StepView(
|
||||
step=session.step, script=node.get("script", ""),
|
||||
input_mode=node.get("next_input_mode", "null"), input_options=node.get("input_options", []),
|
||||
chat_end=session.ended, client_step=self.step_map.get(session.step, session.step), error=msg,
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""ChatSessionRepository — /chat 세션 상태 DB 영속화 (P8-A).
|
||||
|
||||
인메모리 대신 learning.chat_sessions 에 진행 상태를 저장 → 서버 재시작/멀티워커 안전.
|
||||
company_id 스코프. ChatSession(dataclass) ↔ row 직렬화.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import ChatSessionRow
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.utils.gtime import GTime
|
||||
from negotiation.chat.service.chat_engine import ChatSession
|
||||
|
||||
|
||||
class ChatSessionRepository:
|
||||
def __init__(self, company_id: str):
|
||||
self.company_id = company_id
|
||||
|
||||
async def get(self, session_id: Optional[str]) -> Optional[ChatSession]:
|
||||
if not session_id:
|
||||
return None
|
||||
|
||||
def _q(s: AsyncSession):
|
||||
stmt = select(ChatSessionRow).where(
|
||||
ChatSessionRow.session_id == session_id,
|
||||
ChatSessionRow.company_id == self.company_id,
|
||||
).limit(1)
|
||||
return DB_SESSION_MNG.execute(s, stmt)
|
||||
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
if err != ErrorType.SUCCESS or not rows:
|
||||
return None
|
||||
r = rows[0]
|
||||
return ChatSession(
|
||||
session_id=str(r.session_id), tenant_id=r.tenant_id, company_id=r.company_id,
|
||||
rq_type=r.rq_type, step=r.step, context=dict(r.context or {}),
|
||||
used_action_ids=set(r.used_action_ids or []), action_space_size=r.action_space_size,
|
||||
ended=r.ended,
|
||||
)
|
||||
|
||||
async def save(self, session: ChatSession) -> ErrorType:
|
||||
values = dict(
|
||||
session_id=session.session_id, company_id=session.company_id, tenant_id=session.tenant_id,
|
||||
rq_type=session.rq_type, step=session.step, context=session.context,
|
||||
used_action_ids=sorted(session.used_action_ids), action_space_size=session.action_space_size,
|
||||
ended=session.ended, updated_at=GTime.UTC(),
|
||||
)
|
||||
|
||||
def _do(s: AsyncSession):
|
||||
stmt = pg_insert(ChatSessionRow.__table__).values(**values).on_conflict_do_update(
|
||||
index_elements=[ChatSessionRow.session_id],
|
||||
set_={k: values[k] for k in ("step", "context", "used_action_ids", "ended", "updated_at")},
|
||||
)
|
||||
return DB_SESSION_MNG.add(s, stmt)
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
|
||||
@@ -0,0 +1,105 @@
|
||||
"""ScriptRepository — 테넌트 대화 스크립트 로드 + 치환 (P7 대화엔진의 데이터 계층).
|
||||
|
||||
- rq_type("재협상"|"재견적")별 스크립트 + 와일드카드 스크립트 + step 매핑 + 변수 매핑 로드.
|
||||
- 탐색 순서: tenants/<id>/resources/ → 없으면 tenants/_base/resources/ 폴백.
|
||||
- 브랜드({company_name}/{service_name})는 TenantConfig.resources 에서 주입(클린룸: 특정사 브랜드 비포함).
|
||||
- 협상 변수({input_price}, {target}, {offer_1pct} 등)는 format_script 에서 치환.
|
||||
|
||||
Chat_server 구조 참고, 동적 import 해킹/특정사 표현은 제거(CLEANROOM.md).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from tenancy.config import TenantConfig
|
||||
|
||||
_RQ_FILES = {"재협상": "scripts_renegotiation.json", "재견적": "scripts_requote.json"}
|
||||
|
||||
|
||||
class ScriptRepository:
|
||||
def __init__(self, config: TenantConfig, tenants_dir: str):
|
||||
self._config = config
|
||||
self._tenants_dir = tenants_dir
|
||||
self._cache: Dict[str, Any] = {}
|
||||
|
||||
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
||||
def _resource_path(self, filename: str) -> Optional[str]:
|
||||
scripts_dir = self._config.resources.scripts_dir
|
||||
candidates = [
|
||||
os.path.join(self._tenants_dir, self._config.tenant_id, scripts_dir, filename),
|
||||
os.path.join(self._tenants_dir, "_base", scripts_dir, filename),
|
||||
]
|
||||
for p in candidates:
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
return None
|
||||
|
||||
def _load_json(self, filename: str) -> dict:
|
||||
if filename in self._cache:
|
||||
return self._cache[filename]
|
||||
path = self._resource_path(filename)
|
||||
if not path:
|
||||
LOG.w(f"[ScriptRepository] resource not found: {filename} (tenant={self._config.tenant_id})")
|
||||
self._cache[filename] = {}
|
||||
return {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
data.pop("_comment", None)
|
||||
self._cache[filename] = data
|
||||
return data
|
||||
|
||||
# ---- 로드 ----------------------------------------------------------
|
||||
def load_scripts(self, rq_type: str = "재협상") -> dict:
|
||||
"""rq_type 스크립트 + 와일드카드 병합(가격협상_와일드 진입용)."""
|
||||
filename = _RQ_FILES.get(rq_type, _RQ_FILES["재협상"])
|
||||
scripts = dict(self._load_json(filename))
|
||||
# 와일드카드는 재협상 흐름에 병합 (Chat_server 와 동일 동작).
|
||||
if rq_type == "재협상":
|
||||
for card_id, cfg in self._load_json("scripts_wildcard.json").items():
|
||||
scripts[card_id] = cfg
|
||||
return scripts
|
||||
|
||||
def wildcard_scripts(self) -> dict:
|
||||
return self._load_json("scripts_wildcard.json")
|
||||
|
||||
def client_step_mapping(self) -> dict:
|
||||
return self._load_json("client_step_mapping.json")
|
||||
|
||||
def variable_mapping(self) -> dict:
|
||||
return self._load_json("variable_mapping.json")
|
||||
|
||||
# ---- 치환 ----------------------------------------------------------
|
||||
def _brand_vars(self) -> Dict[str, str]:
|
||||
return {
|
||||
"company_name": self._config.resources.company_name,
|
||||
"service_name": self._config.resources.service_name,
|
||||
}
|
||||
|
||||
def format_script(self, text: str, variables: Optional[Dict[str, Any]] = None) -> str:
|
||||
"""{company_name}/{service_name} + 협상 변수 치환. 누락 변수는 원형 유지(KeyError 방지)."""
|
||||
if not text:
|
||||
return text
|
||||
ctx = self._brand_vars()
|
||||
if variables:
|
||||
ctx.update({k: v for k, v in variables.items() if v is not None})
|
||||
|
||||
class _Safe(dict):
|
||||
def __missing__(self, key):
|
||||
return "{" + key + "}"
|
||||
|
||||
try:
|
||||
return text.format_map(_Safe(ctx))
|
||||
except (ValueError, IndexError):
|
||||
return text # 형식 토큰 충돌 시 원형
|
||||
|
||||
def get_step(self, step: str, rq_type: str = "재협상", variables: Optional[Dict[str, Any]] = None) -> Optional[dict]:
|
||||
"""step 정의를 반환하되 script 를 치환해서 돌려준다."""
|
||||
scripts = self.load_scripts(rq_type)
|
||||
node = scripts.get(step)
|
||||
if node is None:
|
||||
return None
|
||||
node = dict(node)
|
||||
node["script"] = self.format_script(node.get("script", ""), variables)
|
||||
return node
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,108 @@
|
||||
"""정책 컨텍스트/결정 + 요청 스코프 episode 상태 (계획서 B 동시성, F 추상화 출발점).
|
||||
|
||||
핵심(계획서 리스크): Chat_server 의 UCBPolicy._episode_actions 는 **인스턴스 멤버**라,
|
||||
테넌트 엔진을 여러 요청이 공유하면 세션 간 오염이 발생한다. 여기서는 episode 상태를
|
||||
**요청 스코프 객체(EpisodeState)** 로 외부화하고, 정책은 stateless 하게 이를 주입받는다.
|
||||
|
||||
NegotiationPolicy(상위 추상)의 train/predict_action_dist 등 전체 인터페이스는 H0 에서 확장한다.
|
||||
P4 는 동시성에 필요한 PolicyContext/ActionDecision/EpisodeState 만 정의한다.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional, Set
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
|
||||
|
||||
@dataclass
|
||||
class EpisodeState:
|
||||
"""한 협상 세션(요청 흐름)의 가변 상태. 절대 정책/엔진 인스턴스에 두지 않는다.
|
||||
|
||||
used_action_ids: 이 에피소드에서 이미 제시한 action(중복 방지 마스킹용).
|
||||
"""
|
||||
|
||||
used_action_ids: Set[int] = field(default_factory=set)
|
||||
|
||||
def mark_used(self, action_id: int):
|
||||
self.used_action_ids.add(action_id)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PolicyContext:
|
||||
"""정책이 행동을 고르기 위해 받는 입력. state_index(이산)와 snapshot(연속) 모두 포함
|
||||
→ Q-Table/LinUCB/Offline RL 이 같은 컨텍스트를 공유한다(계획서 F).
|
||||
"""
|
||||
|
||||
state_index: int
|
||||
snapshot: NegotiationSnapshot
|
||||
action_space_size: int
|
||||
episode: EpisodeState
|
||||
available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActionDecision:
|
||||
"""정책의 출력. propensity(행동확률)는 OPE 의 전제(계획서 H0)."""
|
||||
|
||||
action_id: int
|
||||
propensity: float
|
||||
card_id: Optional[str] = None
|
||||
q_value: Optional[float] = None
|
||||
ucb_score: Optional[float] = None
|
||||
available_actions: Optional[List[int]] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Transition:
|
||||
"""학습용 (s, a, r, s', done) + OPE 메타. experience_logs 한 row 에 대응."""
|
||||
|
||||
state_index: int
|
||||
action_id: int
|
||||
reward: float
|
||||
next_state_index: Optional[int] = None
|
||||
done: bool = False
|
||||
propensity: Optional[float] = None
|
||||
|
||||
|
||||
class NegotiationPolicy(ABC):
|
||||
"""상위 정책 추상 (계획서 F). Q-Table/LinUCB/Offline RL 이 모두 이 인터페이스를 구현한다.
|
||||
|
||||
Chat_server 의 Policy.select_action(state_index, q_values: np.ndarray, ...) 는 Q값 배열에
|
||||
결합돼 LinUCB/CQL 을 감쌀 수 없었다. 여기서는 PolicyContext(state_index+snapshot)를 받아
|
||||
ActionDecision(propensity 포함)을 돌려주는 알고리즘-중립 인터페이스로 둔다.
|
||||
"""
|
||||
|
||||
name: str = "base"
|
||||
|
||||
@abstractmethod
|
||||
def select(self, ctx: PolicyContext) -> ActionDecision:
|
||||
"""행동 선택. propensity(선택확률)를 반드시 채운다(OPE 전제)."""
|
||||
|
||||
@abstractmethod
|
||||
def update(self, transition: Transition) -> None:
|
||||
"""온라인 1-스텝 갱신 (Q-learning 등). 배치 학습은 train()."""
|
||||
|
||||
def train(self, transitions: List[Transition]) -> None:
|
||||
"""오프라인 배치 학습 (기본: update 반복). 알고리즘별 override."""
|
||||
for t in transitions:
|
||||
self.update(t)
|
||||
|
||||
def predict_action_dist(self, ctx: PolicyContext) -> np.ndarray:
|
||||
"""상태에서의 행동 분포 (OPE/시뮬레이터용). 기본: 선택 액션에 1.0."""
|
||||
dist = np.zeros(ctx.action_space_size)
|
||||
dist[self.select(ctx).action_id] = 1.0
|
||||
return dist
|
||||
|
||||
def warm_start(self, other: "NegotiationPolicy") -> None:
|
||||
"""베이스 정책으로부터 초기화 (계획서 D). 기본: 미지원."""
|
||||
raise NotImplementedError
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
"""직렬화 가능한 파라미터 스냅샷(저장용). 알고리즘별 구현."""
|
||||
raise NotImplementedError
|
||||
|
||||
def load_snapshot(self, data: dict) -> None:
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,103 @@
|
||||
"""UCBQTablePolicy — UCB 탐색 기반 Q-Table 정책 (NegotiationPolicy 구현, 우리 자체 구현).
|
||||
|
||||
select: 가용 액션 중 UCB 점수 최대 선택 (중복방지 마스킹 + propensity 산출).
|
||||
update: Q-learning 1-스텝.
|
||||
|
||||
propensity(계획서 G): UCB 는 결정론적이라 그대로면 IPS 지지(support)가 0 이 된다.
|
||||
과거 로그를 ε-greedy 근사로 본다 — 선택(greedy) 액션에 (1-ε)+ε/n, 나머지 ε/n.
|
||||
이렇게 로깅된 propensity 가 OPE(IPS/DR/SNIPS)의 입력이 된다.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.policies.base import ActionDecision, NegotiationPolicy, PolicyContext, Transition
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
|
||||
|
||||
class UCBQTablePolicy(NegotiationPolicy):
|
||||
name = "qtable_ucb"
|
||||
|
||||
def __init__(self, qtable: QTable, exploration_constant: float = math.sqrt(2.0),
|
||||
epsilon: float = 0.1, mark_visits: bool = True):
|
||||
self.qtable = qtable
|
||||
self.c = exploration_constant
|
||||
self.epsilon = epsilon # propensity 근사용 ε (로깅 전용, 선택 자체는 결정론적 UCB)
|
||||
self.mark_visits = mark_visits
|
||||
|
||||
# ---- 선택 ----------------------------------------------------------
|
||||
def _available(self, ctx: PolicyContext) -> List[int]:
|
||||
if ctx.available_mask is not None:
|
||||
avail = [a for a in range(ctx.action_space_size) if ctx.available_mask[a]]
|
||||
else:
|
||||
used = ctx.episode.used_action_ids if ctx.episode else set()
|
||||
avail = [a for a in range(ctx.action_space_size) if a not in used]
|
||||
return avail or list(range(ctx.action_space_size)) # 다 썼으면 전체 허용
|
||||
|
||||
def _ucb_scores(self, state_index: int, available: List[int]) -> np.ndarray:
|
||||
q = self.qtable.row(state_index)
|
||||
visits = self.qtable.visit_row(state_index)
|
||||
total = self.qtable.state_visits(state_index)
|
||||
ln = math.log(total + 1.0)
|
||||
scores = np.full(self.qtable.action_space_size, -np.inf)
|
||||
for a in available:
|
||||
bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6))
|
||||
scores[a] = q[a] + bonus
|
||||
return scores
|
||||
|
||||
def select(self, ctx: PolicyContext) -> ActionDecision:
|
||||
available = self._available(ctx)
|
||||
scores = self._ucb_scores(ctx.state_index, available)
|
||||
action_id = int(np.argmax(scores))
|
||||
n = len(available)
|
||||
# ε-greedy 근사 propensity (greedy 액션)
|
||||
propensity = (1.0 - self.epsilon) + self.epsilon / n
|
||||
if self.mark_visits:
|
||||
self.qtable.mark_visit(ctx.state_index, action_id)
|
||||
if ctx.episode:
|
||||
ctx.episode.mark_used(action_id)
|
||||
return ActionDecision(
|
||||
action_id=action_id,
|
||||
propensity=propensity,
|
||||
q_value=float(self.qtable.row(ctx.state_index)[action_id]),
|
||||
ucb_score=float(scores[action_id]),
|
||||
available_actions=available,
|
||||
)
|
||||
|
||||
# ---- 학습 ----------------------------------------------------------
|
||||
def update(self, transition: Transition) -> None:
|
||||
self.qtable.update(
|
||||
transition.state_index, transition.action_id, transition.reward,
|
||||
next_state_index=transition.next_state_index, done=transition.done,
|
||||
)
|
||||
|
||||
def predict_action_dist(self, ctx: PolicyContext) -> np.ndarray:
|
||||
"""ε-greedy 근사 분포 (OPE/시뮬레이터용)."""
|
||||
available = self._available(ctx)
|
||||
scores = self._ucb_scores(ctx.state_index, available)
|
||||
greedy = int(np.argmax(scores))
|
||||
n = len(available)
|
||||
dist = np.zeros(ctx.action_space_size)
|
||||
for a in available:
|
||||
dist[a] = self.epsilon / n
|
||||
dist[greedy] += (1.0 - self.epsilon)
|
||||
return dist
|
||||
|
||||
# ---- warm-start / 직렬화 ------------------------------------------
|
||||
def warm_start(self, other: "UCBQTablePolicy") -> None:
|
||||
if (other.qtable.state_space_size != self.qtable.state_space_size
|
||||
or other.qtable.action_space_size != self.qtable.action_space_size):
|
||||
raise ValueError("dimension mismatch — warm-start 불가 (휴리스틱 init 폴백 필요)")
|
||||
self.qtable.q = other.qtable.q.copy()
|
||||
# 탐색 여지를 위해 visit 은 감쇠 복제 (계획서 D)
|
||||
self.qtable.visits = (other.qtable.visits * 0.5).astype(np.int64)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"cells": self.qtable.nonzero_cells(),
|
||||
"state_space_size": self.qtable.state_space_size,
|
||||
"action_space_size": self.qtable.action_space_size}
|
||||
|
||||
def load_snapshot(self, data: dict) -> None:
|
||||
self.qtable.load_cells(data.get("cells", []))
|
||||
Whitespace-only changes.
@@ -0,0 +1,67 @@
|
||||
"""QTablePolicyStore — learning 스키마에서 테넌트 UCBQTablePolicy 를 로드/영속화 (H1).
|
||||
|
||||
요청마다 활성 버전의 q_values/visit_counts 를 numpy QTable 로 적재해 정책을 조립한다(상태는 DB 가
|
||||
단일 소스). 갱신은 touched 셀만 write-through → 재시작/요청 간 학습이 보존된다.
|
||||
|
||||
PoC 단순화: 온라인 single-step 갱신(다음상태 부트스트랩은 outcome 종료 시 생략). 시퀀스 보상링크는
|
||||
P5/H 트랙에서 transition_id 기반으로 정교화한다.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import Tuple
|
||||
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
|
||||
class QTablePolicyStore:
|
||||
@staticmethod
|
||||
async def load(engine: TenantEngine) -> Tuple[UCBQTablePolicy, object, LearningRepository]:
|
||||
repo = LearningRepository(engine.company_id)
|
||||
S = engine.state_space_size
|
||||
A = engine.action_space_size
|
||||
pol_cfg = engine.config.policy
|
||||
lr = pol_cfg.learning_rate
|
||||
gamma = pol_cfg.gamma
|
||||
|
||||
# cold-start 3단 (계획서 D):
|
||||
# ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시)
|
||||
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
if active is not None:
|
||||
version_id = active.version_id
|
||||
else:
|
||||
version_id = None
|
||||
if engine.config.inherits_base:
|
||||
version_id = await repo.warm_start_from_base(
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma)
|
||||
if version_id is None:
|
||||
version_id = await repo.get_or_create_active_version(
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma)
|
||||
|
||||
qtable = QTable(S, A, learning_rate=lr, discount_factor=gamma)
|
||||
qrows, vrows = await repo.load_cells(version_id)
|
||||
for st, a, q in qrows:
|
||||
if 0 <= st < S and 0 <= a < A:
|
||||
qtable.q[st, a] = q
|
||||
for st, a, c in vrows:
|
||||
if 0 <= st < S and 0 <= a < A:
|
||||
qtable.visits[st, a] = c
|
||||
|
||||
params = pol_cfg.params or {}
|
||||
policy = UCBQTablePolicy(
|
||||
qtable,
|
||||
exploration_constant=params.get("exploration_constant", math.sqrt(2.0)),
|
||||
epsilon=params.get("propensity_epsilon", 0.1),
|
||||
)
|
||||
return policy, version_id, repo
|
||||
|
||||
@staticmethod
|
||||
async def persist_cell(repo: LearningRepository, version_id, policy: UCBQTablePolicy,
|
||||
state_index: int, action_id: int):
|
||||
"""(state, action) 셀 write-through (select 의 visit 증가 + update 의 Q 변화 반영)."""
|
||||
q_value = float(policy.qtable.q[state_index, action_id])
|
||||
count = int(policy.qtable.visits[state_index, action_id])
|
||||
await repo.upsert_cell(version_id, state_index, action_id, q_value, count)
|
||||
@@ -0,0 +1,12 @@
|
||||
"""profiling 패키지 (구 N-profiling).
|
||||
|
||||
Chat_server 의 `N-profiling` 은 패키지명에 하이픈(`-`)이 들어가 정상 import 가 불가능했고,
|
||||
`chat_engine.py` 에서 `importlib.util.spec_from_file_location` + `sys.modules` 수동 등록으로
|
||||
동적 로드하는 해킹(`_load_dynamic_module`)으로 우회했다.
|
||||
|
||||
여기서는 `profiling` 으로 개명하여 정식 패키지 import 로 전환한다.
|
||||
before: ScriptModifier = _load_dynamic_module("script_modifier", "ScriptModifier")
|
||||
after : from negotiation.profiling.script_modifier import ScriptModifier
|
||||
|
||||
LLM 자격증명은 P7 에서 TenantConfig.llm 주입으로 전환한다(현재는 env 폴백).
|
||||
"""
|
||||
@@ -0,0 +1,34 @@
|
||||
"""LLM 자격증명 — OpenAIConfig(toml)에서 주입.
|
||||
|
||||
프로젝트 컨벤션대로 toml 로 관리한다. P7 에서 TenantConfig.llm 로 테넌트별 오버라이드를 얹을 수 있다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class LlmCredentials:
|
||||
"""LLM 접속 정보. provider 로 openai/azure 분기."""
|
||||
|
||||
provider: str = "openai" # "openai" | "azure"
|
||||
api_key: Optional[str] = None
|
||||
model: Optional[str] = None # openai 모델명 / azure 배포 이름
|
||||
base_url: Optional[str] = None
|
||||
azure_endpoint: Optional[str] = None
|
||||
api_version: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls) -> "LlmCredentials":
|
||||
"""server_configs.openai_config 에서 생성 (전역 기본값)."""
|
||||
from config.server_configs import openai_config as c
|
||||
return cls(
|
||||
provider=c.provider, api_key=c.api_key or None, model=c.model or None,
|
||||
base_url=c.base_url or None, azure_endpoint=c.azure_endpoint or None,
|
||||
api_version=c.api_version or None,
|
||||
)
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
if self.provider == "azure":
|
||||
return bool(self.api_key and self.azure_endpoint and self.model)
|
||||
return bool(self.api_key and self.model)
|
||||
Whitespace-only changes.
@@ -0,0 +1,34 @@
|
||||
"""LangGraph 기반 대화 그래프 (구 N-profiling/domain/graph.py 이식).
|
||||
|
||||
원본 import 버그 수정: `n_profiling.llm`(존재하지 않음) → `negotiation.profiling.infra.llm_adapter`.
|
||||
chat_engine 은 이 모듈을 사용하지 않으며(script_modifier/verifier 만 사용), langgraph 는 선택 의존성이다.
|
||||
직접 import 할 때만 langgraph 가 필요하다.
|
||||
"""
|
||||
|
||||
from typing import List, TypedDict
|
||||
|
||||
from langchain_core.messages import BaseMessage
|
||||
from langgraph.graph import StateGraph
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
|
||||
from negotiation.profiling.infra.llm_adapter import get_llm
|
||||
|
||||
|
||||
class AgentState(TypedDict):
|
||||
"""대화 상태. messages: 대화 히스토리."""
|
||||
|
||||
messages: List[BaseMessage]
|
||||
|
||||
|
||||
def call_model(state: AgentState):
|
||||
response = get_llm().invoke(state["messages"])
|
||||
return {"messages": [response]}
|
||||
|
||||
|
||||
# 대화 상태를 메모리에 임시 저장하는 체크포인터.
|
||||
memory = SqliteSaver.from_conn_string(":memory:")
|
||||
|
||||
graph = StateGraph(AgentState)
|
||||
graph.add_node("llm", call_model)
|
||||
graph.set_entry_point("llm")
|
||||
graph.set_finish_point("llm")
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
"""LLM 어댑터 — openai SDK 직접 호출 (langchain 미사용).
|
||||
|
||||
provider 로 OpenAI / Azure OpenAI 분기. 무거운 import 는 호출 시점에 한다.
|
||||
chat_complete: messages → 응답 텍스트. json_mode 면 JSON 객체 강제(response_format).
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional
|
||||
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
|
||||
def _client(creds: LlmCredentials):
|
||||
if creds.provider == "azure":
|
||||
from openai import AzureOpenAI
|
||||
return AzureOpenAI(api_key=creds.api_key, azure_endpoint=creds.azure_endpoint,
|
||||
api_version=creds.api_version or "2024-06-01")
|
||||
from openai import OpenAI
|
||||
kwargs = {"api_key": creds.api_key}
|
||||
if creds.base_url:
|
||||
kwargs["base_url"] = creds.base_url
|
||||
return OpenAI(**kwargs)
|
||||
|
||||
|
||||
def chat_complete(messages: List[dict], creds: Optional[LlmCredentials] = None,
|
||||
json_mode: bool = False, temperature: float = 0.7, max_tokens: int = 1024) -> str:
|
||||
"""OpenAI(또는 Azure) chat completion 호출 → 응답 텍스트.
|
||||
|
||||
Args:
|
||||
messages: [{"role": "system"|"user"|"assistant", "content": "..."}]
|
||||
creds: 자격증명(없으면 OpenAIConfig 전역값).
|
||||
json_mode: True 면 JSON 객체 응답 강제.
|
||||
"""
|
||||
if creds is None:
|
||||
creds = LlmCredentials.from_config()
|
||||
if not creds.is_configured():
|
||||
raise RuntimeError("LLM 미설정 (OpenAIConfig.api_key/model 확인)")
|
||||
|
||||
client = _client(creds)
|
||||
kwargs = {"model": creds.model, "messages": messages,
|
||||
"temperature": temperature, "max_tokens": max_tokens}
|
||||
if json_mode:
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
resp = client.chat.completions.create(**kwargs)
|
||||
return resp.choices[0].message.content or ""
|
||||
|
||||
|
||||
def chat_json(messages: List[dict], creds: Optional[LlmCredentials] = None, **kw) -> dict:
|
||||
"""JSON 응답을 파싱해 dict 로 반환."""
|
||||
text = chat_complete(messages, creds=creds, json_mode=True, **kw)
|
||||
return json.loads(text)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""ScriptModifier — LLM 으로 협상 스크립트 어조/내용을 다듬되 구조·치환자·스타일 보존.
|
||||
|
||||
openai SDK 직접 호출(langchain 미사용). 프롬프트 문구는 우리 자체 작성(CLEANROOM.md).
|
||||
LLM 미설정/실패 시 원본을 그대로 반환(안전 폴백).
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SYSTEM = """역할: 협상 스크립트 문장 다듬기 도우미.
|
||||
입력은 JSON 블록 리스트다. 각 블록의 text 만 다듬고 그 외 모든 것은 그대로 둔다.
|
||||
규칙:
|
||||
- 출력은 입력과 동일 구조의 유효한 JSON 이어야 한다. {"script": [...]} 형태로 반환한다.
|
||||
- {price} 같은 치환자는 추가/삭제/변경하지 않는다. 입력에 있던 것만 유지한다.
|
||||
- color/bold 등 스타일 키와 children 배열 구조는 변경하지 않는다.
|
||||
- text 값만 요청된 어조/맥락에 맞게 자연스럽게 다시 쓴다(한국어).
|
||||
- 새로운 키를 추가하지 않는다."""
|
||||
|
||||
|
||||
class ScriptModifier:
|
||||
def __init__(self, creds: Optional[LlmCredentials] = None):
|
||||
self._creds = creds
|
||||
|
||||
def is_available(self) -> bool:
|
||||
creds = self._creds or LlmCredentials.from_config()
|
||||
return creds.is_configured()
|
||||
|
||||
def modify_script(self, original_script: list, context: dict = None) -> list:
|
||||
"""context(예: {'tone': 'polite'})에 맞춰 스크립트 텍스트 수정. 실패 시 원본 반환."""
|
||||
if not original_script or not isinstance(original_script, list):
|
||||
return original_script
|
||||
try:
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content":
|
||||
"원본 스크립트:\n" + json.dumps(original_script, ensure_ascii=False) +
|
||||
"\n\n맥락/지시:\n" + json.dumps(context or {}, ensure_ascii=False) +
|
||||
"\n\n위 규칙대로 다듬어 {\"script\": [...]} 로 출력."},
|
||||
]
|
||||
result = chat_json(messages, creds=self._creds)
|
||||
modified = result.get("script", result) if isinstance(result, dict) else result
|
||||
return modified if isinstance(modified, list) else original_script
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to modify script via LLM: {e}")
|
||||
return original_script
|
||||
@@ -0,0 +1,47 @@
|
||||
import re
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ScriptVerifier:
|
||||
"""수정된 스크립트가 원본의 필수 구조/데이터(파라미터 placeholder)를 유지하는지 검증.
|
||||
|
||||
구 N-profiling/script_verifier.py 이식 (로직 동일, 외부 의존성 없음).
|
||||
"""
|
||||
|
||||
def verify_script(self, original_script: list, modified_script: list) -> bool:
|
||||
if not isinstance(modified_script, list):
|
||||
logger.warning("Verification Failed: Modified script is not a list.")
|
||||
return False
|
||||
|
||||
original_params = self._extract_params(original_script)
|
||||
modified_params = self._extract_params(modified_script)
|
||||
|
||||
# 원본의 모든 파라미터가 수정본에 존재해야 한다(데이터 주입 보장).
|
||||
missing_params = original_params - modified_params
|
||||
if missing_params:
|
||||
logger.warning(f"Verification Failed: Missing parameters {missing_params}")
|
||||
return False
|
||||
|
||||
# 환각으로 추가된 파라미터(원본에 없던 변수) 금지.
|
||||
added_params = modified_params - original_params
|
||||
if added_params:
|
||||
logger.warning(f"Verification Failed: Added unknown parameters {added_params}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _extract_params(self, script: list) -> set:
|
||||
"""스크립트 구조에서 {param_name} 형태 파라미터를 추출한다."""
|
||||
params = set()
|
||||
for block in script:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
children = block.get("children", [])
|
||||
for child in children:
|
||||
text = child.get("text", "")
|
||||
matches = re.findall(r"\{([^}]+)\}", text)
|
||||
for match in matches:
|
||||
params.add(match)
|
||||
return params
|
||||
Whitespace-only changes.
Whitespace-only changes.
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
|
||||
Whitespace-only changes.
@@ -0,0 +1,74 @@
|
||||
"""RewardCalculator — 협상 라운드 보상 계산 (우리 자체 공식, RewardConfig 주입).
|
||||
|
||||
클린룸: 보상 공식의 '형태'(가격보상 + 종료보상 - 페널티, 동적 가중치)는 기능적 아이디어이고,
|
||||
아래 산식은 우리 자체 설계다(특정 고객 산식 복제 아님). 모든 계수는 RewardConfig 에서 주입.
|
||||
|
||||
PoC 의도: 학습 루프가 협상 성과(타결 여부·타결가·턴 수)를 보상으로 흡수하는지 검증.
|
||||
산식은 결정론적이며 RewardConfig 로 튜닝 가능하다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from tenancy.config import RewardConfig
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RewardBreakdown:
|
||||
"""보상 구성요소(투명성/디버깅용). total 이 학습에 쓰인다."""
|
||||
|
||||
price_reward: float
|
||||
end_reward: float
|
||||
penalty: float
|
||||
weight: float
|
||||
total: float
|
||||
|
||||
|
||||
def _clip(v: float, lo: float, hi: float) -> float:
|
||||
return max(lo, min(hi, v))
|
||||
|
||||
|
||||
class RewardCalculator:
|
||||
def __init__(self, config: RewardConfig):
|
||||
self._cfg = config
|
||||
|
||||
def _price_reward(self, snapshot: NegotiationSnapshot) -> float:
|
||||
"""KT 구매자 관점: 협력사 제시가가 낮을수록 보상↑ (anchor 앵커링가 < target 목표 매입가).
|
||||
|
||||
progress = clip((target - input) / (target - anchor), 0, 1).
|
||||
제시가가 목표가면 0, 앵커링가까지 내려오면 1, 더 낮으면 1로 캡.
|
||||
"""
|
||||
band = snapshot.target_price - snapshot.anchor_price
|
||||
if band <= 0:
|
||||
return 0.0
|
||||
return _clip((snapshot.target_price - snapshot.input_price) / band, 0.0, 1.0)
|
||||
|
||||
def _end_reward(self, outcome: NegotiationOutcome) -> float:
|
||||
if outcome == NegotiationOutcome.SUCCESS:
|
||||
return self._cfg.success_reward
|
||||
if outcome == NegotiationOutcome.FAILURE:
|
||||
return self._cfg.failure_penalty
|
||||
return self._cfg.ongoing_reward
|
||||
|
||||
def _dynamic_weight(self, snapshot: NegotiationSnapshot) -> float:
|
||||
"""라운드가 진행될수록 가중치를 beta 만큼 감쇠해 [min_weight, max_weight] 로 클립.
|
||||
|
||||
w = max_weight - beta * round_number → 초반 라운드일수록 가격보상을 더 크게 본다.
|
||||
(w1~w5 는 차원별 가중치로 P-후속 단계에서 state 차원 중요도에 결합 예정.)
|
||||
"""
|
||||
w = self._cfg.max_weight - self._cfg.beta * max(0, snapshot.round_number)
|
||||
return _clip(w, self._cfg.min_weight, self._cfg.max_weight)
|
||||
|
||||
def calculate(self, snapshot: NegotiationSnapshot) -> RewardBreakdown:
|
||||
price_reward = self._price_reward(snapshot)
|
||||
end_reward = self._end_reward(snapshot.outcome)
|
||||
weight = self._dynamic_weight(snapshot)
|
||||
penalty = self._cfg.penalty_lambda * max(0, snapshot.round_number)
|
||||
total = weight * price_reward + end_reward - penalty
|
||||
return RewardBreakdown(
|
||||
price_reward=price_reward,
|
||||
end_reward=end_reward,
|
||||
penalty=penalty,
|
||||
weight=weight,
|
||||
total=total,
|
||||
)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""build_state — NegotiationSnapshot + StateConfig → State/state_index (우리 자체 구현).
|
||||
|
||||
각 차원 인덱스 산출 규칙(기능적 방법)은 우리 설계이며, 임계값/코드맵은 config 주입이다.
|
||||
도메인은 tenant-agnostic: 같은 config + 같은 snapshot 이면 항상 같은 출력(결정론).
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.model.state import State, encode_index
|
||||
from tenancy.config import StateConfig
|
||||
|
||||
|
||||
def _threshold_bucket(value: float, thresholds: List[float]) -> int:
|
||||
"""thresholds 경계로 구간 인덱스 산출. value <= thresholds[i] 이면 i, 모두 초과면 마지막 구간.
|
||||
|
||||
경계 포함 규칙: value <= threshold → 해당 구간(하한). (예: th=[10,30] → ≤10:0, ≤30:1, else:2)
|
||||
"""
|
||||
for i, th in enumerate(thresholds):
|
||||
if value <= th:
|
||||
return i
|
||||
return len(thresholds) # 마지막 구간 (= dim-1, dim = len(thresholds)+1)
|
||||
|
||||
|
||||
def _acceptance_bucket(ratio: float, thresholds: List[float]) -> int:
|
||||
"""수용률 구간: < thresholds[0] → 0, <= thresholds[1] → 1, ... else 마지막.
|
||||
|
||||
하한은 strict-less, 이후 경계는 inclusive (low 는 미만, mid 이상은 이하).
|
||||
"""
|
||||
if ratio < thresholds[0]:
|
||||
return 0
|
||||
for i in range(1, len(thresholds)):
|
||||
if ratio <= thresholds[i]:
|
||||
return i
|
||||
return len(thresholds)
|
||||
|
||||
|
||||
def _partner_bucket(count: int) -> int:
|
||||
"""파트너 수 → 인덱스. 규약: single=0, multiple=1, none=2."""
|
||||
if count <= 0:
|
||||
return 2 # none
|
||||
if count == 1:
|
||||
return 0 # single
|
||||
return 1 # multiple
|
||||
|
||||
|
||||
def _price_zone_bucket(input_price: float, anchor_price: float, target_price: float) -> int:
|
||||
"""입력가격 구간 (KT 구매자 관점, anchor=협력사 기준가 ≥ target=KT 목표 매입가).
|
||||
|
||||
협력사 제시가가 앵커가 이하면 우선협상 가능 구간(0), 초과면 추가 협상 구간(1).
|
||||
"""
|
||||
if anchor_price <= 0 or target_price <= 0:
|
||||
raise ValueError("anchor_price/target_price must be positive")
|
||||
if input_price <= anchor_price:
|
||||
return 0 # at_or_below_anchor (우선협상 가능)
|
||||
return 1 # above_anchor (협상 지속)
|
||||
|
||||
|
||||
def state_dims(cfg: StateConfig) -> List[int]:
|
||||
"""각 차원의 크기. config 의 weights/code_map 길이로 결정."""
|
||||
return [
|
||||
len(cfg.revenue.weights),
|
||||
len(cfg.distribution.weights),
|
||||
len(cfg.partner.weights),
|
||||
len(cfg.acceptance.weights),
|
||||
len(cfg.price_zone.weights),
|
||||
]
|
||||
|
||||
|
||||
def build_state(snapshot: NegotiationSnapshot, cfg: StateConfig) -> State:
|
||||
"""snapshot 을 config 기준으로 이산 State 로 변환."""
|
||||
revenue_idx = _threshold_bucket(snapshot.revenue_amount, cfg.revenue.thresholds)
|
||||
|
||||
code = (snapshot.distribution_code or "").strip()
|
||||
if code not in cfg.distribution.code_map:
|
||||
raise ValueError(f"unknown distribution code: {snapshot.distribution_code!r} (code_map keys={list(cfg.distribution.code_map)})")
|
||||
distribution_idx = cfg.distribution.code_map[code]
|
||||
|
||||
partner_idx = _partner_bucket(snapshot.partner_count)
|
||||
acceptance_idx = _acceptance_bucket(snapshot.acceptance_ratio, cfg.acceptance.thresholds)
|
||||
price_zone_idx = _price_zone_bucket(snapshot.input_price, snapshot.anchor_price, snapshot.target_price)
|
||||
|
||||
return State(revenue_idx, distribution_idx, partner_idx, acceptance_idx, price_zone_idx)
|
||||
|
||||
|
||||
def state_index(snapshot: NegotiationSnapshot, cfg: StateConfig) -> int:
|
||||
"""snapshot → 단일 정수 state_index (mixed-radix)."""
|
||||
st = build_state(snapshot, cfg)
|
||||
return encode_index(list(st.to_tuple()), state_dims(cfg))
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,339 @@
|
||||
"""LearningRepository — learning.* 테이블 접근 (company_id 스코프, backend CRUD 컨벤션).
|
||||
|
||||
핵심 안전장치(계획서 리스크): company_id 를 **생성자에 박아** 모든 쿼리에 자동 주입한다.
|
||||
삭제/리셋도 ORM core where(company_id=...)로만 수행 → "raw SQL 전체삭제로 타사 데이터 파괴" 불가.
|
||||
메서드는 backend crud 처럼 (session, ...) 을 받고, service 는 DB_SESSION_MNG 람다로 호출한다.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import (
|
||||
BASE_COMPANY_ID,
|
||||
ExperienceLog,
|
||||
QTableVersion,
|
||||
QValue,
|
||||
TenantActionCard,
|
||||
VisitCount,
|
||||
)
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
class LearningRepository:
|
||||
def __init__(self, company_id: str):
|
||||
if not company_id:
|
||||
raise ValueError("company_id is required (테넌트 스코프 필수)")
|
||||
self.company_id = company_id
|
||||
|
||||
# ---- 버전 ----------------------------------------------------------
|
||||
async def create_version(self, s: AsyncSession, *, version_name: str, scope: int,
|
||||
state_space_size: int, action_space_size: int,
|
||||
learning_rate: float = 0.1, discount_factor: float = 0.95,
|
||||
base_version_id=None, is_active: bool = False) -> ErrorType:
|
||||
obj = QTableVersion(
|
||||
company_id=self.company_id,
|
||||
version_name=version_name,
|
||||
scope=scope,
|
||||
base_version_id=base_version_id,
|
||||
state_space_size=state_space_size,
|
||||
action_space_size=action_space_size,
|
||||
learning_rate=learning_rate,
|
||||
discount_factor=discount_factor,
|
||||
is_active=is_active,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
async def get_version_by_name(self, s: AsyncSession, version_name: str) -> Tuple[ErrorType, Optional[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.version_name == version_name, QTableVersion.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, rows[0] if rows else None
|
||||
|
||||
async def list_versions(self, s: AsyncSession) -> Tuple[ErrorType, List[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.deleted == False) # noqa: E712
|
||||
.order_by(QTableVersion.created_at.asc())
|
||||
)
|
||||
return await DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
async def get_active_version(self, s: AsyncSession) -> Tuple[ErrorType, Optional[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.is_active == True, QTableVersion.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, rows[0] if rows else None
|
||||
|
||||
# ---- 경험 로그 -----------------------------------------------------
|
||||
async def log_transition(self, s: AsyncSession, data: Dict[str, Any]) -> ErrorType:
|
||||
"""data 의 알려진 필드만 채워 ExperienceLog insert. company_id 는 항상 강제 주입."""
|
||||
allowed = {c.name for c in ExperienceLog.__table__.columns}
|
||||
payload = {k: v for k, v in data.items() if k in allowed}
|
||||
payload["company_id"] = self.company_id # 위조 방지: 항상 덮어쓴다
|
||||
return await DB_SESSION_MNG.insert(s, ExperienceLog(**payload))
|
||||
|
||||
async def update_transition_reward(self, s: AsyncSession, transition_id, *, reward: float,
|
||||
next_state_index: Optional[int] = None, done: bool = False,
|
||||
settled_price: Optional[int] = None) -> ErrorType:
|
||||
q = (
|
||||
update(ExperienceLog)
|
||||
.where(ExperienceLog.company_id == self.company_id, ExperienceLog.transition_id == transition_id)
|
||||
.values(reward=reward, next_state_index=next_state_index, done=done, settled_price=settled_price)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(s, q)
|
||||
|
||||
async def count_experience(self, s: AsyncSession) -> Tuple[ErrorType, int]:
|
||||
q = select(ExperienceLog).where(ExperienceLog.company_id == self.company_id)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, 0
|
||||
return ErrorType.SUCCESS, len(rows)
|
||||
|
||||
async def invalidate_by_session(self, s: AsyncSession, session_id, reason: str = "") -> ErrorType:
|
||||
q = (
|
||||
update(ExperienceLog)
|
||||
.where(ExperienceLog.company_id == self.company_id, ExperienceLog.session_id == session_id)
|
||||
.values(is_invalidated=True, invalidated_reason=reason)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(s, q)
|
||||
|
||||
# ---- 리셋 (스코프 강제, 타테넌트 무영향) ---------------------------
|
||||
async def _delete_experience(self, s: AsyncSession) -> ErrorType:
|
||||
# 계획서 리스크: 구 코드의 'DELETE FROM experience_logs' (WHERE 없음)를 대체.
|
||||
return await DB_SESSION_MNG.add(s, delete(ExperienceLog).where(ExperienceLog.company_id == self.company_id))
|
||||
|
||||
async def _delete_learning_rows(self, s: AsyncSession) -> ErrorType:
|
||||
for model in (QValue, VisitCount):
|
||||
err = await DB_SESSION_MNG.add(s, delete(model).where(model.company_id == self.company_id))
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
async def _delete_nonactive_versions(self, s: AsyncSession) -> ErrorType:
|
||||
return await DB_SESSION_MNG.add(
|
||||
s,
|
||||
delete(QTableVersion).where(QTableVersion.company_id == self.company_id, QTableVersion.is_active == False), # noqa: E712
|
||||
)
|
||||
|
||||
async def reset_learning(self) -> ErrorType:
|
||||
"""학습 데이터(q_values/visit_counts/experience)만 초기화. 자사 스코프."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[self._delete_learning_rows, self._delete_experience],
|
||||
)
|
||||
|
||||
async def reset_all(self) -> ErrorType:
|
||||
"""완전 초기화: 자사 experience 전체 + q_values/visit + 비활성 버전 삭제. 타테넌트 무영향."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[self._delete_experience, self._delete_learning_rows, self._delete_nonactive_versions],
|
||||
)
|
||||
|
||||
# ---- 람다 facade (service/test 용) ---------------------------------
|
||||
async def read(self, func):
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, func)
|
||||
|
||||
async def write_one(self, func):
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [func])
|
||||
|
||||
# ---- Q-Table 영속화 (H1) -------------------------------------------
|
||||
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
|
||||
learning_rate: float, discount_factor: float,
|
||||
scope: int = 2, version_name: str = "v000") -> Optional[uuid.UUID]:
|
||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)"""
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
if err == ErrorType.SUCCESS and existing is not None:
|
||||
return existing.version_id
|
||||
|
||||
vid = uuid.uuid4()
|
||||
|
||||
async def _create(s: AsyncSession) -> ErrorType:
|
||||
obj = QTableVersion(
|
||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope,
|
||||
state_space_size=state_space_size, action_space_size=action_space_size,
|
||||
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||
if err != ErrorType.SUCCESS:
|
||||
# 동시 생성 경합 등 → 다시 읽어 활성 버전 반환
|
||||
err2, existing2 = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
return existing2.version_id if existing2 else None
|
||||
return vid
|
||||
|
||||
async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int,
|
||||
learning_rate: float, discount_factor: float, visit_decay: float = 0.5,
|
||||
version_name: str = "v000_warmstart_from_base") -> Optional[uuid.UUID]:
|
||||
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
||||
|
||||
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
||||
"""
|
||||
base_repo = LearningRepository(BASE_COMPANY_ID)
|
||||
err, base_ver = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: base_repo.get_active_version(s))
|
||||
if err != ErrorType.SUCCESS or base_ver is None:
|
||||
return None
|
||||
if base_ver.state_space_size != state_space_size or base_ver.action_space_size != action_space_size:
|
||||
return None # 차원 불일치 → 휴리스틱 폴백
|
||||
|
||||
qcells, vcells = await base_repo.load_cells(base_ver.version_id)
|
||||
vid = uuid.uuid4()
|
||||
|
||||
async def _create(s: AsyncSession) -> ErrorType:
|
||||
ver = QTableVersion(
|
||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
|
||||
base_version_id=base_ver.version_id, state_space_size=state_space_size,
|
||||
action_space_size=action_space_size, learning_rate=learning_rate,
|
||||
discount_factor=discount_factor, is_active=True,
|
||||
)
|
||||
e = await DB_SESSION_MNG.insert(s, ver)
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
qobjs = [QValue(company_id=self.company_id, version_id=vid, state_index=st, action_id=a, q_value=q)
|
||||
for st, a, q in qcells]
|
||||
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=a,
|
||||
count=int(c * visit_decay)) for st, a, c in vcells]
|
||||
if qobjs:
|
||||
e = await DB_SESSION_MNG.insert(s, qobjs)
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
if vobjs:
|
||||
e = await DB_SESSION_MNG.insert(s, vobjs)
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||
return vid if err == ErrorType.SUCCESS else None
|
||||
|
||||
async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]:
|
||||
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
|
||||
def _q(s):
|
||||
q = select(QValue.state_index, QValue.action_id, QValue.q_value).where(
|
||||
QValue.company_id == self.company_id, QValue.version_id == version_id)
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
def _v(s):
|
||||
q = select(VisitCount.state_index, VisitCount.action_id, VisitCount.count).where(
|
||||
VisitCount.company_id == self.company_id, VisitCount.version_id == version_id)
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
err, qrows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
err, vrows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _v)
|
||||
return list(qrows), list(vrows)
|
||||
|
||||
# ---- 버전 전환 / 요약 (관리 API) ----------------------------------
|
||||
async def set_active_version(self, version_name: str) -> ErrorType:
|
||||
"""version_name 을 활성으로 전환(나머지 비활성). 자사 스코프."""
|
||||
err, target = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_version_by_name(s, version_name))
|
||||
if err != ErrorType.SUCCESS or target is None:
|
||||
return ErrorType.DB_INVALID_KEY
|
||||
|
||||
async def _deactivate(s):
|
||||
return await DB_SESSION_MNG.add(s, update(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id).values(is_active=False))
|
||||
|
||||
async def _activate(s):
|
||||
return await DB_SESSION_MNG.add(s, update(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.version_name == version_name)
|
||||
.values(is_active=True))
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_deactivate, _activate])
|
||||
|
||||
async def qvalue_count(self, version_id) -> int:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(QValue.id).where(
|
||||
QValue.company_id == self.company_id, QValue.version_id == version_id))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return len(rows)
|
||||
|
||||
async def recent_experience(self, limit: int = 50) -> List[dict]:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(
|
||||
ExperienceLog.transition_id, ExperienceLog.session_id, ExperienceLog.state_index,
|
||||
ExperienceLog.action_id, ExperienceLog.card_id, ExperienceLog.reward, ExperienceLog.turn,
|
||||
ExperienceLog.propensity, ExperienceLog.done, ExperienceLog.created_at,
|
||||
).where(ExperienceLog.company_id == self.company_id).order_by(ExperienceLog.id.desc()).limit(limit))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [dict(state_index=r[2], action_id=r[3], card_id=r[4], reward=r[5], turn=r[6],
|
||||
propensity=r[7], done=r[8], session_id=str(r[1]) if r[1] else None,
|
||||
transition_id=str(r[0]), created_at=str(r[9])) for r in rows]
|
||||
|
||||
async def load_transitions(self) -> List[tuple]:
|
||||
"""학습용 (state_index, action_id, reward, next_state_index, done). reward 있는 row 만."""
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(
|
||||
ExperienceLog.state_index, ExperienceLog.action_id, ExperienceLog.reward,
|
||||
ExperienceLog.next_state_index, ExperienceLog.done,
|
||||
).where(ExperienceLog.company_id == self.company_id, ExperienceLog.reward.isnot(None),
|
||||
ExperienceLog.is_invalidated == False)) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [(r[0], r[1], r[2], r[3], r[4]) for r in rows]
|
||||
|
||||
# ---- 카드 매핑 (card-update/search) -------------------------------
|
||||
async def upsert_action_card(self, action_id: int, card_id: str) -> ErrorType:
|
||||
async def _do(s):
|
||||
q = select(TenantActionCard).where(
|
||||
TenantActionCard.company_id == self.company_id, TenantActionCard.action_id == action_id,
|
||||
TenantActionCard.deleted == False) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if rows:
|
||||
return await DB_SESSION_MNG.add(s, update(TenantActionCard)
|
||||
.where(TenantActionCard.company_id == self.company_id, TenantActionCard.action_id == action_id)
|
||||
.values(card_id=card_id, updated_at=GTime.UTC()))
|
||||
return await DB_SESSION_MNG.insert(s, TenantActionCard(
|
||||
company_id=self.company_id, action_id=action_id, card_id=card_id))
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
|
||||
|
||||
async def get_action_cards(self) -> List[dict]:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(TenantActionCard.action_id, TenantActionCard.card_id)
|
||||
.where(TenantActionCard.company_id == self.company_id, TenantActionCard.deleted == False)) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [dict(action_id=r[0], card_id=r[1]) for r in rows]
|
||||
|
||||
async def upsert_cell(self, version_id, state_index: int, action_id: int, q_value: float, count: int) -> ErrorType:
|
||||
"""단일 (state, action) 셀 write-through (q_values + visit_counts). company_id 스코프."""
|
||||
def _q(s):
|
||||
stmt = pg_insert(QValue.__table__).values(
|
||||
company_id=self.company_id, version_id=version_id,
|
||||
state_index=state_index, action_id=action_id, q_value=q_value,
|
||||
).on_conflict_do_update(
|
||||
index_elements=[QValue.company_id, QValue.version_id, QValue.state_index, QValue.action_id],
|
||||
set_={"q_value": q_value},
|
||||
)
|
||||
return DB_SESSION_MNG.add(s, stmt)
|
||||
|
||||
def _v(s):
|
||||
stmt = pg_insert(VisitCount.__table__).values(
|
||||
company_id=self.company_id, version_id=version_id,
|
||||
state_index=state_index, action_id=action_id, count=count,
|
||||
).on_conflict_do_update(
|
||||
index_elements=[VisitCount.company_id, VisitCount.version_id, VisitCount.state_index, VisitCount.action_id],
|
||||
set_={"count": count},
|
||||
)
|
||||
return DB_SESSION_MNG.add(s, stmt)
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_q, _v])
|
||||
Whitespace-only changes.
Reference in new issue
Block a user