data(train 520·holdout 120), server(발화 생성 서버), eval(grounding_eval), run_eval.py·run_test.sh. logs/ 는 실행 때마다 생기는 기록이라 README.md 만 올리고 나머지는 .gitignore 로 뺀다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
134 lines
7.3 KiB
Python
134 lines
7.3 KiB
Python
"""턴별 지식 선택 — 이번 턴 상황(첫 턴·협상카드·행동전략)에 맞는 지식 항목과 주의 사항을 고른다.
|
|
|
|
규칙은 resources/grounding/grounding_policy.json 에 둔다 (정본). 비공개 기준은 여기서 고르지 않고
|
|
prompt_builder 가 별도 절로 넣는다 (가격 판단에만 쓰고 발화에 노출하지 않음).
|
|
이번 턴 판단: 수락 여부, 제시가(price_advice — services/grounding/pricing.py), 첫 턴 지침.
|
|
"""
|
|
|
|
import json
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional
|
|
|
|
from common.paths import RESOURCES_DIR
|
|
from services.grounding.parser import KnowledgeItem, NegotiationContext
|
|
from services.grounding.pricing import suggest_offer
|
|
|
|
POLICY_PATH = RESOURCES_DIR / "grounding" / "grounding_policy.json"
|
|
|
|
|
|
@dataclass
|
|
class GroundingSelection:
|
|
items: List[KnowledgeItem] = field(default_factory=list)
|
|
notes: List[str] = field(default_factory=list)
|
|
rule: str = "" # 적용한 규칙 (로그용)
|
|
decision: Optional[str] = None # 이번 턴 수락 판단 (accept / continue)
|
|
decision_text: Optional[str] = None # 프롬프트에 넣을 판단 문장
|
|
act: str = "inform" # 이번 턴 예상 행위 (offer / accept / inform) — 경험 예시 검색용
|
|
offer: Optional[int] = None # 이번 턴 제시가 (price_advice)
|
|
offer_rule: Optional[str] = None # 제시가 규칙 (로그용)
|
|
guides: List[str] = field(default_factory=list) # 이번 턴 판단에 덧붙일 지침 (첫 턴·제시가)
|
|
|
|
@property
|
|
def ids(self) -> List[str]:
|
|
return [item.id for item in self.items]
|
|
|
|
|
|
class GroundingPolicy:
|
|
"""grounding_policy.json 을 읽어 들인 선택 규칙."""
|
|
|
|
def __init__(self, json_file_path: Optional[Path] = None):
|
|
path = Path(json_file_path) if json_file_path else POLICY_PATH
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
raw = json.load(f)
|
|
self.always: List[str] = raw.get("always", [])
|
|
self.first_turn: List[str] = raw.get("first_turn", [])
|
|
self.with_card: Dict[str, List[str]] = raw.get("with_card", {})
|
|
self.without_card: List[str] = raw.get("without_card", [])
|
|
self.strategy_guide: Dict[str, str] = raw.get("strategy_guide", {})
|
|
self.notes: Dict[str, str] = raw.get("notes", {})
|
|
self.short_tenure_years: int = raw.get("short_tenure_years", 3)
|
|
self.private_terms_allowed_cards: List[str] = raw.get("private_terms_allowed_cards", [])
|
|
self.turn_guides: Dict[str, str] = raw.get("turn_guides", {})
|
|
self.step_ratio: Dict[str, float] = raw.get("pricing", {}).get("step_ratio", {})
|
|
self.experience_intro: str = raw.get("experience", {}).get("intro", "")
|
|
|
|
|
|
class KnowledgeSelector:
|
|
def __init__(self, policy: Optional[GroundingPolicy] = None):
|
|
self.policy = policy or GroundingPolicy()
|
|
|
|
def select(self, ctx: NegotiationContext, price_advice: bool = False) -> GroundingSelection:
|
|
p = self.policy
|
|
if ctx.is_first_turn:
|
|
wanted, rule = p.always + p.first_turn, "first_turn"
|
|
elif ctx.card_name:
|
|
wanted, rule = p.always + p.with_card.get(ctx.card_name, []), f"card:{ctx.card_name}"
|
|
else:
|
|
wanted, rule = p.always + p.without_card, "no_card"
|
|
|
|
seen, items = set(), []
|
|
for kid in wanted:
|
|
if kid in ctx.knowledge and kid not in seen:
|
|
seen.add(kid)
|
|
items.append(ctx.knowledge[kid])
|
|
decision, decision_text = self._accept_decision(ctx)
|
|
selection = GroundingSelection(items=items, notes=self._notes(ctx, seen), rule=rule,
|
|
decision=decision, decision_text=decision_text)
|
|
self._turn_plan(ctx, selection, price_advice)
|
|
return selection
|
|
|
|
def _turn_plan(self, ctx: NegotiationContext, sel: GroundingSelection, price_advice: bool) -> None:
|
|
"""이번 턴 행위(제시·수락·질문)와 지침. price_advice 면 제시가를 계산해 알려 준다."""
|
|
guides = self.policy.turn_guides
|
|
if ctx.is_first_turn or ctx.strategy == "탐색":
|
|
sel.act = "inform"
|
|
if ctx.is_first_turn and guides.get("first_turn"):
|
|
sel.guides.append(guides["first_turn"])
|
|
return
|
|
if sel.decision == "accept":
|
|
sel.act = "accept" # 마무리 방식은 작성 규칙(두 프로필 공통)에 있다
|
|
return
|
|
sel.act = "offer"
|
|
if price_advice:
|
|
advice = suggest_offer(ctx, self.policy.step_ratio)
|
|
if advice is not None:
|
|
sel.offer, sel.offer_rule = advice.price, advice.rule
|
|
if guides.get("offer"):
|
|
sel.guides.append(guides["offer"].format(price=advice.price))
|
|
|
|
def _accept_decision(self, ctx: NegotiationContext):
|
|
"""구매자 자신의 비공개 기준으로 이번 턴 수락 여부를 판단한다 (상대에게 노출하지 않는 내부 판단).
|
|
|
|
수락 조건: 협상카드가 없는 턴, 최소 종료턴 이후, 판매자 직전 제시가 ≤ 최대 수용가,
|
|
그리고 (마지막 회차(남은 턴 2 이하) 또는 만족형이면서 판매자 가격 ≤ 목표가).
|
|
근거: 학습 데이터 구매자 턴의 수락 340건이 모두 이 조건에 해당한다.
|
|
"""
|
|
if ctx.is_first_turn or ctx.prev_seller_price is None or not ctx.private_prices:
|
|
return None, None
|
|
price = ctx.prev_seller_price
|
|
target, max_price = ctx.private_prices.get("target"), ctx.private_prices.get("max")
|
|
if ctx.card_name:
|
|
return "continue", f"이번 턴은 협상카드로 말하는 턴입니다. 판매자 직전 제시가 {price:,}원을 아직 수락하지 않습니다."
|
|
if ctx.min_end_turn is not None and ctx.turn is not None and ctx.turn < ctx.min_end_turn:
|
|
return "continue", f"아직 수락할 수 없는 턴입니다. 판매자 직전 제시가 {price:,}원에 대해 협상을 이어 갑니다."
|
|
satisfied = any("만족형" in line for line in ctx.private_lines)
|
|
last_round = ctx.remaining is not None and ctx.remaining <= 2
|
|
if max_price is not None and price <= max_price and (
|
|
last_round or (satisfied and target is not None and price <= target)):
|
|
return "accept", f"판매자 직전 제시가 {price:,}원을 수락합니다."
|
|
return "continue", f"판매자 직전 제시가 {price:,}원을 아직 수락하지 않고 협상을 이어 갑니다."
|
|
|
|
def _notes(self, ctx: NegotiationContext, selected: set) -> List[str]:
|
|
"""사실 크기 규칙 — 근거를 부풀리지 않도록 붙이는 주의 사항."""
|
|
p, notes = self.policy, []
|
|
if ctx.tenure_years is not None and ctx.tenure_years < p.short_tenure_years:
|
|
notes.append(p.notes.get("short_tenure", ""))
|
|
if ctx.alt_supplier_count == 0:
|
|
notes.append(p.notes.get("no_alt_supplier", ""))
|
|
if "K-suppliers" in selected:
|
|
notes.append(p.notes.get("suppliers_include_partner", ""))
|
|
if ctx.card_name not in p.private_terms_allowed_cards:
|
|
notes.append(p.notes.get("private_terms", ""))
|
|
return [n for n in notes if n]
|