[feat] agent: 완전 자율 협상 모드 (AUTONOMY_MODE) + LLM 멘트
판정 룰(앵커타결/와일드존/3라운드결렬)과 카드 선택을 학습 정책으로 대체: 수락/역제안 금액/압박 화법/결렬 전부 행동 30개(수락1+결렬1+역제안 6단x화법4+압박4)에서 선택. - autonomy_actions: 행동 공간·특징 인코딩 (학습/서빙 공유) - autonomy_store: numpy 서빙 + 행동 봉투 7개(수락<=목표가 / 역제안 단조 / 역제시·결렬은 설득 2회 후 해금 / 마무리국면 압박 금지 / 첫 역제안 앵커 이하 / 최종제안 1회 보장) - chat_engine: 자율 스텝(역제안/최종제안/압박1~4), 최종제안 금액=목표가, 턴캡 12 - ment_generator: Gemini 멘트 생성 + 가드(숫자 화이트리스트·목표가 비공개·금지어·문장완결, 실패시 템플릿 폴백, 6초 컷), 인터넷최저가 근거 인용(수집됨+제시가 초과시만), 대화 기억 - chat_service: 자율 행동 experience_logs 로깅(AUT|종류|위치|전략), 대화기억 ctx 관리 - context loader/CRUD: 인터넷최저가·견적기간·협력사 이력 로드 (v3 상태 21차원) - train_full_autonomy: 시뮬 15k ep — 앵커율 0.8~6% 정합, 협력사 현실화(컷반발·반복짜증· 양보 상호성), 관측성 마스크(마감 40% 미관측·15% 전부미상 — 서빙 중립값 분포 정합), 보상 수정(목표가 초과 타결=결렬 취급) - 서빙 v3.5 (v3.3 목표가 즉시지르기 퇴화, v3.4 소액지형 첫턴 통보 퇴화 — 게이트 반려 이력 보관) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d4acdd0ac5
commit
51b3820cc9
16 files changed
+1361
-8
No files matched your search
@@ -26,13 +26,21 @@ _SESSIONS = table(
|
||||
column("deleted"),
|
||||
schema="negotiation",
|
||||
)
|
||||
_ITEMS = table("items", column("item_id"), column("price"), column("deleted"), schema="partner")
|
||||
_ITEMS = table("items", column("item_id"), column("price"), column("internet_lowest_price"),
|
||||
column("deleted"), schema="partner")
|
||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner")
|
||||
_QUOTATIONS = table(
|
||||
"quotations",
|
||||
column("qt_id"), column("version_id"), column("supplier_type"), column("deleted"),
|
||||
column("qt_id"), column("version_id"), column("supplier_type"),
|
||||
column("start_time"), column("end_time"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
# 자율 에이전트 이력 특징용 — agent 소유 learning 스키마 (done 행 = 협상 1건의 최종 결과).
|
||||
_EXP_LOGS = table(
|
||||
"experience_logs",
|
||||
column("session_id"), column("company_id"), column("done"), column("settled_price"),
|
||||
schema="learning",
|
||||
)
|
||||
_VERSION_NEGO_CARDS = table(
|
||||
"version_nego_cards",
|
||||
column("version_id"), column("nego_card_id"), column("created_at"), column("deleted"),
|
||||
@@ -98,6 +106,22 @@ class INegoContextCRUD(ABC):
|
||||
"""견적 version_id 에 연결된 (일반카드 번호 목록, 와일드카드 번호 목록). 없으면 빈 목록."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품 인터넷최저가(items.internet_lowest_price). 미수집이면 0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""견적 협상 기간 (start_time, end_time). 없으면 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||
"""이 협력사와의 과거 협상 이력 (횟수, 성사율, 평균 타결가/목표가). 없으면 (0, None, None)."""
|
||||
pass
|
||||
|
||||
|
||||
class NegoContextCRUD(INegoContextCRUD):
|
||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
@@ -131,6 +155,67 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품의 인터넷최저가(partner.items.internet_lowest_price). 미수집이면 0."""
|
||||
try:
|
||||
query = (
|
||||
select(_ITEMS.c.internet_lowest_price)
|
||||
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_internet_lowest failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||
return err_type, 0
|
||||
return ErrorType.SUCCESS, int(rows[0])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""견적 협상 기간 (start_time, end_time). 자율 에이전트의 마감 잔여율 특징용."""
|
||||
try:
|
||||
query = (
|
||||
select(_QUOTATIONS.c.start_time, _QUOTATIONS.c.end_time)
|
||||
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_period failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, None
|
||||
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||
"""이 협력사와의 과거 협상 이력 집계 → (횟수, 성사율, 평균 타결가/목표가).
|
||||
|
||||
소스 = learning.experience_logs 의 종료행(done=True) ⨝ negotiation.sessions
|
||||
(agent 가 직접 기록한 결과라 카드/자율 모드 무관하게 쌓인다). 이력 없으면 (0, None, None).
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
select(_EXP_LOGS.c.settled_price, _SESSIONS.c.target_price)
|
||||
.select_from(_EXP_LOGS.join(_SESSIONS, _SESSIONS.c.session_id == _EXP_LOGS.c.session_id))
|
||||
.where(_EXP_LOGS.c.done == True, # noqa: E712
|
||||
_EXP_LOGS.c.company_id == company_id,
|
||||
_SESSIONS.c.supplier_id == supplier_id,
|
||||
_EXP_LOGS.c.session_id != exclude_session_id,
|
||||
_SESSIONS.c.deleted == False) # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_history failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, (0, None, None)
|
||||
n = len(rows)
|
||||
settled = [(int(sp), int(tp)) for sp, tp in rows if sp and tp]
|
||||
success = len([1 for sp, tp in rows if sp]) / n
|
||||
avg_ratio = (sum(sp / tp for sp, tp in settled) / len(settled)) if settled else None
|
||||
return ErrorType.SUCCESS, (n, success, avg_ratio)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, (0, None, None)
|
||||
|
||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||
try:
|
||||
query = (
|
||||
|
||||
@@ -16,6 +16,50 @@ MAX_ROUNDS = 3
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
# ---- 완전 자율 모드 (AUTONOMY_MODE, autonomy_store) --------------------------------
|
||||
# 가격협상 판정 룰(check_price_match/wildcard_entry/iteration_limit)과 카드 선택을
|
||||
# 정책 행동(수락/역제안/압박/결렬)으로 대체할 때 쓰는 스텝들. autonomy_decider 미주입이면 도달 불가.
|
||||
_AUTONOMY_TURN_CAP = 12 # 엔지니어링 타임아웃(무한 세션 방지) — 협상 룰이 아니다
|
||||
|
||||
_AUTONOMY_PRESS_SCRIPTS = {
|
||||
1: "동일 품목에 대해 복수 공급처의 견적이 함께 검토되고 있습니다. 현재 제시가로는 우선순위 확보가 어려운 상황입니다. 경쟁력 있는 가격으로 다시 제안해 주시겠어요?",
|
||||
2: "제안하신 조건의 취지는 충분히 이해했습니다. 저희도 최대한 맞춰보려 합니다. 조금만 더 조정해 주시면 내부 설득이 가능할 것 같습니다. 다시 제안해 주시겠어요?",
|
||||
3: "내부 산정 기준과 현재 제시가 사이에 아직 차이가 있습니다. 기준에 부합하는 수준으로 재검토하여 다시 제안해 주시기를 부탁드립니다.",
|
||||
4: "귀사를 장기적으로 함께할 파트너로 검토하고 있습니다. 이번 협상이 원만히 마무리되면 후속 거래 확대도 논의하고 싶습니다. 서로 만족할 수 있는 가격으로 다시 제안해 주시겠어요?",
|
||||
}
|
||||
|
||||
_AUTONOMY_STEPS = {
|
||||
"자율_역제안": {
|
||||
"script": "제안해 주신 **{input_price}원**, 내부 검토를 마쳤습니다. **{autonomy_offer}원**이라면 즉시 수락하고 우선협상 대상으로 확정하겠습니다. 수락하시겠습니까?",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": {"예": "협상완료", "아니오": "가격협상_재입력"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
},
|
||||
# 최종 통보(WC-03 의 자율 버전): 정책이 직전과 같은 금액을 다시 부르는 순간(단조 봉투상
|
||||
# 더 올릴 수 없음 = 탄약 소진) 발동. 거절하면 협상을 정리한다 — 어정쩡한 반복 대신 명확한 마무리.
|
||||
"자율_최종제안": {
|
||||
"script": "지금까지 협의에 성실히 임해 주셔서 감사합니다. **{autonomy_offer}원**은 저희가 제시할 수 있는 마지막 제안입니다. 수락해 주시면 즉시 우선협상 대상으로 확정되며, 어려우시다면 이번 협상은 여기서 마무리하겠습니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": {"예": "협상완료", "아니오": "협상실패"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
},
|
||||
**{
|
||||
f"자율_압박_{s}": {
|
||||
"script": t,
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {"default": "가격협상_확인"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
}
|
||||
for s, t in _AUTONOMY_PRESS_SCRIPTS.items()
|
||||
},
|
||||
}
|
||||
|
||||
# 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬.
|
||||
# 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가
|
||||
# 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다.
|
||||
@@ -70,8 +114,11 @@ class ChatEngine:
|
||||
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
|
||||
self.repo = scripts_repo
|
||||
self.rq_type = rq_type
|
||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
||||
# 자율 스텝은 병합만 해둔다(repo 캐시 오염 방지 위해 새 dict) — decider 미주입 시 도달 불가.
|
||||
self.scripts = {**scripts_repo.load_scripts(rq_type), **_AUTONOMY_STEPS}
|
||||
self.step_map = scripts_repo.client_step_mapping()
|
||||
# 완전 자율 모드: ChatService 가 AutonomyStore 정책을 주입하면 가격협상 판정 룰을 대체한다.
|
||||
self.autonomy_decider = None # Callable[[dict], autonomy_actions.Action]
|
||||
|
||||
# ---- public --------------------------------------------------------
|
||||
def start(self, session: ChatSession) -> StepView:
|
||||
@@ -99,6 +146,10 @@ class ChatEngine:
|
||||
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
||||
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
||||
session.context["input_price"] = float(session.context["offer_1pct"])
|
||||
# 자율 역제안/최종제안 수락("예") → 합의가는 에이전트 제안가다 (wild_card_1pct 와 동일 원리).
|
||||
if session.step in ("자율_역제안", "자율_최종제안") and user_input == "예" \
|
||||
and session.context.get("autonomy_offer"):
|
||||
session.context["input_price"] = float(session.context["autonomy_offer"])
|
||||
nxt = self._choice_next(node, user_input, session)
|
||||
else:
|
||||
nxt = self._default_next(node)
|
||||
@@ -136,7 +187,15 @@ class ChatEngine:
|
||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||
|
||||
완전 자율 모드(autonomy_decider 주입)에서는 위 룰 전체를 정책 행동으로 대체한다.
|
||||
"""
|
||||
# 가격협상 판정 지점(check_price_match 포함 조건 리스트)에서만 자율 정책이 개입한다.
|
||||
if self.autonomy_decider is not None and any(
|
||||
c.get("condition") == "check_price_match" for c in conds):
|
||||
nxt = self._autonomy_next(session)
|
||||
if nxt is not None:
|
||||
return nxt # 정책 실패(예외) 시에만 아래 룰로 폴백
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
@@ -172,6 +231,52 @@ class ChatEngine:
|
||||
return c.get("next")
|
||||
return "가격협상"
|
||||
|
||||
def _autonomy_next(self, session: ChatSession) -> Optional[str]:
|
||||
"""완전 자율: 정책 행동 → 스텝. 수락/역제안 금액/압박 화법/결렬 타이밍 전부 정책이 결정.
|
||||
|
||||
유일한 강제 종료는 턴 상한(_AUTONOMY_TURN_CAP) — 무한 세션 방지용 엔지니어링 타임아웃.
|
||||
정책 호출이 실패하면 None 을 반환해 기존 룰 평가로 폴백한다(서비스 연속성).
|
||||
"""
|
||||
ctx = session.context
|
||||
if ctx.get("round", 0) > _AUTONOMY_TURN_CAP:
|
||||
# 턴 상한도 최종제안 보장(봉투 ⑥)을 우회하지 않는다 — 어떤 경로로 끝나든
|
||||
# "끝내기 전에 한 번 더"(제품 결정)를 거친다. 최종 거절 후에만 협상실패.
|
||||
if not ctx.get("autonomy_final_asked"):
|
||||
ctx["autonomy_final_asked"] = True
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "협상실패"
|
||||
try:
|
||||
act = self.autonomy_decider(ctx)
|
||||
except Exception: # 정책 오류 → 룰 폴백 (호출부에서 로깅)
|
||||
return None
|
||||
session.context["autonomy_action"] = f"{act.kind}:{act.strategy}:{act.counter_q}"
|
||||
span = max(ctx.get("target_price", 0) - ctx.get("anchor_price", 0), 1.0)
|
||||
# 탄약소진(같은 금액 재호출) 판정은 '마지막 역제안' 기준 — autonomy_last(마지막 행동)는
|
||||
# 사이에 낀 설득이 덮어써 판정이 리셋된다 (chat_service 가 counter 마다 별도 보존).
|
||||
last = ctx.get("autonomy_last_counter") or {}
|
||||
if act.kind == "accept":
|
||||
return "협상완료"
|
||||
if act.kind == "walk":
|
||||
# 결렬 전 마지막 제안 1회 보장 — "끝내기 전에 한 번 더 물어보고 종료" (제품 결정).
|
||||
# 최종제안을 이미 거쳤으면(autonomy_final_asked) 그대로 종료한다.
|
||||
if not ctx.get("autonomy_final_asked"):
|
||||
ctx["autonomy_final_asked"] = True
|
||||
# 최종제안 금액 = 목표가. 마지막 기회에 직전 역제안 금액을 반복하면 승인 범위의
|
||||
# 여지(목표가까지)를 남긴 채 결렬된다 — 최종에는 우리가 수락 가능한 최대치를 부른다.
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "협상실패"
|
||||
if act.kind == "counter":
|
||||
ctx["autonomy_offer"] = int(round(ctx.get("anchor_price", 0) + act.counter_q * span))
|
||||
# 직전과 같은 금액을 다시 부름 = 단조 봉투상 더 올릴 수 없음(탄약 소진) → 최종 통보로 전환.
|
||||
if last.get("kind") == "counter" and act.counter_q <= float(last.get("q", -9)) + 1e-9:
|
||||
ctx["autonomy_final_asked"] = True
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "자율_역제안"
|
||||
return f"자율_압박_{act.strategy or 3}"
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가에 아주 근접(≤ anchor*1.02)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
@@ -201,10 +306,25 @@ class ChatEngine:
|
||||
out["input_price"] = int(ctx["input_price"])
|
||||
if "target_price" in ctx:
|
||||
out["target"] = int(ctx["target_price"])
|
||||
# DB 카드 정본(negodata 편집, card.nego_cards.script)은 {target_price} 변수명을 쓴다
|
||||
# — 파일 스크립트의 {target}과 별개로 둘 다 지원(미치환 토큰 노출 방지).
|
||||
out["target_price"] = int(ctx["target_price"])
|
||||
if "anchor_price" in ctx:
|
||||
out["anchor"] = int(ctx["anchor_price"])
|
||||
out["anchoring_price"] = int(ctx["anchor_price"]) # DB 카드 정본 변수명(NGC-007 등)
|
||||
if "offer_1pct" in ctx:
|
||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||
if "autonomy_offer" in ctx:
|
||||
out["autonomy_offer"] = int(ctx["autonomy_offer"])
|
||||
# 인터넷 최저가(NGC-008): 수집값이 컨텍스트에 없으면 앵커가로 폴백 — 원형 토큰 노출 방지.
|
||||
# TODO: partner.item_internet_lowest_prices 최신 성공 수집값을 context loader 로 연결.
|
||||
if ctx.get("internet_lowest_price"):
|
||||
out["internet_lowest_price"] = int(ctx["internet_lowest_price"])
|
||||
elif "anchor_price" in ctx:
|
||||
out["internet_lowest_price"] = int(ctx["anchor_price"])
|
||||
# 고객사 교환·요구 조건(NGC-009/010): 런타임 소스 미구현 — 중립 문구 폴백.
|
||||
# TODO: 견적/카드 편집 단계에서 입력받아 컨텍스트로 전달.
|
||||
out["customer_condition"] = ctx.get("customer_condition") or "상호 협의된 조건"
|
||||
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
base = ctx.get("item_price") or 0
|
||||
if base > 1 and "input_price" in ctx:
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""MentGenerator — 자율 협상 행동을 LLM 이 자연어 멘트로 표현 (v2: 행동은 RL, 문장은 LLM).
|
||||
|
||||
역할 분리(안전 설계):
|
||||
- 무엇을 말할지(수락/역제안 금액/압박 전략/결렬)는 RL 정책이 결정 — LLM 은 표현만 담당.
|
||||
- 가드레일: 역제안 멘트에 제안 금액이 정확히 포함되지 않으면 폐기, 예외/미설정 시 None
|
||||
→ 호출부(ChatService)가 기존 템플릿 멘트로 폴백한다. LLM 이 죽어도 협상은 계속된다.
|
||||
|
||||
설정: config.local.toml [OpenAIConfig] (Gemini 는 OpenAI 호환 base_url 로 접속).
|
||||
비활성화: AUTONOMY_LLM=0.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
_STRATEGY_TONE = {
|
||||
1: "경쟁 압박형 — 복수 공급처와 비교 검토 중임을 암시하며 긴장감을 준다",
|
||||
2: "수용 공감형 — 상대 제안의 취지에 공감하며 부드럽게 조정을 요청한다",
|
||||
3: "기준 고수형 — 내부 산정 기준과 목표가를 근거로 원칙을 지킨다",
|
||||
4: "협력 파트너형 — 장기 파트너십과 후속 거래 확대 가능성을 강조한다",
|
||||
}
|
||||
|
||||
_SYSTEM = """너는 대기업 구매팀의 가격 협상 챗봇이다. 주어진 '전달 의도'를 자연스러운 한국어 협상 멘트로 바꿔 쓴다.
|
||||
규칙 (위반 시 출력은 폐기된다):
|
||||
- 1~3문장, 정중하되 간결하게. 출력은 멘트 텍스트만 (따옴표·설명 없이).
|
||||
- 금액 숫자는 주어진 그대로 정확히 포함하고 단위는 '원'을 쓴다. 주어지지 않은 숫자·비율을 절대 만들지 않는다.
|
||||
- 지정된 '화법' 전략 안에서만 말한다. 그 외의 협상 전술(물량·기간 약속, 조건 교환, 거래 연계,
|
||||
독점 제안, 시장가·최저가 주장, 할인 약속 등)을 지어내지 않는다.
|
||||
- 회사의 정책·사실을 단정하지 않는다. 주어진 의도에 없는 정보는 말하지 않는다.
|
||||
- 상대는 협력사(판매자)이고 우리는 구매자다."""
|
||||
|
||||
# 생성문 금지어 — 승인되지 않은 커밋/주장 계열. 걸리면 템플릿 폴백(협상은 계속).
|
||||
_FORBIDDEN = ("보장", "물량", "독점", "무조건", "최저가", "시장 가격", "시장가", "계약 기간",
|
||||
"법적", "위약", "%")
|
||||
|
||||
|
||||
def _configured() -> bool:
|
||||
if os.getenv("AUTONOMY_LLM", "1").lower() in ("0", "false", "no"):
|
||||
return False
|
||||
try:
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _digits(s) -> str:
|
||||
return re.sub(r"[^\d]", "", str(s))
|
||||
|
||||
|
||||
def _history_hints(ctx: dict) -> str:
|
||||
"""대화 기억 힌트 — 무기억 생성이 '매번 같은 멘트'를 만들던 문제의 해법.
|
||||
|
||||
① 직전 우리 제안이 거절된 사실과 이번 제안과의 관계(양보/입장유지)를 짚게 하고
|
||||
② 직전 봇 멘트를 보여주며 같은 문장 구조·표현의 반복을 금지한다."""
|
||||
hints = []
|
||||
prev = ctx.get("autonomy_prev")
|
||||
if prev and prev.get("kind") == "counter":
|
||||
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||
cur_offer = int(ctx.get("autonomy_offer") or 0)
|
||||
if cur_offer > prev_offer:
|
||||
hints.append(f"참고: 직전 라운드에 우리가 {prev_offer:,}원을 제안했으나 거절당했고, "
|
||||
f"이번에는 {cur_offer - prev_offer:,}원 더 양보한 제안이다. 이 진전을 자연스럽게 짚어라.")
|
||||
elif cur_offer == prev_offer and cur_offer > 0:
|
||||
hints.append(f"참고: 직전에 제안한 {prev_offer:,}원을 거절당했지만 같은 금액을 유지한다. "
|
||||
f"입장이 확고함을 정중하게 전하라.")
|
||||
elif prev_offer > 0:
|
||||
hints.append(f"참고: 직전 제안({prev_offer:,}원)이 거절된 뒤의 재제안이다.")
|
||||
last_ment = ctx.get("autonomy_last_ment")
|
||||
if last_ment:
|
||||
hints.append(f'직전 봇 멘트: "{last_ment}" — 이와 같은 문장 구조·표현을 반복하지 말고 다르게 써라.')
|
||||
return " ".join(hints)
|
||||
|
||||
|
||||
def _prompt_for(step: str, ctx: dict) -> Optional[str]:
|
||||
price = int(ctx.get("input_price") or 0)
|
||||
rnd = ctx.get("round", 1)
|
||||
if step in ("자율_역제안", "자율_최종제안"):
|
||||
offer = int(ctx.get("autonomy_offer") or 0)
|
||||
if offer <= 0:
|
||||
return None
|
||||
strategy = int((ctx.get("autonomy_last") or {}).get("s") or 3)
|
||||
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||
final = ("이번이 우리가 제시할 수 있는 마지막 제안이며, 거절하시면 이번 협상은 종료됨을 "
|
||||
"분명하되 정중하게 밝혀라. " if step == "자율_최종제안" else "")
|
||||
return (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||
f"전달 의도: 우리는 **{offer:,}원**이면 즉시 수락하고 우선협상 대상으로 확정할 수 있다 — "
|
||||
f"이 핵심 의미는 유지하되 문장 표현은 자유롭게 새로 써라. {final}화법: {tone}. "
|
||||
f"{_history_hints(ctx)} 마지막에 수락 여부를 물어라.")
|
||||
if step.startswith("자율_압박_"):
|
||||
strategy = int(step.rsplit("_", 1)[1])
|
||||
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||
# 주의: 목표가는 프롬프트에 넣지 않는다 — 압박 중 목표가 노출은 우리 상한을 까는 것
|
||||
# (상대가 그 밑으로 내려올 이유가 사라진다). 숫자 커밋은 역제안/최종제안에서만.
|
||||
base = (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||
f"전달 의도: 어떤 금액도 언급하지 말고(내부 기준·목표가 숫자 금지), 제시가와 우리 기준의 "
|
||||
f"거리가 있다는 취지로 가격 재제안을 요청한다. 화법: {tone}. "
|
||||
f"{_history_hints(ctx)}")
|
||||
# 시장가 근거 (구 NGC-008 의 자율 버전): 수집된 인터넷최저가가 실재하고 제시가가 그보다
|
||||
# 높을 때만 사실 근거로 인용을 허용한다 — 미수집 품목에서 지어내는 주장은 가드가 차단.
|
||||
if _market_evidence(ctx):
|
||||
il = int(ctx["internet_lowest_price"])
|
||||
base += (f" 참고 사실(인용 허용되는 유일한 금액): 동일 품목의 인터넷 최저가가 {il:,}원으로 "
|
||||
f"확인된다. 현재 제시가가 이보다 높다는 점을 근거로 조정 여지를 정중히 짚어라.")
|
||||
return base
|
||||
return None
|
||||
|
||||
|
||||
def _market_evidence(ctx: dict) -> bool:
|
||||
"""시장가 근거 인용 가능 조건: 인터넷최저가 수집됨 + 제시가가 그보다 높음."""
|
||||
il = int(ctx.get("internet_lowest_price") or 0)
|
||||
return il > 0 and float(ctx.get("input_price") or 0) > il
|
||||
|
||||
|
||||
def _allowed_amounts(ctx: dict) -> set:
|
||||
"""멘트에 등장해도 되는 숫자 집합 — 우리가 프롬프트로 준 값들뿐. 이 밖의 금액 = 할루시네이션."""
|
||||
# 목표가는 화이트리스트에 없다 — 압박 멘트가 목표가를 새면(상한 노출) 즉시 폐기된다.
|
||||
# 역제안·최종제안의 제안가(autonomy_offer)가 목표가와 같은 경우만 그 값으로 허용된다.
|
||||
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||
out = {int(ctx.get("input_price") or 0), int(ctx.get("autonomy_offer") or 0),
|
||||
int(ctx.get("round") or 0)}
|
||||
if _market_evidence(ctx):
|
||||
out.add(int(ctx["internet_lowest_price"])) # 시장가 근거 인용 시 그 수치만 허용
|
||||
prev = ctx.get("autonomy_prev")
|
||||
if prev and prev.get("kind") == "counter":
|
||||
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||
out |= {prev_offer, abs(int(ctx.get("autonomy_offer") or 0) - prev_offer)}
|
||||
return {str(v) for v in out if v}
|
||||
|
||||
|
||||
def _guard(step: str, ctx: dict, text: str) -> bool:
|
||||
"""LLM 출력 검증(할루시네이션 차단) — 실패 시 템플릿 폴백.
|
||||
|
||||
① 길이/문장 완결 ② 금지어(승인 안 된 커밋·주장) ③ 숫자 화이트리스트: 멘트의 모든
|
||||
3자리+ 숫자는 우리가 준 값(제시가·제안가·목표가·직전제안가)이어야 한다 — 지어낸 금액 즉시 폐기.
|
||||
④ 역제안은 제안 금액 포함 필수."""
|
||||
if not text or len(text) < 10 or len(text) > 600:
|
||||
return False
|
||||
if not text.rstrip().endswith(("다.", "요.", "요?", "까?", "니까?", ".", "?")):
|
||||
return False # 문장 중간 잘림(thinking 토큰에 한도 소진 등) → 템플릿 폴백
|
||||
forbidden = _FORBIDDEN
|
||||
if _market_evidence(ctx):
|
||||
# 시장가 근거가 정당한 턴에는 '최저가/시장가' 언급을 허용 (수치는 아래 화이트리스트가 검증).
|
||||
forbidden = tuple(w for w in _FORBIDDEN if w not in ("최저가", "시장가", "시장 가격"))
|
||||
if any(w in text for w in forbidden):
|
||||
return False
|
||||
allowed = _allowed_amounts(ctx)
|
||||
for num in re.findall(r"\d{3,}", text.replace(",", "")):
|
||||
if num not in allowed:
|
||||
return False # 프롬프트에 없던 금액 생성 = 할루시네이션
|
||||
if step in ("자율_역제안", "자율_최종제안"):
|
||||
return _digits(ctx.get("autonomy_offer")) in _digits(text)
|
||||
return True
|
||||
|
||||
|
||||
async def generate(step: str, ctx: dict) -> Optional[str]:
|
||||
"""자율 스텝 멘트 생성. 미설정/실패/검증불통과 → None (호출부 템플릿 유지)."""
|
||||
if not _configured():
|
||||
return None
|
||||
prompt = _prompt_for(step, ctx)
|
||||
if prompt is None:
|
||||
return None
|
||||
try:
|
||||
from negotiation.profiling.infra.llm_adapter import chat_complete
|
||||
# openai SDK 는 동기 — 이벤트루프 블로킹 방지 위해 스레드로 넘긴다.
|
||||
# max_tokens 넉넉히 — Gemini 2.5 계열은 thinking 토큰이 한도에 포함돼 짧으면 본문이 잘린다.
|
||||
# 시간 상한: backend→agent 타임아웃(10s)보다 확실히 짧아야 한다 — 초과 시 템플릿 폴백으로
|
||||
# 협상은 즉시 계속된다("협상 응답 지연" 토스트 방지). LLM_TIMEOUT_S 로 조절.
|
||||
text = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
chat_complete,
|
||||
[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}],
|
||||
None, False, 0.9, 2048, # temperature 0.9 — 표현 다양성 (의미는 프롬프트 가드)
|
||||
),
|
||||
timeout=float(os.getenv("LLM_TIMEOUT_S", "6")),
|
||||
)
|
||||
text = (text or "").strip().strip('"')
|
||||
if _guard(step, ctx, text):
|
||||
return text
|
||||
LOG.w(f"[MentGenerator] 가드레일 불통과 → 템플릿 폴백 (step={step})")
|
||||
return None
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[MentGenerator] LLM 실패 → 템플릿 폴백: {ex}")
|
||||
return None
|
||||
@@ -44,14 +44,23 @@ class NegotiationDbContext:
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
|
||||
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
|
||||
# ---- 자율 에이전트 v3 상태 특징 소스 (없으면 0/None — 특징은 중립 기본값으로 폴백) ----
|
||||
internet_lowest_price: int = 0 # items.internet_lowest_price (미수집 0)
|
||||
deadline_end_ts: Optional[float] = None # 견적 마감(epoch 초) — quotations.end_time
|
||||
deadline_total_s: Optional[float] = None # 협상 전체 기간(초) — end−start
|
||||
hist_n: int = 0 # 이 협력사와의 과거 협상 횟수
|
||||
hist_success: Optional[float] = None # 과거 성사율 (이력 없으면 None)
|
||||
hist_settle_ratio: Optional[float] = None # 과거 평균 타결가/목표가 (성사 이력 없으면 None)
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
def __init__(self, crud: Optional[INegoContextCRUD] = None):
|
||||
self.crud: INegoContextCRUD = crud or NegoContextCRUD()
|
||||
|
||||
async def load(self, session_id: Optional[str]) -> Optional[NegotiationDbContext]:
|
||||
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백)."""
|
||||
async def load(self, session_id: Optional[str],
|
||||
company_id: Optional[str] = None) -> Optional[NegotiationDbContext]:
|
||||
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백).
|
||||
company_id 는 협력사 이력 집계(experience_logs 테넌트 스코프)용 — 없으면 이력 특징 생략."""
|
||||
if not session_id:
|
||||
return None
|
||||
try:
|
||||
@@ -97,6 +106,21 @@ class NegotiationContextLoader:
|
||||
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||
selected_nego_cards, selected_wild_cards = selected_cards
|
||||
|
||||
# ---- 자율 에이전트 v3 특징 소스 (조회 실패는 전부 중립 폴백 — 협상은 계속돼야 한다) ----
|
||||
_, internet_lowest = await self.crud.get_item_internet_lowest(s, item_id)
|
||||
_, period = await self.crud.get_quotation_period(s, quotation_id)
|
||||
deadline_end_ts = deadline_total_s = None
|
||||
if period and period[1] is not None:
|
||||
end_ts = period[1].timestamp()
|
||||
start_ts = period[0].timestamp() if period[0] is not None else None
|
||||
total = (end_ts - start_ts) if start_ts else None
|
||||
if total and total > 0:
|
||||
deadline_end_ts, deadline_total_s = end_ts, total
|
||||
hist_n, hist_success, hist_settle = 0, None, None
|
||||
if company_id:
|
||||
_, hist = await self.crud.get_supplier_history(s, company_id, supplier_id, sid)
|
||||
hist_n, hist_success, hist_settle = hist
|
||||
|
||||
return NegotiationDbContext(
|
||||
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
||||
target_price=target,
|
||||
@@ -107,6 +131,12 @@ class NegotiationContextLoader:
|
||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||
selected_nego_card_numbers=selected_nego_cards,
|
||||
selected_wild_card_numbers=selected_wild_cards,
|
||||
internet_lowest_price=internet_lowest,
|
||||
deadline_end_ts=deadline_end_ts,
|
||||
deadline_total_s=deadline_total_s,
|
||||
hist_n=hist_n,
|
||||
hist_success=hist_success,
|
||||
hist_settle_ratio=hist_settle,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""완전 자율 협상 행동 공간 (numpy 전용 — 학습(tools)과 서빙(policy)이 공유).
|
||||
|
||||
카드 카탈로그 대신 행동의 '의미'만 남긴다:
|
||||
ACCEPT 현재 제시가로 타결
|
||||
WALK 협상 결렬 선언
|
||||
COUNTER(q, s) "C원이면 수락" 역제안. C = anchor + q×(target−anchor), s = 화법 전략
|
||||
PRESS(s) 설득 압박 (카드의 일반화 — 전략 1경쟁/2수용/3고수/4협력)
|
||||
|
||||
특징 벡터(ACTION_DIM=8) = 유형 one-hot(3) + 가격 위치(1) + 전략 one-hot(4).
|
||||
ScoreNet(상태 + 행동특징) → 스칼라 점수로 후보 30개를 채점해 argmax 한다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
COUNTER_GRID = [-0.05, 0.0, 0.25, 0.5, 0.75, 1.0] # C = anchor + q×(target−anchor)
|
||||
ACTION_DIM = 3 + 1 + 4 + 1 # 유형(3) + 위치(1) + 전략(4) + 컷폭(1: 현 제시가 대비 인하 요구율)
|
||||
|
||||
# 자율 전용 추가 상태 (v3):
|
||||
# [0] 직전 역제안 존재(0/1) [1] 직전 역제안 위치 q ← 에피소드 기억(같은 숫자 반복 방지)
|
||||
# [2] 마감 잔여율(남은시간/전체, 미상 0.5) ← 견적 마감(quotations.end_time)
|
||||
# [3] 과거 협상 횟수 min(n,5)/5 [4] 과거 성사율(미상 0.5)
|
||||
# [5] 과거 평균 타결수준 norm((타결가/목표가−0.8)/0.4, 미상 0.5) ← 이 협력사와의 이력(experience_logs)
|
||||
# [6] 인터넷최저가 갭 clip((최저가−앵커)/앵커/0.1, ±1, 미상 0) ← 숨은 하한가의 관측 가능한 힌트
|
||||
# 특징은 학습 시뮬에도 동일하게 존재해야 한다(train_full_autonomy 가 대응물을 생성).
|
||||
EXTRA_STATE_DIM = 7
|
||||
|
||||
|
||||
def extra_state(last_kind: str = "", last_q: float = 0.0, deadline: float = 0.5,
|
||||
hist_n: float = 0.0, hist_success: float = 0.5, hist_settle: float = 0.5,
|
||||
internet_gap: float = 0.0) -> np.ndarray:
|
||||
has_counter = 1.0 if last_kind == "counter" else 0.0
|
||||
return np.array([
|
||||
has_counter,
|
||||
float(np.clip(last_q, -1.0, 1.0)) * has_counter,
|
||||
float(np.clip(deadline, 0.0, 1.0)),
|
||||
float(np.clip(hist_n, 0.0, 1.0)),
|
||||
float(np.clip(hist_success, 0.0, 1.0)),
|
||||
float(np.clip(hist_settle, 0.0, 1.0)),
|
||||
float(np.clip(internet_gap, -1.0, 1.0)),
|
||||
], dtype=np.float32)
|
||||
|
||||
|
||||
def settle_norm(avg_settle_ratio: float) -> float:
|
||||
"""평균 (타결가/목표가) → 0~1 정규화 (0.8→0, 1.0→0.5, 1.2→1)."""
|
||||
return float(np.clip((avg_settle_ratio - 0.8) / 0.4, 0.0, 1.0))
|
||||
|
||||
|
||||
def internet_gap_feat(internet_lowest: float, anchor: float) -> float:
|
||||
"""인터넷최저가의 앵커 대비 갭 (±10% 스케일). 최저가 없으면 0을 쓴다."""
|
||||
if not internet_lowest or anchor <= 0:
|
||||
return 0.0
|
||||
return float(np.clip((internet_lowest - anchor) / anchor / 0.1, -1.0, 1.0))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Action:
|
||||
kind: str # accept | walk | counter | press
|
||||
counter_q: float = 0.0 # counter 위치 (anchor~target 스팬 비율)
|
||||
strategy: int = 0 # press/counter 의 화법 전략 (1~4, 0=없음)
|
||||
|
||||
def feat(self, price_pos: float, cut: float = 0.0) -> np.ndarray:
|
||||
"""cut: 이 행동이 요구하는 인하폭 (현 제시가 대비, counter 만 >0) — 대형컷의 무례함을
|
||||
정책이 지각하게 한다. 갭이 크면 역제안 대신 압박이 낫다는 걸 배우는 근거 특징."""
|
||||
t = {"accept": [1, 0, 0], "walk": [0, 1, 0]}.get(self.kind, [0, 0, 1])
|
||||
pos = price_pos if self.kind == "accept" else self.counter_q
|
||||
s = np.zeros(4, dtype=np.float32)
|
||||
if self.strategy:
|
||||
s[self.strategy - 1] = 1.0
|
||||
return np.concatenate([np.array(t, dtype=np.float32),
|
||||
np.array([float(np.clip(pos, -1.0, 2.0)),
|
||||
], dtype=np.float32), s,
|
||||
np.array([float(np.clip(cut, 0.0, 1.0))], dtype=np.float32)])
|
||||
|
||||
|
||||
def candidate_actions():
|
||||
"""전 행동 후보: 수락 1 + 결렬 1 + 역제안 6×전략4 + 압박 4 = 30."""
|
||||
out = [Action("accept"), Action("walk")]
|
||||
out += [Action("counter", q, s) for q in COUNTER_GRID for s in (1, 2, 3, 4)]
|
||||
out += [Action("press", 0.0, s) for s in (1, 2, 3, 4)]
|
||||
return out
|
||||
|
||||
|
||||
ACTIONS = candidate_actions()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""AutonomyStore — 완전 자율 협상 정책 서빙 (룰 대체, numpy 전용).
|
||||
|
||||
AUTONOMY_MODE=1 이면 가격협상 판정 룰(앵커 이하 타결 / 와일드카드 존 / 라운드 상한)과
|
||||
카드 선택을 전부 이 정책의 행동 결정으로 대체한다:
|
||||
accept → 협상완료 (제시가 타결) walk → 협상실패
|
||||
counter → "C원이면 수락" 역제안 스텝 press → 전략별 압박 멘트 스텝
|
||||
|
||||
행동의 유일한 유인은 보상 함수다. 남는 제한은 두 가지뿐이며 비즈니스 룰이 아니다:
|
||||
- 역제안 후보 격자가 [anchor−5%span, target] 안 (행동 공간 정의)
|
||||
- 세션 턴 상한(엔지니어링 타임아웃, ChatEngine._AUTONOMY_TURN_CAP)
|
||||
|
||||
번들: artifacts/autonomy_serving.npz (tools/export_autonomy_serving.py).
|
||||
불가(플래그 꺼짐/번들 없음)면 None → 기존 룰 엔진 그대로 (즉시 롤백 경로).
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.policies.autonomy_actions import (
|
||||
ACTIONS, Action, extra_state, internet_gap_feat, settle_norm)
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
build_state_features, build_tenant_features)
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "autonomy_serving.npz")
|
||||
|
||||
|
||||
class AutonomyPolicy:
|
||||
"""세션 컨텍스트 → 상태특징 → 행동(greedy). ChatEngine 에 decider 로 주입된다."""
|
||||
|
||||
name = "full_autonomy"
|
||||
|
||||
def __init__(self, z, reward_cfg):
|
||||
self._W = (z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"])
|
||||
self._state_dim = int(z["state_dim"])
|
||||
self._tenant_feat = build_tenant_features(reward_cfg)
|
||||
|
||||
@staticmethod
|
||||
def _acceptance(ctx: dict) -> float:
|
||||
base = ctx.get("item_price") or ctx.get("first_offer_price") or 0
|
||||
cur = ctx.get("input_price") or 0
|
||||
if base <= 0 or cur <= 0:
|
||||
return 0.0
|
||||
return max(0.0, (base - cur) / base)
|
||||
|
||||
def decide(self, ctx: dict) -> Action:
|
||||
"""ChatSession.context → Action. 상태 구성은 ChatService._snapshot 과 동일 규칙."""
|
||||
snap = NegotiationSnapshot(
|
||||
revenue_amount=ctx["revenue_amount"], distribution_code=ctx["distribution_code"],
|
||||
partner_count=ctx["partner_count"], acceptance_ratio=self._acceptance(ctx),
|
||||
input_price=ctx.get("input_price", ctx["anchor_price"]), anchor_price=ctx["anchor_price"],
|
||||
target_price=ctx["target_price"], round_number=ctx.get("round", 0),
|
||||
)
|
||||
# v3 추가 특징: 직전 역제안 기억 + 마감 잔여율 + 협력사 이력 + 인터넷최저가 갭.
|
||||
# 소스가 없으면 전부 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일해야 한다.
|
||||
# 역제안 기억은 autonomy_last_counter(역제안만 갱신) — autonomy_last(마지막 행동)를 쓰면
|
||||
# 사이에 낀 설득이 기억을 지워 단조 봉투가 뚫린다(counter→press→counter 철회 실버그).
|
||||
# 시뮬의 last_kind/last_q 도 역제안만 추적하므로 이쪽이 학습 분포와도 일치한다.
|
||||
last = ctx.get("autonomy_last_counter") or {}
|
||||
deadline = 0.5
|
||||
end_ts, total_s = ctx.get("deadline_end_ts"), ctx.get("deadline_total_s")
|
||||
if end_ts and total_s:
|
||||
import time
|
||||
deadline = float(np.clip((end_ts - time.time()) / total_s, 0.0, 1.0))
|
||||
hist_n = int(ctx.get("hist_n") or 0)
|
||||
hist_success = float(ctx["hist_success"]) if ctx.get("hist_success") is not None else 0.5
|
||||
hist_settle = (settle_norm(float(ctx["hist_settle_ratio"]))
|
||||
if ctx.get("hist_settle_ratio") is not None else 0.5)
|
||||
sf = np.concatenate([build_state_features(snap), self._tenant_feat, extra_state(
|
||||
last.get("kind", ""), float(last.get("q", 0.0)),
|
||||
deadline=deadline, hist_n=min(hist_n, 5) / 5.0,
|
||||
hist_success=hist_success if hist_n else 0.5,
|
||||
hist_settle=hist_settle,
|
||||
internet_gap=internet_gap_feat(float(ctx.get("internet_lowest_price") or 0),
|
||||
float(snap.anchor_price)),
|
||||
)])
|
||||
span = max(snap.target_price - snap.anchor_price, 1.0)
|
||||
pos = (snap.input_price - snap.anchor_price) / span
|
||||
# 행동 봉투 (학습 available_actions 와 동일해야 한다):
|
||||
# ① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(v3.1 착취 방지)
|
||||
# ② 직전 역제안보다 낮은 금액의 역제안 제외 — 단조 양보 원칙(제안 철회는 협상 예절 위반;
|
||||
# 올리는 '속도'는 정책 학습, 후퇴 '금지'만 구조로 보장)
|
||||
# ③ 역제시 해금 조건 — 옛 제품 의미론 복원(제품 결정 2026-07-10): 일반 카드는 설득만,
|
||||
# 역제시(숫자 제안)는 와일드카드처럼 마무리 수단. 최소 AUTONOMY_MIN_PRESS(기본 2)회
|
||||
# 설득 이후에만 역제시 후보가 열린다. 해금 후의 타이밍·금액은 정책 학습.
|
||||
# ④ 마무리 국면 — 제시가가 목표가 0.5% 이내로 붙으면 압박 제외(+역제시 잠금 해제):
|
||||
# 푼돈 차이에서 '재검토 부탁' 반복은 상대만 지치게 한다. 클로징(역제안/최종제안)하거나 끝내거나.
|
||||
min_press = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||
near_target = snap.input_price <= snap.target_price * 1.005
|
||||
counter_locked = (int(ctx.get("autonomy_press_n") or 0) < min_press) and not near_target
|
||||
last_counter_q = float(last["q"]) if last.get("kind") == "counter" else None
|
||||
if last_counter_q is not None:
|
||||
counter_locked = False # 이미 역제시를 시작했으면 잠그지 않는다(단조 봉투가 관리)
|
||||
# ⑤ 첫 역제안은 앵커가 이하(q ≤ 0)만 — 낮게 개시해 목표가까지 천천히 올라간다
|
||||
# (제품 결정: 사다리를 다 쓰는 앵커링 개시. 이후 단조 봉투가 상향을 관리).
|
||||
# ⑥ 결렬(walk)도 해금 전 금지 — 설득 0회에 walk 를 고르면 최종제안 보장(엔진)과 결합해
|
||||
# '첫 턴 목표가 통보'가 된다(v3.4 라이브 결함). 해금 전에는 설득만 가능.
|
||||
cands = [a for a in ACTIONS
|
||||
if not (a.kind == "accept" and snap.input_price > snap.target_price)
|
||||
and not (a.kind == "counter" and counter_locked)
|
||||
and not (a.kind == "walk" and counter_locked)
|
||||
and not (a.kind == "press" and near_target)
|
||||
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||
and not (a.kind == "counter" and last_counter_q is not None
|
||||
and a.counter_q < last_counter_q - 1e-9)]
|
||||
feats = []
|
||||
for a in cands:
|
||||
cut = 0.0
|
||||
if a.kind == "counter":
|
||||
c = snap.anchor_price + a.counter_q * span
|
||||
cut = max(0.0, (snap.input_price - c) / max(snap.input_price, 1.0))
|
||||
feats.append(a.feat(pos, cut))
|
||||
feats = np.stack(feats)
|
||||
W0, b0, W1, b1, W2, b2 = self._W
|
||||
x = np.concatenate([np.repeat(sf[None, :], feats.shape[0], axis=0), feats], axis=1)
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
scores = (h @ W2.T + b2).squeeze(-1)
|
||||
return cands[int(np.argmax(scores))]
|
||||
|
||||
@staticmethod
|
||||
def counter_price(ctx: dict, act: Action) -> int:
|
||||
span = max(ctx["target_price"] - ctx["anchor_price"], 1.0)
|
||||
return int(round(ctx["anchor_price"] + act.counter_q * span))
|
||||
|
||||
|
||||
class AutonomyStore:
|
||||
_z = None
|
||||
_load_failed = False
|
||||
|
||||
@classmethod
|
||||
def enabled(cls) -> bool:
|
||||
return os.getenv("AUTONOMY_MODE", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
@classmethod
|
||||
def policy_for(cls, engine) -> Optional[AutonomyPolicy]:
|
||||
"""engine: tenancy.registry.TenantEngine. 비활성/번들 없음 → None (룰 엔진 유지)."""
|
||||
if not cls.enabled() or cls._load_failed:
|
||||
return None
|
||||
if cls._z is None:
|
||||
try:
|
||||
cls._z = np.load(BUNDLE_PATH, allow_pickle=False)
|
||||
LOG.i("[Autonomy] 완전 자율 정책 번들 로드 완료 — 협상 판정 룰 대체 모드")
|
||||
except Exception as ex:
|
||||
cls._load_failed = True
|
||||
LOG.e_no_callstack(f"[Autonomy] 번들 로드 실패 → 룰 엔진 유지: {ex}")
|
||||
return None
|
||||
return AutonomyPolicy(cls._z, engine.config.reward)
|
||||
Reference in new issue
Block a user