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.
@@ -0,0 +1,65 @@
|
||||
"""테스트 공용 — 서버 루트를 import 경로에 넣고, 홀드아웃 문항과 같은 형식의 가짜 messages 를 준다.
|
||||
|
||||
테스트는 임시 설정 파일(GROUNDING_AGENT_CONFIG)로 기동해, 측정 증빙 폴더(2차년도_성능평가/data)에 기록을 남기지 않는다.
|
||||
"""
|
||||
|
||||
import atexit
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
_TEST_DIR = Path(tempfile.mkdtemp(prefix="grounding_agent_test_"))
|
||||
(_TEST_DIR / "config.toml").write_text(f"""
|
||||
[instrument]
|
||||
log_dir = "{_TEST_DIR / 'logs'}"
|
||||
generation_log = "{_TEST_DIR / 'generation_log.jsonl'}"
|
||||
response_time_log = "{_TEST_DIR / 'response_time.jsonl'}"
|
||||
""", encoding="utf-8")
|
||||
os.environ["GROUNDING_AGENT_CONFIG"] = str(_TEST_DIR / "config.toml")
|
||||
atexit.register(shutil.rmtree, _TEST_DIR, ignore_errors=True)
|
||||
|
||||
import pytest
|
||||
|
||||
SYSTEM = """당신은 구매자(MD) 협상 에이전트입니다. 판매자(협력사)와 단가 협상을 합니다.
|
||||
[공개 정보]
|
||||
- 상품: 도어벨 (화이트 · 테스트전자 / TD-100) / 협상구분: 재견적
|
||||
- 현 공급단가(기존공급가): 71,300원 (EA 기준)
|
||||
- 최근 1년 거래량: 130EA (거래액 9,269,000원)
|
||||
- 거래기간 2년, 현 대금지급조건: 입고 월의 익월 말 지급 (그룹사 기준)
|
||||
- 대체 공급사: 1곳
|
||||
- 단가 적용 기간: 이번 협상 단가를 약 1년간 유지
|
||||
- 경쟁 상황: 복수공급, 경쟁 강도 중간
|
||||
- 타 공급사 견적: 유사 품목 65,980원 수준
|
||||
- 해당 카테고리 공급 가능 업체: 약 2개 (귀사 포함)
|
||||
[비공개 기준] (상대에게 말하지 않음)
|
||||
- 하한선 65,980원, 목표가 68,730원, 최대 수용가 70,000원, 첫 제안가 66,000원
|
||||
- 성향: 극대화형 — 상대가 계속 양보하고 있다면 서두르지 말고 목표가보다 더 낮은 가격을 끝까지 노립니다.
|
||||
- 협상 5턴 전에는 수락하지 않습니다.
|
||||
[이번 턴 협상카드] 경쟁사 비교 전략: 타 공급사가 판매자 직전 제시가보다 4.1% 낮은 가격을 제안했다는 점을 들되, 신뢰 관계를 존중해 우선 협상하고 있다고 설명
|
||||
[이번 턴 행동 전략] 양보"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def turn5_messages():
|
||||
"""5턴 구매자 차례 — 경쟁사 비교 카드, 판매자 직전 68,800원, 구매자 직전 66,000원."""
|
||||
return [
|
||||
{"role": "system", "content": SYSTEM},
|
||||
{"role": "assistant", "content": "테스트전자 도어벨이 1년에 130EA 정도 나갑니다. 71,300원 기준으로 조정 여지가 있을까요?"},
|
||||
{"role": "user", "content": "[판매자] 유통 마진이 얇은 품목이지만 70,900원으로 내려 드리겠습니다."},
|
||||
{"role": "assistant", "content": "내부에서 정한 목표 가격이 66,000원입니다."},
|
||||
{"role": "user", "content": "[판매자] 66,000원은 매입가와 차이가 거의 없습니다. 68,800원까지는 가능합니다.\n"
|
||||
"[진행] 5/7턴, 이번 턴 포함 남은 턴 3"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def turn1_messages():
|
||||
system = SYSTEM.split("[이번 턴 협상카드]")[0] + "[이번 턴 행동 전략] 탐색"
|
||||
return [
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": "[진행] 협상을 시작하십시오. [진행] 1/7턴, 이번 턴 포함 남은 턴 7"},
|
||||
]
|
||||
@@ -0,0 +1,151 @@
|
||||
"""생성기 — 프로필별 입력 구성, 후처리, 그라운딩 로그 (가짜 LLM)."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from config.config_models import AppConfig, InstrumentConfig, ProfileConfig
|
||||
from services.generation.generator import Generator, UnknownProfileError
|
||||
from services.generation.llm_client import LLMResult
|
||||
from services.generation.postprocess import clean_utterance
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""받은 messages 를 기록하고 정해진 답을 돌려준다."""
|
||||
|
||||
def __init__(self, reply: str):
|
||||
self.reply = reply
|
||||
self.calls = []
|
||||
|
||||
def chat(self, messages, temperature, top_p, seed, max_tokens):
|
||||
self.calls.append({"messages": messages, "temperature": temperature, "top_p": top_p,
|
||||
"seed": seed, "max_tokens": max_tokens})
|
||||
return LLMResult(content=self.reply, finish_reason="stop", model="fake", prompt_tokens=10, completion_tokens=5,
|
||||
system_fingerprint="fp_test")
|
||||
|
||||
|
||||
def make_generator(tmp_path, reply="[구매자] 67,000원으로 올려 보겠습니다.\n[판매자] 감사합니다.", **baseline_opts):
|
||||
config = AppConfig(
|
||||
profiles={"baseline": ProfileConfig(grounding=False, **baseline_opts),
|
||||
"developed": ProfileConfig(grounding=True)},
|
||||
instrument=InstrumentConfig(generation_log=str(tmp_path / "gen.jsonl"), response_time_log=""),
|
||||
)
|
||||
clients = {"baseline": FakeClient(reply), "developed": FakeClient(reply)}
|
||||
return Generator(config, clients=clients), clients
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
("[구매자] 67,000원으로 하겠습니다.", "67,000원으로 하겠습니다."),
|
||||
("구매자: \"67,000원으로 하겠습니다.\"", "67,000원으로 하겠습니다."),
|
||||
("67,000원 드리겠습니다.\n[판매자] 네", "67,000원 드리겠습니다."),
|
||||
("첫 문장입니다.\n둘째 문장입니다.", "첫 문장입니다. 둘째 문장입니다."),
|
||||
("```\n확인했습니다.\n```", "확인했습니다."),
|
||||
])
|
||||
def test_clean_utterance(raw, expected):
|
||||
assert clean_utterance(raw) == expected
|
||||
|
||||
|
||||
def test_baseline_rules_plus_original(tmp_path, turn5_messages):
|
||||
"""베이스라인 = 같은 작성 규칙 + 원래 system 그대로 (지식 선택·판단 없음)."""
|
||||
gen, clients = make_generator(tmp_path)
|
||||
result = gen.generate("baseline", turn5_messages, seed=0, max_tokens=512)
|
||||
sent = clients["baseline"].calls[0]["messages"]
|
||||
assert sent[0]["content"].startswith(gen.builder.rules)
|
||||
assert sent[0]["content"].endswith(turn5_messages[0]["content"])
|
||||
assert "[이번 턴 판단]" not in sent[0]["content"]
|
||||
assert sent[1:] == turn5_messages[1:]
|
||||
assert result.content == "67,000원으로 올려 보겠습니다."
|
||||
assert result.trace.grounding is False and result.trace.used_knowledge == []
|
||||
|
||||
|
||||
def test_same_rules_both_profiles(tmp_path, turn5_messages):
|
||||
"""확인서: 프롬프트 골격 동일 — 두 프로필 system 이 같은 작성 규칙으로 시작한다."""
|
||||
gen, clients = make_generator(tmp_path)
|
||||
gen.generate("baseline", turn5_messages)
|
||||
gen.generate("developed", turn5_messages)
|
||||
rules = gen.builder.rules
|
||||
assert clients["baseline"].calls[0]["messages"][0]["content"].startswith(rules)
|
||||
assert clients["developed"].calls[0]["messages"][0]["content"].startswith(rules)
|
||||
|
||||
|
||||
def test_developed_accept_decision(tmp_path, turn5_messages):
|
||||
"""카드 없는 마지막 회차, 판매자 가격 ≤ 최대 수용가 → 수락 판단을 넣는다."""
|
||||
system = turn5_messages[0]["content"].split("[이번 턴 협상카드]")[0] + "[이번 턴 행동 전략] 양보"
|
||||
last_user = {"role": "user", "content": "[판매자] 오늘 확정해 주시면 67,400원까지 맞출 수 있습니다.\n"
|
||||
"[진행] 7/7턴, 이번 턴 포함 남은 턴 1"}
|
||||
messages = [{"role": "system", "content": system}] + turn5_messages[1:-1] + [
|
||||
{"role": "user", "content": "[판매자] 68,800원까지는 가능합니다."},
|
||||
{"role": "assistant", "content": "67,000원으로 맞춰 주시면 좋겠습니다."}, last_user]
|
||||
gen, clients = make_generator(tmp_path)
|
||||
result = gen.generate("developed", messages)
|
||||
assert result.trace.decision == "accept"
|
||||
assert "[이번 턴 판단] 판매자 직전 제시가 67,400원을 수락합니다." in clients["developed"].calls[0]["messages"][0]["content"]
|
||||
|
||||
|
||||
def test_developed_fallback_without_system(tmp_path):
|
||||
gen, clients = make_generator(tmp_path)
|
||||
messages = [{"role": "user", "content": "[판매자] 10,000원입니다."}]
|
||||
result = gen.generate("developed", messages)
|
||||
assert result.trace.rule == "fallback"
|
||||
sent = clients["developed"].calls[0]["messages"]
|
||||
assert sent[0] == {"role": "system", "content": gen.builder.rules} and sent[1:] == messages
|
||||
|
||||
|
||||
def test_baseline_strip_knowledge(tmp_path, turn5_messages):
|
||||
gen, clients = make_generator(tmp_path, strip_knowledge=True)
|
||||
gen.generate("baseline", turn5_messages)
|
||||
system = clients["baseline"].calls[0]["messages"][0]["content"]
|
||||
assert "타 공급사" not in system and "[이번 턴 협상카드]" not in system
|
||||
|
||||
|
||||
def test_developed_grounds_and_logs(tmp_path, turn5_messages):
|
||||
gen, clients = make_generator(tmp_path)
|
||||
result = gen.generate("developed", turn5_messages, temperature=0.0, top_p=1.0, seed=7, max_tokens=256)
|
||||
call = clients["developed"].calls[0]
|
||||
assert "[이번 턴 근거 지식]" in call["messages"][0]["content"]
|
||||
assert call["messages"][1:] == turn5_messages[1:]
|
||||
assert (call["temperature"], call["top_p"], call["seed"], call["max_tokens"]) == (0.0, 1.0, 7, 256)
|
||||
assert result.trace.rule == "card:경쟁사 비교 전략"
|
||||
assert result.trace.decision == "continue"
|
||||
assert "K-competitor" in result.trace.used_knowledge
|
||||
|
||||
rows = [json.loads(line) for line in (tmp_path / "gen.jsonl").read_text(encoding="utf-8").splitlines()]
|
||||
assert rows[-1]["profile"] == "developed"
|
||||
assert rows[-1]["candidate"] == "67,000원으로 올려 보겠습니다."
|
||||
assert rows[-1]["turn"] == 5
|
||||
assert rows[-1]["system_fingerprint"] == "fp_test"
|
||||
# 측정 문항과 잇는 입력 해시, 실제로 보낸 프롬프트, 디코딩 설정, 토큰·호출 시간
|
||||
assert rows[-1]["messages_sha256"] == gen.messages_sha256(turn5_messages)
|
||||
assert rows[-1]["prompt"] == call["messages"]
|
||||
assert rows[-1]["decoding"] == {"temperature": 0.0, "top_p": 1.0, "seed": 7, "max_tokens": 256}
|
||||
assert (rows[-1]["prompt_tokens"], rows[-1]["completion_tokens"]) == (10, 5)
|
||||
assert rows[-1]["llm_ms"] >= 0
|
||||
|
||||
|
||||
def test_unknown_profile(tmp_path, turn5_messages):
|
||||
gen, _ = make_generator(tmp_path)
|
||||
with pytest.raises(UnknownProfileError):
|
||||
gen.generate("gpt-4o", turn5_messages)
|
||||
|
||||
|
||||
def test_developed_price_and_examples(tmp_path, turn5_messages):
|
||||
"""price_advice·experience_examples 를 켜면 제시가 안내와 경험 예시가 system 에 들어가고 근거 로그에 남는다."""
|
||||
config = AppConfig(
|
||||
profiles={"baseline": ProfileConfig(grounding=False),
|
||||
"developed": ProfileConfig(grounding=True, price_advice=True, experience_examples=2)},
|
||||
instrument=InstrumentConfig(generation_log=str(tmp_path / "gen.jsonl"), response_time_log=""))
|
||||
clients = {"baseline": FakeClient("네."), "developed": FakeClient("네.")}
|
||||
gen = Generator(config, clients=clients)
|
||||
system = turn5_messages[0]["content"].split("[이번 턴 협상카드]")[0] + "[이번 턴 행동 전략] 양보"
|
||||
msgs = [{"role": "system", "content": system}] + turn5_messages[1:]
|
||||
result = gen.generate("developed", msgs)
|
||||
sent = clients["developed"].calls[0]["messages"][0]["content"]
|
||||
assert "이번 턴 제시가는 67,000원입니다" in sent
|
||||
assert "[비슷한 과거 발화]" in sent
|
||||
assert result.trace.offer == 67_000 and result.trace.offer_rule == "step" and len(result.trace.examples) == 2
|
||||
row = json.loads((tmp_path / "gen.jsonl").read_text(encoding="utf-8").splitlines()[-1])
|
||||
assert row["offer"] == 67_000 and row["examples"] == result.trace.examples
|
||||
# 베이스라인은 바뀌지 않는다
|
||||
gen.generate("baseline", msgs)
|
||||
base = clients["baseline"].calls[0]["messages"][0]["content"]
|
||||
assert "[비슷한 과거 발화]" not in base and "이번 턴 제시가" not in base
|
||||
@@ -0,0 +1,157 @@
|
||||
"""그라운딩 선택기·프롬프트 구성기."""
|
||||
|
||||
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) == []
|
||||
@@ -0,0 +1,49 @@
|
||||
"""messages 파서 — 지식 항목, 비공개 기준, 카드·전략, 진행, 직전 제시가."""
|
||||
|
||||
from services.grounding.parser import parse_messages
|
||||
|
||||
|
||||
def test_public_knowledge_ids(turn5_messages):
|
||||
ctx = parse_messages(turn5_messages)
|
||||
assert list(ctx.knowledge)[:11] == [
|
||||
"K-product", "K-list_price", "K-volume", "K-tenure", "K-payment", "K-alt_supplier",
|
||||
"K-validity", "K-competition", "K-competitor", "K-suppliers", "K-prev_seller",
|
||||
]
|
||||
assert ctx.knowledge["K-tenure"].content == "거래기간 2년"
|
||||
assert ctx.knowledge["K-payment"].content.startswith("현 대금지급조건: 입고 월의 익월 말")
|
||||
assert ctx.tenure_years == 2
|
||||
assert ctx.alt_supplier_count == 1
|
||||
assert ctx.unknown_lines == []
|
||||
|
||||
|
||||
def test_private_card_strategy_progress(turn5_messages):
|
||||
ctx = parse_messages(turn5_messages)
|
||||
assert ctx.private_prices == {"floor": 65980, "target": 68730, "max": 70000, "open": 66000}
|
||||
assert ctx.min_end_turn == 5
|
||||
assert ctx.card_name == "경쟁사 비교 전략"
|
||||
assert ctx.card_guide.startswith("타 공급사가 판매자 직전 제시가보다 4.1%")
|
||||
assert ctx.strategy == "양보"
|
||||
assert (ctx.turn, ctx.max_turns, ctx.remaining) == (5, 7, 3)
|
||||
|
||||
|
||||
def test_previous_offers_skip_quotes(turn5_messages):
|
||||
"""판매자 발화의 구매자 가격 인용(66,000원), 구매자 첫 턴의 현 단가 언급은 제시가가 아니다."""
|
||||
ctx = parse_messages(turn5_messages)
|
||||
assert ctx.prev_seller_price == 68800
|
||||
assert ctx.prev_buyer_price == 66000
|
||||
assert ctx.knowledge["K-prev_seller"].content == "판매자 직전 제시가 68,800원"
|
||||
|
||||
|
||||
def test_first_turn(turn1_messages):
|
||||
ctx = parse_messages(turn1_messages)
|
||||
assert ctx.is_first_turn
|
||||
assert ctx.card_name is None
|
||||
assert ctx.strategy == "탐색"
|
||||
assert (ctx.turn, ctx.max_turns, ctx.remaining) == (1, 7, 7)
|
||||
assert ctx.prev_seller_price is None and ctx.prev_buyer_price is None
|
||||
|
||||
|
||||
def test_without_system():
|
||||
ctx = parse_messages([{"role": "user", "content": "[판매자] 10,000원입니다."}])
|
||||
assert ctx.knowledge.keys() == {"K-prev_seller"}
|
||||
assert ctx.strategy is None
|
||||
@@ -0,0 +1,84 @@
|
||||
"""서버 스모크 테스트 — 기동, OpenAI 호환 응답 형식, 프로필 선택, 오류 코드 (가짜 LLM)."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from router.router import app
|
||||
from services.generation.llm_client import LLMError
|
||||
from tests.test_generation import FakeClient, make_generator
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_generator(tmp_path):
|
||||
original = app.state.generator
|
||||
gen, clients = make_generator(tmp_path, reply="다른 공급사 견적이 4.1% 낮게 와 있습니다. 67,000원으로 올려 보겠습니다.")
|
||||
app.state.generator = gen
|
||||
yield gen, clients
|
||||
app.state.generator = original
|
||||
|
||||
|
||||
def test_health():
|
||||
res = client.get("/health")
|
||||
assert res.status_code == 200
|
||||
assert res.json()["status"] == "OK"
|
||||
|
||||
|
||||
def test_tests_do_not_write_evidence_folder():
|
||||
"""테스트는 임시 설정으로 기동한다 — 측정 증빙 폴더(../logs/server)에 쓰지 않는다."""
|
||||
from config.config_loader import CONFIG_PATH
|
||||
assert "grounding_agent_test_" in str(CONFIG_PATH)
|
||||
assert "grounding_agent_test_" in client.get("/v1/config").json()["instrument"]["generation_log"]
|
||||
|
||||
|
||||
def test_models_and_config():
|
||||
ids = [m["id"] for m in client.get("/v1/models").json()["data"]]
|
||||
assert {"baseline", "developed"} <= set(ids)
|
||||
body = client.get("/v1/config").json()
|
||||
assert body["profiles"]["developed"]["grounding"] is True
|
||||
assert "api_key" not in str(body["profiles"]).replace("api_key_env", "")
|
||||
|
||||
|
||||
def test_chat_completions_openai_format(fake_generator, turn5_messages):
|
||||
"""Grounding_Eval generate 가 읽는 필드: choices[0].message.content, model, usage, finish_reason."""
|
||||
res = client.post("/v1/chat/completions", json={
|
||||
"model": "developed", "messages": turn5_messages,
|
||||
"temperature": 0, "top_p": 1.0, "seed": 0, "max_tokens": 512,
|
||||
})
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["object"] == "chat.completion"
|
||||
assert body["model"] == "developed"
|
||||
assert body["choices"][0]["message"] == {"role": "assistant",
|
||||
"content": "다른 공급사 견적이 4.1% 낮게 와 있습니다. 67,000원으로 올려 보겠습니다."}
|
||||
assert body["choices"][0]["finish_reason"] == "stop"
|
||||
assert body["usage"]["total_tokens"] == 15
|
||||
assert body["grounding"]["rule"] == "card:경쟁사 비교 전략"
|
||||
assert body["system_fingerprint"] == "fp_test"
|
||||
assert "X-Response-Time-Ms" in res.headers
|
||||
|
||||
|
||||
def test_baseline_profile(fake_generator, turn5_messages):
|
||||
_, clients = fake_generator
|
||||
res = client.post("/v1/chat/completions", json={"model": "baseline", "messages": turn5_messages})
|
||||
assert res.status_code == 200
|
||||
assert res.json()["grounding"]["grounding"] is False
|
||||
assert clients["baseline"].calls[0]["messages"][1:] == turn5_messages[1:]
|
||||
|
||||
|
||||
def test_unknown_profile_404(fake_generator, turn5_messages):
|
||||
res = client.post("/v1/chat/completions", json={"model": "gpt-4o", "messages": turn5_messages})
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
def test_llm_failure_502(fake_generator, turn5_messages):
|
||||
gen, clients = fake_generator
|
||||
|
||||
class Broken(FakeClient):
|
||||
def chat(self, *args, **kwargs):
|
||||
raise LLMError("연결 실패")
|
||||
|
||||
gen.clients["developed"] = Broken("")
|
||||
res = client.post("/v1/chat/completions", json={"model": "developed", "messages": turn5_messages})
|
||||
assert res.status_code == 502
|
||||
Reference in new issue
Block a user