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.
Whitespace-only changes.
@@ -0,0 +1,150 @@
|
||||
"""프로필별 발화 생성 — 그라운딩 적용 여부만 다르고 입력·디코딩은 같다.
|
||||
|
||||
baseline : 작성 규칙 + messages 그대로 (strip_knowledge 면 지식을 뺀 사본) → LLM
|
||||
developed: messages → 파서 → 지식 선택·수락 판단·제시가(price_advice) → 경험 예시(experience_examples)
|
||||
→ 작성 규칙 + 프롬프트 재구성 → LLM
|
||||
입력을 해석하지 못하면(system 절이 없음) baseline 과 같은 방식으로 대신 처리한다 (rule = fallback)
|
||||
두 프로필 모두 후처리(postprocess)로 발화 하나만 남기고, 턴별 그라운딩 근거를 generation_log 에 남긴다.
|
||||
근거 로그 한 줄 = 요청 하나: 입력 해시(messages_sha256 — 측정 문항과 잇는 키), 적용 규칙·사용 지식, LLM 에 보낸 messages
|
||||
(instrument.log_prompt), 디코딩 설정, 토큰 수, LLM 호출 시간, 생성 발화(후처리 전·후).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from common.paths import resolve_data_path
|
||||
from config.config_models import AppConfig, ProfileConfig
|
||||
from services.generation.llm_client import LLMClient, LLMResult
|
||||
from services.generation.postprocess import clean_utterance
|
||||
from services.grounding.experience import ExperienceStore, situation_of
|
||||
from services.grounding.parser import parse_messages
|
||||
from services.grounding.prompt_builder import PromptBuilder, strip_knowledge
|
||||
from services.grounding.selector import GroundingPolicy, KnowledgeSelector
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
|
||||
class UnknownProfileError(KeyError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroundingTrace:
|
||||
profile: str
|
||||
grounding: bool
|
||||
rule: Optional[str] = None
|
||||
decision: Optional[str] = None
|
||||
offer: Optional[int] = None
|
||||
offer_rule: Optional[str] = None
|
||||
examples: List[str] = field(default_factory=list) # 붙인 경험 예시 sample_id (모두 train 분할)
|
||||
used_knowledge: List[str] = field(default_factory=list)
|
||||
notes: List[str] = field(default_factory=list)
|
||||
card: Optional[str] = None
|
||||
strategy: Optional[str] = None
|
||||
turn: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class GenerationResult:
|
||||
content: str
|
||||
raw_content: str
|
||||
llm: LLMResult
|
||||
trace: GroundingTrace
|
||||
|
||||
|
||||
class Generator:
|
||||
def __init__(self, config: AppConfig, clients: Optional[Dict[str, LLMClient]] = None):
|
||||
self.config = config
|
||||
self.profiles: Dict[str, ProfileConfig] = config.profiles
|
||||
# 테스트에서는 가짜 클라이언트를 주입한다
|
||||
self.clients = clients if clients is not None else {name: LLMClient(p) for name, p in self.profiles.items()}
|
||||
policy = GroundingPolicy()
|
||||
self.selector = KnowledgeSelector(policy)
|
||||
self.builder = PromptBuilder(policy)
|
||||
needs_examples = any(p.grounding and p.experience_examples > 0 for p in self.profiles.values())
|
||||
self.experience = ExperienceStore() if needs_examples else None
|
||||
log_path = config.instrument.generation_log
|
||||
self._log_path = resolve_data_path(log_path) if log_path else None
|
||||
if self._log_path is not None:
|
||||
self._log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def generate(self, profile_name: str, messages: List[dict], temperature: float = 0.0, top_p: float = 1.0,
|
||||
seed: Optional[int] = 0, max_tokens: Optional[int] = 512) -> GenerationResult:
|
||||
prompt, trace = self.build_prompt(profile_name, messages) # 없는 프로필이면 UnknownProfileError
|
||||
profile = self.profiles[profile_name]
|
||||
|
||||
started = time.perf_counter()
|
||||
llm = self.clients[profile_name].chat(prompt, temperature, top_p, seed, max_tokens)
|
||||
llm_ms = (time.perf_counter() - started) * 1000
|
||||
content = clean_utterance(llm.content) if profile.postprocess else llm.content
|
||||
result = GenerationResult(content=content, raw_content=llm.content, llm=llm, trace=trace)
|
||||
self._write_log(result, messages, prompt, profile,
|
||||
{"temperature": temperature, "top_p": top_p, "seed": seed, "max_tokens": max_tokens}, llm_ms)
|
||||
return result
|
||||
|
||||
def build_prompt(self, profile_name: str, messages: List[dict],
|
||||
exclude_dialogue: Optional[str] = None) -> Tuple[List[dict], GroundingTrace]:
|
||||
"""프로필의 LLM 입력(messages)과 그라운딩 근거를 만든다 — 생성과 미세조정 학습 파일이 같은 형식을 쓰도록 한곳에 둔다.
|
||||
exclude_dialogue: 경험 예시에서 뺄 대화 (학습 샘플이 자기 대화의 정답을 예시로 받지 않게)."""
|
||||
if profile_name not in self.profiles:
|
||||
raise UnknownProfileError(profile_name)
|
||||
profile = self.profiles[profile_name]
|
||||
ctx = parse_messages(messages)
|
||||
trace = GroundingTrace(profile=profile_name, grounding=profile.grounding, card=ctx.card_name,
|
||||
strategy=ctx.strategy, turn=ctx.turn)
|
||||
|
||||
parsed = ctx.strategy is not None and bool(ctx.private_lines)
|
||||
if profile.grounding and parsed:
|
||||
selection = self.selector.select(ctx, price_advice=profile.price_advice)
|
||||
examples = []
|
||||
if self.experience is not None and profile.experience_examples > 0:
|
||||
examples = self.experience.find(situation_of(ctx.is_first_turn, ctx.card_name), ctx.strategy,
|
||||
selection.act, ctx.turn, ctx.remaining,
|
||||
key=self.messages_sha256(messages), k=profile.experience_examples,
|
||||
exclude_dialogue=exclude_dialogue)
|
||||
prompt = self.builder.build_messages(ctx, selection, examples)
|
||||
trace.rule, trace.used_knowledge, trace.notes = selection.rule, selection.ids, selection.notes
|
||||
trace.decision, trace.offer, trace.offer_rule = selection.decision, selection.offer, selection.offer_rule
|
||||
trace.examples = [e.sample_id for e in examples]
|
||||
else:
|
||||
if profile.grounding:
|
||||
trace.rule = "fallback"
|
||||
logger.warning("[generator] 입력을 해석하지 못해 그라운딩 없이 처리합니다 (rule=fallback)")
|
||||
source = strip_knowledge(messages) if profile.strip_knowledge else messages
|
||||
prompt = [{"role": m["role"], "content": m.get("content") or ""} for m in source]
|
||||
if profile.writing_rules:
|
||||
prompt = self.builder.with_writing_rules(prompt)
|
||||
return prompt, trace
|
||||
|
||||
@staticmethod
|
||||
def messages_sha256(messages: List[dict]) -> str:
|
||||
"""입력 messages 의 해시 — 측정 도구의 문항(같은 messages)과 근거 로그를 잇는 키."""
|
||||
canonical = json.dumps([{"role": m.get("role"), "content": m.get("content") or ""} for m in messages],
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
def _write_log(self, result: GenerationResult, messages: List[dict], prompt: List[dict], profile: ProfileConfig,
|
||||
decoding: dict, llm_ms: float) -> None:
|
||||
if self._log_path is None:
|
||||
return
|
||||
row = {"ts": datetime.now(KST).isoformat(), "messages_sha256": self.messages_sha256(messages),
|
||||
**asdict(result.trace), "model": result.llm.model, "base_url": profile.base_url,
|
||||
"system_fingerprint": result.llm.system_fingerprint, "decoding": decoding,
|
||||
"prompt_tokens": result.llm.prompt_tokens, "completion_tokens": result.llm.completion_tokens,
|
||||
"llm_ms": round(llm_ms, 1),
|
||||
"candidate": result.content, "raw": result.raw_content if result.raw_content != result.content else None,
|
||||
"finish_reason": result.llm.finish_reason}
|
||||
if self.config.instrument.log_prompt:
|
||||
row["prompt"] = prompt
|
||||
try:
|
||||
with open(self._log_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
except OSError as e:
|
||||
logger.error(f"[generator] 그라운딩 로그 기록 실패: {e}")
|
||||
@@ -0,0 +1,60 @@
|
||||
"""OpenAI 호환 Chat Completions 호출 — OpenAI API, vLLM 등은 base_url 만 바꿔 쓴다."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
from openai import OpenAI, OpenAIError
|
||||
|
||||
from config.config_models import ProfileConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NO_KEY = "EMPTY" # 키가 필요 없는 로컬 서버용 자리값 (openai SDK 는 빈 키를 허용하지 않음)
|
||||
|
||||
|
||||
class LLMError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class LLMResult:
|
||||
content: str
|
||||
finish_reason: Optional[str]
|
||||
model: str
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
system_fingerprint: Optional[str] = None # OpenAI 서버 구성 식별자 — 같은 seed 에서 결과가 달라질 때 설명 근거
|
||||
|
||||
|
||||
class LLMClient:
|
||||
def __init__(self, profile: ProfileConfig):
|
||||
self.profile = profile
|
||||
api_key = os.getenv(profile.api_key_env, "") if profile.api_key_env else ""
|
||||
if profile.api_key_env and not api_key:
|
||||
logger.warning(f"[LLMClient] 환경변수 {profile.api_key_env} 가 비어 있습니다 — 호출 시 인증 오류가 날 수 있습니다")
|
||||
self.client = OpenAI(base_url=profile.base_url, api_key=api_key or NO_KEY,
|
||||
timeout=profile.timeout, max_retries=0)
|
||||
|
||||
def chat(self, messages: List[dict], temperature: float, top_p: float,
|
||||
seed: Optional[int], max_tokens: Optional[int]) -> LLMResult:
|
||||
kwargs = {"model": self.profile.model, "messages": messages, "temperature": temperature, "top_p": top_p}
|
||||
if seed is not None:
|
||||
kwargs["seed"] = seed
|
||||
if max_tokens is not None:
|
||||
kwargs["max_tokens"] = max_tokens
|
||||
try:
|
||||
response = self.client.chat.completions.create(**kwargs)
|
||||
except OpenAIError as e:
|
||||
raise LLMError(f"{self.profile.model} 호출 실패: {e}") from e
|
||||
choice = response.choices[0]
|
||||
usage = response.usage
|
||||
return LLMResult(
|
||||
content=choice.message.content or "",
|
||||
finish_reason=choice.finish_reason,
|
||||
model=response.model or self.profile.model,
|
||||
prompt_tokens=usage.prompt_tokens if usage else 0,
|
||||
completion_tokens=usage.completion_tokens if usage else 0,
|
||||
system_fingerprint=getattr(response, "system_fingerprint", None),
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""생성 결과 정리 — 구매자 발화 하나만 남긴다.
|
||||
|
||||
ROUGE 는 표면 어휘를 비교하므로 화자 표시·따옴표·코드펜스·이어 쓴 판매자 발화가 섞이면 점수가 떨어진다.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
ROLE_PREFIX_RE = re.compile(r"^\s*(?:\[\s*(?:구매자|MD|바이어)\s*\]|(?:구매자|MD|바이어)\s*[::])\s*")
|
||||
CUT_MARKERS = ("[판매자]", "판매자:", "판매자 :", "[진행]")
|
||||
QUOTE_PAIRS = (('"', '"'), ("“", "”"), ("'", "'"), ("‘", "’"))
|
||||
|
||||
|
||||
def clean_utterance(text: str) -> str:
|
||||
text = (text or "").strip()
|
||||
if text.startswith("```"):
|
||||
text = text.strip("`").strip()
|
||||
for marker in CUT_MARKERS:
|
||||
idx = text.find(marker)
|
||||
if idx > 0:
|
||||
text = text[:idx]
|
||||
elif idx == 0:
|
||||
text = ""
|
||||
text = ROLE_PREFIX_RE.sub("", text.strip())
|
||||
text = " ".join(line.strip() for line in text.splitlines() if line.strip())
|
||||
for left, right in QUOTE_PAIRS:
|
||||
if len(text) >= 2 and text.startswith(left) and text.endswith(right):
|
||||
text = text[1:-1].strip()
|
||||
return text
|
||||
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