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

View File
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