chore: 2차년도 성능평가 측정 구성 초기 업로드
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>
This commit is contained in:
commit
13ab9dee84
70 files changed
+17141
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,74 @@
|
||||
"""경험 예시 — 학습 데이터(train)의 비슷한 과거 구매자 턴 발화를 찾아 프롬프트에 붙인다 (확인서: 경험학습·장기기억).
|
||||
|
||||
예시 원천은 resources/grounding/experience_examples.jsonl 이고 tools/build_experience.py 로 만든다.
|
||||
- train 분할만 쓰고 홀드아웃 대화는 넣지 않는다 (만들 때 검사).
|
||||
- 예시 발화의 숫자는 ○ 로 가려 두어 다른 대화의 금액·비율을 옮겨 쓰지 않게 한다.
|
||||
비슷함의 기준: 같은 상황(첫 턴 / 같은 협상카드 / 카드 없음) → 같은 행동 전략 → 같은 행위(제시·수락·질문)
|
||||
순으로 맞추고, 남은 턴·턴 번호가 가까운 것을 고른다. 같은 조건이면 입력에 고정된 순서로 고르므로 같은 입력은 같은 예시를 받는다.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EXAMPLES_PATH = RESOURCES_DIR / "grounding" / "experience_examples.jsonl"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Example:
|
||||
sample_id: str
|
||||
dialogue_id: str
|
||||
situation: str # first_turn / card:<이름> / no_card
|
||||
strategy: str
|
||||
act: str # offer / accept / inform
|
||||
turn: int
|
||||
remaining: int
|
||||
response: str # 숫자를 가린 정답 발화
|
||||
|
||||
|
||||
def situation_of(is_first_turn: bool, card_name: Optional[str]) -> str:
|
||||
if is_first_turn:
|
||||
return "first_turn"
|
||||
return f"card:{card_name}" if card_name else "no_card"
|
||||
|
||||
|
||||
class ExperienceStore:
|
||||
def __init__(self, json_file_path: Optional[Path] = None):
|
||||
path = Path(json_file_path) if json_file_path else EXAMPLES_PATH
|
||||
self.examples: List[Example] = []
|
||||
if not path.exists():
|
||||
logger.warning(f"[experience] 예시 파일이 없습니다: {path} (tools/build_experience.py 로 만든다)")
|
||||
return
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
self.examples = [Example(**json.loads(line)) for line in f if line.strip()]
|
||||
|
||||
def find(self, situation: str, strategy: Optional[str], act: str, turn: Optional[int],
|
||||
remaining: Optional[int], key: str, k: int, exclude_dialogue: Optional[str] = None) -> List[Example]:
|
||||
"""조건을 넓혀 가며 k 개(서로 다른 대화)를 고른다. key: 같은 입력에 같은 순서를 주는 고정 문자열.
|
||||
exclude_dialogue: 이 대화의 예시는 고르지 않는다 (미세조정 학습 샘플의 정답이 자기 입력에 새지 않게)."""
|
||||
if k <= 0 or not self.examples:
|
||||
return []
|
||||
filters = [
|
||||
lambda e: e.situation == situation and e.strategy == strategy and e.act == act,
|
||||
lambda e: e.situation == situation and e.strategy == strategy,
|
||||
lambda e: e.situation == situation,
|
||||
]
|
||||
chosen, dialogues = [], {exclude_dialogue} if exclude_dialogue else set()
|
||||
for keep in filters:
|
||||
pool = sorted((e for e in self.examples if keep(e) and e.dialogue_id not in dialogues),
|
||||
key=lambda e: (abs(e.remaining - (remaining or 0)), abs(e.turn - (turn or 0)),
|
||||
hashlib.sha256(f"{key}|{e.sample_id}".encode("utf-8")).hexdigest()))
|
||||
for e in pool:
|
||||
if len(chosen) >= k:
|
||||
return chosen
|
||||
if e.dialogue_id not in dialogues:
|
||||
dialogues.add(e.dialogue_id)
|
||||
chosen.append(e)
|
||||
return chosen
|
||||
@@ -0,0 +1,189 @@
|
||||
"""대화 messages 파서 — system 메시지를 지식 항목으로, 히스토리를 직전 제시가·진행 정보로 나눈다.
|
||||
|
||||
입력은 홀드아웃 문항의 messages(OpenAI 형식)이다.
|
||||
- system: 역할 문장 + [공개 정보] + [비공개 기준] + [이번 턴 협상카드](선택) + [이번 턴 행동 전략]
|
||||
- assistant: 구매자(자기) 이전 발화, user: "[판매자] …" 판매자 발화
|
||||
- 마지막 user 메시지 끝: "[진행] t/N턴, 이번 턴 포함 남은 턴 k"
|
||||
지식 id·유형은 지시순응_변환.py 의 knowledge 체계(K-product, K-volume, …)와 같다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from common.enums import KnowledgeType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SECTION_RE = re.compile(r"^\[([^\]]+)\]\s*(.*)$")
|
||||
PROGRESS_RE = re.compile(r"\[진행\]\s*(\d+)\s*/\s*(\d+)\s*턴,\s*이번 턴 포함 남은 턴\s*(\d+)")
|
||||
PRICE_RE = re.compile(r"(\d[\d,]*)\s*원")
|
||||
SELLER_PREFIX = "[판매자]"
|
||||
|
||||
# 공개 정보 줄의 머리말 → (지식 id, 유형). 위에서부터 먼저 맞는 것을 쓴다.
|
||||
PUBLIC_FIELDS = [
|
||||
("상품", "K-product", KnowledgeType.PRODUCT_FEATURE),
|
||||
("현 공급단가", "K-list_price", KnowledgeType.PRICE_INFO),
|
||||
("최근 1년 거래량", "K-volume", KnowledgeType.SCENARIO_VARIABLE),
|
||||
("대체 공급사", "K-alt_supplier", KnowledgeType.SCENARIO_VARIABLE),
|
||||
("단가 적용 기간", "K-validity", KnowledgeType.SCENARIO_VARIABLE),
|
||||
("경쟁 상황", "K-competition", KnowledgeType.SCENARIO_VARIABLE),
|
||||
("타 공급사 견적", "K-competitor", KnowledgeType.CARD_FACT),
|
||||
("해당 카테고리 공급 가능 업체", "K-suppliers", KnowledgeType.CARD_FACT),
|
||||
("시장 근거", "K-market", KnowledgeType.KTC_VARIABLE),
|
||||
("B2C 유통 매입가", "K-b2c", KnowledgeType.CARD_FACT),
|
||||
]
|
||||
TENURE_PAYMENT_RE = re.compile(r"^거래기간\s*(\d+)\s*년,\s*현 대금지급조건:\s*(.+)$")
|
||||
PRIVATE_PRICES_RE = re.compile(
|
||||
r"하한선\s*([\d,]+)원,\s*목표가\s*([\d,]+)원,\s*최대 수용가\s*([\d,]+)원,\s*첫 제안가\s*([\d,]+)원")
|
||||
MIN_END_RE = re.compile(r"협상\s*(\d+)턴 전에는 수락하지 않습니다")
|
||||
|
||||
|
||||
@dataclass
|
||||
class KnowledgeItem:
|
||||
id: str
|
||||
type: KnowledgeType
|
||||
content: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class NegotiationContext:
|
||||
role_line: str = ""
|
||||
knowledge: Dict[str, KnowledgeItem] = field(default_factory=dict) # 공개 지식 (순서 유지)
|
||||
private_lines: List[str] = field(default_factory=list) # [비공개 기준] 원문 줄
|
||||
private_prices: Dict[str, int] = field(default_factory=dict) # floor·target·max·open
|
||||
min_end_turn: Optional[int] = None
|
||||
card_name: Optional[str] = None
|
||||
card_guide: Optional[str] = None
|
||||
strategy: Optional[str] = None
|
||||
turn: Optional[int] = None
|
||||
max_turns: Optional[int] = None
|
||||
remaining: Optional[int] = None
|
||||
history: List[dict] = field(default_factory=list) # system 다음 메시지들 (원문)
|
||||
prev_seller_price: Optional[int] = None
|
||||
prev_buyer_price: Optional[int] = None
|
||||
list_price: Optional[int] = None # 현 공급단가 (제시 단위 계산용)
|
||||
tenure_years: Optional[int] = None
|
||||
alt_supplier_count: Optional[int] = None
|
||||
unknown_lines: List[str] = field(default_factory=list) # 해석하지 못한 줄 (로그용)
|
||||
|
||||
@property
|
||||
def is_first_turn(self) -> bool:
|
||||
return not any(m.get("role") == "assistant" for m in self.history)
|
||||
|
||||
|
||||
def _to_int(text: str) -> int:
|
||||
return int(text.replace(",", ""))
|
||||
|
||||
|
||||
def _last_price(text: str, exclude: tuple = ()) -> Optional[int]:
|
||||
"""발화에서 마지막으로 언급한 금액 — 제시가는 보통 문장 끝쪽에 온다.
|
||||
exclude: 제시가가 아닌 인용 금액(상대 직전 제시가, 현 공급단가)."""
|
||||
found = [_to_int(p) for p in PRICE_RE.findall(text or "")]
|
||||
found = [p for p in found if p not in exclude]
|
||||
return found[-1] if found else None
|
||||
|
||||
|
||||
def _add(ctx: NegotiationContext, kid: str, ktype: KnowledgeType, content: str) -> None:
|
||||
ctx.knowledge[kid] = KnowledgeItem(kid, ktype, content)
|
||||
|
||||
|
||||
def _parse_public_line(ctx: NegotiationContext, line: str) -> None:
|
||||
body = line[1:].strip() if line.startswith("-") else line.strip()
|
||||
m = TENURE_PAYMENT_RE.match(body)
|
||||
if m:
|
||||
ctx.tenure_years = int(m.group(1))
|
||||
_add(ctx, "K-tenure", KnowledgeType.SCENARIO_VARIABLE, f"거래기간 {m.group(1)}년")
|
||||
_add(ctx, "K-payment", KnowledgeType.SCENARIO_VARIABLE, f"현 대금지급조건: {m.group(2).strip()}")
|
||||
return
|
||||
for head, kid, ktype in PUBLIC_FIELDS:
|
||||
if body.startswith(head):
|
||||
_add(ctx, kid, ktype, body)
|
||||
if kid == "K-list_price":
|
||||
price = PRICE_RE.search(body)
|
||||
ctx.list_price = _to_int(price.group(1)) if price else None
|
||||
if kid == "K-alt_supplier":
|
||||
count = re.search(r"(\d+)\s*곳", body)
|
||||
ctx.alt_supplier_count = int(count.group(1)) if count else None
|
||||
return
|
||||
ctx.unknown_lines.append(line)
|
||||
|
||||
|
||||
def _parse_system(ctx: NegotiationContext, system: str) -> None:
|
||||
section = None
|
||||
lines = system.split("\n")
|
||||
ctx.role_line = lines[0].strip() if lines else ""
|
||||
for line in lines[1:]:
|
||||
if not line.strip():
|
||||
continue
|
||||
m = SECTION_RE.match(line)
|
||||
if m:
|
||||
section, rest = m.group(1), m.group(2).strip()
|
||||
if section == "이번 턴 협상카드" and rest:
|
||||
name, _, guide = rest.partition(":")
|
||||
ctx.card_name, ctx.card_guide = name.strip(), guide.strip()
|
||||
elif section == "이번 턴 행동 전략" and rest:
|
||||
ctx.strategy = rest
|
||||
continue
|
||||
if section == "공개 정보":
|
||||
_parse_public_line(ctx, line)
|
||||
elif section == "비공개 기준":
|
||||
ctx.private_lines.append(line.strip())
|
||||
prices = PRIVATE_PRICES_RE.search(line)
|
||||
if prices:
|
||||
ctx.private_prices = dict(zip(("floor", "target", "max", "open"), map(_to_int, prices.groups())))
|
||||
min_end = MIN_END_RE.search(line)
|
||||
if min_end:
|
||||
ctx.min_end_turn = int(min_end.group(1))
|
||||
else:
|
||||
ctx.unknown_lines.append(line)
|
||||
|
||||
|
||||
def _public_amounts(ctx: NegotiationContext) -> tuple:
|
||||
"""현 공급단가·거래액 — 인용일 뿐 제시가가 아니다.
|
||||
타사 견적은 앵커링가 수준이라 구매자가 같은 금액을 제시할 수 있어 빼지 않는다."""
|
||||
items = [ctx.knowledge[k] for k in ("K-list_price", "K-volume") if k in ctx.knowledge]
|
||||
return tuple(_to_int(p) for item in items for p in PRICE_RE.findall(item.content))
|
||||
|
||||
|
||||
def _parse_history(ctx: NegotiationContext, history: List[dict]) -> None:
|
||||
ctx.history = history
|
||||
public = _public_amounts(ctx)
|
||||
buyer_turns = 0
|
||||
for msg in history:
|
||||
content = msg.get("content") or ""
|
||||
if msg.get("role") == "assistant":
|
||||
buyer_turns += 1
|
||||
if buyer_turns == 1:
|
||||
continue # 구매자 첫 발화는 탐색(가격 제시 없음) — §4-B 탐색 판정 규칙
|
||||
# 공개 정보 금액 인용("○○원 기준으로 …")과 판매자 가격 인용은 구매자 제시가가 아니다
|
||||
price = _last_price(content, exclude=public + (ctx.prev_seller_price,))
|
||||
ctx.prev_buyer_price = price if price is not None else ctx.prev_buyer_price
|
||||
elif msg.get("role") == "user":
|
||||
utterance = content.split("[진행]")[0]
|
||||
if utterance.strip().startswith(SELLER_PREFIX):
|
||||
price = _last_price(utterance, exclude=(ctx.prev_buyer_price,))
|
||||
ctx.prev_seller_price = price if price is not None else ctx.prev_seller_price
|
||||
last_user = next((m for m in reversed(history) if m.get("role") == "user"), None)
|
||||
if last_user:
|
||||
found = PROGRESS_RE.findall(last_user.get("content") or "")
|
||||
if found:
|
||||
ctx.turn, ctx.max_turns, ctx.remaining = map(int, found[-1])
|
||||
|
||||
|
||||
def parse_messages(messages: List[dict]) -> NegotiationContext:
|
||||
"""messages → NegotiationContext. system 이 없으면 히스토리만 채운다."""
|
||||
ctx = NegotiationContext()
|
||||
if messages and messages[0].get("role") == "system":
|
||||
_parse_system(ctx, messages[0].get("content") or "")
|
||||
_parse_history(ctx, messages[1:])
|
||||
else:
|
||||
_parse_history(ctx, messages)
|
||||
if ctx.prev_seller_price is not None:
|
||||
_add(ctx, "K-prev_seller", KnowledgeType.PREVIOUS_TURN, f"판매자 직전 제시가 {ctx.prev_seller_price:,}원")
|
||||
if ctx.prev_buyer_price is not None:
|
||||
_add(ctx, "K-prev_buyer", KnowledgeType.PREVIOUS_TURN, f"구매자 직전 제시가 {ctx.prev_buyer_price:,}원")
|
||||
if ctx.unknown_lines:
|
||||
logger.warning(f"[parser] 해석하지 못한 줄 {len(ctx.unknown_lines)}개: {ctx.unknown_lines[:3]}")
|
||||
return ctx
|
||||
@@ -0,0 +1,64 @@
|
||||
"""이번 턴 제시가 계산 보조 — 구매자 자신의 비공개 기준과 히스토리로 이번 턴에 낼 가격을 정한다.
|
||||
|
||||
규칙은 학습 데이터(train) 구매자 제시 턴에서 확인한 것이다 (홀드아웃은 확인에만 씀).
|
||||
- 와일드카드(1% 추가네고·재원부족·양보 전략): 카드 안내의 금액 그대로
|
||||
- 구매자의 마지막 회차(남은 턴 2 이하)에서 수락하지 않으면: 최대 수용가 (77/77)
|
||||
- 아직 가격을 낸 적이 없으면: 첫 제안가 (261/261)
|
||||
- 주장: 직전 가격 유지 (88/88)
|
||||
- 양보·타협: 직전 가격에서 판매자 직전 제시가 쪽으로 간격의 일정 비율만큼 (비율은 grounding_policy.json 의 pricing)
|
||||
제시 단위는 시뮬레이터와 같다: 현 단가 1천원 미만 1원, 1만원 미만 10원, 100만원 미만 100원, 그 이상 1,000원.
|
||||
"""
|
||||
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Optional
|
||||
|
||||
from services.grounding.parser import NegotiationContext
|
||||
|
||||
PRICE_UNITS = ((1_000, 1), (10_000, 10), (1_000_000, 100), (math.inf, 1_000))
|
||||
GUIDE_PRICE_RE = re.compile(r"(\d[\d,]*)원")
|
||||
WILDCARDS = ("1% 추가네고", "재원부족", "양보 전략")
|
||||
|
||||
|
||||
@dataclass
|
||||
class OfferAdvice:
|
||||
price: int
|
||||
rule: str # 로그용 (wildcard / last_round / first_offer / hold / step)
|
||||
|
||||
|
||||
def price_unit(list_price: Optional[int]) -> int:
|
||||
if not list_price:
|
||||
return 1
|
||||
return next(unit for bound, unit in PRICE_UNITS if list_price < bound)
|
||||
|
||||
|
||||
def round_price(value: float, unit: int) -> int:
|
||||
"""단위 가격으로 반올림 (.5 는 올림) — 시뮬레이터 round_price 와 같다."""
|
||||
return int(math.floor(round(value / unit, 6) + 0.5) * unit)
|
||||
|
||||
|
||||
def suggest_offer(ctx: NegotiationContext, step_ratio: Dict[str, float]) -> Optional[OfferAdvice]:
|
||||
"""이번 턴 제시가. 탐색 턴·첫 턴·수락 턴은 호출하지 않는다 (None 이면 제시가 안내 없음)."""
|
||||
prices = ctx.private_prices
|
||||
if not prices:
|
||||
return None
|
||||
if ctx.card_name in WILDCARDS:
|
||||
found = GUIDE_PRICE_RE.search(ctx.card_guide or "")
|
||||
return OfferAdvice(int(found.group(1).replace(",", "")), "wildcard") if found else None
|
||||
own, seller = ctx.prev_buyer_price, ctx.prev_seller_price
|
||||
if ctx.remaining is not None and ctx.remaining <= 2 and seller is not None:
|
||||
return OfferAdvice(max(prices["max"], own or 0), "last_round")
|
||||
if own is None:
|
||||
return OfferAdvice(prices["open"], "first_offer")
|
||||
ratio = step_ratio.get(ctx.strategy or "")
|
||||
if ratio is None or seller is None or seller <= own:
|
||||
return OfferAdvice(own, "hold")
|
||||
unit = price_unit(ctx.list_price)
|
||||
upper = min(seller, prices["max"])
|
||||
while unit > 1 and round_price(own + ratio * (seller - own), unit) <= own:
|
||||
unit //= 10 # 간격이 단위보다 좁으면 더 작은 단위로 (시뮬레이터 규칙)
|
||||
offer = round_price(own + ratio * (seller - own), unit)
|
||||
if offer <= own or offer > upper:
|
||||
offer = max(own, min(offer, upper))
|
||||
return OfferAdvice(offer, "step")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""생성용 messages 구성.
|
||||
|
||||
- 작성 규칙(resources/prompts/writing_rules.txt)은 두 프로필에 똑같이 붙인다 (확인서: 프롬프트 골격 동일).
|
||||
- baseline: 작성 규칙 + 원래 system 그대로 (with_writing_rules).
|
||||
- developed: 작성 규칙 + 그라운딩 선택 결과 (이번 턴 근거 지식 + 주의 + 비공개 기준 + 카드 + 행동 전략 + 이번 턴 판단
|
||||
+ 비슷한 과거 발화(경험 예시, 선택)).
|
||||
대화 히스토리(assistant/user)와 마지막 user 의 [진행] 줄은 원문 그대로 둔다.
|
||||
- strip_knowledge: 대안 베이스라인 — system 의 [공개 정보]를 상품·현 공급단가만 남기고 [이번 턴 협상카드] 절을 뺀다.
|
||||
미세조정 학습 입력도 이 모듈로 만들어야 학습·추론 형식이 같아진다.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Sequence
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
from services.grounding.experience import Example
|
||||
from services.grounding.parser import SECTION_RE, NegotiationContext
|
||||
from services.grounding.selector import GroundingPolicy, GroundingSelection
|
||||
|
||||
WRITING_RULES_PATH = RESOURCES_DIR / "prompts" / "writing_rules.txt"
|
||||
GROUNDED_INTRO = "아래 [이번 턴 근거 지식]에 있는 사실만 근거로 씁니다."
|
||||
STRIP_KEEP_PUBLIC = ("- 상품", "- 현 공급단가")
|
||||
STRIP_DROP_SECTIONS = ("이번 턴 협상카드",)
|
||||
|
||||
|
||||
class PromptBuilder:
|
||||
def __init__(self, policy: Optional[GroundingPolicy] = None, rules_path: Optional[Path] = None):
|
||||
self.policy = policy or GroundingPolicy()
|
||||
path = Path(rules_path) if rules_path else WRITING_RULES_PATH
|
||||
self.rules = path.read_text(encoding="utf-8").strip()
|
||||
|
||||
def with_writing_rules(self, messages: List[dict]) -> List[dict]:
|
||||
"""베이스라인 입력 — 원래 system 앞에 같은 작성 규칙만 붙인다."""
|
||||
if not messages or messages[0].get("role") != "system":
|
||||
return [{"role": "system", "content": self.rules}] + list(messages)
|
||||
return [{"role": "system", "content": f"{self.rules}\n\n{messages[0].get('content') or ''}"}] + list(messages[1:])
|
||||
|
||||
def build_system(self, ctx: NegotiationContext, selection: GroundingSelection,
|
||||
examples: Sequence[Example] = ()) -> str:
|
||||
lines = [self.rules, "", GROUNDED_INTRO, "[이번 턴 근거 지식]"]
|
||||
lines += [f"- {item.content}" for item in selection.items] or ["- (없음)"]
|
||||
if selection.notes:
|
||||
lines += ["[주의]"] + [f"- {note}" for note in selection.notes]
|
||||
if ctx.private_lines:
|
||||
lines += ["[비공개 기준] (상대에게 말하지 않음)"] + ctx.private_lines
|
||||
if ctx.card_name:
|
||||
lines.append(f"[이번 턴 협상카드] {ctx.card_name}: {ctx.card_guide}")
|
||||
if ctx.strategy:
|
||||
guide = self.policy.strategy_guide.get(ctx.strategy, "")
|
||||
lines.append(f"[이번 턴 행동 전략] {ctx.strategy}" + (f" — {guide}" if guide else ""))
|
||||
judgement = " ".join(t for t in [selection.decision_text] + selection.guides if t)
|
||||
if judgement:
|
||||
lines.append(f"[이번 턴 판단] {judgement}")
|
||||
if examples:
|
||||
lines.append(self.policy.experience_intro or "[비슷한 과거 발화]")
|
||||
lines += [f"- {e.response}" for e in examples]
|
||||
return "\n".join(lines)
|
||||
|
||||
def build_messages(self, ctx: NegotiationContext, selection: GroundingSelection,
|
||||
examples: Sequence[Example] = ()) -> List[dict]:
|
||||
return [{"role": "system", "content": self.build_system(ctx, selection, examples)}] + [
|
||||
{"role": m["role"], "content": m.get("content") or ""} for m in ctx.history]
|
||||
|
||||
|
||||
def strip_knowledge(messages: List[dict]) -> List[dict]:
|
||||
"""대안 베이스라인 입력 — 그라운딩 지식을 뺀 messages 사본."""
|
||||
if not messages or messages[0].get("role") != "system":
|
||||
return list(messages)
|
||||
out, section = [], None
|
||||
for line in (messages[0].get("content") or "").split("\n"):
|
||||
m = SECTION_RE.match(line)
|
||||
if m:
|
||||
section = m.group(1)
|
||||
if section not in STRIP_DROP_SECTIONS:
|
||||
out.append(line)
|
||||
continue
|
||||
if section in STRIP_DROP_SECTIONS:
|
||||
continue
|
||||
if section == "공개 정보" and not line.startswith(STRIP_KEEP_PUBLIC):
|
||||
continue
|
||||
out.append(line)
|
||||
return [{"role": "system", "content": "\n".join(out)}] + list(messages[1:])
|
||||
@@ -0,0 +1,133 @@
|
||||
"""턴별 지식 선택 — 이번 턴 상황(첫 턴·협상카드·행동전략)에 맞는 지식 항목과 주의 사항을 고른다.
|
||||
|
||||
규칙은 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]
|
||||
Reference in new issue
Block a user