[feat] agent: 협상 고도화 — LLM 표현/이해층 + 카드 전술 실행계층 + ktcommerce 정리
카드 재설계("멘트 카드 → 전술 카드"):
- tactics.py 신설: 카드번호→전술(카운터 산식) 레지스트리, min(counter,target) 클램프
- 카운터 수락=즉시 타결(pending_counter_price 일반화, 구 offer_1pct 흡수)
- 목표가 초과 타결 금지(성공스텝 진입 가드) + "카드 소진=실패" 폐지→종결 국면
- 선택형 와일드카드(WC-*) 발동 + card.wild_cards 멘트 DB 어댑터
LLM 계층:
- Phase 2 표현층 ScriptNaturalizer(카드 멘트 자연화, 마커·치환자·숫자 보존 검증)
- Phase 3 이해층 InputInterpreter(자유발화 NLU→기대입력, 한국어 가격 파서)
- OPENAI_API_KEY env override(server_configs) + 전역 자격증명 게이트
결정 스택(Phase 1):
- 협상 규칙 데이터화(negotiation.wildcard_*_ratio/max_counter_rounds)
- 선택카드 우선순위 prior(UCB 방문수 감쇠, Q-table 오염 없음)
버그픽스:
- 인하율 음수 표기 제거 + 인상/동일/인하 구분(discount_phrase)
- 자연화 강조마커 보존(볼드/색 소실 시 원본 폴백)
- 카드 시드 가격변수(prev_partner_price·target_mid_price·middle_price 등) 치환
정리:
- ktcommerce 테넌트 삭제 + 테스트 21파일 imarketkorea/_base 로 마이그레이션
- 실 LLM 호출 차단 conftest 가드
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b368a19f79
commit
1682481b01
46 files changed
+2091
-240
No files matched your search
@@ -10,9 +10,10 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from negotiation.cards.domain.tactics import compute_counter, tactic_for
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
|
||||
MAX_ROUNDS = 3
|
||||
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
@@ -22,6 +23,9 @@ _CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
_SUCCESS_STEPS = ("협상완료", "결과제출")
|
||||
_FAILURE_STEPS = ("협상실패",)
|
||||
|
||||
# 카운터 제안(pending_counter_price) 수락으로 인정하는 선택 입력.
|
||||
_ACCEPT_INPUTS = ("예", "수락")
|
||||
|
||||
# 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등
|
||||
# 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이
|
||||
# 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.)
|
||||
@@ -72,6 +76,9 @@ class ChatEngine:
|
||||
self.rq_type = rq_type
|
||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
||||
self.step_map = scripts_repo.client_step_mapping()
|
||||
# 결정 스택 규칙층(Phase 1): 와일드카드 진입 임계·라운드 상한을 테넌트 config 에서 읽는다.
|
||||
# (하드코딩 1.02/1.05/3 을 데이터화 — 고객사별로 튜닝 가능, 코드 수정 불필요)
|
||||
self.rules = scripts_repo.config.negotiation
|
||||
|
||||
# ---- public --------------------------------------------------------
|
||||
def start(self, session: ChatSession) -> StepView:
|
||||
@@ -89,21 +96,27 @@ class ChatEngine:
|
||||
if price is None:
|
||||
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
||||
session.context["input_price"] = price
|
||||
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
|
||||
session.context.pop("pending_counter_price", None)
|
||||
session.context["prev_partner_price"] = price
|
||||
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
|
||||
session.context.setdefault("first_offer_price", price)
|
||||
session.context["round"] = session.context.get("round", 0) + 1
|
||||
nxt = self._default_next(node)
|
||||
elif mode in _CHOICE_MODES:
|
||||
# 와일드카드 1% 인하 제안을 수락("예")하면 합의가를 제안가(offer_1pct)로 확정한다.
|
||||
# (멘트에만 쓰이던 offer_1pct 가 input_price 에 반영되지 않아, 요약/입찰가가
|
||||
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
||||
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
||||
session.context["input_price"] = float(session.context["offer_1pct"])
|
||||
nxt = self._choice_next(node, user_input, session)
|
||||
else:
|
||||
nxt = self._default_next(node)
|
||||
|
||||
nxt = self._resolve(nxt, session)
|
||||
# 카운터 수락 일반 메커니즘: 카드/와일드카드가 제시한 카운터가(pending_counter_price)를
|
||||
# 협력사가 수락("예"/"수락")한 채 성공 스텝으로 전이하면 합의가 = 카운터가.
|
||||
# (구 offer_1pct 특수 분기의 일반화. 거절인데 성공 스텝으로 가는 경로 — 1% 거절 시
|
||||
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
|
||||
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
|
||||
pending = session.context.pop("pending_counter_price", None)
|
||||
if pending and user_input in _ACCEPT_INPUTS:
|
||||
session.context["input_price"] = float(pending)
|
||||
return self._render(session, nxt)
|
||||
|
||||
# ---- transition ----------------------------------------------------
|
||||
@@ -131,9 +144,9 @@ class ChatEngine:
|
||||
return nxt
|
||||
|
||||
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
|
||||
"""KT 구매자 관점 조건 평가.
|
||||
"""KT 구매자 관점 조건 평가 (임계값은 config negotiation.* — 규칙층 데이터화).
|
||||
- 협력사 제시가 ≤ anchor → 우선협상(협상완료).
|
||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- anchor 살짝 초과(≤ anchor×wildcard_entry_ratio) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||
"""
|
||||
@@ -151,21 +164,31 @@ class ChatEngine:
|
||||
and anchor > 0
|
||||
and anchor < price
|
||||
and (
|
||||
price <= anchor * 1.02
|
||||
or (bool(ctx.get("allow_selected_wildcards", True)) and price <= anchor * 1.05)
|
||||
price <= anchor * self.rules.wildcard_1pct_ratio
|
||||
or (bool(ctx.get("allow_selected_wildcards", True))
|
||||
and price <= anchor * self.rules.wildcard_entry_ratio)
|
||||
)
|
||||
)
|
||||
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": # 협상 라운드 상한 또는 카드 소진
|
||||
# round 는 매 가격입력마다 증가(기존가격제시=1). 그 이후 카운터제안이 MAX_ROUNDS 회를
|
||||
# 넘으면 종료한다. 카드선택(RL)이 실패(state ValueError)해도 used_action_ids 가 안 늘어
|
||||
# 카드 소진 조건만으로는 종료되지 않으므로, 라운드 상한을 독립적으로 둬 무한 가격입력을 막는다.
|
||||
# (선행 chat_server 의 `iteration >= 3` 와 동일한 안전장치.)
|
||||
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진 → 종결 국면
|
||||
# round 는 매 가격입력마다 증가(기존가격제시=1). 카운터제안이 상한을 넘거나 카드가
|
||||
# 소진되면 곧장 실패가 아니라 **종결 국면**으로 처리한다(실제 MD 협상 방식):
|
||||
# ① 아직 종결 전술을 안 썼으면 → 가격협상으로 보내되 force_closing 마킹
|
||||
# (ChatService 가 종결 전술 — 중간값 절충/최후통첩 — 을 강제 발동)
|
||||
# ② 종결 전술까지 소진(closing_played)이면 → 최종 제시가 ≤ target 은 타결,
|
||||
# 초과는 결렬(협상실패) — "목표가 초과 타결 금지" 가드레일과 정합.
|
||||
counter_rounds = max(0, ctx.get("round", 0) - 1)
|
||||
ok = counter_rounds >= MAX_ROUNDS or (cards_total > 0 and cards_used >= cards_total)
|
||||
exhausted = counter_rounds >= self.rules.max_counter_rounds or (cards_total > 0 and cards_used >= cards_total)
|
||||
if exhausted:
|
||||
target = ctx.get("target_price", 0)
|
||||
if not ctx.get("closing_played"):
|
||||
ctx["force_closing"] = True
|
||||
return "가격협상"
|
||||
return "협상완료" if (target > 0 and price <= target) else c.get("next")
|
||||
ok = False
|
||||
elif cond == "default":
|
||||
ok = True
|
||||
if ok:
|
||||
@@ -173,7 +196,7 @@ class ChatEngine:
|
||||
return "가격협상"
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가에 아주 근접(≤ anchor*1.02)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
|
||||
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
|
||||
@@ -184,12 +207,23 @@ class ChatEngine:
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
if anchor > 0 and price <= anchor * 1.02:
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
|
||||
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
|
||||
return "wild_card_1pct"
|
||||
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_entry_ratio:
|
||||
for number in (ctx.get("selected_wild_card_numbers") or []):
|
||||
counter = compute_counter(tactic_for(str(number)), ctx)
|
||||
if counter is not None:
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["pending_counter_price"] = counter
|
||||
ctx["active_wild_card_number"] = str(number)
|
||||
return "wild_card_dynamic"
|
||||
return "가격협상"
|
||||
|
||||
# ---- render --------------------------------------------------------
|
||||
@@ -199,26 +233,73 @@ class ChatEngine:
|
||||
out = {}
|
||||
if "input_price" in ctx:
|
||||
out["input_price"] = int(ctx["input_price"])
|
||||
# 목표가/앵커가: 엔진 내부 파일 스크립트는 {target}/{anchor}, negodata 카드 에디터는
|
||||
# {target_price}/{anchor_price}(variables.ts) 를 쓴다 — 양쪽 이름 모두 채워 치환 누락 방지.
|
||||
if "target_price" in ctx:
|
||||
out["target"] = int(ctx["target_price"])
|
||||
out["target"] = out["target_price"] = int(ctx["target_price"])
|
||||
if "anchor_price" in ctx:
|
||||
out["anchor"] = int(ctx["anchor_price"])
|
||||
# anchoring_price = DB 시드 기본 카드/sessions 컬럼 표기, anchor_price = 카드 에디터 표기.
|
||||
out["anchor"] = out["anchor_price"] = out["anchoring_price"] = int(ctx["anchor_price"])
|
||||
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
|
||||
if ctx.get("partner_name"):
|
||||
out["partner_name"] = str(ctx["partner_name"])
|
||||
if ctx.get("product_name"):
|
||||
out["product_name"] = str(ctx["product_name"])
|
||||
if "offer_1pct" in ctx:
|
||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.compute_counter 산식과 동일 정의.
|
||||
anchor = ctx.get("anchor_price") or 0
|
||||
target = ctx.get("target_price") or 0
|
||||
if "input_price" in ctx:
|
||||
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
|
||||
prev_customer = ctx.get("prev_customer_price") or anchor
|
||||
if prev_customer:
|
||||
out["prev_customer_price"] = int(prev_customer)
|
||||
if anchor and target:
|
||||
out["target_mid_price"] = int(round((anchor + target) / 2))
|
||||
if prev_customer and "input_price" in ctx:
|
||||
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
|
||||
if ctx.get("pending_counter_price"):
|
||||
out["counter_price"] = int(ctx["pending_counter_price"])
|
||||
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
|
||||
base = ctx.get("item_price") or 0
|
||||
if base > 1 and "input_price" in ctx:
|
||||
out["discount_rate"] = f"{((base - ctx['input_price']) / base) * 100:.1f}"
|
||||
rate = ((base - ctx["input_price"]) / base) * 100
|
||||
out["discount_rate"] = f"{max(0.0, rate):.1f}"
|
||||
if rate >= 0.05:
|
||||
out["discount_phrase"] = f"기존 공급가 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
|
||||
elif rate <= -0.05:
|
||||
out["discount_phrase"] = (
|
||||
f"기존 공급가(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
|
||||
else:
|
||||
out["discount_phrase"] = "기존 공급가와 동일한 수준의 금액입니다. "
|
||||
else:
|
||||
out["discount_rate"] = "0.0"
|
||||
out["discount_phrase"] = ""
|
||||
return out
|
||||
|
||||
def _vars(self, session: ChatSession) -> Dict[str, Any]:
|
||||
return self.vars_for(session)
|
||||
|
||||
def render_step(self, session: ChatSession, step_key: str) -> StepView:
|
||||
"""지정 스텝으로 전이·렌더 (공개) — ChatService 가 카드 카운터 제시 시
|
||||
가격협상 → 가격협상_카운터로 스텝을 전환할 때 사용한다."""
|
||||
return self._render(session, step_key)
|
||||
|
||||
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}")
|
||||
# 가드레일(최후 방어선): 구매자 대리는 목표가 초과로 절대 타결하지 않는다.
|
||||
# 카운터 클램프·종결 규칙이 정상이면 도달하지 않지만, 스크립트 편집 실수 등으로
|
||||
# 성공 스텝에 초과가로 진입하면 결렬로 강제 전환한다. (재협상 흐름 한정)
|
||||
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
|
||||
ctx = session.context
|
||||
target = ctx.get("target_price") or 0
|
||||
if target > 0 and ctx.get("input_price", 0) > target:
|
||||
step_key = "협상실패"
|
||||
node = self.scripts[step_key]
|
||||
session.step = step_key
|
||||
chat_end = bool(node.get("chat_end"))
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""InputInterpreter — 협력사 자유 발화를 대화 단계 기대 입력으로 구조화 (Phase 3 이해층).
|
||||
|
||||
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" (ScriptNaturalizer 와 동일 철학) —
|
||||
- LLM 의 역할은 ① 의도 분류(choice|price|unknown) ② 가격 '표현의 위치' 찾기까지다.
|
||||
가격 숫자 계산은 LLM 출력이 아니라 결정론 한국어 가격 파서(parse_korean_price)가 수행한다.
|
||||
- 검증: choice 는 허용 선택지 목록에 철자 그대로 있어야 하고, price_text 는 사용자 원문의
|
||||
부분 문자열이어야 한다(환각 차단). 하나라도 어긋나면 None → 호출부가 원문 그대로 폴백
|
||||
(기존 엔진의 재질문 흐름 유지 — 협상은 절대 멈추지 않는다).
|
||||
|
||||
게이트: tenant llm.enabled + 전역 자격증명(ScriptNaturalizer 와 동일). 미설정이면 무동작 —
|
||||
기존 버튼/정형 입력 경로는 그대로 두고, 자유 텍스트일 때만 해석을 시도한다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
# 정형 가격 입력(버튼/필드) — LLM 없이 기존 결정론 경로로 처리 가능한 형태.
|
||||
SIMPLE_PRICE_RE = re.compile(r"\s*[\d,]+(\.\d+)?\s*원?\s*")
|
||||
|
||||
# 한국어 단위 (큰 단위 → 작은 단위 순서로 등장한다고 가정: "1만 2천 500원")
|
||||
_KOREAN_UNITS = {"억": 100_000_000, "만": 10_000, "천": 1_000, "백": 100}
|
||||
_PRICE_TOKEN_RE = re.compile(r"[\d.억만천백]+")
|
||||
|
||||
|
||||
def parse_korean_price(text: str) -> Optional[float]:
|
||||
"""가격 표현 문자열 → 숫자 (결정론). "10,500원"→10500, "1만 500원"→10500, "만원"→10000,
|
||||
"1.5만"→15000, "3만2천원"→32000. 해석 불가/0 이하 → None.
|
||||
"""
|
||||
t = (text or "").replace(",", "").replace(" ", "").replace("원", "").strip()
|
||||
if not t:
|
||||
return None
|
||||
if re.fullmatch(r"\d+(\.\d+)?", t):
|
||||
v = float(t)
|
||||
return v if v > 0 else None
|
||||
if not re.fullmatch(r"[\d.억만천백]+", t):
|
||||
return None # 단위·숫자 외 문자 포함 → 해석 불가(안전 폴백)
|
||||
total, num = 0.0, ""
|
||||
for ch in t:
|
||||
if ch.isdigit() or ch == ".":
|
||||
num += ch
|
||||
else: # 단위 문자
|
||||
try:
|
||||
n = float(num) if num else 1.0 # "만원" = 1만
|
||||
except ValueError:
|
||||
return None
|
||||
total += n * _KOREAN_UNITS[ch]
|
||||
num = ""
|
||||
if num:
|
||||
try:
|
||||
total += float(num) # 잔여 숫자: "1만500" 의 500
|
||||
except ValueError:
|
||||
return None
|
||||
return total if total > 0 else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class InterpretedInput:
|
||||
kind: str # "choice" | "price"
|
||||
value: str # ChatEngine.advance 에 그대로 전달할 문자열 ("예" / "10500")
|
||||
source: str # 판단 근거(선택지 원문 또는 가격 표현 원문) — 로깅/투명성용
|
||||
|
||||
|
||||
_SYSTEM = """너는 B2B 구매 협상 챗봇의 입력 해석기다. 협력사(사용자)의 자유 발화를 현재 대화 단계가 기대하는 입력으로 구조화한다.
|
||||
|
||||
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||
- 출력은 JSON 하나만: {"intent": "choice"|"price"|"unknown", "choice": "<선택지 철자 그대로>"|null, "price_text": "<원문 속 가격 표현 그대로>"|null}
|
||||
- choice 는 발화의 '의미'를 선택지 중 하나에 대응시켜, 그 선택지 문자열을 철자 그대로 복사한다.
|
||||
예) 선택지 ["예","아니오"]: "네 접니다"/"맞습니다"/"진행해주세요"/"동의합니다" → "예",
|
||||
"아닌데요"/"제가 아닙니다"/"어렵습니다"/"거절하겠습니다" → "아니오"
|
||||
- 사용자가 구체적 가격을 제시/역제안하면 intent=price. price_text 는 반드시 사용자 원문에 등장한
|
||||
표현을 그대로 복사한다(예: "10,500원", "1만 500원"). 숫자를 계산하거나 변형하지 마라.
|
||||
- 발화가 어느 선택지의 의미인지 정말 판단할 수 없거나 주제와 무관할 때만 intent=unknown."""
|
||||
|
||||
|
||||
def _default_llm_call(messages: List[dict]) -> dict:
|
||||
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 주입 대체 지점."""
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
return chat_json(messages, temperature=0.0, max_tokens=200)
|
||||
|
||||
|
||||
class InputInterpreter:
|
||||
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||
timeout_seconds: float = 6.0):
|
||||
self._llm_call = llm_call or _default_llm_call
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
|
||||
async def interpret(self, user_input: str, *, input_mode: str,
|
||||
input_options: Optional[List[str]] = None,
|
||||
step_script: Optional[str] = None) -> Optional[InterpretedInput]:
|
||||
"""자유 발화 → 기대 입력. 검증 불통과/실패/타임아웃 시 None(호출부 원문 폴백).
|
||||
|
||||
step_script: 직전 봇 질문(맥락) — "네 접니다" 같은 발화는 질문 없이는 의도 판단이
|
||||
애매해 unknown 이 되므로, 무엇에 대한 답인지 함께 준다.
|
||||
"""
|
||||
text = (user_input or "").strip()
|
||||
options = [str(o) for o in (input_options or [])]
|
||||
if not text:
|
||||
return None
|
||||
payload = {
|
||||
"현재 단계 기대 입력": "가격(숫자)" if input_mode == "price" else "선택지 중 하나",
|
||||
"선택지": options,
|
||||
"사용자 발화": text,
|
||||
}
|
||||
if step_script:
|
||||
payload["직전 봇 질문"] = step_script[:300]
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content": json.dumps(payload, ensure_ascii=False) + "\n\nJSON 으로만 답하라."},
|
||||
]
|
||||
try:
|
||||
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||
except Exception as ex: # 타임아웃 포함 — 원문 폴백
|
||||
LOG.w(f"[InputInterpreter] LLM 호출 실패(원문 폴백): {ex}")
|
||||
return None
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
|
||||
intent = result.get("intent")
|
||||
if intent == "choice":
|
||||
choice = result.get("choice")
|
||||
# 결정: 선택지 목록에 철자 그대로 있어야만 채택 (LLM 이 지어낸 분기 차단).
|
||||
if isinstance(choice, str) and choice in options:
|
||||
return InterpretedInput(kind="choice", value=choice, source=choice)
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: choice={choice!r} ∉ {options}")
|
||||
return None
|
||||
if intent == "price":
|
||||
span = result.get("price_text")
|
||||
# 환각 차단: 가격 표현은 사용자 원문의 부분 문자열이어야 한다.
|
||||
if not isinstance(span, str) or not span.strip() or span.strip() not in text:
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: price_text={span!r} 가 원문에 없음")
|
||||
return None
|
||||
price = parse_korean_price(span.strip()) # 숫자 계산은 결정론 파서가
|
||||
if price is None:
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: 가격 해석 불가 span={span!r}")
|
||||
return None
|
||||
return InterpretedInput(kind="price", value=str(int(price)), source=span.strip())
|
||||
return None # unknown → 원문 폴백(엔진 재질문)
|
||||
@@ -39,6 +39,8 @@ class NegotiationDbContext:
|
||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
|
||||
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
|
||||
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||
@@ -84,6 +86,10 @@ class NegotiationContextLoader:
|
||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||
_, item_price = await self.crud.get_item_price(s, item_id)
|
||||
|
||||
# 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백).
|
||||
_, partner_name = await self.crud.get_supplier_name(s, supplier_id)
|
||||
_, product_name = await self.crud.get_item_name(s, item_id)
|
||||
|
||||
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
|
||||
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
|
||||
err, supplier_count = await self.crud.count_item_suppliers(s, item_id)
|
||||
@@ -102,6 +108,8 @@ class NegotiationContextLoader:
|
||||
target_price=target,
|
||||
anchor_price=anchor,
|
||||
item_price=item_price,
|
||||
partner_name=partner_name,
|
||||
product_name=product_name,
|
||||
partner_type=PartnerType.from_count(supplier_count),
|
||||
revenue_amount=revenue_amount,
|
||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""ScriptNaturalizer — 협상 카드 멘트를 LLM 으로 상황에 맞게 자연화 (Phase 2 표현층).
|
||||
|
||||
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" —
|
||||
- 입력은 **치환 전 템플릿**({input_price} 등 placeholder 유지 상태). LLM 은 숫자를 절대 만들지 않는다.
|
||||
- 상황(라운드·가격구간·수용률)은 **정성 라벨**로만 전달(수치 미노출 → 숫자 환각 원천 차단).
|
||||
- 검증 실패/타임아웃/미설정 시 None → 호출부가 원본 템플릿 폴백(협상은 절대 안 멈춤).
|
||||
|
||||
검증(ScriptVerifier 철학의 플레인 텍스트판):
|
||||
① {placeholder} 집합이 원본과 정확히 동일(누락·추가 금지)
|
||||
② 원본에 없던 숫자 등장 금지(가격 환각 차단)
|
||||
③ 비어있지 않고 길이 폭주 금지
|
||||
|
||||
게이트: tenant llm.enabled(기본 false) + 전역 LLM 자격증명(config.local.toml [OpenAIConfig]
|
||||
또는 OPENAI_API_KEY env). 호출은 스레드로 넘겨 이벤트루프 비차단 + 타임아웃.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
|
||||
_DIGITS_RE = re.compile(r"\d+")
|
||||
# 강조 마커(negodata Slate 편집 정본) — 고객사가 지정한 표시라 자연화가 보존해야 한다.
|
||||
# 색 마커 {{강조|..}} {{안내|..}} 는 여는 토큰 개수로, 굵게/밑줄은 구분자 개수(짝수=쌍)로 센다.
|
||||
_COLOR_OPEN_RE = re.compile(r"\{\{(강조|안내)\|")
|
||||
|
||||
# 카드 메타 코드 → 프롬프트 라벨 (init-data.sql CardTone/CardStrategyType 정의와 동일)
|
||||
_TONE_LABEL = {1: "강경", 2: "정중", 3: "우호", 4: "중립", 5: "단호"}
|
||||
_STRATEGY_LABEL = {1: "경쟁", 2: "수용", 3: "고수", 4: "협력", 5: "선점", 6: "종결"}
|
||||
|
||||
_SYSTEM = """너는 B2B 구매 협상 챗봇의 문장 작성기다. 주어진 협상 카드 멘트 '템플릿'을 협상 상황에 맞게 자연스럽게 다시 쓴다.
|
||||
|
||||
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||
- {변수명} 치환자는 철자 그대로 유지한다. 추가/삭제/변경 금지.
|
||||
- 숫자를 직접 쓰지 마라. 가격·비율 등 모든 수치는 치환자로만 표현한다.
|
||||
- 강조 마커(**굵게** __밑줄__ {{강조|...}} {{안내|...}})는 **개수와 종류를 그대로 유지**한다.
|
||||
고객사가 지정한 강조 표시이므로 삭제·추가·종류변경 금지. 감싼 문구는 자연스럽게 바꿔도 되지만
|
||||
강조된 구절 수만큼 같은 마커로 반드시 다시 감싼다(예: **굵게** 2개면 결과도 **…** 2쌍).
|
||||
- 새로운 약속·할인 조건·법적 표현을 만들지 마라. 원 템플릿의 협상 의도(전술)는 유지한다.
|
||||
- 한국어 존댓말, 2~5문장, 채팅 말풍선에 어울리게 간결히.
|
||||
- 출력은 JSON 하나만: {"script": "다시 쓴 멘트"}"""
|
||||
|
||||
|
||||
def _default_llm_call(messages: List[dict]) -> dict:
|
||||
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 monkeypatch 지점."""
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
return chat_json(messages, temperature=0.5, max_tokens=600)
|
||||
|
||||
|
||||
class ScriptNaturalizer:
|
||||
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||
timeout_seconds: float = 8.0):
|
||||
self._llm_call = llm_call or _default_llm_call
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
|
||||
async def naturalize(self, template: str, *, situation: Optional[Dict[str, Any]] = None,
|
||||
tone: Optional[int] = None, strategy: Optional[int] = None) -> Optional[str]:
|
||||
"""템플릿(치환 전)을 상황 맞춤 문장으로 재작성. 실패/검증불통과 시 None(호출부 폴백)."""
|
||||
if not template or not template.strip():
|
||||
return None
|
||||
ctx = dict(situation or {})
|
||||
if tone in _TONE_LABEL:
|
||||
ctx["톤"] = _TONE_LABEL[tone]
|
||||
if strategy in _STRATEGY_LABEL:
|
||||
ctx["전략"] = _STRATEGY_LABEL[strategy]
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content":
|
||||
"템플릿:\n" + template +
|
||||
"\n\n협상 상황:\n" + json.dumps(ctx, ensure_ascii=False) +
|
||||
'\n\n규칙대로 다시 써서 {"script": "..."} 로만 출력.'},
|
||||
]
|
||||
try:
|
||||
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||
except Exception as ex: # 타임아웃 포함 — 폴백
|
||||
LOG.w(f"[ScriptNaturalizer] LLM 호출 실패(폴백): {ex}")
|
||||
return None
|
||||
|
||||
text = result.get("script") if isinstance(result, dict) else None
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return None
|
||||
return text if self._verify(template, text) else None
|
||||
|
||||
# ---- 검증 ----------------------------------------------------------
|
||||
@staticmethod
|
||||
def _verify(template: str, rewritten: str) -> bool:
|
||||
orig = set(_PLACEHOLDER_RE.findall(template))
|
||||
new = set(_PLACEHOLDER_RE.findall(rewritten))
|
||||
if orig != new:
|
||||
LOG.w(f"[ScriptNaturalizer] 검증 실패: 치환자 불일치 (누락={orig - new}, 추가={new - orig})")
|
||||
return False
|
||||
# 원본에 없던 숫자 금지 — 가격/비율 환각 차단 (수치는 치환자로만).
|
||||
orig_digits = set(_DIGITS_RE.findall(template))
|
||||
new_digits = set(_DIGITS_RE.findall(rewritten)) - orig_digits
|
||||
if new_digits:
|
||||
LOG.w(f"[ScriptNaturalizer] 검증 실패: 새 숫자 등장 {new_digits}")
|
||||
return False
|
||||
if len(rewritten) > max(600, len(template) * 4):
|
||||
LOG.w("[ScriptNaturalizer] 검증 실패: 길이 폭주")
|
||||
return False
|
||||
# 강조 마커 보존 — 고객사가 지정한 볼드/밑줄/색을 LLM 이 떨어뜨리면 폐기(원본 폴백).
|
||||
# 굵게/밑줄: 구분자 총 개수가 같아야 짝(쌍)이 보존됨. 색: 여는 토큰 개수 동일.
|
||||
if (template.count("**") != rewritten.count("**")
|
||||
or template.count("__") != rewritten.count("__")
|
||||
or len(_COLOR_OPEN_RE.findall(template)) != len(_COLOR_OPEN_RE.findall(rewritten))):
|
||||
LOG.w("[ScriptNaturalizer] 검증 실패: 강조 마커 불일치(볼드/색 소실) → 원본 유지")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def build_situation(context: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""세션 컨텍스트 → 정성 상황 라벨 (수치 미노출 — 숫자 환각 차단의 핵심).
|
||||
|
||||
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 기존 공급가 대비.
|
||||
"""
|
||||
out: Dict[str, Any] = {}
|
||||
rnd = context.get("round") or 0
|
||||
if rnd:
|
||||
out["라운드"] = "첫 제안" if rnd <= 1 else ("초반 조율" if rnd == 2 else "막바지 조율")
|
||||
price = context.get("input_price") or 0
|
||||
anchor = context.get("anchor_price") or 0
|
||||
target = context.get("target_price") or 0
|
||||
if price and anchor and target:
|
||||
if price <= anchor:
|
||||
out["가격구간"] = "목표 범위 도달(마무리 국면)"
|
||||
elif price <= target:
|
||||
out["가격구간"] = "목표 범위 근접(조율 국면)"
|
||||
else:
|
||||
out["가격구간"] = "목표 상회(추가 인하 필요)"
|
||||
base = context.get("item_price") or 0
|
||||
if base and price:
|
||||
rate = (base - price) / base
|
||||
out["인하 진행"] = "아직 미미" if rate < 0.01 else ("일부 진행" if rate < 0.05 else "상당히 진행")
|
||||
return out
|
||||
@@ -38,6 +38,11 @@ class ScriptRepository:
|
||||
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
|
||||
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
|
||||
|
||||
@property
|
||||
def config(self) -> TenantConfig:
|
||||
"""테넌트 config 노출 — ChatEngine 이 협상 규칙(negotiation.*)을 읽는다."""
|
||||
return self._config
|
||||
|
||||
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
||||
def _resource_path(self, filename: str) -> Optional[str]:
|
||||
scripts_dir = self._config.resources.scripts_dir
|
||||
@@ -89,25 +94,47 @@ class ScriptRepository:
|
||||
return None
|
||||
return self.format_script(text, variables)
|
||||
|
||||
async def resolve_card_template(self, action_id: int, card_id: Optional[str],
|
||||
prefer_db: bool = False) -> tuple:
|
||||
"""카드 멘트의 **치환 전 템플릿**과 메타를 해석 → (template, tone, strategy_type).
|
||||
|
||||
cards.source_type == 'backoffice_db' 면 card.nego_cards(DB, tone/strategy 포함) 우선,
|
||||
없거나 file 모드면 scripts_cards.json(파일, 메타 None) 폴백. 둘 다 없으면 (None, None, None).
|
||||
치환 전 템플릿을 그대로 주는 이유: LLM 표현층이 placeholder 를 유지한 채 재작성한 뒤
|
||||
format_script 로 치환해야 숫자를 LLM 이 절대 만지지 않기 때문.
|
||||
"""
|
||||
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
||||
card = await self._fetch_card_db(card_id)
|
||||
if card:
|
||||
return card # (script, tone, strategy)
|
||||
return self.card_scripts().get(str(action_id)), None, None # 파일 폴백(메타 없음)
|
||||
|
||||
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
||||
variables: Optional[Dict[str, Any]] = None,
|
||||
prefer_db: bool = False) -> Optional[str]:
|
||||
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
||||
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
||||
"""카드 멘트 해석(템플릿 + 변수 치환). DB(정본) 우선 → 파일 폴백. 마커는 불투명 텍스트."""
|
||||
template, _, _ = await self.resolve_card_template(action_id, card_id, prefer_db=prefer_db)
|
||||
if not template:
|
||||
return None
|
||||
return self.format_script(template, variables)
|
||||
|
||||
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
||||
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
||||
"""
|
||||
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
||||
db_text = await self._fetch_card_script_db(card_id)
|
||||
if db_text:
|
||||
return self.format_script(db_text, variables)
|
||||
return self.card_script(action_id, variables) # 파일 폴백
|
||||
|
||||
async def _fetch_card_script_db(self, card_id: str) -> Optional[str]:
|
||||
async def resolve_wild_card_template(self, number: str) -> Optional[str]:
|
||||
"""선택형 와일드카드(WC-*) 멘트 템플릿 — card.wild_cards(DB, negodata 편집 정본) 조회.
|
||||
없거나 DB 불가면 None(호출부가 스텝 기본 멘트 폴백)."""
|
||||
async def _q(s):
|
||||
_, text = await self._card_repo.get_script_by_number(s, card_id)
|
||||
return text
|
||||
_, script = await self._card_repo.get_wild_card_by_number(s, number)
|
||||
return script
|
||||
|
||||
try:
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[ScriptRepository] 와일드카드 멘트 DB 조회 실패 number={number}: {ex}")
|
||||
return None
|
||||
|
||||
async def _fetch_card_db(self, card_id: str) -> Optional[tuple]:
|
||||
async def _q(s):
|
||||
_, card = await self._card_repo.get_card_by_number(s, card_id)
|
||||
return card
|
||||
|
||||
try:
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
|
||||
Reference in new issue
Block a user