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>
83 lines
4.4 KiB
Python
83 lines
4.4 KiB
Python
"""생성용 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:])
|