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>
158 lines
7.8 KiB
Python
158 lines
7.8 KiB
Python
"""그라운딩 선택기·프롬프트 구성기."""
|
||
|
||
from services.grounding.parser import parse_messages
|
||
from services.grounding.prompt_builder import PromptBuilder, strip_knowledge
|
||
from services.grounding.selector import KnowledgeSelector
|
||
|
||
|
||
def test_select_card_turn(turn5_messages):
|
||
ctx = parse_messages(turn5_messages)
|
||
sel = KnowledgeSelector().select(ctx)
|
||
assert sel.rule == "card:경쟁사 비교 전략"
|
||
assert sel.ids == ["K-list_price", "K-competitor", "K-alt_supplier", "K-prev_seller", "K-tenure"]
|
||
# 거래기간 2년 → 장기 거래 금지 주의
|
||
assert any("3년 미만" in note for note in sel.notes)
|
||
|
||
|
||
def test_select_first_turn(turn1_messages):
|
||
sel = KnowledgeSelector().select(parse_messages(turn1_messages))
|
||
assert sel.rule == "first_turn"
|
||
assert sel.ids == ["K-list_price", "K-product", "K-volume"]
|
||
|
||
|
||
def test_select_without_card(turn5_messages):
|
||
system = turn5_messages[0]["content"].split("[이번 턴 협상카드]")[0] + "[이번 턴 행동 전략] 타협"
|
||
ctx = parse_messages([{"role": "system", "content": system}] + turn5_messages[1:])
|
||
sel = KnowledgeSelector().select(ctx)
|
||
assert sel.rule == "no_card"
|
||
assert sel.ids == ["K-list_price", "K-prev_seller", "K-prev_buyer"]
|
||
|
||
|
||
def test_suppliers_note(turn5_messages):
|
||
system = turn5_messages[0]["content"].replace(
|
||
"[이번 턴 협상카드] 경쟁사 비교 전략: 타 공급사가 판매자 직전 제시가보다 4.1% 낮은 가격을 제안했다는 점을 들되, 신뢰 관계를 존중해 우선 협상하고 있다고 설명",
|
||
"[이번 턴 협상카드] 대체 공급자의 언급: 유사 상품까지 고려하면 약 2개 업체가 관심을 보일 것으로 예상되지만 귀사와 우선 협상한다는 점을 알림")
|
||
sel = KnowledgeSelector().select(parse_messages([{"role": "system", "content": system}] + turn5_messages[1:]))
|
||
assert "K-suppliers" in sel.ids
|
||
assert any("상대 회사가 포함" in note for note in sel.notes)
|
||
|
||
|
||
def test_build_messages_keeps_history(turn5_messages):
|
||
ctx = parse_messages(turn5_messages)
|
||
sel = KnowledgeSelector().select(ctx)
|
||
msgs = PromptBuilder().build_messages(ctx, sel)
|
||
system = msgs[0]["content"]
|
||
assert "[이번 턴 근거 지식]" in system
|
||
assert "- 타 공급사 견적: 유사 품목 65,980원 수준" in system
|
||
assert "- 판매자 직전 제시가 68,800원" in system
|
||
assert "최근 1년 거래량" not in system # 고르지 않은 지식은 빠진다
|
||
assert "[이번 턴 행동 전략] 양보 — " in system
|
||
assert "[이번 턴 판단] 이번 턴은 협상카드로 말하는 턴입니다." in system
|
||
assert "하한선 65,980원" in system # 비공개 기준은 가격 판단용으로 유지
|
||
assert msgs[1:] == turn5_messages[1:]
|
||
|
||
|
||
def test_strip_knowledge(turn5_messages):
|
||
msgs = strip_knowledge(turn5_messages)
|
||
system = msgs[0]["content"]
|
||
assert "- 상품: 도어벨" in system and "- 현 공급단가" in system
|
||
assert "거래량" not in system and "타 공급사" not in system
|
||
assert "[이번 턴 협상카드]" not in system
|
||
assert "[이번 턴 행동 전략] 양보" in system
|
||
assert msgs[1:] == turn5_messages[1:]
|
||
|
||
|
||
# ---- 제시가 계산 보조 (pricing) ----
|
||
|
||
from services.grounding.pricing import price_unit, suggest_offer # noqa: E402
|
||
|
||
RATIO = {"양보": 0.36, "타협": 0.30}
|
||
|
||
|
||
def _with(messages, strategy, card=None, progress=None):
|
||
"""turn5 messages 의 행동 전략·카드·진행 줄을 바꾼 사본."""
|
||
system = messages[0]["content"].split("[이번 턴 협상카드]")[0]
|
||
system += (f"[이번 턴 협상카드] {card}\n" if card else "") + f"[이번 턴 행동 전략] {strategy}"
|
||
out = [{"role": "system", "content": system}] + [dict(m) for m in messages[1:]]
|
||
if progress:
|
||
out[-1]["content"] = out[-1]["content"].replace("[진행] 5/7턴, 이번 턴 포함 남은 턴 3", progress)
|
||
return out
|
||
|
||
|
||
def test_price_unit():
|
||
assert [price_unit(p) for p in (999, 9_999, 71_300, 1_200_000)] == [1, 10, 100, 1_000]
|
||
|
||
|
||
def test_offer_step(turn5_messages):
|
||
"""양보: 66,000 + 0.36 × (68,800 − 66,000) = 67,008 → 100원 단위 67,000원."""
|
||
advice = suggest_offer(parse_messages(_with(turn5_messages, "양보")), RATIO)
|
||
assert (advice.price, advice.rule) == (67_000, "step")
|
||
|
||
|
||
def test_offer_hold_on_assert(turn5_messages):
|
||
advice = suggest_offer(parse_messages(_with(turn5_messages, "주장")), RATIO)
|
||
assert (advice.price, advice.rule) == (66_000, "hold")
|
||
|
||
|
||
def test_offer_last_round_is_max(turn5_messages):
|
||
msgs = _with(turn5_messages, "양보", progress="[진행] 5/6턴, 이번 턴 포함 남은 턴 2")
|
||
advice = suggest_offer(parse_messages(msgs), RATIO)
|
||
assert (advice.price, advice.rule) == (70_000, "last_round")
|
||
|
||
|
||
def test_offer_wildcard_uses_guide(turn5_messages):
|
||
card = "양보 전략: 와일드카드: 판매자 투찰단가와 앵커링가의 중앙값인 67,400원으로 수정 제안하고, 이 범위에서 제안하면 빠르게 결정할 수 있다고 알림"
|
||
advice = suggest_offer(parse_messages(_with(turn5_messages, "양보", card=card)), RATIO)
|
||
assert (advice.price, advice.rule) == (67_400, "wildcard")
|
||
|
||
|
||
def test_offer_first_price_is_open(turn5_messages):
|
||
msgs = _with(turn5_messages[:3], "주장")
|
||
msgs[-1]["content"] += "\n[진행] 3/7턴, 이번 턴 포함 남은 턴 5"
|
||
advice = suggest_offer(parse_messages(msgs), RATIO)
|
||
assert (advice.price, advice.rule) == (66_000, "first_offer")
|
||
|
||
|
||
def test_select_offer_guide(turn5_messages):
|
||
sel = KnowledgeSelector().select(parse_messages(_with(turn5_messages, "타협")), price_advice=True)
|
||
assert sel.act == "offer" and sel.offer == 66_800 and sel.offer_rule == "step" # 66,000 + 0.30 × 2,800 = 66,840
|
||
assert any("66,800원" in g for g in sel.guides)
|
||
assert KnowledgeSelector().select(parse_messages(_with(turn5_messages, "타협"))).offer is None # 끄면 안내 없음
|
||
|
||
|
||
def test_first_turn_guide_and_private_note(turn1_messages, turn5_messages):
|
||
sel = KnowledgeSelector().select(parse_messages(turn1_messages), price_advice=True)
|
||
assert sel.act == "inform" and sel.offer is None
|
||
assert any("첫 발화" in g for g in sel.guides)
|
||
assert any("내부 기준 용어" in n for n in sel.notes)
|
||
card = "상호 이익 강조 전략: 장기 협력 시 안정적인 수요라는 상호 이익을 강조하며, 당사 목표 가격으로 66,000원을 제시"
|
||
sel = KnowledgeSelector().select(parse_messages(_with(turn5_messages, "주장", card=card)))
|
||
assert not any("내부 기준 용어" in n for n in sel.notes) # 목표 가격을 말해도 되는 카드
|
||
|
||
|
||
# ---- 경험 예시 (experience) ----
|
||
|
||
import json # noqa: E402
|
||
|
||
from common.paths import SERVER_ROOT # noqa: E402
|
||
from services.grounding.experience import EXAMPLES_PATH, ExperienceStore # noqa: E402
|
||
|
||
|
||
def test_experience_examples_train_only():
|
||
"""예시 파일에는 train 분할만 있고 홀드아웃 대화·숫자가 없다."""
|
||
holdout = set((SERVER_ROOT.parent / "data" / "holdout" / "대상_홀드아웃.txt").read_text(encoding="utf-8").split())
|
||
rows = [json.loads(line) for line in EXAMPLES_PATH.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||
assert rows
|
||
assert not {r["dialogue_id"].removeprefix("DLG-") for r in rows} & holdout
|
||
assert not any(ch.isdigit() for r in rows for ch in r["response"])
|
||
|
||
|
||
def test_experience_find_is_stable_and_distinct():
|
||
store = ExperienceStore()
|
||
args = ("no_card", "양보", "offer", 7, 3)
|
||
a = store.find(*args, key="abc", k=3)
|
||
assert a == store.find(*args, key="abc", k=3) # 같은 입력 → 같은 예시
|
||
assert len({e.dialogue_id for e in a}) == 3
|
||
assert all((e.situation, e.strategy, e.act) == ("no_card", "양보", "offer") for e in a)
|
||
assert store.find(*args, key="abc", k=0) == []
|