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>
75 lines
3.5 KiB
Python
75 lines
3.5 KiB
Python
"""경험 예시 — 학습 데이터(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
|