초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,578 @@
|
||||
"""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
|
||||
@@ -0,0 +1,113 @@
|
||||
"""스크립트 포매터 — 평문 템플릿에 요청 데이터를 치환한다."""
|
||||
|
||||
import math
|
||||
from typing import Any, Dict
|
||||
|
||||
from common.textutil import hide_unresolved_lines, safe_format
|
||||
from router.v1.nego.protocol import NegotiationRequest
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from services.negotiation.korean import number_to_korean
|
||||
|
||||
|
||||
class ScriptFormatter:
|
||||
"""평문 script 템플릿 치환 (Slate/editor_script 구조 없음 — 평문이 단일 정본)."""
|
||||
|
||||
def __init__(self, card_repository: CardScriptRepository = None):
|
||||
self._repo = card_repository or CardScriptRepository()
|
||||
self.card_scripts = self._load_card_scripts()
|
||||
|
||||
def reload(self):
|
||||
self.card_scripts = self._load_card_scripts()
|
||||
|
||||
def _load_card_scripts(self) -> Dict[str, str]:
|
||||
scripts = {}
|
||||
for card in self._repo.find_all():
|
||||
card_id = card.get("card_id")
|
||||
content = card.get("script")
|
||||
if card_id and content:
|
||||
scripts[card_id] = content
|
||||
return scripts
|
||||
|
||||
def format_script(self, script_identifier: str, request: NegotiationRequest) -> str:
|
||||
"""
|
||||
Args:
|
||||
script_identifier: 템플릿 문자열 또는 카드 ID (예: "NC26-002")
|
||||
"""
|
||||
if not script_identifier:
|
||||
return ""
|
||||
|
||||
context = self._build_context(request)
|
||||
|
||||
# 카드 ID면 템플릿 조회, 아니면 식별자 자체가 템플릿
|
||||
template = self.card_scripts.get(script_identifier, script_identifier)
|
||||
|
||||
formatted = safe_format(template, context)
|
||||
return hide_unresolved_lines(formatted, source=script_identifier[:30])
|
||||
|
||||
def _build_context(self, request: NegotiationRequest) -> Dict[str, Any]:
|
||||
context = {}
|
||||
|
||||
def safe_format_number(val):
|
||||
if isinstance(val, (int, float)):
|
||||
return f"{val:,.0f}"
|
||||
return str(val)
|
||||
|
||||
user_input_val = request.user_input
|
||||
if user_input_val and self._is_number(user_input_val):
|
||||
try:
|
||||
context["price"] = f"{float(user_input_val):,.0f}"
|
||||
except ValueError:
|
||||
context["price"] = user_input_val
|
||||
else:
|
||||
context["price"] = str(user_input_val) if user_input_val is not None else ""
|
||||
|
||||
fields_to_map = [
|
||||
"revenue", "partners", "anchor", "target", "initial", "input",
|
||||
"iteration", "item_price", "deadline", "vat",
|
||||
]
|
||||
for field in fields_to_map:
|
||||
val = getattr(request, field, None)
|
||||
context[field] = safe_format_number(val) if val is not None else ""
|
||||
|
||||
# 1% 추가 협상 제안가
|
||||
if request.input is not None:
|
||||
context["offer_1pct"] = safe_format_number(math.floor(request.input * 0.99))
|
||||
else:
|
||||
context["offer_1pct"] = ""
|
||||
|
||||
context["dist"] = str(request.dist) if request.dist else ""
|
||||
|
||||
if request.card_data:
|
||||
for k, v in request.card_data.model_dump().items():
|
||||
if v is not None:
|
||||
# 경쟁사 가격차는 최소 1% 표기
|
||||
if k == "competitor_price_diff" and isinstance(v, (int, float)) and v < 1:
|
||||
v = 1
|
||||
context[k] = safe_format_number(v)
|
||||
else:
|
||||
context[k] = ""
|
||||
|
||||
# 할인율 (기존가 대비 현재 제안가)
|
||||
if request.item_price is not None and request.input is not None and request.item_price > 1:
|
||||
discount = ((request.item_price - request.input) / request.item_price) * 100
|
||||
context["discount_rate"] = f"{discount:.1f}"
|
||||
else:
|
||||
context["discount_rate"] = "0.0"
|
||||
|
||||
# 한국어 가격 표기
|
||||
if request.input is not None:
|
||||
try:
|
||||
context["input_kr"] = number_to_korean(int(request.input))
|
||||
except Exception:
|
||||
context["input_kr"] = str(request.input)
|
||||
else:
|
||||
context["input_kr"] = ""
|
||||
|
||||
return context
|
||||
|
||||
def _is_number(self, s) -> bool:
|
||||
try:
|
||||
float(s)
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
@@ -0,0 +1,71 @@
|
||||
"""3구간 가격 지표 — Price(P), Anchor(A), Target(T) 기반 점수(1~99).
|
||||
|
||||
⑩ 실시간 페르소나 정확도의 긴장도(Tension) 계측 근거이기도 하다.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import IndicatorRangeEnum, IndicatorType
|
||||
|
||||
|
||||
class IndicatorResponse(BaseModel):
|
||||
indicator_type: IndicatorType
|
||||
indicator_value: int
|
||||
indicator_range: IndicatorRangeEnum
|
||||
|
||||
|
||||
class ThreeSegIndicator:
|
||||
"""3-Segment Indicator — 구간별 점수 산출."""
|
||||
|
||||
def _case1(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 1: Optimal Zone (PZ1) — P ≤ A, 점수 99 고정."""
|
||||
if anchoring_price >= current_price:
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=99,
|
||||
indicator_range=IndicatorRangeEnum.PZ1,
|
||||
)
|
||||
return None
|
||||
|
||||
def _case2(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 2: Negotiable Zone (PZ2) — A < P < T, 99→80 선형 보간."""
|
||||
if anchoring_price < current_price < target_price:
|
||||
percent = int(math.floor(
|
||||
99 - ((current_price - anchoring_price)
|
||||
/ (target_price - anchoring_price) * 19)))
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=percent,
|
||||
indicator_range=IndicatorRangeEnum.PZ2,
|
||||
)
|
||||
return None
|
||||
|
||||
def _case3(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 3: Target Exceeded Zone (PZ3) — P ≥ T, 79에서 지수 감쇠."""
|
||||
if target_price <= current_price:
|
||||
scale_exponent = int(math.floor(math.log10(target_price)))
|
||||
k = math.pow(10, -scale_exponent)
|
||||
exponent = -k * (current_price - target_price)
|
||||
raw_score = 79 * math.exp(exponent)
|
||||
percent = max(1, int(math.floor(raw_score)))
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=percent,
|
||||
indicator_range=IndicatorRangeEnum.PZ3,
|
||||
)
|
||||
return None
|
||||
|
||||
def calculate(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
ret = [
|
||||
self._case1(anchoring_price, current_price, target_price),
|
||||
self._case2(anchoring_price, current_price, target_price),
|
||||
self._case3(anchoring_price, current_price, target_price),
|
||||
]
|
||||
return next((r for r in ret if r is not None), None)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""숫자 → 한국어 표기 변환 (예: 1234 → 천이백삼십사)."""
|
||||
|
||||
|
||||
def number_to_korean(number: int) -> str:
|
||||
"""정수를 한국어 표기로 변환한다. 조 단위까지 지원."""
|
||||
if number == 0:
|
||||
return "영"
|
||||
|
||||
big_units = ["", "만", "억", "조"]
|
||||
digits = ["", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구"]
|
||||
|
||||
chunks = []
|
||||
temp_num = number
|
||||
while temp_num > 0:
|
||||
chunks.append(temp_num % 10000)
|
||||
temp_num //= 10000
|
||||
|
||||
res_str = ""
|
||||
for i, chunk in enumerate(chunks):
|
||||
if chunk == 0:
|
||||
continue
|
||||
|
||||
chunk_str = ""
|
||||
digit_1000 = chunk // 1000
|
||||
if digit_1000 > 0:
|
||||
chunk_str += (digits[digit_1000] if digit_1000 > 1 else "") + "천"
|
||||
|
||||
digit_100 = (chunk % 1000) // 100
|
||||
if digit_100 > 0:
|
||||
chunk_str += (digits[digit_100] if digit_100 > 1 else "") + "백"
|
||||
|
||||
digit_10 = (chunk % 100) // 10
|
||||
if digit_10 > 0:
|
||||
chunk_str += (digits[digit_10] if digit_10 > 1 else "") + "십"
|
||||
|
||||
digit_1 = chunk % 10
|
||||
if digit_1 > 0:
|
||||
chunk_str += digits[digit_1]
|
||||
|
||||
res_str = chunk_str + big_units[i] + res_str
|
||||
|
||||
return res_str
|
||||
@@ -0,0 +1,91 @@
|
||||
"""협상 오케스트레이터 — Q-Table·정책·카드 저장소를 조립해 카드를 선택한다.
|
||||
|
||||
Q-Table은 resources/policy/q_table.json (휴리스틱 초기값)에서 로드한다. DB 없음.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
from services.cards.mapper import ActionCardMapper
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from services.policy.q_table import QTable
|
||||
from services.policy.selector import CardSelector
|
||||
from services.policy.state import State
|
||||
from services.policy.ucb import UCBPolicy
|
||||
from services.policy.visit_table import VisitTable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATE_SPACE_SIZE = 162
|
||||
|
||||
|
||||
class NegotiationOrchestrator:
|
||||
def __init__(self):
|
||||
self.mapper = ActionCardMapper()
|
||||
self.script_repo = CardScriptRepository()
|
||||
self.action_space_size = self.mapper.get_action_space_size()
|
||||
|
||||
self.q_table = self._load_q_table()
|
||||
self.visit_table = VisitTable(
|
||||
state_space_size=STATE_SPACE_SIZE,
|
||||
action_space_size=self.action_space_size,
|
||||
)
|
||||
|
||||
self.policy = UCBPolicy(visit_table=self.visit_table)
|
||||
self.selector = CardSelector(
|
||||
q_table=self.q_table,
|
||||
policy=self.policy,
|
||||
action_card_mapper=self.mapper,
|
||||
)
|
||||
|
||||
def _load_q_table(self) -> QTable:
|
||||
q_json = RESOURCES_DIR / "policy" / "q_table.json"
|
||||
if q_json.exists():
|
||||
with open(q_json, "r", encoding="utf-8") as f:
|
||||
q_table = QTable.from_dict(json.load(f))
|
||||
logger.info(f"Q-Table 로드: {q_json} "
|
||||
f"({q_table.state_space_size}×{q_table.action_space_size})")
|
||||
return q_table
|
||||
|
||||
logger.warning("q_table.json 없음 — 빈 Q-Table로 기동")
|
||||
return QTable(
|
||||
state_space_size=STATE_SPACE_SIZE,
|
||||
action_space_size=self.action_space_size,
|
||||
)
|
||||
|
||||
def select_card(self, state: State, excluded_cards: list = None,
|
||||
isolate_learning: bool = False) -> dict:
|
||||
"""
|
||||
Args:
|
||||
excluded_cards: 제외할 card_id 리스트
|
||||
isolate_learning: True면 UCB 격리(방문수 미증가, argmax) — 신규견적 등
|
||||
"""
|
||||
logger.info(f"[Input State] {state}")
|
||||
|
||||
excluded_actions = []
|
||||
if excluded_cards:
|
||||
for card_id in excluded_cards:
|
||||
action_id = self.mapper.get_action_id(card_id)
|
||||
if action_id is not None:
|
||||
excluded_actions.append(action_id)
|
||||
|
||||
result = self.selector.execute(
|
||||
state,
|
||||
use_policy=not isolate_learning,
|
||||
excluded_actions=excluded_actions,
|
||||
)
|
||||
|
||||
if result.get("card_id"):
|
||||
card = self.script_repo.find_by_id(result["card_id"])
|
||||
if card:
|
||||
result["card_name"] = card.get("card_name")
|
||||
result["script"] = card.get("script")
|
||||
else:
|
||||
result["script"] = "Script not found in repository."
|
||||
|
||||
return result
|
||||
|
||||
def reset_episode(self):
|
||||
"""협상 세션 경계에서 정책의 에피소드 상태 초기화"""
|
||||
self.selector.reset_episode()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""스텝 후처리 — 응답 확정 직전의 스텝별 비즈니스 로직."""
|
||||
|
||||
from router.v1.nego.protocol import ChatMetadata, NegotiationRequest, NegotiationResponse
|
||||
|
||||
|
||||
class StepActionHandler:
|
||||
"""스텝 처리 후, 응답 확정 전에 실행되는 부수 로직 (가격 갱신 등)."""
|
||||
|
||||
def execute_post_step_actions(self, request: NegotiationRequest,
|
||||
response: NegotiationResponse):
|
||||
"""response 객체를 in-place로 수정한다."""
|
||||
if request.step == "추가할인요청":
|
||||
self._handle_requote_additional_discount(request, response)
|
||||
|
||||
def _handle_requote_additional_discount(self, request: NegotiationRequest,
|
||||
response: NegotiationResponse):
|
||||
"""재견적 추가할인: 사용자가 [예]를 선택하면 1% 할인 적용."""
|
||||
if response.step not in ["결과안내", "협상완료"]:
|
||||
return
|
||||
|
||||
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 = int(input_price * 0.99)
|
||||
else:
|
||||
response.chat_metadata.price = int(input_price)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
@@ -0,0 +1,64 @@
|
||||
"""협상 긴장도(Tension) 추정 + 페르소나 선택 (지표 ⑩).
|
||||
|
||||
계획서 정의:
|
||||
- 협상 단계마다 0~1 백분위 환산 가능한 수치를 협상 긴장도로 정의하여 활용
|
||||
- 단계별 변수를 수치화 후 수치에 따라 페르소나를 적용 — 적용된 페르소나의 정확도 측정
|
||||
|
||||
설계 (2026-08-28 확정):
|
||||
- 실제 긴장도(사후 정의) = clip((제안가 − 목표가) / (초기제안가 − 목표가), 0, 1)
|
||||
- 예측 긴장도(서버 실시간) = 단계 변수인 지표점수(ThreeSegIndicator, 정수 1~99)로부터
|
||||
역산한 추정치 — 정수 양자화·스케일 의존 손실이 있어 실제값과 독립적으로 검증 가능
|
||||
- 페르소나 = 예측 긴장도 3구간(저/중/고)으로 선택, profiling 활성 시 스크립트 톤에 적용
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def clip01(v: float) -> float:
|
||||
return max(0.0, min(1.0, v))
|
||||
|
||||
|
||||
def actual_tension(initial: float, target: float, price: float) -> float:
|
||||
"""실제 긴장도 정의 (사후 산출용 — 하네스/집계기가 사용하는 기준 정의)."""
|
||||
if initial <= target:
|
||||
raise ValueError("initial must exceed target")
|
||||
return clip01((price - target) / (initial - target))
|
||||
|
||||
|
||||
def estimate_tension(indicator_value: int, target: float, initial: float) -> float:
|
||||
"""지표점수(1~99) → 긴장도 추정 (모델 변수 경유 역산).
|
||||
|
||||
PZ1/PZ2(80~99, 제안가 ≤ 목표가 구간) → 긴장도 0.
|
||||
PZ3(1~79)는 지표 산식 79·exp(−k(P−T))의 역함수로 (P−T)를 복원해 정규화한다.
|
||||
지표가 정수로 절사되어 있어 실제 긴장도와 양자화 오차가 존재한다 (독립 검증 근거).
|
||||
"""
|
||||
if initial <= target:
|
||||
return 0.0
|
||||
if indicator_value >= 80:
|
||||
return 0.0
|
||||
k = math.pow(10, -int(math.floor(math.log10(target))))
|
||||
p_minus_t = -math.log(indicator_value / 79) / k
|
||||
return clip01(p_minus_t / (initial - target))
|
||||
|
||||
|
||||
# 페르소나 프리셋 — 예측 긴장도 3구간
|
||||
PERSONAS = [
|
||||
# (하한, 이름, profiling 톤 지시문)
|
||||
(2 / 3, "단호한 압박형",
|
||||
"Firm and assertive negotiation stance. Emphasize competition, alternatives, "
|
||||
"and deadlines. Keep it professional but apply clear pressure in Korean."),
|
||||
(1 / 3, "균형 협상형",
|
||||
"Balanced, data-driven negotiation stance. Emphasize mutual benefit and "
|
||||
"objective grounds. Professional and persuasive in Korean."),
|
||||
(0.0, "우호적 마무리형",
|
||||
"Warm, appreciative closing stance. The deal is close — emphasize partnership "
|
||||
"and a smooth finish. Polite and collaborative in Korean."),
|
||||
]
|
||||
|
||||
|
||||
def select_persona(tension: float) -> dict:
|
||||
"""예측 긴장도 → 페르소나 (저/중/고 3구간)."""
|
||||
for lower_bound, name, tone in PERSONAS:
|
||||
if tension >= lower_bound:
|
||||
return {"name": name, "tone": tone}
|
||||
return {"name": PERSONAS[-1][1], "tone": PERSONAS[-1][2]}
|
||||
Reference in new issue
Block a user