"""ChatEngine — 스텝 기반 협상 대화 엔진. 고정 스텝은 스크립트 JSON, 동적 스텝('가격협상')은 Q-Table 카드 선택으로 처리한다. """ import json import logging import math from pathlib import Path from typing import Optional from common.paths import RESOURCES_DIR, resolve_data_path from config.config_models import AppConfig from router.v1.nego.protocol import ( ChatMetadata, NegotiationRequest, NegotiationResponse, ) from services.cards.completer import CardScriptCompleter from services.cards.repository import CardScriptRepository from services.negotiation.formatting import ScriptFormatter from services.negotiation.indicator import ThreeSegIndicator from services.negotiation.orchestrator import NegotiationOrchestrator from services.negotiation.steps import StepActionHandler from services.negotiation.tension import estimate_tension, select_persona from services.policy.snapshot import NegotiationSnapshot, build_state from services.profiling import build_profiler logger = logging.getLogger(__name__) SCRIPTS_DIR = RESOURCES_DIR / "scripts" MAX_ITERATION = 5 class ChatEngine: def __init__(self, config: AppConfig): self.config = config self.orchestrator = NegotiationOrchestrator() self.card_script_repo = CardScriptRepository() self.script_formatter = ScriptFormatter(self.card_script_repo) self.indicator_calculator = ThreeSegIndicator() self.step_action_handler = StepActionHandler() self.completer = CardScriptCompleter(self.card_script_repo) self.scripts = self._load_scripts() # N-profiling (on/off) — 비활성/키 없음이면 None self.profiler = build_profiler( api_key=config.openai.api_key, model=config.openai.model, enabled=config.profiling.enabled, ) # 긴장도 계측 경로 (빈 문자열이면 끔) self._tension_log_path: Optional[Path] = None if config.instrument.tension_log: self._tension_log_path = resolve_data_path(config.instrument.tension_log) self._tension_log_path.parent.mkdir(parents=True, exist_ok=True) # ⑦ 계약 데이터화 경로 (빈 문자열이면 끔) self._contracts_log_path: Optional[Path] = None if config.instrument.contracts_log: self._contracts_log_path = resolve_data_path(config.instrument.contracts_log) self._contracts_log_path.parent.mkdir(parents=True, exist_ok=True) # 세션 경계 감지용 — 세션이 바뀌면 UCB 에피소드 초기화 self._last_session_id: Optional[str] = None # ------------------------------------------------------------------ setup def reload_scripts(self): self.script_formatter.reload() self.scripts = self._load_scripts() def _load_scripts(self) -> dict: scripts = {} config_map = { "재협상": "scripts_renegotiation.json", "재견적": "scripts_requote.json", } for rq_type, filename in config_map.items(): path = SCRIPTS_DIR / filename try: with open(path, "r", encoding="utf-8") as f: scripts[rq_type] = json.load(f) except FileNotFoundError: logger.warning(f"{filename} not found at {path}") scripts[rq_type] = {} # 와일드카드 스크립트 로드 후 '재협상'에 병합 (직접 전이 허용) wildcard_path = RESOURCES_DIR / "cards" / "wild_card.json" try: with open(wildcard_path, "r", encoding="utf-8") as f: self.wildcard_scripts = json.load(f) except FileNotFoundError: logger.warning(f"wild_card.json not found at {wildcard_path}") self.wildcard_scripts = {} if "재협상" in scripts: for card_id, config in self.wildcard_scripts.items(): scripts["재협상"][card_id] = config mapping_path = SCRIPTS_DIR / "client_step_mapping.json" try: with open(mapping_path, "r", encoding="utf-8") as f: self.client_step_mapping = json.load(f) except FileNotFoundError: logger.warning(f"client_step_mapping.json not found at {mapping_path}") self.client_step_mapping = {} return scripts def _get_client_step(self, internal_step: str) -> str: if internal_step in self.client_step_mapping: return self.client_step_mapping[internal_step] # 협상 카드류(no_*, wild_*)는 모두 '가격협상' 소속 if internal_step.startswith("no_") or internal_step.startswith("wild_"): return "가격협상" return "가격협상" # ---------------------------------------------------------------- session def reset_episode(self, session_id: Optional[str] = None): """협상 세션 경계에서 UCB 에피소드 상태 초기화""" self.orchestrator.reset_episode() logger.info(f"[ChatEngine] episode reset (session={session_id})") def _check_session_boundary(self, request: NegotiationRequest): """세션이 바뀌면 에피소드를 자동 초기화한다 (카드 라운드로빈 방지).""" if request.session_id and request.session_id != self._last_session_id: if self._last_session_id is not None: self.reset_episode(request.session_id) self._last_session_id = request.session_id # ------------------------------------------------------------------ main def process_request(self, request: NegotiationRequest) -> NegotiationResponse: self._check_session_boundary(request) rq_type = request.rq_type current_scripts = self.scripts.get(rq_type, self.scripts.get("재협상", {})) step = request.step step_config = current_scripts.get(step) if not step_config: return NegotiationResponse( index=request.index + 1, script=f"해당 단계({step})에 대한 정의가 없습니다. (Type: {rq_type})", step=step, client_step=self._get_client_step(step), next_input_mode="null", sender="bot", type="text", chat_end=True, input_options=[], ) next_step = self._resolve_next_step(step_config.get("next_step", ""), request) next_step_config = current_scripts.get(next_step) if next_step == "가격협상": response = self._handle_dynamic_step(request, step_config, next_step) else: response = self._handle_fixed_step(request, next_step, next_step_config) # 스텝 후처리 (재견적 1% 할인 등) self.step_action_handler.execute_post_step_actions(request, response) # 1% 와일드카드 최종가 주입 if request.step == "wild_card_1pct" and response.step == "협상완료": try: input_price = float(request.input or 0) if response.chat_metadata is None: response.chat_metadata = ChatMetadata() if request.user_input == "예": response.chat_metadata.price = math.floor(input_price * 0.99) else: response.chat_metadata.price = int(input_price) except (ValueError, TypeError): pass # 가격 전파 — 핸들러가 안 채웠으면 요청의 현재가를 채운다 if response.chat_metadata is None: response.chat_metadata = ChatMetadata() if response.chat_metadata.price is None and request.input is not None: try: response.chat_metadata.price = float(request.input) except (ValueError, TypeError): pass # 카드 데이터 전파 if request.card_data: response.chat_metadata.card_data = request.card_data # [⑦ 계약 데이터화] 협상완료 도달 시 계약 레코드 기록 if response.step == "협상완료": self._log_contract(request, response) return response def _log_contract(self, request: NegotiationRequest, response: NegotiationResponse): """협상 챗봇으로 이루어진 계약의 데이터화 (config.instrument.contracts_log).""" if self._contracts_log_path is None: return try: from datetime import datetime, timezone, timedelta final_price = response.chat_metadata.price if response.chat_metadata else None record = { "ts": datetime.now(timezone(timedelta(hours=9))).isoformat(), "session_id": request.session_id, "rq_type": request.rq_type, "item_price": request.item_price, "initial": request.initial, "final_price": final_price, "target": request.target, "anchor": request.anchor, "iteration": request.iteration, "dist": request.dist, "partners_yn": request.partners_yn, "reduction_pct": (round(100 * (float(request.item_price) - float(final_price)) / float(request.item_price), 3) if request.item_price and final_price else None), } with open(self._contracts_log_path, "a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") except (TypeError, ValueError, OSError) as e: logger.warning(f"[contracts] 계약 기록 실패(무시): {e}") # ----------------------------------------------------------- fixed steps def _handle_fixed_step(self, request: NegotiationRequest, next_step: str, next_step_config: dict) -> NegotiationResponse: chat_metadata = ChatMetadata(iteration=request.iteration) if next_step_config is None: return NegotiationResponse( index=request.index + 1, script="", sender="bot", type="text", chat_end=True, next_input_mode="null", input_options=[], step=next_step, client_step=self._get_client_step(next_step), chat_metadata=chat_metadata, ) raw_script = next_step_config.get("script", "") formatted_script = self.script_formatter.format_script(raw_script, request) return NegotiationResponse( index=request.index + 1, script=formatted_script, sender="bot", type=next_step_config.get("type", "text"), chat_end=next_step_config.get("chat_end", False), next_input_mode=next_step_config.get("next_input_mode", "null"), input_options=next_step_config.get("input_options", []), step=next_step, client_step=self._get_client_step(next_step), chat_metadata=chat_metadata, ) # ---------------------------------------------------------- dynamic step def _handle_dynamic_step(self, request: NegotiationRequest, config: dict, next_step_id: str = "가격협상") -> NegotiationResponse: """'가격협상' 동적 스텝 — Q-Table 카드 선택.""" # user_input이 숫자면 현재가로 반영, 아니면 보존된 request.input 사용 try: request.input = float(request.user_input) except (ValueError, TypeError): if request.input is None: return NegotiationResponse( index=request.index + 1, sender="bot", type="text", script="가격 정보가 유실되었습니다. 처음부터 다시 시작해 주세요.", step=request.step, client_step=self._get_client_step(request.step), next_input_mode="null", chat_end=True, input_options=[], ) if request.revenue is None: logger.warning("[DynamicStep] revenue 없음 — 기본값 1,000,000 적용") request.revenue = 1000000.0 if any(v is None for v in [request.revenue, request.dist, request.partners, request.anchor, request.target, request.input, request.initial]): return NegotiationResponse( index=request.index + 1, sender="bot", type="text", script="가격 협상을 위해서는 추가 정보(매출, 유통코드, 파트너수, 가격정보 등)가 필요합니다.", step=request.step, client_step=self._get_client_step(request.step), next_input_mode="null", chat_end=True, input_options=[], ) current_iteration = request.iteration or 0 if current_iteration >= MAX_ITERATION: return NegotiationResponse( index=request.index + 1, sender="bot", type="text", script=f"더 이상 가격 협상을 진행할 수 없습니다. (최대 {MAX_ITERATION}회 초과)", step="협상종료", client_step="협상종료", chat_end=True, next_input_mode="null", input_options=[], chat_metadata=ChatMetadata(iteration=current_iteration), ) # [⑩ 계측] 가격 지표(단계 변수) → 예측 긴장도 추정 → 페르소나 선택 → 로그 indicator_result = None tension_est, persona = None, None try: indicator_result = self.indicator_calculator.calculate( int(request.anchor), int(request.input), int(request.target)) except (ValueError, TypeError): pass if indicator_result is not None and request.initial \ and float(request.initial) > float(request.target): tension_est = estimate_tension(indicator_result.indicator_value, float(request.target), float(request.initial)) persona = select_persona(tension_est) self._log_tension(request, tension_est, indicator_result.indicator_value, persona["name"]) # 1. 스냅샷 → State acceptance_ratio = None if request.initial and request.initial > 0 and request.input is not None: try: acceptance_ratio = (float(request.initial) - float(request.input)) \ / float(request.initial) except (ValueError, TypeError): acceptance_ratio = 0.0 snapshot = NegotiationSnapshot( revenue_amount=request.revenue, distribution_code=request.dist, partner_count=request.partners, anchor_price=request.anchor, target_price=request.target, input_price=request.input, initial_price=request.initial, acceptance_ratio=acceptance_ratio, ) current_state = build_state(snapshot) # 2. 카드 선택 (신규견적은 학습 격리 — 방문수 미증가, argmax) result = self.orchestrator.select_card( current_state, excluded_cards=request.excluded_cards, isolate_learning=request.is_new_quote, ) # 3. 카드 스크립트 완성 (card_data 치환 + 미치환 문장 숨김) card_id = result.get("card_id") if card_id: completed_script = self.completer.execute(card_id, request.card_data) if completed_script: result["script"] = completed_script # 4. N-profiling — LLM 톤 재작성 (요청별 override > 서버 설정) # 톤은 예측 긴장도로 선택된 페르소나를 따른다 (⑩ "수치에 따라 페르소나 적용") if self._profiling_active(request) and result.get("script"): context = { "price": request.input, "anchor": request.anchor, "target": request.target, "partner_personality": request.mbti, "persona": persona["name"] if persona else None, "tone": persona["tone"] if persona else "Professional, polite, yet firm in negotiation stance. " "Adapt to the partner's personality if provided.", } rewritten = self.profiler.rewrite(result["script"], context) if rewritten: result["script"] = rewritten logger.info(f"[profiling] 스크립트 재작성 적용 (card={card_id})") else: logger.info(f"[profiling] 재작성 실패/검증 탈락 — 원문 유지 (card={card_id})") # 5. 다음 스텝 결정 rq_type = request.rq_type current_scripts = self.scripts.get(rq_type, self.scripts.get("재협상", {})) dynamic_step_config = current_scripts.get(next_step_id, {}) next_step_def = dynamic_step_config.get("next_step", {}) next_step = next_step_def.get("default", "가격협상_확인") script_text = result.get("script", "") if "수락" in script_text or "타결" in script_text: next_step = "협상종료" chat_metadata = ChatMetadata( card_id=result.get("card_id"), q_value=result.get("q_value"), visit_count=result.get("visit_count"), iteration=current_iteration + 1, indicator_value=indicator_result.indicator_value if indicator_result else None, indicator_range=indicator_result.indicator_range if indicator_result else None, tension=round(tension_est, 4) if tension_est is not None else None, persona=persona["name"] if persona else None, price=request.input, ) return NegotiationResponse( index=request.index + 1, sender="bot", type=dynamic_step_config.get("type", "text"), script=script_text, chat_end=dynamic_step_config.get("chat_end", False), next_input_mode=dynamic_step_config.get("next_input_mode", "percent"), input_options=dynamic_step_config.get("input_options", []), step=next_step_id, client_step=self._get_client_step(next_step_id), chat_metadata=chat_metadata, ) def _profiling_active(self, request: NegotiationRequest) -> bool: """요청별 override가 있으면 우선, 없으면 서버 설정. 프로파일러 미생성 시 항상 False.""" if self.profiler is None: if request.profiling: logger.warning("[profiling] 요청이 활성화를 원했지만 프로파일러 미생성 상태") return False if request.profiling is not None: return request.profiling return self.config.profiling.enabled def _log_tension(self, request: NegotiationRequest, tension_est: float, indicator_value: int, persona_name: str): """⑩ 계측 기록 — 지표점수 역산 예측 긴장도 + 적용 페르소나 (config.instrument.tension_log).""" if self._tension_log_path is None: return try: with open(self._tension_log_path, "a", encoding="utf-8") as f: f.write(json.dumps({ "session_id": request.session_id, "index": request.index, "iteration": request.iteration or 0, "rq_type": request.rq_type, "predicted": round(tension_est, 4), "indicator": indicator_value, "persona": persona_name, }, ensure_ascii=False) + "\n") except (TypeError, ValueError, OSError): pass # --------------------------------------------------------- step routing def _resolve_next_step(self, next_step_def, request: NegotiationRequest) -> str: """ next_step 정의 해석: - 문자열: 직접 전이 - 딕셔너리: 사용자 입력 기반 매핑 (값이 리스트면 조건 규칙 평가) """ user_input = request.user_input if isinstance(next_step_def, dict): if user_input in next_step_def: target = next_step_def[user_input] elif "default" in next_step_def: target = next_step_def["default"] else: return "input_error" if isinstance(target, list): return self._evaluate_rules(target, request) return target elif isinstance(next_step_def, str): return next_step_def return "" def _evaluate_rules(self, rules: list, request: NegotiationRequest) -> str: """조건 규칙 리스트에서 첫 번째로 매칭되는 전이를 찾는다.""" for rule in rules: condition = rule.get("condition") next_target = rule.get("next") # 동적 와일드카드 선택 if condition == "check_wildcard_entry": selected_card = self._select_best_wildcard(request) if selected_card: return selected_card continue # 적합한 와일드카드 없음 — 다음 규칙 시도 if self._evaluate_condition(condition, request): return next_target return "협상종료" def _select_best_wildcard(self, request: NegotiationRequest) -> Optional[str]: """와일드카드 발동 판단. card_id("wild_card_1pct" 등) 또는 None.""" current_iteration = request.iteration or 0 input_price = request.input or float("inf") anchor_price = request.anchor or 0.0 supplier_type = self._determine_supplier_type( request.dist, partners_yn=request.partners_yn) # 1. [1% 추가 네고] 조기 성공: 최종 라운드 이전 AND 입력가 ≤ 앵커 AND 유형 A/B/C if current_iteration <= MAX_ITERATION - 1 and input_price <= anchor_price: if supplier_type in ["A", "B", "C"]: return "wild_card_1pct" # 2. [재원부족 전략] 마지막 회차, Type C, 목표가 +3% 이내 if current_iteration >= MAX_ITERATION and supplier_type == "C": target_price = request.target or 0 if target_price < input_price <= target_price * 1.03: return "wild_card_budget" # 3. [1% 추가 네고 — 최종 라운드 무조건 발동] # 가격 라운드 소진 시 유형·가격대와 무관하게 최종 제안 카드를 발동한다. if current_iteration >= MAX_ITERATION: return "wild_card_1pct" return None def _determine_supplier_type(self, dist: str, partners_yn: str = None) -> str: """ 공급사 유형: A=유통(R), B=총판(W)+다수, C=제조(M) 또는 총판(W)+단독/없음 """ if dist == "R": return "A" if dist == "W": if partners_yn == "다수": return "B" elif partners_yn in ["단독", "없음"]: return "C" return "Unknown" if dist == "M": return "C" return "Unknown" def _evaluate_condition(self, condition: str, request: NegotiationRequest) -> bool: if condition == "default": return True try: input_price = float(request.user_input) \ if self.script_formatter._is_number(request.user_input) \ else (request.input or 0.0) anchor_price = request.anchor or 0.0 target_price = request.target or float("inf") except (ValueError, TypeError): input_price = 0.0 anchor_price = 0.0 target_price = float("inf") if condition == "check_price_match": return input_price <= anchor_price elif condition == "check_is_supplier_type_c": # Type C는 가격이 앵커 이하이거나 라운드 소진 시 성공 처리 supplier_type = self._determine_supplier_type( request.dist, partners_yn=request.partners_yn) current_iteration = request.iteration or 0 return (supplier_type == "C" and (input_price <= anchor_price or current_iteration >= MAX_ITERATION)) elif condition == "check_iteration_limit": return (request.iteration or 0) >= MAX_ITERATION return False