와일들카드 선택 수정 .

This commit is contained in:
HyeongBaeYang committed 2026-07-07 17:16:19 +09:00
1 parent 8c700b1e08
commit 15f3d10eb6
11 files changed
+266 -10

No files matched your search

+34 -6
View File
@@ -63,11 +63,20 @@ class ChatService:
)
if session is None:
selected_nego_cards = db_ctx.selected_nego_card_numbers if db_ctx else []
selected_wild_cards = db_ctx.selected_wild_card_numbers if db_ctx else []
# 운영 DB 세션은 견적 version_id 에 묶인 카드만 사용한다. 직접 호출/데모(DB context 없음)는
# 기존 테넌트 기본 action mapping 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
action_space_size = (
min(len(selected_nego_cards), engine.action_space_size)
if db_ctx is not None
else engine.action_space_size
)
# session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
session = ChatSession(
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
rq_type=rq_type, action_space_size=engine.action_space_size,
rq_type=rq_type, action_space_size=action_space_size,
context={
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader).
# 미기재/미지정이면 기본값 폴백.
@@ -83,6 +92,13 @@ class ChatService:
"round": 0,
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
"item_price": db_ctx.item_price if db_ctx else 0,
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
# 선택된 와일드카드가 있을 때만 허용한다.
"db_context_loaded": db_ctx is not None,
"selected_nego_card_numbers": selected_nego_cards,
"selected_wild_card_numbers": selected_wild_cards,
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
},
)
view = chat_engine.start(session)
@@ -105,7 +121,7 @@ class ChatService:
res.settled_price = int(session.context["input_price"])
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
if view.error is None and engine.action_space_size > 0:
if view.error is None and session.action_space_size > 0:
if view.needs_card_selection:
await self._select_and_learn(engine, chat_engine, repo, session, res)
elif view.outcome is not None:
@@ -172,11 +188,11 @@ class ChatService:
LOG.e_no_callstack(f"[ChatService] state error: {ex}")
return
policy, version_id, repo = await QTablePolicyStore.load(engine)
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=session.action_space_size,
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
decision = policy.select(ctx)
session.used_action_ids.add(decision.action_id)
card_id = engine.mapper.get_card_id(decision.action_id)
card_id = self._card_id_for_action(engine, session, decision.action_id)
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
@@ -195,7 +211,12 @@ class ChatService:
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
card_script = await scripts.resolve_card_script(decision.action_id, card_id, chat_engine.vars_for(session))
card_script = await scripts.resolve_card_script(
decision.action_id,
card_id,
chat_engine.vars_for(session),
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
)
if card_script:
res.script = card_script
c = session.context
@@ -218,9 +239,16 @@ class ChatService:
policy.update(Transition(state_index=last_state, action_id=last_action, reward=reward.total, done=True))
await QTablePolicyStore.persist_cell(repo, version_id, policy, last_state, last_action)
await self._log(repo, session, last_state, last_action,
engine.mapper.get_card_id(last_action), snap, reward, None, done=True)
self._card_id_for_action(engine, session, last_action), snap, reward, None, done=True)
res.updated_q = float(policy.qtable.q[last_state, last_action])
@staticmethod
def _card_id_for_action(engine: TenantEngine, session: ChatSession, action_id: int) -> Optional[str]:
selected = session.context.get("selected_nego_card_numbers") or []
if 0 <= action_id < len(selected):
return str(selected[action_id])
return engine.mapper.get_card_id(action_id)
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
data = {
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,