협상 불가 사유를 내면 500 이 나고, 거부 폼은 목록·채팅이 따로 놀았으며,
제출한 내용을 다시 볼 방법이 없었다. 결렬 건은 협력사가 낸 거부가를 계약가로
간주해 낙찰시켜 절감 통계가 음수로 뒤집힐 수 있었고, 견적 상세는 판정 가격이
세 곳에 흩어져 대화 탭에선 아예 보이지 않았다.
agent
- 결렬 종료 로깅 크래시 수정 — _log 를 action_id 기반으로 되돌리고 선택 근거
(Q·UCB·방문수)는 decision/policy 가 있을 때만 채운다. 종료 행은 카드 선택이
없고 policy.update 뒤라 값을 넣으면 학습 화면 집계가 오염된다
negosium
- 거부 폼을 목록·채팅 공용 컴포넌트 하나로 통일(사유 3종 + 공급 희망가·의견 선택)
- 거부 사유 열람 — 목록에 '거부 사유 보기'(부가정보 보기와 같은 규격), 채팅
재진입 시 대화 끝에 거부 내역 카드. 목록·채팅 init 응답에 reject_reason·reject_price 추가
- 자유 입력 거부("협상 포기합니다")가 사유 NULL 로 저장되던 문제 수정 — 폼 마커가
없으면 원문을 사유로 쓰고, 문장 속 숫자를 희망가로 오인하지 않는다
- koreanNumber 를 전역 lib 으로 이동(공용 폼이 쓴다)
negodata
- 직접 낙찰에 계약가 입력 — 결렬·미응찰 건을 오프라인으로 다시 협상한 결과를
담당자가 확정해 넣는다. 후보는 초청 협력사 전부(가격 미제출도 포함),
계약가는 sessions.custom.offline_award 에 근거·작성자·시각과 함께 남긴다
- 통계 계약가 = 담당자 확정가 우선, 없으면 투찰가. 거부가를 계약가로 치던 파생 제거.
KPI 에 오프라인 반영 건수 추가
- 견적 상세 리모델링 — 가격 레일(앵커링가/투찰현황 · 목표가 · 타결 상한가 · 결과가)을
시트에 고정해 접힘·탭 전환에도 남기고, 스펙트럼에 타결 판정선과 구간색 추가.
라벨은 폭을 실측해 두 레인으로 배치(겹침 불가). 상품·마감시각 등 전 행 동일 컬럼 제거,
협상현황에 부가정보 노출, 1:1 은 협력사·세션상태를 결과 밴드로 올림
테스트: negosium 58 · negodata 110 통과. 프론트 빌드/린트 통과.
121 lines
6.1 KiB
Python
121 lines
6.1 KiB
Python
"""NegotiationService — 협상 한 라운드 (실제 UCB Q-Table 학습 정책, H1).
|
|
|
|
흐름: 관측치 → build_state → 정책 로드(learning 스키마) → UCB 선택(propensity) → reward
|
|
→ Q-learning 온라인 갱신 + touched 셀 write-through → experience_logs 기록.
|
|
|
|
반복 호출하면 visit/Q 가 DB 에 누적되어 학습이 진행된다(같은 state 를 칠수록 탐색 보너스↓, Q 수렴).
|
|
대화형 /chat·step 체계·시퀀스 보상링크는 P5/P7. 여기는 단일 라운드 단위.
|
|
"""
|
|
|
|
import uuid
|
|
|
|
from common.enums import DBType, ErrorType
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.logger import LOG
|
|
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
|
from negotiation.policy.model_store import QTablePolicyStore
|
|
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
|
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
|
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
|
from negotiation.qtable.domain.service.state_calculator import build_state, state_index
|
|
from router.v1.negotiation.protocol import Req_NegotiationStep, Res_NegotiationStep, RewardView, StateView
|
|
from tenancy.registry import TenantEngine
|
|
|
|
|
|
class NegotiationService:
|
|
async def step(self, engine: TenantEngine, req: Req_NegotiationStep) -> Res_NegotiationStep:
|
|
res = Res_NegotiationStep(tenant_id=engine.tenant_id, company_id=engine.company_id)
|
|
|
|
# 1) 관측치 → snapshot
|
|
try:
|
|
outcome = NegotiationOutcome(req.outcome)
|
|
except ValueError:
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
res.msg = f"outcome must be ongoing|success|failure, got {req.outcome!r}"
|
|
return res
|
|
|
|
# 앵커링값은 갑(KT/iMK)이 직접 입력한 값을 사용.
|
|
snap = NegotiationSnapshot(
|
|
revenue_amount=req.revenue_amount, distribution_code=req.distribution_code,
|
|
partner_count=req.partner_count, acceptance_ratio=req.acceptance_ratio,
|
|
input_price=req.input_price, anchor_price=req.anchor_price, target_price=req.target_price,
|
|
round_number=req.round_number, outcome=outcome,
|
|
)
|
|
|
|
# 2) 상태 산출 (config 주입)
|
|
try:
|
|
st = build_state(snap, engine.config.state)
|
|
idx = state_index(snap, engine.config.state)
|
|
except ValueError as ex:
|
|
res.result.SetResult(ErrorType.NEGO_INVALID_STEP)
|
|
res.msg = str(ex)
|
|
return res
|
|
|
|
# 3) 정책 로드 (learning 스키마 활성 버전) → UCB 선택
|
|
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
|
episode = EpisodeState(used_action_ids=set(req.used_action_ids or []))
|
|
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size, episode=episode)
|
|
decision = policy.select(ctx)
|
|
decision.card_id = engine.mapper.get_card_id(decision.action_id)
|
|
|
|
# 4) 보상
|
|
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
|
|
|
# 5) 학습: Q-learning 온라인 갱신 + touched 셀 영속화
|
|
updated_q = decision.q_value
|
|
if req.learn:
|
|
done = outcome != NegotiationOutcome.ONGOING
|
|
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=done))
|
|
updated_q = float(policy.qtable.q[idx, decision.action_id])
|
|
try:
|
|
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
|
res.learned = True
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(f"[NegotiationService] persist failed: {ex}")
|
|
|
|
# 6) 응답 채우기
|
|
session_id = req.session_id or str(uuid.uuid4())
|
|
res.session_id = session_id
|
|
res.state_index = idx
|
|
res.state = StateView(
|
|
revenue_idx=st.revenue_idx, distribution_idx=st.distribution_idx, partner_idx=st.partner_idx,
|
|
acceptance_idx=st.acceptance_idx, price_zone_idx=st.price_zone_idx,
|
|
)
|
|
res.action_id = decision.action_id
|
|
res.card_id = decision.card_id
|
|
res.propensity = decision.propensity
|
|
res.available_actions = decision.available_actions
|
|
res.reward = RewardView(
|
|
price_reward=reward.price_reward, end_reward=reward.end_reward,
|
|
penalty=reward.penalty, weight=reward.weight, total=reward.total,
|
|
)
|
|
res.policy = policy.name
|
|
res.q_value = decision.q_value
|
|
res.ucb_score = decision.ucb_score
|
|
res.updated_q = updated_q
|
|
res.visit_count = int(policy.qtable.visits[idx, decision.action_id])
|
|
|
|
# 7) experience_logs 기록
|
|
if req.log:
|
|
res.logged = await self._log(engine, session_id, idx, decision, snap, reward, policy)
|
|
return res
|
|
|
|
async def _log(self, engine, session_id, idx, decision, snap, reward, policy) -> bool:
|
|
repo = LearningRepository(engine.company_id)
|
|
data = {
|
|
"session_id": session_id, "state_index": idx, "action_id": decision.action_id,
|
|
"card_id": decision.card_id, "snapshot": snap.to_dict(), "propensity": decision.propensity,
|
|
"turn": snap.round_number, "available_actions": decision.available_actions,
|
|
"reward": reward.total, "done": snap.outcome != NegotiationOutcome.ONGOING,
|
|
"q_value_at_selection": decision.q_value, "ucb_score_at_selection": decision.ucb_score,
|
|
"visit_count_at_selection": int(policy.qtable.visits[idx, decision.action_id]),
|
|
"total_visits_at_selection": int(policy.qtable.state_visits(idx)),
|
|
"settled_price": int(snap.input_price) if snap.outcome == NegotiationOutcome.SUCCESS else None,
|
|
}
|
|
try:
|
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [lambda s: repo.log_transition(s, data)])
|
|
return err == ErrorType.SUCCESS
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(f"[NegotiationService] log failed: {ex}")
|
|
return False
|