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
@@ -0,0 +1,100 @@
|
||||
# GROUNDING_AGENT 서버
|
||||
|
||||
2차년도 공인시험 「대화 상황 지식 그라운딩 적절성 개선율 (ROUGE)」의 개발 프레임워크 발화 생성 서버입니다.
|
||||
대화 히스토리(messages)를 받아 **구매자 다음 발화 1개**를 돌려줍니다. 같은 서버에서 프로필로 베이스라인과 개발 모델을 같은 조건으로 실행합니다.
|
||||
|
||||
- 아키텍처·코드 스타일: `Nego/server` 패턴(router / services / common / config, `config.toml` 단일 설정, JSON 리소스). Nego 코드는 import 하지 않는 독립 코드입니다.
|
||||
- 평가환경: Python 3.10 문법 범위로 작성(로컬 3.14에서 테스트).
|
||||
- 상태 없음: 요청마다 messages 만으로 처리합니다. 같은 입력이면 같은 처리를 합니다.
|
||||
|
||||
## 실행
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
|
||||
cp config.toml.example config.toml # 프로필별 base_url·model 수정. API 키는 파일에 쓰지 않고 api_key_env 환경변수로
|
||||
.venv/bin/python web_main.py # → http://localhost:3400/docs
|
||||
.venv/bin/python -m pytest tests/ # 가짜 LLM 사용, API 비용 없음
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
| 엔드포인트 | 설명 |
|
||||
|---|---|
|
||||
| `POST /v1/chat/completions` | OpenAI 호환. `model` = 프로필 이름(`baseline` / `developed`), `messages` = 홀드아웃 문항의 messages → `choices[0].message.content` = 구매자 발화. 확장 필드 `grounding`(적용 규칙·사용 지식 id·주의 사항) |
|
||||
| `GET /v1/models` | 프로필 목록 (OpenAI 호환) |
|
||||
| `GET /v1/config` | 프로필별 호출 대상·그라운딩 여부 (키 값은 내보내지 않음) |
|
||||
| `GET /health` | 상태 확인 |
|
||||
|
||||
오류: 없는 프로필 404, LLM 호출 실패 502(측정 도구가 재시도).
|
||||
|
||||
## 프로필 (`config.toml`)
|
||||
|
||||
| 항목 | baseline | developed |
|
||||
|---|---|---|
|
||||
| 모델 | `gpt-4o-2024-08-06` (OpenAI) | 같은 원본 모델 (미세조정 없음. 준비해 둔 미세조정 코드는 `../../보관/gpt4o_미세조정_코드_20261019/`) |
|
||||
| `writing_rules` | true — 작성 규칙 + 원래 system | true — 같은 작성 규칙 (확인서 "프롬프트 골격 동일") |
|
||||
| `grounding` | false — 지식 선택·판단 없음 | true — 파서 → 지식 선택·수락 판단 → 프롬프트 재구성 (해석 실패 시 baseline 방식으로 대신 처리, `rule = fallback`) |
|
||||
| `price_advice` | — | true — 이번 턴 제시가 계산 보조 (`pricing.py`) |
|
||||
| `experience_examples` | — | 2 — 학습 데이터(train)의 비슷한 과거 발화 예시 수 (`experience.py`, 0 이면 끔) |
|
||||
| `strip_knowledge` | false (true 면 공개 정보를 상품·현 단가만 남기는 대안 베이스라인) | — |
|
||||
| `postprocess` | true | true (화자 표시·따옴표·이어 쓴 판매자 발화 제거, 두 프로필 동일) |
|
||||
| 디코딩 | 요청 값 그대로 (temperature·top_p·seed·max_tokens) | 같음 |
|
||||
|
||||
## 그라운딩 모듈 (`services/grounding/`)
|
||||
|
||||
| 파일 | 역할 |
|
||||
|---|---|
|
||||
| `parser.py` | system → 지식 항목(K-product, K-list_price, K-volume, K-tenure, K-payment, K-alt_supplier, K-validity, K-competition, K-competitor, K-suppliers, K-market, K-b2c), 비공개 기준, 이번 턴 카드·행동 전략, `[진행]` 턴 정보, 히스토리의 직전 제시가(K-prev_seller / K-prev_buyer). id 체계는 `지시순응_변환.py` 와 같음 |
|
||||
| `selector.py` | 턴별 지식 선택 (첫 턴 / 카드별 / 카드 없음) + 사실 크기 주의(거래 3년 미만, 대체 공급사 0곳, 공급 가능 업체 수에 상대 포함) + 수락 판단(카드 없는 턴·최소 종료턴 이후·판매자 가격 ≤ 최대 수용가·(마지막 회차 또는 만족형이면서 ≤ 목표가)) |
|
||||
| `pricing.py` | 이번 턴 제시가 (2026-10-13): 와일드카드 = 카드 안내 금액, 구매자 마지막 회차 = 최대 수용가, 첫 가격 = 첫 제안가, 주장 = 직전 가격 유지, 양보·타협 = 직전 가격 + 비율 × (판매자 직전 제시가 − 직전 가격)(비율 양보 0.36·타협 0.30, 정책 json 의 `pricing`) |
|
||||
| `experience.py` | 경험 예시 (2026-10-13): `resources/grounding/experience_examples.jsonl`(train 2,054개, 대화 468건, 숫자는 ○)에서 같은 상황(첫 턴/같은 카드/카드 없음)·행동 전략·행위의 발화를 남은 턴이 가까운 순으로 고른다. 같은 입력이면 같은 예시. `tools/build_experience.py` 로 다시 만든다(valid·홀드아웃 제외 검사) |
|
||||
| `generator.py` `build_prompt` | 프로필별 LLM 입력 구성 (2026-10-19 분리). 생성 경로와 (보관한) 미세조정 학습 파일 생성이 같은 함수를 쓴다 |
|
||||
| `prompt_builder.py` | 작성 규칙(`resources/prompts/writing_rules.txt`, 두 프로필 공통) + 이번 턴 근거 지식 + 주의 + 비공개 기준 + 카드 + 행동 전략 + 이번 턴 판단으로 system 재구성. 히스토리는 원문 유지. **미세조정 학습 입력도 이 모듈로 만들어야 학습·추론 형식이 같습니다** |
|
||||
|
||||
선택 규칙의 정본은 `resources/grounding/grounding_policy.json` 입니다(규칙 v1 — 2026-10-13 첫 턴 지침·내부 기준 용어 주의·제시가 비율·예시 머리말 추가). 학습 데이터의 `grounded_on` 빈도로 정했고 홀드아웃은 확인에만 썼습니다.
|
||||
|
||||
검증(2026-10-12, 학습·검증 + 홀드아웃 문항 2,808개)
|
||||
- 파서: 전략·카드·턴·비공개 기준 100%, 직전 제시가 100%(데이터의 K-prev_* 와 일치), 해석 못 한 줄 0
|
||||
- 선택기: 데이터의 `grounded_on`(K-card·K-target 제외) 재현율 학습·검증 94.5%, 홀드아웃 92.1%
|
||||
- 수락 판단: 정답 수락 턴 재현 학습·검증 375/380, 홀드아웃 86/89, 잘못된 수락 0
|
||||
|
||||
검증(2026-10-13, 제시가 보조 — 비율은 train 으로만 정함)
|
||||
- 정답 제시가와 정확히 같은 비율: train 793/1,240, 홀드아웃 199/319. 규칙별 홀드아웃: 첫 제안가 109/109, 유지 24/24, 와일드카드 29/29, 마지막 회차 10/17, 양보·타협 27/140
|
||||
- 홀드아웃 마지막 회차 7건 불일치는 시뮬레이터의 '마지막 턴 최대 수용가' 규칙이 생기기 전에 만든 홀드아웃 대화라서다(train 은 69/69). 홀드아웃에 맞춰 바꾸지 않았다
|
||||
- 홀드아웃 529문항 전체를 가짜 LLM 으로 처리: fallback 0, 문항마다 예시 2개
|
||||
|
||||
## 측정 연결
|
||||
|
||||
측정은 `../run_eval.py` 가 이 서버를 불러 진행합니다(사용법은 `../README.md`). 서버 기동·측정·종료는 `../run_test.sh` 가 한 번에 합니다.
|
||||
|
||||
측정 기록은 `../logs/server/` 에 쌓입니다 (`[instrument]` 로 변경 가능, 구성은 `../logs/README.md`).
|
||||
- `generation_log.jsonl`: 요청별 입력 해시(`messages_sha256`, 측정 문항과 잇는 키)·적용 규칙·수락 판단·제시가·경험 예시·사용 지식·LLM 에 보낸 messages·디코딩 설정·토큰·호출 시간·OpenAI `system_fingerprint` (확인서 "그라운딩 근거 로그")
|
||||
- `response_time.jsonl`: 응답시간, `logs/server.log`: 애플리케이션 로그
|
||||
- 테스트는 임시 설정(`GROUNDING_AGENT_CONFIG` 환경변수)으로 돌아 이 폴더에 쓰지 않습니다.
|
||||
예비 측정(2026-10-12, gpt-4o, 홀드아웃 20문항): ROUGE-1 0.388 → 0.442, 개선율 +14.0% (95% 구간 +3.0~+26.9%). 결과는 `../../보관/2차년도_성능평가/5_시험결과/예비측정_2026-10-12/`
|
||||
2026-10-12 가짜 OpenAI 호환 백엔드로 위 경로 전체(홀드아웃 세션 5개·22문항 × 2프로필)를 실행해 생성 실패 0, 채점 파일 생성까지 확인했습니다.
|
||||
|
||||
## 구조
|
||||
|
||||
```
|
||||
server/
|
||||
├── web_main.py # 진입점 (포트 3400)
|
||||
├── config.toml.example # 단일 설정 예시 (config.toml 은 직접 만든다)
|
||||
├── config/ # 설정 모델·로더
|
||||
├── common/ # paths·logger·enums(지식 유형·행동 전략)
|
||||
├── router/
|
||||
│ ├── router.py # 앱 조립 + 응답시간 미들웨어
|
||||
│ └── v1/ # protocol(OpenAI 호환 스키마)·chat·admin
|
||||
├── services/
|
||||
│ ├── grounding/ # parser·selector·pricing·experience·prompt_builder
|
||||
│ └── generation/ # llm_client(OpenAI 호환)·generator(프로필)·postprocess
|
||||
├── resources/ # grounding/grounding_policy.json·experience_examples.jsonl, prompts/writing_rules.txt
|
||||
├── tools/ # build_experience.py (경험 학습 메모리 생성)
|
||||
(기록은 ../logs/server/ — 서버 폴더 밖)
|
||||
└── tests/ # 파서·그라운딩·제시가·경험 학습·생성·스모크 테스트 41개
|
||||
```
|
||||
|
||||
## 남은 일
|
||||
- OpenAI 미세조정: 하지 않음. 코드·학습 파일은 `../../보관/gpt4o_미세조정_코드_20261019/` 로 옮김(2026-10-21)
|
||||
- 시험기관과 베이스라인 정의 합의(`strip_knowledge` 사용 여부)
|
||||
- 2026-10-13 개선 후 같은 20문항 재측정: ROUGE-1 0.381 → 0.559, **+46.6%** (95% 구간 +26.3~+71.8%, Wilcoxon p=8.2e-05, 개발 우세 18/20). `../../보관/2차년도_성능평가/logs_이전측정/runs/20261013_162928_개선1_20문항/`. NW-0261(단위 혼동 데이터)은 제시가 보조가 22,500원을 안내해 틀림 — 단위 혼동 4건 처리 결정 필요
|
||||
Whitespace-only changes.
@@ -0,0 +1,23 @@
|
||||
"""공용 Enum 정의."""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class KnowledgeType(str, Enum):
|
||||
"""지식 유형 — 데이터양식 §4-C knowledge.type 과 같은 값."""
|
||||
PRODUCT_FEATURE = "product_feature"
|
||||
PRICE_INFO = "price_info"
|
||||
SCENARIO_VARIABLE = "scenario_variable"
|
||||
KTC_VARIABLE = "ktc_variable"
|
||||
CARD_FACT = "card_fact"
|
||||
NEGOTIATION_CARD = "negotiation_card"
|
||||
PRIVATE_TARGET = "private_target"
|
||||
PREVIOUS_TURN = "previous_turn"
|
||||
|
||||
|
||||
class Strategy(str, Enum):
|
||||
"""행동 전략 4종 [계획서 p.31]."""
|
||||
CONCESSION = "양보"
|
||||
ASSERTION = "주장"
|
||||
INQUIRY = "탐색"
|
||||
COMPROMISE = "타협"
|
||||
@@ -0,0 +1,28 @@
|
||||
"""로깅 설정 — KST 타임스탬프, 파일 회전 + 콘솔."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from common.paths import LOGS_DIR
|
||||
|
||||
|
||||
def _kst_converter(*args):
|
||||
return datetime.now(timezone(timedelta(hours=9))).timetuple()
|
||||
|
||||
|
||||
def setup_logging(level: int = logging.INFO, log_dir: Optional[Path] = None) -> None:
|
||||
log_dir = log_dir or LOGS_DIR
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
logging.Formatter.converter = _kst_converter
|
||||
logging.basicConfig(
|
||||
level=level,
|
||||
format="[%(asctime)s] [%(levelname)s] %(name)s: %(message)s",
|
||||
handlers=[
|
||||
RotatingFileHandler(log_dir / "server.log", maxBytes=10 * 1024 * 1024,
|
||||
backupCount=5, encoding="utf-8"),
|
||||
logging.StreamHandler(),
|
||||
],
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""서버 루트 기준 경로 정의."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
SERVER_ROOT = Path(__file__).resolve().parents[1]
|
||||
RESOURCES_DIR = SERVER_ROOT / "resources"
|
||||
DATA_DIR = SERVER_ROOT / "data"
|
||||
LOGS_DIR = SERVER_ROOT / "logs"
|
||||
|
||||
|
||||
def resolve_data_path(path_str: str) -> Path:
|
||||
"""config 의 상대경로를 서버 루트 기준 절대경로로 변환한다."""
|
||||
p = Path(path_str)
|
||||
return p if p.is_absolute() else SERVER_ROOT / p
|
||||
@@ -0,0 +1,31 @@
|
||||
# GROUNDING_AGENT 서버 설정 (단일 파일 — 환경 구분 없음)
|
||||
# 이 파일을 config.toml 로 복사해 쓴다. API 키는 파일에 쓰지 않고 api_key_env 의 환경변수로 넘긴다.
|
||||
|
||||
[server]
|
||||
name = "GROUNDING_AGENT"
|
||||
port = 3400
|
||||
host = "0.0.0.0"
|
||||
|
||||
# 요청의 model 값 = 프로필 이름 (grounding-eval generate --model baseline / developed)
|
||||
# 베이스 모델: gpt-4o 고정 버전 (OpenAI 미세조정이 지원되는 스냅샷, 재현성을 위해 날짜 버전으로 고정)
|
||||
[profiles.baseline]
|
||||
base_url = "https://api.openai.com/v1"
|
||||
model = "gpt-4o-2024-08-06" # 학습·그라운딩 미적용
|
||||
api_key_env = "OPENAI_API_KEY"
|
||||
grounding = false
|
||||
strip_knowledge = false # true 면 공개 정보를 상품·현 단가만 남긴다 (대안 베이스라인)
|
||||
|
||||
[profiles.developed]
|
||||
base_url = "https://api.openai.com/v1"
|
||||
model = "gpt-4o-2024-08-06" # 미세조정 후 "ft:gpt-4o-2024-08-06:<조직>::<id>" 로 바꾼다
|
||||
api_key_env = "OPENAI_API_KEY"
|
||||
grounding = true
|
||||
price_advice = true # 이번 턴 제시가 계산 보조 (학습 데이터 제시가 규칙)
|
||||
experience_examples = 2 # 학습 데이터(train)의 비슷한 과거 발화 예시 수 (0 이면 끔)
|
||||
|
||||
[instrument]
|
||||
# 평가 계측 — 경로를 비우면("") 해당 계측을 끈다. 상대경로는 서버 루트 기준 → 기본은 2차년도_성능평가/logs/server/
|
||||
log_dir = "../logs/server/logs" # 서버 애플리케이션 로그
|
||||
generation_log = "../logs/server/generation_log.jsonl" # 턴별 그라운딩 근거 로그 (성능평가 증빙)
|
||||
response_time_log = "../logs/server/response_time.jsonl" # 응답시간
|
||||
log_prompt = true # LLM 에 보낸 messages 전체를 근거 로그에 남김
|
||||
@@ -0,0 +1,31 @@
|
||||
# GROUNDING_AGENT 서버 설정 (단일 파일 — 환경 구분 없음)
|
||||
# 이 파일을 config.toml 로 복사해 쓴다. API 키는 파일에 쓰지 않고 api_key_env 의 환경변수로 넘긴다.
|
||||
|
||||
[server]
|
||||
name = "GROUNDING_AGENT"
|
||||
port = 3400
|
||||
host = "0.0.0.0"
|
||||
|
||||
# 요청의 model 값 = 프로필 이름 (grounding-eval generate --model baseline / developed)
|
||||
# 베이스 모델: gpt-4o 고정 버전 (OpenAI 미세조정이 지원되는 스냅샷, 재현성을 위해 날짜 버전으로 고정)
|
||||
[profiles.baseline]
|
||||
base_url = "https://api.openai.com/v1"
|
||||
model = "gpt-4o-2024-08-06" # 학습·그라운딩 미적용
|
||||
api_key_env = "OPENAI_API_KEY"
|
||||
grounding = false
|
||||
strip_knowledge = false # true 면 공개 정보를 상품·현 단가만 남긴다 (대안 베이스라인)
|
||||
|
||||
[profiles.developed]
|
||||
base_url = "https://api.openai.com/v1"
|
||||
model = "gpt-4o-2024-08-06" # 미세조정 후 "ft:gpt-4o-2024-08-06:<조직>::<id>" 로 바꾼다
|
||||
api_key_env = "OPENAI_API_KEY"
|
||||
grounding = true
|
||||
price_advice = true # 이번 턴 제시가 계산 보조 (학습 데이터 제시가 규칙)
|
||||
experience_examples = 2 # 학습 데이터(train)의 비슷한 과거 발화 예시 수 (0 이면 끔)
|
||||
|
||||
[instrument]
|
||||
# 평가 계측 — 경로를 비우면("") 해당 계측을 끈다. 상대경로는 서버 루트 기준 → 기본은 2차년도_성능평가/logs/server/
|
||||
log_dir = "../logs/server/logs" # 서버 애플리케이션 로그
|
||||
generation_log = "../logs/server/generation_log.jsonl" # 턴별 그라운딩 근거 로그 (성능평가 증빙)
|
||||
response_time_log = "../logs/server/response_time.jsonl" # 응답시간
|
||||
log_prompt = true # LLM 에 보낸 messages 전체를 근거 로그에 남김
|
||||
Whitespace-only changes.
@@ -0,0 +1,28 @@
|
||||
"""config.toml 로더 — 파일이 없으면 기본값으로 기동한다.
|
||||
|
||||
GROUNDING_AGENT_CONFIG 환경변수로 다른 설정 파일을 지정할 수 있다 (테스트가 증빙 로그 폴더에 쓰지 않게 할 때 등).
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from common.paths import SERVER_ROOT
|
||||
from config.config_models import AppConfig
|
||||
|
||||
try:
|
||||
import tomllib # Python 3.11+
|
||||
except ImportError:
|
||||
import tomli as tomllib # Python 3.10 (평가환경)
|
||||
|
||||
CONFIG_PATH = Path(os.getenv("GROUNDING_AGENT_CONFIG") or SERVER_ROOT / "config.toml")
|
||||
|
||||
|
||||
def load_config() -> AppConfig:
|
||||
if CONFIG_PATH.exists():
|
||||
with open(CONFIG_PATH, "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
return AppConfig(**raw)
|
||||
return AppConfig()
|
||||
|
||||
|
||||
app_config = load_config()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""설정 모델 — config.toml 의 구조를 정의한다."""
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ServerConfig(BaseModel):
|
||||
name: str = "GROUNDING_AGENT"
|
||||
port: int = 3400
|
||||
host: str = "0.0.0.0"
|
||||
|
||||
|
||||
class ProfileConfig(BaseModel):
|
||||
"""요청의 model 값으로 고르는 생성 프로필.
|
||||
|
||||
baseline 과 developed 를 같은 서버·같은 입력으로 실행해 그라운딩 효과만 비교한다.
|
||||
"""
|
||||
base_url: str = "https://api.openai.com/v1" # OpenAI 호환 서버 (vLLM 등)
|
||||
model: str = "gpt-4o-2024-08-06" # 실제로 호출할 모델명 (미세조정 모델은 ft:… 이름)
|
||||
api_key_env: str = "OPENAI_API_KEY" # 비워두면 키 없이 호출 (로컬 vLLM)
|
||||
grounding: bool = False # True 면 그라운딩 모듈로 프롬프트를 다시 구성한다
|
||||
price_advice: bool = False # grounding 일 때 이번 턴 제시가를 계산해 알려 준다 (services/grounding/pricing.py)
|
||||
experience_examples: int = 0 # grounding 일 때 붙일 학습 데이터 경험 예시 수 (0 이면 안 붙임)
|
||||
strip_knowledge: bool = False # True 면 system 의 공개 정보를 상품·현 단가만 남긴다 (대안 베이스라인)
|
||||
writing_rules: bool = True # 작성 규칙(resources/prompts/writing_rules.txt)을 붙인다 (두 프로필 동일 — 프롬프트 골격 동일)
|
||||
postprocess: bool = True # 화자 표시·따옴표 제거 등 형식 정리 (두 프로필 동일 적용 권장)
|
||||
timeout: float = 120.0
|
||||
|
||||
|
||||
class InstrumentConfig(BaseModel):
|
||||
"""평가 계측 — 경로를 비우면 해당 계측을 끈다. 상대경로는 서버 루트 기준.
|
||||
|
||||
기본 위치는 성능평가 자료 폴더의 logs/server/ (2차년도_성능평가/logs/server) — 측정 증빙을 한곳에 모은다.
|
||||
"""
|
||||
log_dir: str = "../logs/server/logs" # 서버 애플리케이션 로그 (server.log, 회전)
|
||||
generation_log: str = "../logs/server/generation_log.jsonl" # 턴별 그라운딩 근거 로그
|
||||
response_time_log: str = "../logs/server/response_time.jsonl" # 응답시간
|
||||
log_prompt: bool = True # LLM 에 보낸 messages 전체를 근거 로그에 남김
|
||||
|
||||
|
||||
def _default_profiles() -> Dict[str, ProfileConfig]:
|
||||
return {
|
||||
"baseline": ProfileConfig(grounding=False),
|
||||
"developed": ProfileConfig(grounding=True, price_advice=True, experience_examples=2),
|
||||
}
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
server: ServerConfig = ServerConfig()
|
||||
profiles: Dict[str, ProfileConfig] = _default_profiles()
|
||||
instrument: InstrumentConfig = InstrumentConfig()
|
||||
@@ -0,0 +1,7 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
pydantic>=2.6
|
||||
openai>=1.30
|
||||
tomli>=2.0; python_version < "3.11"
|
||||
httpx>=0.27
|
||||
pytest>=8.0
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"_설명": "턴별 지식 선택 규칙 v1 (규칙 기반). 근거: 학습 데이터(train) strategy_conditioned_response 의 grounded_on 빈도(카드별 30% 이상)·제시가 규칙과 다시쓰기_가이드.md 의 사실 크기 규칙. 홀드아웃은 확인에만 썼다.",
|
||||
"always": [
|
||||
"K-list_price"
|
||||
],
|
||||
"first_turn": [
|
||||
"K-product",
|
||||
"K-volume"
|
||||
],
|
||||
"with_card": {
|
||||
"경쟁사 비교 전략": [
|
||||
"K-competitor",
|
||||
"K-alt_supplier",
|
||||
"K-prev_seller",
|
||||
"K-tenure"
|
||||
],
|
||||
"최후 통첩 전략": [
|
||||
"K-competitor",
|
||||
"K-alt_supplier"
|
||||
],
|
||||
"대체 공급자의 언급": [
|
||||
"K-suppliers",
|
||||
"K-alt_supplier"
|
||||
],
|
||||
"결제 기한 전략": [
|
||||
"K-payment"
|
||||
],
|
||||
"데이터 기반 가격 설정": [
|
||||
"K-market",
|
||||
"K-b2c"
|
||||
],
|
||||
"상호 이익 강조 전략": [
|
||||
"K-volume",
|
||||
"K-tenure",
|
||||
"K-competition",
|
||||
"K-validity"
|
||||
],
|
||||
"시장 동향 감안, 열린 협상 전략": [
|
||||
"K-competition",
|
||||
"K-tenure",
|
||||
"K-validity"
|
||||
],
|
||||
"재원부족": [
|
||||
"K-prev_seller"
|
||||
],
|
||||
"1% 추가네고": [
|
||||
"K-prev_seller"
|
||||
],
|
||||
"양보 전략": [
|
||||
"K-prev_seller",
|
||||
"K-prev_buyer"
|
||||
]
|
||||
},
|
||||
"without_card": [
|
||||
"K-prev_seller",
|
||||
"K-prev_buyer"
|
||||
],
|
||||
"strategy_guide": {
|
||||
"탐색": "가격을 제시하지 않고, 상대의 사정이나 조정 여지를 묻는 질문으로 끝낸다.",
|
||||
"주장": "가격을 움직이지 않는다. 직전 가격을 유지하거나 첫 가격을 제시하며 근거 하나를 든다.",
|
||||
"양보": "조건 없이 가격을 상대 쪽으로 움직이거나 상대 가격을 받아들인다. 제시가는 숫자로 말한다.",
|
||||
"타협": "가격을 움직이면서 조건을 붙인다(~해 주시면, ~라면). 제시가는 숫자로 말한다."
|
||||
},
|
||||
"notes": {
|
||||
"short_tenure": "거래기간이 3년 미만이므로 '오랜 거래·장기 거래'라고 말하지 않는다.",
|
||||
"no_alt_supplier": "대체 공급사가 없으므로 다른 업체·경쟁 견적·대체 공급을 말하지 않는다.",
|
||||
"suppliers_include_partner": "공급 가능 업체 수에는 상대 회사가 포함되어 있다. 경쟁 업체 수로 부풀려 말하지 않는다.",
|
||||
"private_terms": "'목표가·하한선·최대 수용가·첫 제안가' 같은 내부 기준 용어를 말하지 않는다. 목표 가격을 밝히는 것은 '상호 이익 강조 전략' 카드 턴, 예산을 밝히는 것은 '재원부족' 턴뿐이다."
|
||||
},
|
||||
"short_tenure_years": 3,
|
||||
"private_terms_allowed_cards": [
|
||||
"상호 이익 강조 전략",
|
||||
"재원부족"
|
||||
],
|
||||
"turn_guides": {
|
||||
"first_turn": "첫 발화입니다. 상품을 짧게 부르고 현 공급단가를 말한 뒤 조정 여지가 있는지 묻습니다. 가격을 제시하지 않고, 원자재·시장 상황처럼 주어지지 않은 사정을 묻거나 가정하지 않습니다.",
|
||||
"offer": "이번 턴 제시가는 {price:,}원입니다. 이 금액을 숫자로 말합니다."
|
||||
},
|
||||
"pricing": {
|
||||
"_설명": "양보·타협 턴의 제시가 = 직전 가격 + 비율 × (판매자 직전 제시가 − 직전 가격), 제시 단위 반올림, 최대 수용가 이하. 비율은 학습 데이터(train) 양보·타협 제시 턴 567개에서 정확 일치가 가장 많은 값(130/567, 2026-10-13)",
|
||||
"step_ratio": {
|
||||
"양보": 0.36,
|
||||
"타협": 0.3
|
||||
}
|
||||
},
|
||||
"experience": {
|
||||
"_설명": "예시 머리말. 예시는 표현만 참고하고 상품·수치는 이번 대화 것을 쓴다",
|
||||
"intro": "[비슷한 과거 발화] 학습 데이터에서 같은 상황의 구매자 발화입니다. 말투와 구성만 참고하고, 상품명·숫자(○)는 이번 대화의 정보로 채웁니다."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
당신은 구매대행사의 구매 담당자(MD)입니다. 협력사 영업 담당자와 기존 공급 품목의 단가를 실시간 채팅으로 재협상합니다.
|
||||
이번 턴에 할 구매자 발화 하나만 출력합니다.
|
||||
|
||||
[작성 규칙]
|
||||
- 한국어 존댓말로 1~2문장(길어도 3문장). 인사·설명·따옴표·화자 표시 없이 발화 문장만 씁니다.
|
||||
- 근거는 한 턴에 하나(많아야 둘)만 듭니다. 주어진 정보에 없는 수치나 사실을 만들지 않습니다.
|
||||
- 가격을 제시하거나 받아들일 때는 금액을 숫자와 '원'으로 말합니다(예: 12,300원).
|
||||
- [비공개 기준]은 가격 판단에만 쓰고 그 용어와 금액을 상대에게 말하지 않습니다. 협상카드가 허용한 경우만 예외입니다.
|
||||
- 협상카드가 있으면 그 안내의 핵심 근거와 수치를 자연스럽게 녹여 말합니다.
|
||||
- 자기 제안을 "합리적·공정한 가격"이라고 부르지 않습니다. "최종·한계"는 실제 마지막 가격에서만 씁니다.
|
||||
- 수락할 때는 받아들이는 금액을 말하고 수정 견적서·품의 같은 다음 절차로 마무리합니다.
|
||||
Whitespace-only changes.
@@ -0,0 +1,75 @@
|
||||
"""FastAPI 앱 조립 — 미들웨어(응답시간 계측) + 라우터 등록.
|
||||
|
||||
import 시점에 app 및 발화 생성기가 초기화된다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from common.logger import setup_logging
|
||||
from common.paths import resolve_data_path
|
||||
from config.config_loader import app_config
|
||||
|
||||
setup_logging(log_dir=resolve_data_path(app_config.instrument.log_dir) if app_config.instrument.log_dir else None)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(
|
||||
title=f"{app_config.server.name} Knowledge Grounding Service",
|
||||
description="지식 그라운딩 협상 발화 생성 서버 — 2차년도 성능평가(ROUGE) 측정용",
|
||||
version="0.1.0",
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 응답시간 계측 — 요청 수신 → 응답 완료 ms
|
||||
_rt_log_path = None
|
||||
if app_config.instrument.response_time_log:
|
||||
_rt_log_path = resolve_data_path(app_config.instrument.response_time_log)
|
||||
_rt_log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def response_time_middleware(request: Request, call_next):
|
||||
t0 = time.perf_counter()
|
||||
response = await call_next(request)
|
||||
elapsed_ms = (time.perf_counter() - t0) * 1000
|
||||
response.headers["X-Response-Time-Ms"] = f"{elapsed_ms:.2f}"
|
||||
|
||||
if _rt_log_path is not None and request.url.path.endswith("/chat/completions"):
|
||||
try:
|
||||
with open(_rt_log_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({
|
||||
"ts": datetime.now(timezone(timedelta(hours=9))).isoformat(),
|
||||
"path": request.url.path,
|
||||
"status": response.status_code,
|
||||
"ms": round(elapsed_ms, 2),
|
||||
}) + "\n")
|
||||
except OSError as e:
|
||||
logger.error(f"[middleware] 응답시간 기록 실패: {e}")
|
||||
|
||||
return response
|
||||
|
||||
|
||||
# 생성기 초기화 (라우터 import보다 먼저 — 엔드포인트가 app.state.generator를 사용)
|
||||
from services.generation.generator import Generator # noqa: E402
|
||||
|
||||
app.state.config = app_config
|
||||
app.state.generator = Generator(app_config)
|
||||
logger.info(f"[startup] generator ready — profiles="
|
||||
f"{ {name: ('grounding' if p.grounding else 'plain') for name, p in app_config.profiles.items()} }")
|
||||
|
||||
from router.v1 import admin, chat # noqa: E402
|
||||
|
||||
app.include_router(admin.router)
|
||||
app.include_router(chat.router)
|
||||
Whitespace-only changes.
@@ -0,0 +1,43 @@
|
||||
"""상태 확인 엔드포인트."""
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from router.v1.protocol import HealthResponse
|
||||
|
||||
router = APIRouter(tags=["admin"])
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
async def health_check():
|
||||
return HealthResponse(status="OK", message="GROUNDING_AGENT server is running")
|
||||
|
||||
|
||||
@router.get("/v1/models")
|
||||
async def list_models(request: Request):
|
||||
"""OpenAI 호환 모델 목록 — 프로필 이름을 모델 id 로 보여 준다."""
|
||||
profiles = request.app.state.config.profiles
|
||||
return {"object": "list", "data": [{"id": name, "object": "model", "owned_by": "grounding-agent"}
|
||||
for name in profiles]}
|
||||
|
||||
|
||||
@router.get("/v1/config")
|
||||
async def get_config(request: Request):
|
||||
"""현재 서버 설정 — 프로필별 호출 대상·그라운딩 여부 (API 키 값은 내보내지 않는다)."""
|
||||
config = request.app.state.config
|
||||
return {
|
||||
"server": config.server.name,
|
||||
"port": config.server.port,
|
||||
"profiles": {
|
||||
name: {"base_url": p.base_url, "model": p.model, "grounding": p.grounding,
|
||||
"price_advice": p.price_advice, "experience_examples": p.experience_examples,
|
||||
"strip_knowledge": p.strip_knowledge, "writing_rules": p.writing_rules, "postprocess": p.postprocess,
|
||||
"api_key_env": p.api_key_env}
|
||||
for name, p in config.profiles.items()
|
||||
},
|
||||
"instrument": {
|
||||
"log_dir": config.instrument.log_dir,
|
||||
"log_prompt": config.instrument.log_prompt,
|
||||
"generation_log": config.instrument.generation_log,
|
||||
"response_time_log": config.instrument.response_time_log,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""발화 생성 엔드포인트 — OpenAI Chat Completions 호환."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from router.v1.protocol import (
|
||||
ChatChoice,
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionResponse,
|
||||
ChatMessage,
|
||||
GroundingInfo,
|
||||
Usage,
|
||||
)
|
||||
from services.generation.generator import UnknownProfileError
|
||||
from services.generation.llm_client import LLMError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["chat"])
|
||||
|
||||
|
||||
@router.post("/chat/completions", response_model=ChatCompletionResponse)
|
||||
async def chat_completions(body: ChatCompletionRequest, request: Request):
|
||||
"""대화 히스토리 → 구매자 다음 발화 1개. model 값으로 baseline / developed 프로필을 고른다."""
|
||||
generator = request.app.state.generator
|
||||
messages = [m.model_dump() for m in body.messages]
|
||||
try:
|
||||
result = generator.generate(body.model, messages, temperature=body.temperature, top_p=body.top_p,
|
||||
seed=body.seed, max_tokens=body.max_tokens)
|
||||
except UnknownProfileError:
|
||||
raise HTTPException(status_code=404, detail=f"알 수 없는 프로필(model): {body.model} — "
|
||||
f"사용 가능: {sorted(generator.profiles)}")
|
||||
except LLMError as e:
|
||||
logger.error(f"[API] 생성 실패 profile={body.model}: {e}")
|
||||
raise HTTPException(status_code=502, detail=str(e))
|
||||
|
||||
trace = result.trace
|
||||
logger.info(f"[API_RES] profile={trace.profile} turn={trace.turn} rule={trace.rule} "
|
||||
f"knowledge={trace.used_knowledge}")
|
||||
llm = result.llm
|
||||
return ChatCompletionResponse(
|
||||
id=f"chatcmpl-{uuid.uuid4().hex[:24]}",
|
||||
created=int(time.time()),
|
||||
model=body.model,
|
||||
choices=[ChatChoice(message=ChatMessage(role="assistant", content=result.content),
|
||||
finish_reason=llm.finish_reason)],
|
||||
usage=Usage(prompt_tokens=llm.prompt_tokens, completion_tokens=llm.completion_tokens,
|
||||
total_tokens=llm.prompt_tokens + llm.completion_tokens),
|
||||
system_fingerprint=llm.system_fingerprint,
|
||||
grounding=GroundingInfo(**asdict(trace)),
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""API 프로토콜 — OpenAI Chat Completions 호환 요청/응답 스키마.
|
||||
|
||||
측정 도구(Grounding_Eval generate)가 base_url 만 바꿔 호출할 수 있도록 OpenAI 형식을 따른다.
|
||||
grounding 필드는 확장 필드이며 OpenAI 클라이언트는 무시한다.
|
||||
"""
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
message: str
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
role: str # "system" | "user" | "assistant"
|
||||
content: Optional[str] = ""
|
||||
|
||||
|
||||
class ChatCompletionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore") # stream·n 등 쓰지 않는 OpenAI 필드는 무시
|
||||
|
||||
model: str # 프로필 이름: "baseline" | "developed"
|
||||
messages: List[ChatMessage]
|
||||
temperature: float = 0.0
|
||||
top_p: float = 1.0
|
||||
seed: Optional[int] = 0
|
||||
max_tokens: Optional[int] = 512
|
||||
|
||||
|
||||
class ChatChoice(BaseModel):
|
||||
index: int = 0
|
||||
message: ChatMessage
|
||||
finish_reason: Optional[str] = None
|
||||
|
||||
|
||||
class Usage(BaseModel):
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
total_tokens: int = 0
|
||||
|
||||
|
||||
class GroundingInfo(BaseModel):
|
||||
"""턴별 그라운딩 근거 (확인서 '그라운딩 근거 로그')."""
|
||||
|
||||
profile: str
|
||||
grounding: bool
|
||||
rule: Optional[str] = None
|
||||
decision: Optional[str] = None
|
||||
offer: Optional[int] = None
|
||||
offer_rule: Optional[str] = None
|
||||
examples: List[str] = []
|
||||
used_knowledge: List[str] = []
|
||||
notes: List[str] = []
|
||||
card: Optional[str] = None
|
||||
strategy: Optional[str] = None
|
||||
turn: Optional[int] = None
|
||||
|
||||
|
||||
class ChatCompletionResponse(BaseModel):
|
||||
id: str
|
||||
object: str = "chat.completion"
|
||||
created: int
|
||||
model: str
|
||||
choices: List[ChatChoice]
|
||||
usage: Usage
|
||||
system_fingerprint: Optional[str] = None
|
||||
grounding: Optional[GroundingInfo] = None
|
||||
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]
|
||||
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
|
||||
@@ -0,0 +1,63 @@
|
||||
"""경험 예시 파일 만들기 — 학습 데이터(train)의 구매자 턴 정답 발화 → resources/grounding/experience_examples.jsonl
|
||||
|
||||
cd server && .venv/bin/python tools/build_experience.py
|
||||
|
||||
- 입력: ../data/train/학습검증_지시순응.jsonl 의 strategy_conditioned_response 중 split == train
|
||||
- 홀드아웃(../data/holdout/대상_홀드아웃.txt)의 시나리오가 섞여 있으면 중단한다.
|
||||
- 예시의 상황·전략·남은 턴은 서버와 같은 파서로 messages 에서 다시 읽는다 (추론 때와 같은 기준).
|
||||
- 정답 발화의 숫자는 ○ 로 가린다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
SERVER_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(SERVER_ROOT))
|
||||
|
||||
from services.grounding.experience import EXAMPLES_PATH, situation_of # noqa: E402
|
||||
from services.grounding.parser import parse_messages # noqa: E402
|
||||
|
||||
EVAL_ROOT = SERVER_ROOT.parent
|
||||
SOURCE = EVAL_ROOT / "data" / "train" / "학습검증_지시순응.jsonl"
|
||||
HOLDOUT_IDS = EVAL_ROOT / "data" / "holdout" / "대상_홀드아웃.txt"
|
||||
NUMBER_RE = re.compile(r"\d[\d,]*(?:\.\d+)?")
|
||||
|
||||
|
||||
def mask_numbers(text: str) -> str:
|
||||
return NUMBER_RE.sub("○", text)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
holdout = set(HOLDOUT_IDS.read_text(encoding="utf-8").split())
|
||||
rows, skipped = [], Counter()
|
||||
with open(SOURCE, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
r = json.loads(line)
|
||||
if r["task_type"] != "strategy_conditioned_response":
|
||||
continue
|
||||
if r["split"] != "train":
|
||||
skipped[r["split"]] += 1
|
||||
continue
|
||||
if r["scenario_id"] in holdout:
|
||||
sys.exit(f"홀드아웃 시나리오가 학습 데이터에 있습니다: {r['scenario_id']}")
|
||||
ctx = parse_messages(r["messages"])
|
||||
rows.append({
|
||||
"sample_id": r["sample_id"], "dialogue_id": r["dialogue_id"],
|
||||
"situation": situation_of(ctx.is_first_turn, ctx.card_name), "strategy": ctx.strategy,
|
||||
"act": r["reference_act"], "turn": ctx.turn or r["turn"], "remaining": ctx.remaining or 0,
|
||||
"response": mask_numbers(r["reference_response"]),
|
||||
})
|
||||
EXAMPLES_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(EXAMPLES_PATH, "w", encoding="utf-8") as f:
|
||||
for row in rows:
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
print(f"{EXAMPLES_PATH.relative_to(SERVER_ROOT)}: {len(rows)}개 (대화 {len({r['dialogue_id'] for r in rows})}건), "
|
||||
f"제외 {dict(skipped)}")
|
||||
print("상황별:", Counter(r["situation"] for r in rows).most_common())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
# 실행 방법
|
||||
# pip install -r requirements.txt
|
||||
# python web_main.py
|
||||
#
|
||||
# 또는 uvicorn 직접 실행:
|
||||
# uvicorn router.router:app --host 0.0.0.0 --port 3400
|
||||
|
||||
import uvicorn
|
||||
|
||||
from config.config_loader import app_config
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Server Name : {app_config.server.name}")
|
||||
print(f"Server Port : {app_config.server.port}")
|
||||
uvicorn.run(
|
||||
"router.router:app",
|
||||
host=app_config.server.host,
|
||||
port=app_config.server.port,
|
||||
access_log=False,
|
||||
)
|
||||
Reference in new issue
Block a user