Files
University_Labs_Nego_Agent/server/services/grounding/parser.py
T
민헌andClaude Opus 5.5 13ab9dee84 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>
2026-10-21 14:05:48 +09:00

190 lines
8.8 KiB
Python

"""대화 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