초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
@@ -0,0 +1,6 @@
|
||||
.venv
|
||||
logs
|
||||
data
|
||||
__pycache__
|
||||
.pytest_cache
|
||||
config.toml
|
||||
@@ -0,0 +1,33 @@
|
||||
# 평가환경 재현: Ubuntu 20.04 + Python 3.10 (연구개발계획서 명시 환경)
|
||||
# Python 3.10은 20.04 저장소에 없어 소스 빌드한다 (PPA는 컨테이너 dbus 제약으로 실패,
|
||||
# 소스 빌드는 아키텍처(amd64/arm64) 무관하게 동작).
|
||||
FROM ubuntu:20.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
build-essential wget ca-certificates \
|
||||
libssl-dev zlib1g-dev libbz2-dev libreadline-dev \
|
||||
libsqlite3-dev libffi-dev liblzma-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG PY_VER=3.10.14
|
||||
RUN wget -q "https://www.python.org/ftp/python/${PY_VER}/Python-${PY_VER}.tgz" \
|
||||
&& tar xzf "Python-${PY_VER}.tgz" \
|
||||
&& cd "Python-${PY_VER}" \
|
||||
&& ./configure --with-ensurepip=install > /dev/null \
|
||||
&& make -j"$(nproc)" > /dev/null \
|
||||
&& make altinstall > /dev/null \
|
||||
&& cd .. && rm -rf "Python-${PY_VER}" "Python-${PY_VER}.tgz"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN python3.10 -m pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 53117
|
||||
|
||||
CMD ["python3.10", "web_main.py"]
|
||||
@@ -0,0 +1,69 @@
|
||||
# NEGO_AGENT 서버
|
||||
|
||||
협상 에이전트 경량 서버 — 성능지표 측정용. KT 비종속 독립 프로젝트.
|
||||
|
||||
- 아키텍처: prism/backend 패턴 (router/services/common/config)
|
||||
- 엔진 로직: 협상 카드 Q-Table 추론 + 스텝 기반 대화 (학습·DB 경로 없음)
|
||||
- 평가환경: Python 3.10 / Ubuntu 20.04 (Dockerfile) — 로컬 개발은 상위 버전 무방
|
||||
|
||||
## 실행
|
||||
|
||||
```bash
|
||||
# 로컬
|
||||
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
|
||||
.venv/bin/python web_main.py # → http://localhost:53117/docs
|
||||
|
||||
# 테스트
|
||||
.venv/bin/python -m pytest tests/
|
||||
|
||||
# Docker (평가환경 재현: Ubuntu 20.04 + Python 3.10)
|
||||
docker build -t nego-agent .
|
||||
docker run -p 53117:53117 -e OPENAI_API_KEY=sk-... nego-agent
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
| 엔드포인트 | 설명 |
|
||||
|---|---|
|
||||
| `GET /health` | 상태 확인 |
|
||||
| `POST /v1/nego/chat` | 협상 대화 (고정 스텝 + '가격협상' 동적 카드 선택) |
|
||||
| `POST /v1/nego/session/invalidate` | 세션 무효화 — UCB 에피소드 초기화 |
|
||||
| `GET /v1/nego/config` | 서버 설정 상태 (profiling on/off·카드 수 등) |
|
||||
|
||||
## 설정 — `config.toml` 하나 (환경 구분 없음)
|
||||
|
||||
- `[server]` 포트 53117
|
||||
- `[openai]` 모델·API 키 (비우면 `OPENAI_API_KEY` 환경변수)
|
||||
- `[profiling]` N-profiling(LLM 톤 변환) on/off — 요청 body의 `profiling: true/false`로 건별 override. 키가 없으면 자동 비활성으로 기동
|
||||
- `[instrument]` 계측 경로 — 비우면 끔
|
||||
- `tension_log` : ⑩ 예측 긴장도 JSONL (가격협상 진입마다 기록)
|
||||
- `response_time_log` : ⑥ 답변속도 JSONL (/chat 요청·응답 ms)
|
||||
|
||||
## 구조
|
||||
|
||||
```
|
||||
server/
|
||||
├── web_main.py # 진입점
|
||||
├── config.toml # 단일 설정
|
||||
├── config/ # 설정 모델·로더
|
||||
├── common/ # paths·logger·enums·textutil(치환/Hidden 처리)
|
||||
├── router/
|
||||
│ ├── router.py # 앱 조립 + 응답시간 미들웨어
|
||||
│ └── v1/nego/ # protocol(스키마)·chat·admin
|
||||
├── services/
|
||||
│ ├── negotiation/ # engine(ChatEngine)·orchestrator·formatting·indicator·steps·korean
|
||||
│ ├── policy/ # state(162)·q_table·visit_table·ucb·selector·snapshot
|
||||
│ ├── cards/ # repository(JSON)·mapper(action↔card)·completer
|
||||
│ └── profiling/ # ScriptModifier(OpenAI)·ScriptVerifier — on/off
|
||||
├── resources/ # cards/(협상·와일드 카드 정본), scripts/(스텝 스크립트), policy/(q_table·매핑)
|
||||
├── data/ # 런타임 산출 (tension_log·response_time JSONL)
|
||||
└── tests/ # 스모크 테스트
|
||||
```
|
||||
|
||||
## 원본(chat_server) 대비 변경점
|
||||
|
||||
- DB(PostgreSQL/SQLAlchemy)·Q-학습 경로·관리 엔드포인트 제거 — JSON 파일이 유일한 저장소
|
||||
- N-profiling 정상 패키지화(dynamic import 제거), langchain → openai SDK 직접 호출, 평문 입출력
|
||||
- 세션 경계 자동 감지 → UCB 에피소드 초기화 (기존 reset_episode 미호출로 인한 카드 라운드로빈 수정)
|
||||
- 긴장도(TENSION_LOG env)·응답시간 계측을 config 정식 설정으로 내장
|
||||
- KT 지칭 제거 (스크립트 리소스의 브랜딩 문구 중립화 포함)
|
||||
Whitespace-only changes.
@@ -0,0 +1,13 @@
|
||||
"""공용 Enum 정의."""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class IndicatorRangeEnum(str, Enum):
|
||||
PZ1 = "PZ1"
|
||||
PZ2 = "PZ2"
|
||||
PZ3 = "PZ3"
|
||||
|
||||
|
||||
class IndicatorType(str, Enum):
|
||||
PERCENT_DETAIL = "PERCENT_DETAIL"
|
||||
@@ -0,0 +1,25 @@
|
||||
"""로깅 설정 — KST 타임스탬프, 파일 회전 + 콘솔."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
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) -> None:
|
||||
LOGS_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(LOGS_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,49 @@
|
||||
"""스크립트 템플릿 치환 유틸.
|
||||
|
||||
기능정의서 규칙: 값이 없는 변수가 포함된 문장은 Hidden 처리(문장 제거)한다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 미치환 플레이스홀더 탐지: {internet_min_price} 등
|
||||
_PLACEHOLDER_RE = re.compile(r"\{[A-Za-z_][A-Za-z0-9_]*\}")
|
||||
|
||||
|
||||
class _SafeDict(dict):
|
||||
"""format_map용 — 컨텍스트에 없는 키는 {키} 형태로 남긴다 (이후 문장 Hidden 처리)."""
|
||||
|
||||
def __missing__(self, key):
|
||||
return "{" + key + "}"
|
||||
|
||||
|
||||
def safe_format(template: str, context: Dict[str, Any]) -> str:
|
||||
"""플레이스홀더 치환. 알 수 없는 키는 남겨두고 나머지는 정상 치환한다."""
|
||||
try:
|
||||
return template.format_map(_SafeDict(context))
|
||||
except Exception:
|
||||
return template
|
||||
|
||||
|
||||
def hide_unresolved_lines(text: str, source: str = "") -> str:
|
||||
"""미치환 {변수}가 남은 문장을 제거하고 경고를 남긴다."""
|
||||
if "{" not in text:
|
||||
return text
|
||||
kept = []
|
||||
for line in text.split("\n"):
|
||||
unresolved = _PLACEHOLDER_RE.findall(line)
|
||||
if unresolved:
|
||||
logger.warning(
|
||||
f"[textutil] 미치환 변수 {unresolved} — 문장 숨김 ({source}): {line.strip()[:60]}")
|
||||
else:
|
||||
kept.append(line)
|
||||
result = "\n".join(kept)
|
||||
return re.sub(r"\n{3,}", "\n\n", result).strip("\n")
|
||||
|
||||
|
||||
def extract_placeholders(text: str) -> set:
|
||||
"""텍스트에 포함된 {변수} 이름 집합을 반환한다."""
|
||||
return {m[1:-1] for m in _PLACEHOLDER_RE.findall(text)}
|
||||
@@ -0,0 +1,21 @@
|
||||
# NEGO_AGENT 서버 설정 (단일 파일 — 환경 구분 없음)
|
||||
|
||||
[server]
|
||||
name = "NEGO_AGENT"
|
||||
port = 53117
|
||||
host = "0.0.0.0"
|
||||
|
||||
[openai]
|
||||
model = "gpt-4o"
|
||||
# 비워두면 OPENAI_API_KEY 환경변수를 사용한다
|
||||
api_key = "sk-여기에-OpenAI-키"
|
||||
|
||||
[profiling]
|
||||
# N-profiling (LLM 스크립트 톤 변환) 전역 on/off — 요청별 override 가능
|
||||
enabled = true
|
||||
|
||||
[instrument]
|
||||
# 평가 계측 — 경로를 비우면("") 해당 계측을 끈다
|
||||
tension_log = "data/tension_log.jsonl" # ⑩ 예측 긴장도
|
||||
response_time_log = "data/response_time.jsonl" # ⑥ 답변속도
|
||||
contracts_log = "data/contracts.jsonl" # ⑦ 계약 데이터화
|
||||
Whitespace-only changes.
@@ -0,0 +1,31 @@
|
||||
"""config.toml 로더 — 파일이 없으면 기본값으로 기동한다."""
|
||||
|
||||
import os
|
||||
|
||||
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 = SERVER_ROOT / "config.toml"
|
||||
|
||||
|
||||
def load_config() -> AppConfig:
|
||||
if CONFIG_PATH.exists():
|
||||
with open(CONFIG_PATH, "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
config = AppConfig(**raw)
|
||||
else:
|
||||
config = AppConfig()
|
||||
|
||||
# API 키: config 값 → OPENAI_API_KEY 환경변수 순
|
||||
if not config.openai.api_key:
|
||||
config.openai.api_key = os.getenv("OPENAI_API_KEY", "")
|
||||
|
||||
return config
|
||||
|
||||
|
||||
app_config = load_config()
|
||||
@@ -0,0 +1,34 @@
|
||||
"""설정 모델 — config.toml 의 구조를 정의한다."""
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ServerConfig(BaseModel):
|
||||
name: str = "NEGO_AGENT"
|
||||
port: int = 53117
|
||||
host: str = "0.0.0.0"
|
||||
|
||||
|
||||
class OpenAIConfig(BaseModel):
|
||||
model: str = "gpt-4o"
|
||||
# 비워두면 OPENAI_API_KEY 환경변수를 사용한다
|
||||
api_key: str = ""
|
||||
|
||||
|
||||
class ProfilingConfig(BaseModel):
|
||||
"""N-profiling(LLM 스크립트 톤 변환) — 전역 on/off. 요청별 override 가능."""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class InstrumentConfig(BaseModel):
|
||||
"""평가 계측 — 경로를 비우면 해당 계측을 끈다."""
|
||||
tension_log: str = "data/tension_log.jsonl" # ⑩ 예측 긴장도
|
||||
response_time_log: str = "data/response_time.jsonl" # ⑥ 답변속도
|
||||
contracts_log: str = "data/contracts.jsonl" # ⑦ 계약 데이터화
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
server: ServerConfig = ServerConfig()
|
||||
openai: OpenAIConfig = OpenAIConfig()
|
||||
profiling: ProfilingConfig = ProfilingConfig()
|
||||
instrument: InstrumentConfig = InstrumentConfig()
|
||||
@@ -0,0 +1 @@
|
||||
{"ts": "2026-08-31T13:07:21.020561+09:00", "path": "/v1/nego/chat", "status": 200, "ms": 4.67}
|
||||
@@ -0,0 +1,8 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
pydantic>=2.6
|
||||
numpy>=1.26
|
||||
openai>=1.30
|
||||
tomli>=2.0; python_version < "3.11"
|
||||
httpx>=0.27
|
||||
pytest>=8.0
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"cards": [
|
||||
{
|
||||
"card_id": "NC26-007",
|
||||
"card_name": "결제 기한 전략",
|
||||
"script": "당사의 대금 지급 조건은 {payment_terms}입니다.\n우수한 대금 지급 조건은 귀사의 안정적인 현금 흐름 확보에 도움이 됩니다. 해당 대금 지급 조건을 참고하시어 공급 가능하신 단가를 입력해 주시면 감사하겠습니다.\nB2B 거래 조건을 종합적으로 고려하여 공급 가능한 가격을 제안해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-008",
|
||||
"card_name": "대체 공급자의 언급",
|
||||
"script": "해당 품목의 경우 유사 상품까지 고려하여, 약 {alternative_supplier_count}개 이상의 업체에서 관심을 보일 것으로 예상되고 있습니다.\n하지만 지금까지 안정적으로 운영해 온 귀사에 우선적으로 협상을 요청드리며, 귀사와의 협상이 어려운 경우 안타깝지만 경쟁사와 협상을 진행할 수밖에 없음을 양해 부탁드립니다.\n신중히 고려하여 공급 가능하신 가격을 제안해 주시길 부탁드립니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-000",
|
||||
"card_name": "데이터 기반 가격 설정",
|
||||
"script": "당사가 최근 조사한 인터넷 유통 가격 정보를 검토한 결과, \n최근 인터넷 유통 가격은 대략 {internet_min_price}으로, 통상적인 인터넷 유통 수수료(7% 내외)를 고려시 B2C 인터넷 유통 업계의 매입 가격은 {anchoring_price}원으로 확인됩니다.\n\n귀사와 지속적인 파트너쉽을 유지하기를 희망하며, 유통 업계 최저 매입 가격 이하로 입력 하실 경우, 귀사는 우선협상 대상자로서 최우선의 협상 기회를 보장받게 됩니다.\n협상 가능한 가격을 입력하여 제안해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-001",
|
||||
"card_name": "시장 동향 감안, 열린 협상 전략",
|
||||
"script": "현재 협상 중인 품목은 최근 1년간 꾸준한 수요가 있었으며, 귀사를 포함한 유사 업계 전반에서 가격 제안이 활발히 이루어지고 있는 상황입니다. 이러한 흐름을 종합적으로 판단할 때, 향후 수개월 동안 지속적인 구매가 있을 것으로 예상되는 품목입니다.\n\n이에 따라 당사 역시 해당 협상을 통해 경쟁력 있는 단가를 약 1년간은 유지하고자 합니다. 이에 귀사와의 지속적인 협력 관계를 고려할 때, 이번 협상이 상호 실익을 높이는 계기가 되기를 기대하고 있습니다.\n협상 가능한 가격을 입력하여 제안해 주시기 바랍니다"
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-002",
|
||||
"card_name": "경쟁사 비교 전략",
|
||||
"script": "현재 협상 중인 품목은 다른 공급 업체에서 동일한 제품에 대해 {competitor_price_diff}% 낮은 가격을 제안했습니다.\n다만, 귀사는 신뢰를 바탕으로 안정적인 거래 관계를 유지해 온 만큼, 귀사와의 우선적인 협상을 통해 지속적인 거래를 희망합니다.\n\n귀사에서도 이에 맞춰 조정해 주실 수 있을까요? 협상 가능한 가격을 입력하여 제안해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-003",
|
||||
"card_name": "최후 통첩 전략",
|
||||
"script": "합리적인 기준에 근거하여 목표 가격을 제안 드렸으나, 귀사의 기존 제안 가격으로는 긍정적인 합의가 어려울 것으로 예상됩니다.\n이번 협상도 결렬되는 경우 우선 협상권을 보장하기 어려우며, 다른 공급 업체를 선정하기 위한 검토가 진행될 수 있습니다.\n귀사와 앞으로 보다 많은 협력 기회를 만들어 나가기를 희망하며, 다시 고민후 제안 가격을 입력해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-004",
|
||||
"card_name": "공급사 성과 평가 전략",
|
||||
"script": "귀사와는 지난 {trading_period}년간 긴밀한 협력을 이어오며, 함께 의미있는 성장을 이루어 왔습니다. 현재까지 누적 거래 금액은 총 {cumulative_amount}원에 달합니다.\n\n이번 협상 대상 품목의 거래액은 지난 1년간 {item_amount}원으로, 귀사의 총 거래액 중 약 {item_ratio}%를 차지하고 있습니다.\n또한, 해당 기간 동안 VOC 발생건수는 {voc_count}건이었으며, 귀사의 협상 참여 응답율은 {response_rate}%로 기록되었습니다.\n\n귀사의 책임있는 협상 태도와 대응 품질도 본 협상에서 함께 고려하고 있으며, 이러한 데이터 기반 평가 결과를 토대로, 귀사와의 전략적인 파트너쉽 강화를 위한 가격 제안을 기대하고 있습니다.\n협상 가능한 가격을 입력하여 제안해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-005",
|
||||
"card_name": "충성 고객 보상 전략",
|
||||
"script": "해당 품목은 {product_sales_period} 기간 동안 귀사와 신뢰를 바탕으로 안정적인 거래 관계를 유지해 왔습니다.\n\n앞으로도 지속적으로 해당 품목을 운영하기 위하여 가격 협상을 요청합니다. 경쟁력 있는 가격을 제안하여 주신다면 당사도 가급적 귀사와 지속적으로 운영하는 것을 검토할 예정입니다.\n협상 가능한 가격을 제안해 주시기 바랍니다."
|
||||
},
|
||||
{
|
||||
"card_id": "NC26-006",
|
||||
"card_name": "상호 이익 강조 전략",
|
||||
"script": "당사와의 협력이 장기적으로 이어질 경우, 귀사는 안정적인 수요를 확보하실 수 있으며, 이는 양사 모두 긍정적인 시너지 효과가 발생할 것으로 기대하고 있습니다.\n\n이런 장기 파트너십을 고려하여, 당사 목표 가격인 {anchoring_price}원을 수용해 주실 수 있는지 검토해 주시길 부탁드립니다. 귀사의 긍정적인 검토가 이루어진다면, 저희 또한 귀사와의 지속적인 협력을 위해 최선을 다하겠습니다.\n\n상호 신뢰를 바탕으로 양사가 함께 성장해 나갈 수 있기를 기대하며, 긍정적인 제안 가격을 입력해 주시기 바랍니다."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"wild_card_1pct": {
|
||||
"script": "제시해주신 가격에 감사드립니다. 귀사의 적극적인 협조 덕분에 긍정적인 방향으로 검토되고 있습니다. 다만, 내부 승인을 위해 조금 더 명분이 필요한 상황입니다. 여기서 추가로 약 1% 미만 더 인하하여 {offer_1pct}원에 가능하실까요? 이 조건만 수락해 주신다면, 즉시 우선협상 대상자로 선정하여 품의를 올리도록 하겠습니다.",
|
||||
"type": "text",
|
||||
"chat_end": false,
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "협상완료"
|
||||
}
|
||||
},
|
||||
"wild_card_budget": {
|
||||
"script": "솔직히 말씀드리면, 현재 저희 내부 예산(재원)이 부족하여 귀사의 제안을 수용하기 어렵습니다. 저희의 목표 매입가는 {target}원입니다. 이 가격에 맞춰 주신다면 즉시 계약을 진행하고 싶습니다. 마지막으로 제안 부탁드립니다.",
|
||||
"type": "text",
|
||||
"chat_end": false,
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인_버짓"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"action_to_card": {
|
||||
"0": "NC26-007",
|
||||
"1": "NC26-008",
|
||||
"2": "NC26-000",
|
||||
"3": "NC26-001",
|
||||
"4": "NC26-002",
|
||||
"5": "NC26-003",
|
||||
"6": "NC26-004",
|
||||
"7": "NC26-005",
|
||||
"8": "NC26-006"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"시작": "서비스안내",
|
||||
"서비스안내": "서비스안내",
|
||||
"담당자확인": "담당자확인",
|
||||
"담당자확인_아니오": "담당자확인",
|
||||
"정보변경_완료": "담당자확인",
|
||||
"협상품목안내": "협상품목안내",
|
||||
"기존가격제시": "가격협상",
|
||||
"가격협상": "가격협상",
|
||||
"가격협상_입력": "가격협상",
|
||||
"가격협상_확인": "가격협상",
|
||||
"가격협상_재입력": "가격협상",
|
||||
"가격협상_확인_버짓": "가격협상",
|
||||
"협상완료": "협상종료",
|
||||
"협상실패": "협상종료",
|
||||
"협상종료": "협상종료"
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
{
|
||||
"시작": {
|
||||
"script": "",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "서비스안내"
|
||||
},
|
||||
"type": "null",
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. NEGO 협상 에이전트 입니다. 본 서비스는 당사와 협력사 간의 물품 공급 협상을 목적으로 하며, 귀사가 공급 중인 품목에 대해 새로운 가격 협상을 진행하고자 합니다. 협상 시작에 앞서 안내사항을 참조하여 주시기 바랍니다. [협상 유의 사항 및 서비스 이용 방법 안내]를 읽고 내용을 모두 숙지하고 이해하셨으면, 사용자 정보 확인 후 가격 협상을 진행 하겠습니다. 다음 절차로 넘어가길 원하시면 [확인]을 눌러 주세요.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"확인"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "담당자확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자 이메일 주소로 발송되었습니다. 다시 한번 구매 협상 담당자가 맞는지 확인을 부탁 드립니다. 만약 구매 협상 담당자가 아님에도 협상에 참여할 경우 불이익이 발생될 수 있으니 주의 부탁 드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택하여 주시고, [아니오]를 선택한 경우 반드시 당사의 협력사 관리 시스템에 등록된 담당자 정보를 갱신하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "협상품목안내",
|
||||
"아니오": "담당자확인_아니오"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인_아니오": {
|
||||
"script": "[아니오]를 선택하여 주셨습니다. 담당자가 변경되어 정보를 변경하시려면 [정보변경]을, 만약 실수로 [아니오]를 선택한 경우 다시 협상 진행 과정으로 돌아가시려면 [돌아가기]를 선택해주세요.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"돌아가기",
|
||||
"정보변경"
|
||||
],
|
||||
"next_step": {
|
||||
"돌아가기": "담당자확인",
|
||||
"정보변경": "정보변경_완료"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]를 선택하여 주셨습니다. 본 안내에 따라 당사 협력사 관리 시스템에 로그인하여 담당자 정보를 변경하여 주시기 바랍니다. 정보 변경 후, 당사 고객센터로 새로운 견적 생성 요청해주시기 바랍니다. 다음 절차에 따라 기존 통합플랫폼 협력사 페이지에서 담당자 정보를 변경해주시기 바랍니다. '협력사 관리 > 담당자 관리 > 대표 담당자 변경' 만약 24시간 이내에 갱신되지 않는 경우 참여 의사가 없는 것으로 간주되어, 해당 견적 건을 참여하지 않은 것으로 처리될 수 있습니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": null,
|
||||
"type": "text",
|
||||
"chat_end": true
|
||||
},
|
||||
"협상품목안내": {
|
||||
"script": "당사는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 가격 협상을 위한 기본 정보를 다음과 같이 안내해 드립니다. [협상 품목 상세 안내] 좌측의 상품정보를 확인하여 주시기 바랍니다. 본 협상이 성공적으로 마무리 되면, 귀사와 보다 많은 협력 기회가 마련될 것입니다. 다만, 협상이 모두를 만족시킬지 못할 경우, 해당 품목의 거래 유지가 어려울 수도 있습니다.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"확인"
|
||||
],
|
||||
"next_step": {
|
||||
"확인": "기존가격제시"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"기존가격제시": {
|
||||
"script": "이제 본격적인 가격 협상을 진행합니다. 안내해 드린 품목에 대한 기존 가격 확인 후 제시 가능한 금액을 직접 입력하여 주시기 바랍니다. 기존 가격 : {item_price}원 {vat}",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_재입력": {
|
||||
"script": "[아니오]를 선택하여 주셨습니다. 입력과정에서 실수가 있었다면, 다시 수정된 가격을 입력하여 주시기 바랍니다.",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_확인": {
|
||||
"script": "귀사가 제시한 할인율은 약 {discount_rate}% 미만이며, 기존 공급가격에 제시 할인율을 적용하면 {input}원 ({input_kr}원 / VAT별도)입니다. 해당 금액으로 견적을 제출하고자 하면 [예], 아니면 [아니오]를 눌러 주시고 [아니오]를 누른 경우 다시 수정된 할인율을 입력하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": [
|
||||
{
|
||||
"condition": "check_wildcard_entry",
|
||||
"next": "가격협상_와일드"
|
||||
},
|
||||
{
|
||||
"condition": "check_is_supplier_type_c",
|
||||
"next": "협상완료"
|
||||
},
|
||||
{
|
||||
"condition": "check_price_match",
|
||||
"next": "협상완료"
|
||||
},
|
||||
{
|
||||
"condition": "check_iteration_limit",
|
||||
"next": "협상실패"
|
||||
},
|
||||
{
|
||||
"condition": "default",
|
||||
"next": "가격협상"
|
||||
}
|
||||
],
|
||||
"아니오": "가격협상_재입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_확인_버짓": {
|
||||
"script": "귀사가 제시한 금액은 {input}원이며 해당 금액으로 견적을 제출하고자 하면 [예], 아니면 [아니오]를 눌러 주시고 [아니오]를 누른 경우 다시 수정된 금액을 입력하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "협상완료",
|
||||
"아니오": "가격협상_재입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상": {
|
||||
"script": "",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"type": "indicator",
|
||||
"chat_end": false
|
||||
},
|
||||
"협상완료": {
|
||||
"script": "귀중한 시간을 내어 협상에 응해 주셔서 진심으로 감사드리며, 협조해 주신 덕분에 원만히 협상이 완료되었습니다. 이에 협상 결과를 간단히 요약하여 아래와 같이 전달 드립니다. 소액 거래 약정에 의거, 약간의 가격 조정을 요청 드릴 수도 있으며, 고객사의 수요 변동 등의 요인으로 판매 수량을 보장할 수 없는 점은 참고하여 주시기 바랍니다. 다시 한 번 협상에 성실히 응해 주신 점 감사드리며, 함께 성장해 나가는 당사가 되도록 노력하겠습니다. 감사합니다.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."
|
||||
],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"type": "summaryRSP",
|
||||
"chat_end": false
|
||||
},
|
||||
"협상실패": {
|
||||
"script": "소중한 시간 협조하여 주셔서 감사합니다. 안타깝게도 여러 차례 협상을 진행하였으나, 귀사의 제안은 우리의 기준을 충족하지 못하였습니다. 이에 따라 해당 품목의 거래는 중단될 수 있음을 알려 드립니다. 최종적인 희망 공급가격을 제시하여 주시기 바라며, 견적제출로 반영되니 참고 부탁드립니다. 제안가격을 수용할 수 없는 사유 또한 선택해주시면, 소싱담당자가 거래지속여부 등을 검토하여 최종 판단하겠습니다. 감사합니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"type": "rejectRSP",
|
||||
"chat_end": false
|
||||
},
|
||||
"협상종료": {
|
||||
"script": "지금까지 NEGO 협상 에이전트를 통해 협상에 참여해주셔서 감사합니다. 협상이 종료되었습니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": null,
|
||||
"type": "text",
|
||||
"chat_end": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
{
|
||||
"시작": {
|
||||
"script": "",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "서비스안내"
|
||||
},
|
||||
"type": "null",
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. NEGO 협상 에이전트입니다.\n\n본 서비스는 당사와 협력사 간의 물품 공급 협상을 목적으로 하며, 귀사에 새로운 공급 기회를 제공하여 양사 간의 협력을 확대하고 강화하고자 합니다.\n\n상세한 내용을 전달하기 전에 서비스 이용 방법을 우선 안내해 드리니 확인하여 주시기 바랍니다.\n\n[협상 유의 사항 및 서비스 이용 방법 안내]를 읽고 내용을 모두 숙지하고 이해하셨으면,\n이용자 정보 확인 후 신규 공급사 선정을 위한 절차를 진행하도록 하겠습니다.\n\n다음 절차로 넘어가길 원하시면 [확인]을 눌러 주세요.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"확인"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "담당자확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자 이메일 주소로 발송되었습니다. \n다시 한번 구매 협상 담당자가 맞는지 확인을 부탁 드립니다. \n\n만약 구매 협상 담당자가 아님에도 협상에 참여할 경우 불이익이 발생될 수 있으니 주의 부탁 드립니다. \n\n담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택하여 주시고,\n[아니오]를 선택한 경우 반드시 당사의 협력사 관리 시스템에 등록된 담당자 정보를 갱신하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "협상품목안내",
|
||||
"아니오": "담당자확인_아니오"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인_아니오": {
|
||||
"script": "[아니오]를 선택하여 주셨습니다.\n담당자가 변경되어 정보를 변경하시려면 [정보변경]을, 만약 실수로 [아니오]를 선택한 경우 다시 협상 진행 과정으로 돌아가시려면 [돌아가기]를 선택해주세요.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"돌아가기",
|
||||
"정보변경"
|
||||
],
|
||||
"next_step": {
|
||||
"돌아가기": "담당자확인",
|
||||
"정보변경": "정보변경_완료"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]를 선택하여 주셨습니다. 본 안내에 따라 당사 협력사 관리 시스템에 로그인하여 담당자 정보를 변경하여 주시기 바랍니다. 정보 변경 후, 당사 고객센터로 새로운 견적 생성 요청해주시기 바랍니다. 다음 절차에 따라 기존 통합플랫폼 협력사 페이지에서 담당자 정보를 변경해주시기 바랍니다. '협력사 관리 > 담당자 관리 > 대표 담당자 변경' 만약 24시간 이내에 갱신되지 않는 경우 참여 의사가 없는 것으로 간주되어, 해당 견적 건을 참여하지 않은 것으로 처리될 수 있습니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": null,
|
||||
"type": "text",
|
||||
"chat_end": true
|
||||
},
|
||||
"협상품목안내": {
|
||||
"script": "당사는 아래 상품에 대해 신규 공급 업체를 선정 하고 있으며, 귀사를 초대하여 새로운 사업 협력 기회를 제공하고자 견적을 요청 드립니다.\n\n제출된 견적은 복수 이상의 업체와 비교 평가를 통해 공급사 선정에 반영될 예정입니다. 제출된 견적만으로 거래를 보장하는 것은 아니며, 귀사와의 협상 과정은 기록, 저장되는 점을 알려 드립니다.\n\n[견적 대상 품목 안내]\n\n상품 정보를 확인해 주시길 바랍니다.\n최근 1년간 귀사와의 거래 규모는 증가 추세에 있습니다.\n이번 새로운 기회를 통해 보다 많은 협력 기반을 마련하고 함께 성장해 나갈 수 있는 최고의 파트너가 되길 희망합니다.\n경쟁력 있는 견적을 제안 부탁 드립니다.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"네, 알겠습니다."
|
||||
],
|
||||
"next_step": {
|
||||
"default": "가격제안"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격제안": {
|
||||
"script": "견적 요청 물품은 최근 시장 동향을 분석한 결과, 적정 공급 가격은 {target}원{vat}입니다.\n\n제시된 가격에 동의하는 경우, 우선 협력 기회를 부여할 예정입니다.\n다만, 본 협상은 복수 이상의 업체를 대상으로 동시에 진행되며, 제시 가격에 동의하는 업체가 복수 이상인 경우 동의한 업체에 한정하여 추가 경쟁이 진행될 수 있습니다.\n\n제시한 가격에 동의하시겠습니까? 동의하는 경우 [예] 동의하지 않는 경우 [아니오]를 선택하여 주십시오.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "배송형태선택",
|
||||
"아니오": "협상실패"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"협상실패": {
|
||||
"script": "소중한 시간 협조하여 주셔서 감사합니다. 안타깝게도 여러 차례 협상을 진행하였으나, 귀사의 제안은 우리의 기준을 충족하지 못하였습니다. 이에 따라 해당 품목의 거래는 중단될 수 있음을 알려 드립니다. 최종적인 희망 공급가격을 제시하여 주시기 바라며, 견적제출로 반영되니 참고 부탁드립니다. 제안가격을 수용할 수 없는 사유 또한 선택해주시면, 소싱담당자가 거래지속여부 등을 검토하여 최종 판단하겠습니다. 감사합니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"type": "rejectCM",
|
||||
"chat_end": false
|
||||
},
|
||||
"배송형태선택": {
|
||||
"script": "원하시는 배송형태를 선택해주세요. (협력사배송, 지정택배배송, 픽업배송)",
|
||||
"next_input_mode": "delivery_type",
|
||||
"input_options": [
|
||||
"협력사배송",
|
||||
"지정택배배송",
|
||||
"픽업배송"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "가격협상_입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_입력": {
|
||||
"script": "당사의 제안 가격에 동의해 주신 점 감사합니다.\n\n지금부터 당사의 제안 가격에 동의한 업체에 한정하여 가격 경쟁을 진행합니다.\n{deadline}까지 가격 제안을 요청드립니다.\n\n동일 가격을 제안하는 업체가 있는 경우, 해당 업체에 한정하여 추가 경쟁을 진행할 수 있음을 알려 드립니다. 제안하고자 하는 가격을 입력하여 주시기 바랍니다.",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_확인": {
|
||||
"script": "귀사께서 투찰하신 금액은 {input}원{vat}입니다.\n\n해당 금액이 맞다면 [예] 수정을 원하시면 [아니오]를 선택하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "추가할인요청",
|
||||
"아니오": "가격재입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격재입력": {
|
||||
"script": "[아니오]를 선택하여 주셨습니다.\n입력과정에서 실수가 있었다면, 다시 수정된 가격을 입력하여 주시기 바랍니다.",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"추가할인요청": {
|
||||
"script": "귀중한 시간을 내어 협상에 응해 주셔서 진심으로 감사합니다.\n귀사와의 파트너쉽을 소중하게 생각하며, 동반성장을 희망합니다.\n\n이에 약 1% 미만의 추가 가격 인하 제안을 드리며, 동의여부에 따라 우선협상 대상자가 달라질 수 있으니 협상에 신중을 더해주시기 바랍니다.\n해당 제안에 동의하는 경우 최종 투찰가격({offer_1pct}원{vat})으로 확정됩니다.\n\n동의하시는 경우 [예], 동의하지 않은 경우 [아니오]를 선택하여 주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "결과안내"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"결과안내": {
|
||||
"script": "귀사의 투찰 결과를 안내드립니다.\n아래 내용을 확인하시고 수정이 필요하신 부분은 수정 후 최종 결과를 제출해주시기 바랍니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"투찰확정",
|
||||
"정보수정"
|
||||
],
|
||||
"next_step": {
|
||||
"투찰확정": "결과제출",
|
||||
"정보수정": "가격제안"
|
||||
},
|
||||
"type": "summaryCM",
|
||||
"chat_end": false
|
||||
},
|
||||
"결과제출": {
|
||||
"script": "귀사의 투찰 가격이 확정되었습니다.\n\n아직 다른 경쟁업체들의 가격 투찰이 진행중입니다.\n견적이 마감된 후 가격을 비교하여 낙찰대상자를 선정하고 결과를 통보해드릴 예정입니다.\n다시 한 번 본 견적에 참여해주셔서 감사합니다.",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."
|
||||
],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"type": "summaryCM",
|
||||
"chat_end": false
|
||||
},
|
||||
"협상종료": {
|
||||
"script": "지금까지 NEGO 협상 에이전트를 통해 협상에 참여해주셔서 감사합니다. 협상이 종료되었습니다.",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": null,
|
||||
"type": "text",
|
||||
"chat_end": true
|
||||
}
|
||||
}
|
||||
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()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(
|
||||
title=f"{app_config.server.name} Negotiation Service",
|
||||
description="협상 에이전트 경량 서버 — 성능지표 측정용",
|
||||
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"):
|
||||
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:
|
||||
pass
|
||||
|
||||
return response
|
||||
|
||||
|
||||
# 엔진 초기화 (라우터 import보다 먼저 — 엔드포인트가 app.state.engine을 사용)
|
||||
from services.negotiation.engine import ChatEngine # noqa: E402
|
||||
|
||||
app.state.config = app_config
|
||||
app.state.engine = ChatEngine(app_config)
|
||||
logger.info(f"[startup] engine ready — cards={app.state.engine.card_script_repo.count()}, "
|
||||
f"profiling={'on' if app.state.engine.profiler else 'off'}")
|
||||
|
||||
from router.v1.nego import admin, chat # noqa: E402
|
||||
|
||||
app.include_router(admin.router)
|
||||
app.include_router(chat.router)
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,33 @@
|
||||
"""상태 확인 엔드포인트."""
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from router.v1.nego.protocol import HealthResponse
|
||||
|
||||
router = APIRouter(tags=["admin"])
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
async def health_check():
|
||||
return HealthResponse(status="OK", message="NEGO_AGENT server is running")
|
||||
|
||||
|
||||
@router.get("/v1/nego/config")
|
||||
async def get_config(request: Request):
|
||||
"""현재 서버 설정 상태 — profiling on/off, 계측 경로 등."""
|
||||
config = request.app.state.config
|
||||
engine = request.app.state.engine
|
||||
return {
|
||||
"server": config.server.name,
|
||||
"port": config.server.port,
|
||||
"profiling": {
|
||||
"enabled": config.profiling.enabled,
|
||||
"active": engine.profiler is not None,
|
||||
"model": config.openai.model,
|
||||
},
|
||||
"instrument": {
|
||||
"tension_log": config.instrument.tension_log,
|
||||
"response_time_log": config.instrument.response_time_log,
|
||||
},
|
||||
"cards": engine.card_script_repo.count(),
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""협상 챗 엔드포인트."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from router.v1.nego.protocol import (
|
||||
NegotiationRequest,
|
||||
NegotiationResponse,
|
||||
SessionInvalidateRequest,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/v1/nego", tags=["nego"])
|
||||
|
||||
|
||||
@router.post("/chat", response_model=NegotiationResponse)
|
||||
async def chat(body: NegotiationRequest, request: Request):
|
||||
"""협상 대화 처리 — 고정 스텝 스크립트 + '가격협상' 동적 카드 선택."""
|
||||
engine = request.app.state.engine
|
||||
|
||||
logger.info(f"[API_REQ] {json.dumps(body.model_dump(), ensure_ascii=False, default=str)}")
|
||||
response = engine.process_request(body)
|
||||
logger.info(f"[API_RES] step={response.step} chat_end={response.chat_end}")
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/session/invalidate")
|
||||
async def invalidate_session(body: SessionInvalidateRequest, request: Request):
|
||||
"""세션 무효화 — 해당 세션의 UCB 에피소드 상태를 초기화한다."""
|
||||
engine = request.app.state.engine
|
||||
engine.reset_episode(body.session_id)
|
||||
logger.info(f"[API] session invalidate: session_id={body.session_id}, "
|
||||
f"reason={body.reason}")
|
||||
return {"status": "ok", "session_id": body.session_id}
|
||||
@@ -0,0 +1,103 @@
|
||||
"""협상 API 프로토콜 — 요청/응답 스키마."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import IndicatorRangeEnum
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
message: str
|
||||
|
||||
|
||||
class NegotiationCardData(BaseModel):
|
||||
"""협상 카드 스크립트 치환에 쓰이는 실데이터."""
|
||||
|
||||
internet_min_price: Optional[int] = None # 인터넷 최저가
|
||||
anchoring_price: Optional[int] = None # 앵커링 가격 (목표 매입가 등)
|
||||
competitor_price_diff: Optional[float] = None # 경쟁사 가격 차이 (%)
|
||||
trading_period: Optional[int] = None # 거래 기간 (년)
|
||||
cumulative_amount: Optional[int] = None # 누적 거래 금액
|
||||
supplier_ranking: Optional[float] = None # 공급사 순위
|
||||
item_amount: Optional[int] = None # 해당 품목 거래액 (최근 1년)
|
||||
item_ratio: Optional[float] = None # 전체 거래 중 해당 품목 비중 (%)
|
||||
voc_count: Optional[int] = None # VOC(고객 불만) 발생 건수
|
||||
response_rate: Optional[float] = None # 협상 참여 응답률 (%)
|
||||
product_sales_period: Optional[str] = None # 상품 판매 기간
|
||||
payment_terms: Optional[str] = None # 대금 지급 조건
|
||||
alternative_supplier_count: Optional[int] = None # 대체 공급 가능 업체 수
|
||||
|
||||
|
||||
class NegotiationRequest(BaseModel):
|
||||
rq_type: str # "재협상" | "재견적"
|
||||
index: int
|
||||
step: str
|
||||
user_input: Optional[str] = None
|
||||
item_price: Optional[float] = None
|
||||
session_id: Optional[str] = None
|
||||
|
||||
# 협상 스냅샷 ('가격협상' 단계 필수)
|
||||
revenue: Optional[float] = None
|
||||
dist: Optional[str] = None # "M" | "W" | "R"
|
||||
partners_yn: Optional[str] = None # "다수" | "단독" | "없음"
|
||||
partners: Optional[int] = None
|
||||
anchor: Optional[float] = None
|
||||
target: Optional[float] = None
|
||||
input: Optional[float] = None
|
||||
initial: Optional[float] = None
|
||||
excluded_cards: Optional[list] = None
|
||||
iteration: Optional[int] = 0
|
||||
deadline: Optional[str] = None
|
||||
vat: Optional[str] = None
|
||||
|
||||
# 협상 카드 실데이터
|
||||
card_data: Optional[NegotiationCardData] = None
|
||||
mbti: Optional[str] = None # 상대 성향 (profiling 컨텍스트)
|
||||
|
||||
# 신규견적 식별 (True면 UCB 정책 격리 — 방문수 미증가, argmax 사용)
|
||||
is_new_quote: bool = False
|
||||
|
||||
# N-profiling 요청별 override (None이면 서버 설정을 따름)
|
||||
profiling: Optional[bool] = None
|
||||
|
||||
|
||||
class ChatMetadata(BaseModel):
|
||||
card_id: Optional[str] = None
|
||||
q_value: Optional[float] = None
|
||||
visit_count: Optional[int] = None
|
||||
|
||||
# 가격 지표
|
||||
indicator_value: Optional[int] = None
|
||||
indicator_range: Optional[IndicatorRangeEnum] = None
|
||||
|
||||
# 현재 협상 가격 (1% 와일드카드 등 최종가 포함)
|
||||
price: Optional[float] = None
|
||||
|
||||
# ⑩ 계측 노출 (시연·계기판용)
|
||||
tension: Optional[float] = None
|
||||
persona: Optional[str] = None
|
||||
|
||||
iteration: Optional[int] = 0
|
||||
|
||||
# 카드 실데이터 (Request에서 전파)
|
||||
card_data: Optional[NegotiationCardData] = None
|
||||
|
||||
|
||||
class NegotiationResponse(BaseModel):
|
||||
index: int
|
||||
sender: str = "bot"
|
||||
type: str = "text"
|
||||
script: str
|
||||
chat_end: bool = False
|
||||
next_input_mode: str
|
||||
input_options: Optional[list] = None
|
||||
step: str
|
||||
client_step: Optional[str] = None
|
||||
chat_metadata: Optional[ChatMetadata] = None
|
||||
|
||||
|
||||
class SessionInvalidateRequest(BaseModel):
|
||||
session_id: str
|
||||
reason: Optional[str] = "세션종료"
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,40 @@
|
||||
"""협상 카드 스크립트 완성 — 템플릿 + card_data 치환."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from common.textutil import hide_unresolved_lines, safe_format
|
||||
from router.v1.nego.protocol import NegotiationCardData
|
||||
from services.cards.repository import CardScriptRepository
|
||||
|
||||
|
||||
class CardScriptCompleter:
|
||||
"""
|
||||
1. Repository에서 카드 스크립트 템플릿을 가져온다.
|
||||
2. 입력받은 CardData로 템플릿을 완성한다.
|
||||
3. 값이 없는 변수가 포함된 문장은 숨긴다.
|
||||
"""
|
||||
|
||||
def __init__(self, repository: CardScriptRepository):
|
||||
self.repository = repository
|
||||
|
||||
def execute(self, card_id: str,
|
||||
card_data: Optional[NegotiationCardData] = None) -> Optional[str]:
|
||||
card = self.repository.find_by_id(card_id)
|
||||
if not card:
|
||||
return None
|
||||
|
||||
raw_script = card.get("script", "")
|
||||
|
||||
# 컨텍스트 구성 — None 값 제외, 숫자는 천단위 콤마
|
||||
context = {}
|
||||
if card_data is not None:
|
||||
for k, v in card_data.model_dump().items():
|
||||
if v is None:
|
||||
continue
|
||||
# 경쟁사 가격차는 최소 1% 표기 (0.x% 압박은 무의미)
|
||||
if k == "competitor_price_diff" and isinstance(v, (int, float)) and v < 1:
|
||||
v = 1
|
||||
context[k] = f"{v:,.0f}" if isinstance(v, (int, float)) else str(v)
|
||||
|
||||
completed = safe_format(raw_script, context)
|
||||
return hide_unresolved_lines(completed, source=card_id)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Action-Card 매핑 — Q-Table action_id ↔ 협상 카드 card_id."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
|
||||
|
||||
class ActionCardMapper:
|
||||
"""
|
||||
action_id (0, 1, 2, ...) ↔ card_id ("NC26-000", ...)
|
||||
|
||||
Q_Table은 추상적인 action_id만 다루고, 카드 저장소는 card_id만 다룬다.
|
||||
매핑은 resources/policy/action_card_mapping.json 에서 로드된다.
|
||||
"""
|
||||
|
||||
def __init__(self, mapping_file: Optional[str] = None):
|
||||
if mapping_file is None:
|
||||
mapping_file = RESOURCES_DIR / "policy" / "action_card_mapping.json"
|
||||
|
||||
self.mapping_file = Path(mapping_file)
|
||||
self.action_to_card: Dict[int, str] = {}
|
||||
self.card_to_action: Dict[str, int] = {}
|
||||
self._load_mapping()
|
||||
|
||||
def _load_mapping(self):
|
||||
if not self.mapping_file.exists():
|
||||
raise FileNotFoundError(f"Mapping file not found: {self.mapping_file}")
|
||||
|
||||
with open(self.mapping_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
self.action_to_card = {int(k): v for k, v in data["action_to_card"].items()}
|
||||
self.card_to_action = {v: int(k) for k, v in data["action_to_card"].items()}
|
||||
|
||||
def get_card_id(self, action_id: int) -> Optional[str]:
|
||||
return self.action_to_card.get(action_id)
|
||||
|
||||
def get_action_id(self, card_id: str) -> Optional[int]:
|
||||
return self.card_to_action.get(card_id)
|
||||
|
||||
def get_action_space_size(self) -> int:
|
||||
return len(self.action_to_card)
|
||||
|
||||
def get_all_card_ids(self) -> list:
|
||||
return [self.action_to_card[i] for i in sorted(self.action_to_card.keys())]
|
||||
|
||||
def reload(self):
|
||||
self._load_mapping()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"ActionCardMapper(action_space_size={self.get_action_space_size()}, "
|
||||
f"mapping_file={self.mapping_file})"
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""협상 카드 스크립트 Repository — JSON 파일 기반 (DB 없음)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
|
||||
|
||||
class CardScriptRepository:
|
||||
"""협상 카드 스크립트를 resources/cards/nego_card.json 에서 관리한다."""
|
||||
|
||||
def __init__(self, json_file_path: Optional[str] = None):
|
||||
if json_file_path is None:
|
||||
json_file_path = RESOURCES_DIR / "cards" / "nego_card.json"
|
||||
self.json_file_path = Path(json_file_path)
|
||||
self._ensure_file_exists()
|
||||
|
||||
def _ensure_file_exists(self):
|
||||
if not self.json_file_path.exists():
|
||||
self.json_file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._save_to_file({"cards": []})
|
||||
|
||||
def _load_from_file(self) -> Dict:
|
||||
with open(self.json_file_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def _save_to_file(self, data: Dict):
|
||||
with open(self.json_file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
def find_all(self) -> List[Dict]:
|
||||
return self._load_from_file().get("cards", [])
|
||||
|
||||
def find_by_id(self, card_id: str) -> Optional[Dict]:
|
||||
for card in self.find_all():
|
||||
if card.get("card_id") == card_id:
|
||||
return card
|
||||
return None
|
||||
|
||||
def exists(self, card_id: str) -> bool:
|
||||
return self.find_by_id(card_id) is not None
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self.find_all())
|
||||
Whitespace-only changes.
@@ -0,0 +1,578 @@
|
||||
"""ChatEngine — 스텝 기반 협상 대화 엔진.
|
||||
|
||||
고정 스텝은 스크립트 JSON, 동적 스텝('가격협상')은 Q-Table 카드 선택으로 처리한다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from common.paths import RESOURCES_DIR, resolve_data_path
|
||||
from config.config_models import AppConfig
|
||||
from router.v1.nego.protocol import (
|
||||
ChatMetadata,
|
||||
NegotiationRequest,
|
||||
NegotiationResponse,
|
||||
)
|
||||
from services.cards.completer import CardScriptCompleter
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from services.negotiation.formatting import ScriptFormatter
|
||||
from services.negotiation.indicator import ThreeSegIndicator
|
||||
from services.negotiation.orchestrator import NegotiationOrchestrator
|
||||
from services.negotiation.steps import StepActionHandler
|
||||
from services.negotiation.tension import estimate_tension, select_persona
|
||||
from services.policy.snapshot import NegotiationSnapshot, build_state
|
||||
from services.profiling import build_profiler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCRIPTS_DIR = RESOURCES_DIR / "scripts"
|
||||
MAX_ITERATION = 5
|
||||
|
||||
|
||||
class ChatEngine:
|
||||
def __init__(self, config: AppConfig):
|
||||
self.config = config
|
||||
self.orchestrator = NegotiationOrchestrator()
|
||||
self.card_script_repo = CardScriptRepository()
|
||||
self.script_formatter = ScriptFormatter(self.card_script_repo)
|
||||
self.indicator_calculator = ThreeSegIndicator()
|
||||
self.step_action_handler = StepActionHandler()
|
||||
self.completer = CardScriptCompleter(self.card_script_repo)
|
||||
self.scripts = self._load_scripts()
|
||||
|
||||
# N-profiling (on/off) — 비활성/키 없음이면 None
|
||||
self.profiler = build_profiler(
|
||||
api_key=config.openai.api_key,
|
||||
model=config.openai.model,
|
||||
enabled=config.profiling.enabled,
|
||||
)
|
||||
|
||||
# 긴장도 계측 경로 (빈 문자열이면 끔)
|
||||
self._tension_log_path: Optional[Path] = None
|
||||
if config.instrument.tension_log:
|
||||
self._tension_log_path = resolve_data_path(config.instrument.tension_log)
|
||||
self._tension_log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ⑦ 계약 데이터화 경로 (빈 문자열이면 끔)
|
||||
self._contracts_log_path: Optional[Path] = None
|
||||
if config.instrument.contracts_log:
|
||||
self._contracts_log_path = resolve_data_path(config.instrument.contracts_log)
|
||||
self._contracts_log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 세션 경계 감지용 — 세션이 바뀌면 UCB 에피소드 초기화
|
||||
self._last_session_id: Optional[str] = None
|
||||
|
||||
# ------------------------------------------------------------------ setup
|
||||
|
||||
def reload_scripts(self):
|
||||
self.script_formatter.reload()
|
||||
self.scripts = self._load_scripts()
|
||||
|
||||
def _load_scripts(self) -> dict:
|
||||
scripts = {}
|
||||
config_map = {
|
||||
"재협상": "scripts_renegotiation.json",
|
||||
"재견적": "scripts_requote.json",
|
||||
}
|
||||
for rq_type, filename in config_map.items():
|
||||
path = SCRIPTS_DIR / filename
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
scripts[rq_type] = json.load(f)
|
||||
except FileNotFoundError:
|
||||
logger.warning(f"{filename} not found at {path}")
|
||||
scripts[rq_type] = {}
|
||||
|
||||
# 와일드카드 스크립트 로드 후 '재협상'에 병합 (직접 전이 허용)
|
||||
wildcard_path = RESOURCES_DIR / "cards" / "wild_card.json"
|
||||
try:
|
||||
with open(wildcard_path, "r", encoding="utf-8") as f:
|
||||
self.wildcard_scripts = json.load(f)
|
||||
except FileNotFoundError:
|
||||
logger.warning(f"wild_card.json not found at {wildcard_path}")
|
||||
self.wildcard_scripts = {}
|
||||
|
||||
if "재협상" in scripts:
|
||||
for card_id, config in self.wildcard_scripts.items():
|
||||
scripts["재협상"][card_id] = config
|
||||
|
||||
mapping_path = SCRIPTS_DIR / "client_step_mapping.json"
|
||||
try:
|
||||
with open(mapping_path, "r", encoding="utf-8") as f:
|
||||
self.client_step_mapping = json.load(f)
|
||||
except FileNotFoundError:
|
||||
logger.warning(f"client_step_mapping.json not found at {mapping_path}")
|
||||
self.client_step_mapping = {}
|
||||
|
||||
return scripts
|
||||
|
||||
def _get_client_step(self, internal_step: str) -> str:
|
||||
if internal_step in self.client_step_mapping:
|
||||
return self.client_step_mapping[internal_step]
|
||||
# 협상 카드류(no_*, wild_*)는 모두 '가격협상' 소속
|
||||
if internal_step.startswith("no_") or internal_step.startswith("wild_"):
|
||||
return "가격협상"
|
||||
return "가격협상"
|
||||
|
||||
# ---------------------------------------------------------------- session
|
||||
|
||||
def reset_episode(self, session_id: Optional[str] = None):
|
||||
"""협상 세션 경계에서 UCB 에피소드 상태 초기화"""
|
||||
self.orchestrator.reset_episode()
|
||||
logger.info(f"[ChatEngine] episode reset (session={session_id})")
|
||||
|
||||
def _check_session_boundary(self, request: NegotiationRequest):
|
||||
"""세션이 바뀌면 에피소드를 자동 초기화한다 (카드 라운드로빈 방지)."""
|
||||
if request.session_id and request.session_id != self._last_session_id:
|
||||
if self._last_session_id is not None:
|
||||
self.reset_episode(request.session_id)
|
||||
self._last_session_id = request.session_id
|
||||
|
||||
# ------------------------------------------------------------------ main
|
||||
|
||||
def process_request(self, request: NegotiationRequest) -> NegotiationResponse:
|
||||
self._check_session_boundary(request)
|
||||
|
||||
rq_type = request.rq_type
|
||||
current_scripts = self.scripts.get(rq_type, self.scripts.get("재협상", {}))
|
||||
|
||||
step = request.step
|
||||
step_config = current_scripts.get(step)
|
||||
|
||||
if not step_config:
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
script=f"해당 단계({step})에 대한 정의가 없습니다. (Type: {rq_type})",
|
||||
step=step,
|
||||
client_step=self._get_client_step(step),
|
||||
next_input_mode="null",
|
||||
sender="bot",
|
||||
type="text",
|
||||
chat_end=True,
|
||||
input_options=[],
|
||||
)
|
||||
|
||||
next_step = self._resolve_next_step(step_config.get("next_step", ""), request)
|
||||
next_step_config = current_scripts.get(next_step)
|
||||
|
||||
if next_step == "가격협상":
|
||||
response = self._handle_dynamic_step(request, step_config, next_step)
|
||||
else:
|
||||
response = self._handle_fixed_step(request, next_step, next_step_config)
|
||||
|
||||
# 스텝 후처리 (재견적 1% 할인 등)
|
||||
self.step_action_handler.execute_post_step_actions(request, response)
|
||||
|
||||
# 1% 와일드카드 최종가 주입
|
||||
if request.step == "wild_card_1pct" and response.step == "협상완료":
|
||||
try:
|
||||
input_price = float(request.input or 0)
|
||||
if response.chat_metadata is None:
|
||||
response.chat_metadata = ChatMetadata()
|
||||
if request.user_input == "예":
|
||||
response.chat_metadata.price = math.floor(input_price * 0.99)
|
||||
else:
|
||||
response.chat_metadata.price = int(input_price)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 가격 전파 — 핸들러가 안 채웠으면 요청의 현재가를 채운다
|
||||
if response.chat_metadata is None:
|
||||
response.chat_metadata = ChatMetadata()
|
||||
if response.chat_metadata.price is None and request.input is not None:
|
||||
try:
|
||||
response.chat_metadata.price = float(request.input)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 카드 데이터 전파
|
||||
if request.card_data:
|
||||
response.chat_metadata.card_data = request.card_data
|
||||
|
||||
# [⑦ 계약 데이터화] 협상완료 도달 시 계약 레코드 기록
|
||||
if response.step == "협상완료":
|
||||
self._log_contract(request, response)
|
||||
|
||||
return response
|
||||
|
||||
def _log_contract(self, request: NegotiationRequest, response: NegotiationResponse):
|
||||
"""협상 챗봇으로 이루어진 계약의 데이터화 (config.instrument.contracts_log)."""
|
||||
if self._contracts_log_path is None:
|
||||
return
|
||||
try:
|
||||
from datetime import datetime, timezone, timedelta
|
||||
final_price = response.chat_metadata.price if response.chat_metadata else None
|
||||
record = {
|
||||
"ts": datetime.now(timezone(timedelta(hours=9))).isoformat(),
|
||||
"session_id": request.session_id,
|
||||
"rq_type": request.rq_type,
|
||||
"item_price": request.item_price,
|
||||
"initial": request.initial,
|
||||
"final_price": final_price,
|
||||
"target": request.target,
|
||||
"anchor": request.anchor,
|
||||
"iteration": request.iteration,
|
||||
"dist": request.dist,
|
||||
"partners_yn": request.partners_yn,
|
||||
"reduction_pct": (round(100 * (float(request.item_price) - float(final_price))
|
||||
/ float(request.item_price), 3)
|
||||
if request.item_price and final_price else None),
|
||||
}
|
||||
with open(self._contracts_log_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
except (TypeError, ValueError, OSError) as e:
|
||||
logger.warning(f"[contracts] 계약 기록 실패(무시): {e}")
|
||||
|
||||
# ----------------------------------------------------------- fixed steps
|
||||
|
||||
def _handle_fixed_step(self, request: NegotiationRequest, next_step: str,
|
||||
next_step_config: dict) -> NegotiationResponse:
|
||||
chat_metadata = ChatMetadata(iteration=request.iteration)
|
||||
|
||||
if next_step_config is None:
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
script="",
|
||||
sender="bot",
|
||||
type="text",
|
||||
chat_end=True,
|
||||
next_input_mode="null",
|
||||
input_options=[],
|
||||
step=next_step,
|
||||
client_step=self._get_client_step(next_step),
|
||||
chat_metadata=chat_metadata,
|
||||
)
|
||||
|
||||
raw_script = next_step_config.get("script", "")
|
||||
formatted_script = self.script_formatter.format_script(raw_script, request)
|
||||
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
script=formatted_script,
|
||||
sender="bot",
|
||||
type=next_step_config.get("type", "text"),
|
||||
chat_end=next_step_config.get("chat_end", False),
|
||||
next_input_mode=next_step_config.get("next_input_mode", "null"),
|
||||
input_options=next_step_config.get("input_options", []),
|
||||
step=next_step,
|
||||
client_step=self._get_client_step(next_step),
|
||||
chat_metadata=chat_metadata,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------- dynamic step
|
||||
|
||||
def _handle_dynamic_step(self, request: NegotiationRequest, config: dict,
|
||||
next_step_id: str = "가격협상") -> NegotiationResponse:
|
||||
"""'가격협상' 동적 스텝 — Q-Table 카드 선택."""
|
||||
# user_input이 숫자면 현재가로 반영, 아니면 보존된 request.input 사용
|
||||
try:
|
||||
request.input = float(request.user_input)
|
||||
except (ValueError, TypeError):
|
||||
if request.input is None:
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
sender="bot",
|
||||
type="text",
|
||||
script="가격 정보가 유실되었습니다. 처음부터 다시 시작해 주세요.",
|
||||
step=request.step,
|
||||
client_step=self._get_client_step(request.step),
|
||||
next_input_mode="null",
|
||||
chat_end=True,
|
||||
input_options=[],
|
||||
)
|
||||
|
||||
if request.revenue is None:
|
||||
logger.warning("[DynamicStep] revenue 없음 — 기본값 1,000,000 적용")
|
||||
request.revenue = 1000000.0
|
||||
|
||||
if any(v is None for v in [request.revenue, request.dist, request.partners,
|
||||
request.anchor, request.target, request.input,
|
||||
request.initial]):
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
sender="bot",
|
||||
type="text",
|
||||
script="가격 협상을 위해서는 추가 정보(매출, 유통코드, 파트너수, 가격정보 등)가 필요합니다.",
|
||||
step=request.step,
|
||||
client_step=self._get_client_step(request.step),
|
||||
next_input_mode="null",
|
||||
chat_end=True,
|
||||
input_options=[],
|
||||
)
|
||||
|
||||
current_iteration = request.iteration or 0
|
||||
if current_iteration >= MAX_ITERATION:
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
sender="bot",
|
||||
type="text",
|
||||
script=f"더 이상 가격 협상을 진행할 수 없습니다. (최대 {MAX_ITERATION}회 초과)",
|
||||
step="협상종료",
|
||||
client_step="협상종료",
|
||||
chat_end=True,
|
||||
next_input_mode="null",
|
||||
input_options=[],
|
||||
chat_metadata=ChatMetadata(iteration=current_iteration),
|
||||
)
|
||||
|
||||
# [⑩ 계측] 가격 지표(단계 변수) → 예측 긴장도 추정 → 페르소나 선택 → 로그
|
||||
indicator_result = None
|
||||
tension_est, persona = None, None
|
||||
try:
|
||||
indicator_result = self.indicator_calculator.calculate(
|
||||
int(request.anchor), int(request.input), int(request.target))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if indicator_result is not None and request.initial \
|
||||
and float(request.initial) > float(request.target):
|
||||
tension_est = estimate_tension(indicator_result.indicator_value,
|
||||
float(request.target), float(request.initial))
|
||||
persona = select_persona(tension_est)
|
||||
self._log_tension(request, tension_est, indicator_result.indicator_value,
|
||||
persona["name"])
|
||||
|
||||
# 1. 스냅샷 → State
|
||||
acceptance_ratio = None
|
||||
if request.initial and request.initial > 0 and request.input is not None:
|
||||
try:
|
||||
acceptance_ratio = (float(request.initial) - float(request.input)) \
|
||||
/ float(request.initial)
|
||||
except (ValueError, TypeError):
|
||||
acceptance_ratio = 0.0
|
||||
|
||||
snapshot = NegotiationSnapshot(
|
||||
revenue_amount=request.revenue,
|
||||
distribution_code=request.dist,
|
||||
partner_count=request.partners,
|
||||
anchor_price=request.anchor,
|
||||
target_price=request.target,
|
||||
input_price=request.input,
|
||||
initial_price=request.initial,
|
||||
acceptance_ratio=acceptance_ratio,
|
||||
)
|
||||
current_state = build_state(snapshot)
|
||||
|
||||
# 2. 카드 선택 (신규견적은 학습 격리 — 방문수 미증가, argmax)
|
||||
result = self.orchestrator.select_card(
|
||||
current_state,
|
||||
excluded_cards=request.excluded_cards,
|
||||
isolate_learning=request.is_new_quote,
|
||||
)
|
||||
|
||||
# 3. 카드 스크립트 완성 (card_data 치환 + 미치환 문장 숨김)
|
||||
card_id = result.get("card_id")
|
||||
if card_id:
|
||||
completed_script = self.completer.execute(card_id, request.card_data)
|
||||
if completed_script:
|
||||
result["script"] = completed_script
|
||||
|
||||
# 4. N-profiling — LLM 톤 재작성 (요청별 override > 서버 설정)
|
||||
# 톤은 예측 긴장도로 선택된 페르소나를 따른다 (⑩ "수치에 따라 페르소나 적용")
|
||||
if self._profiling_active(request) and result.get("script"):
|
||||
context = {
|
||||
"price": request.input,
|
||||
"anchor": request.anchor,
|
||||
"target": request.target,
|
||||
"partner_personality": request.mbti,
|
||||
"persona": persona["name"] if persona else None,
|
||||
"tone": persona["tone"] if persona else
|
||||
"Professional, polite, yet firm in negotiation stance. "
|
||||
"Adapt to the partner's personality if provided.",
|
||||
}
|
||||
rewritten = self.profiler.rewrite(result["script"], context)
|
||||
if rewritten:
|
||||
result["script"] = rewritten
|
||||
logger.info(f"[profiling] 스크립트 재작성 적용 (card={card_id})")
|
||||
else:
|
||||
logger.info(f"[profiling] 재작성 실패/검증 탈락 — 원문 유지 (card={card_id})")
|
||||
|
||||
# 5. 다음 스텝 결정
|
||||
rq_type = request.rq_type
|
||||
current_scripts = self.scripts.get(rq_type, self.scripts.get("재협상", {}))
|
||||
dynamic_step_config = current_scripts.get(next_step_id, {})
|
||||
next_step_def = dynamic_step_config.get("next_step", {})
|
||||
next_step = next_step_def.get("default", "가격협상_확인")
|
||||
|
||||
script_text = result.get("script", "")
|
||||
if "수락" in script_text or "타결" in script_text:
|
||||
next_step = "협상종료"
|
||||
|
||||
chat_metadata = ChatMetadata(
|
||||
card_id=result.get("card_id"),
|
||||
q_value=result.get("q_value"),
|
||||
visit_count=result.get("visit_count"),
|
||||
iteration=current_iteration + 1,
|
||||
indicator_value=indicator_result.indicator_value if indicator_result else None,
|
||||
indicator_range=indicator_result.indicator_range if indicator_result else None,
|
||||
tension=round(tension_est, 4) if tension_est is not None else None,
|
||||
persona=persona["name"] if persona else None,
|
||||
price=request.input,
|
||||
)
|
||||
|
||||
return NegotiationResponse(
|
||||
index=request.index + 1,
|
||||
sender="bot",
|
||||
type=dynamic_step_config.get("type", "text"),
|
||||
script=script_text,
|
||||
chat_end=dynamic_step_config.get("chat_end", False),
|
||||
next_input_mode=dynamic_step_config.get("next_input_mode", "percent"),
|
||||
input_options=dynamic_step_config.get("input_options", []),
|
||||
step=next_step_id,
|
||||
client_step=self._get_client_step(next_step_id),
|
||||
chat_metadata=chat_metadata,
|
||||
)
|
||||
|
||||
def _profiling_active(self, request: NegotiationRequest) -> bool:
|
||||
"""요청별 override가 있으면 우선, 없으면 서버 설정. 프로파일러 미생성 시 항상 False."""
|
||||
if self.profiler is None:
|
||||
if request.profiling:
|
||||
logger.warning("[profiling] 요청이 활성화를 원했지만 프로파일러 미생성 상태")
|
||||
return False
|
||||
if request.profiling is not None:
|
||||
return request.profiling
|
||||
return self.config.profiling.enabled
|
||||
|
||||
def _log_tension(self, request: NegotiationRequest, tension_est: float,
|
||||
indicator_value: int, persona_name: str):
|
||||
"""⑩ 계측 기록 — 지표점수 역산 예측 긴장도 + 적용 페르소나 (config.instrument.tension_log)."""
|
||||
if self._tension_log_path is None:
|
||||
return
|
||||
try:
|
||||
with open(self._tension_log_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({
|
||||
"session_id": request.session_id,
|
||||
"index": request.index,
|
||||
"iteration": request.iteration or 0,
|
||||
"rq_type": request.rq_type,
|
||||
"predicted": round(tension_est, 4),
|
||||
"indicator": indicator_value,
|
||||
"persona": persona_name,
|
||||
}, ensure_ascii=False) + "\n")
|
||||
except (TypeError, ValueError, OSError):
|
||||
pass
|
||||
|
||||
# --------------------------------------------------------- step routing
|
||||
|
||||
def _resolve_next_step(self, next_step_def, request: NegotiationRequest) -> str:
|
||||
"""
|
||||
next_step 정의 해석:
|
||||
- 문자열: 직접 전이
|
||||
- 딕셔너리: 사용자 입력 기반 매핑 (값이 리스트면 조건 규칙 평가)
|
||||
"""
|
||||
user_input = request.user_input
|
||||
|
||||
if isinstance(next_step_def, dict):
|
||||
if user_input in next_step_def:
|
||||
target = next_step_def[user_input]
|
||||
elif "default" in next_step_def:
|
||||
target = next_step_def["default"]
|
||||
else:
|
||||
return "input_error"
|
||||
|
||||
if isinstance(target, list):
|
||||
return self._evaluate_rules(target, request)
|
||||
return target
|
||||
|
||||
elif isinstance(next_step_def, str):
|
||||
return next_step_def
|
||||
|
||||
return ""
|
||||
|
||||
def _evaluate_rules(self, rules: list, request: NegotiationRequest) -> str:
|
||||
"""조건 규칙 리스트에서 첫 번째로 매칭되는 전이를 찾는다."""
|
||||
for rule in rules:
|
||||
condition = rule.get("condition")
|
||||
next_target = rule.get("next")
|
||||
|
||||
# 동적 와일드카드 선택
|
||||
if condition == "check_wildcard_entry":
|
||||
selected_card = self._select_best_wildcard(request)
|
||||
if selected_card:
|
||||
return selected_card
|
||||
continue # 적합한 와일드카드 없음 — 다음 규칙 시도
|
||||
|
||||
if self._evaluate_condition(condition, request):
|
||||
return next_target
|
||||
|
||||
return "협상종료"
|
||||
|
||||
def _select_best_wildcard(self, request: NegotiationRequest) -> Optional[str]:
|
||||
"""와일드카드 발동 판단. card_id("wild_card_1pct" 등) 또는 None."""
|
||||
current_iteration = request.iteration or 0
|
||||
input_price = request.input or float("inf")
|
||||
anchor_price = request.anchor or 0.0
|
||||
|
||||
supplier_type = self._determine_supplier_type(
|
||||
request.dist, partners_yn=request.partners_yn)
|
||||
|
||||
# 1. [1% 추가 네고] 조기 성공: 최종 라운드 이전 AND 입력가 ≤ 앵커 AND 유형 A/B/C
|
||||
if current_iteration <= MAX_ITERATION - 1 and input_price <= anchor_price:
|
||||
if supplier_type in ["A", "B", "C"]:
|
||||
return "wild_card_1pct"
|
||||
|
||||
# 2. [재원부족 전략] 마지막 회차, Type C, 목표가 +3% 이내
|
||||
if current_iteration >= MAX_ITERATION and supplier_type == "C":
|
||||
target_price = request.target or 0
|
||||
if target_price < input_price <= target_price * 1.03:
|
||||
return "wild_card_budget"
|
||||
|
||||
# 3. [1% 추가 네고 — 최종 라운드 무조건 발동]
|
||||
# 가격 라운드 소진 시 유형·가격대와 무관하게 최종 제안 카드를 발동한다.
|
||||
if current_iteration >= MAX_ITERATION:
|
||||
return "wild_card_1pct"
|
||||
|
||||
return None
|
||||
|
||||
def _determine_supplier_type(self, dist: str, partners_yn: str = None) -> str:
|
||||
"""
|
||||
공급사 유형: A=유통(R), B=총판(W)+다수, C=제조(M) 또는 총판(W)+단독/없음
|
||||
"""
|
||||
if dist == "R":
|
||||
return "A"
|
||||
|
||||
if dist == "W":
|
||||
if partners_yn == "다수":
|
||||
return "B"
|
||||
elif partners_yn in ["단독", "없음"]:
|
||||
return "C"
|
||||
return "Unknown"
|
||||
|
||||
if dist == "M":
|
||||
return "C"
|
||||
|
||||
return "Unknown"
|
||||
|
||||
def _evaluate_condition(self, condition: str, request: NegotiationRequest) -> bool:
|
||||
if condition == "default":
|
||||
return True
|
||||
|
||||
try:
|
||||
input_price = float(request.user_input) \
|
||||
if self.script_formatter._is_number(request.user_input) \
|
||||
else (request.input or 0.0)
|
||||
anchor_price = request.anchor or 0.0
|
||||
target_price = request.target or float("inf")
|
||||
except (ValueError, TypeError):
|
||||
input_price = 0.0
|
||||
anchor_price = 0.0
|
||||
target_price = float("inf")
|
||||
|
||||
if condition == "check_price_match":
|
||||
return input_price <= anchor_price
|
||||
|
||||
elif condition == "check_is_supplier_type_c":
|
||||
# Type C는 가격이 앵커 이하이거나 라운드 소진 시 성공 처리
|
||||
supplier_type = self._determine_supplier_type(
|
||||
request.dist, partners_yn=request.partners_yn)
|
||||
current_iteration = request.iteration or 0
|
||||
return (supplier_type == "C"
|
||||
and (input_price <= anchor_price
|
||||
or current_iteration >= MAX_ITERATION))
|
||||
|
||||
elif condition == "check_iteration_limit":
|
||||
return (request.iteration or 0) >= MAX_ITERATION
|
||||
|
||||
return False
|
||||
@@ -0,0 +1,113 @@
|
||||
"""스크립트 포매터 — 평문 템플릿에 요청 데이터를 치환한다."""
|
||||
|
||||
import math
|
||||
from typing import Any, Dict
|
||||
|
||||
from common.textutil import hide_unresolved_lines, safe_format
|
||||
from router.v1.nego.protocol import NegotiationRequest
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from services.negotiation.korean import number_to_korean
|
||||
|
||||
|
||||
class ScriptFormatter:
|
||||
"""평문 script 템플릿 치환 (Slate/editor_script 구조 없음 — 평문이 단일 정본)."""
|
||||
|
||||
def __init__(self, card_repository: CardScriptRepository = None):
|
||||
self._repo = card_repository or CardScriptRepository()
|
||||
self.card_scripts = self._load_card_scripts()
|
||||
|
||||
def reload(self):
|
||||
self.card_scripts = self._load_card_scripts()
|
||||
|
||||
def _load_card_scripts(self) -> Dict[str, str]:
|
||||
scripts = {}
|
||||
for card in self._repo.find_all():
|
||||
card_id = card.get("card_id")
|
||||
content = card.get("script")
|
||||
if card_id and content:
|
||||
scripts[card_id] = content
|
||||
return scripts
|
||||
|
||||
def format_script(self, script_identifier: str, request: NegotiationRequest) -> str:
|
||||
"""
|
||||
Args:
|
||||
script_identifier: 템플릿 문자열 또는 카드 ID (예: "NC26-002")
|
||||
"""
|
||||
if not script_identifier:
|
||||
return ""
|
||||
|
||||
context = self._build_context(request)
|
||||
|
||||
# 카드 ID면 템플릿 조회, 아니면 식별자 자체가 템플릿
|
||||
template = self.card_scripts.get(script_identifier, script_identifier)
|
||||
|
||||
formatted = safe_format(template, context)
|
||||
return hide_unresolved_lines(formatted, source=script_identifier[:30])
|
||||
|
||||
def _build_context(self, request: NegotiationRequest) -> Dict[str, Any]:
|
||||
context = {}
|
||||
|
||||
def safe_format_number(val):
|
||||
if isinstance(val, (int, float)):
|
||||
return f"{val:,.0f}"
|
||||
return str(val)
|
||||
|
||||
user_input_val = request.user_input
|
||||
if user_input_val and self._is_number(user_input_val):
|
||||
try:
|
||||
context["price"] = f"{float(user_input_val):,.0f}"
|
||||
except ValueError:
|
||||
context["price"] = user_input_val
|
||||
else:
|
||||
context["price"] = str(user_input_val) if user_input_val is not None else ""
|
||||
|
||||
fields_to_map = [
|
||||
"revenue", "partners", "anchor", "target", "initial", "input",
|
||||
"iteration", "item_price", "deadline", "vat",
|
||||
]
|
||||
for field in fields_to_map:
|
||||
val = getattr(request, field, None)
|
||||
context[field] = safe_format_number(val) if val is not None else ""
|
||||
|
||||
# 1% 추가 협상 제안가
|
||||
if request.input is not None:
|
||||
context["offer_1pct"] = safe_format_number(math.floor(request.input * 0.99))
|
||||
else:
|
||||
context["offer_1pct"] = ""
|
||||
|
||||
context["dist"] = str(request.dist) if request.dist else ""
|
||||
|
||||
if request.card_data:
|
||||
for k, v in request.card_data.model_dump().items():
|
||||
if v is not None:
|
||||
# 경쟁사 가격차는 최소 1% 표기
|
||||
if k == "competitor_price_diff" and isinstance(v, (int, float)) and v < 1:
|
||||
v = 1
|
||||
context[k] = safe_format_number(v)
|
||||
else:
|
||||
context[k] = ""
|
||||
|
||||
# 할인율 (기존가 대비 현재 제안가)
|
||||
if request.item_price is not None and request.input is not None and request.item_price > 1:
|
||||
discount = ((request.item_price - request.input) / request.item_price) * 100
|
||||
context["discount_rate"] = f"{discount:.1f}"
|
||||
else:
|
||||
context["discount_rate"] = "0.0"
|
||||
|
||||
# 한국어 가격 표기
|
||||
if request.input is not None:
|
||||
try:
|
||||
context["input_kr"] = number_to_korean(int(request.input))
|
||||
except Exception:
|
||||
context["input_kr"] = str(request.input)
|
||||
else:
|
||||
context["input_kr"] = ""
|
||||
|
||||
return context
|
||||
|
||||
def _is_number(self, s) -> bool:
|
||||
try:
|
||||
float(s)
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
@@ -0,0 +1,71 @@
|
||||
"""3구간 가격 지표 — Price(P), Anchor(A), Target(T) 기반 점수(1~99).
|
||||
|
||||
⑩ 실시간 페르소나 정확도의 긴장도(Tension) 계측 근거이기도 하다.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import IndicatorRangeEnum, IndicatorType
|
||||
|
||||
|
||||
class IndicatorResponse(BaseModel):
|
||||
indicator_type: IndicatorType
|
||||
indicator_value: int
|
||||
indicator_range: IndicatorRangeEnum
|
||||
|
||||
|
||||
class ThreeSegIndicator:
|
||||
"""3-Segment Indicator — 구간별 점수 산출."""
|
||||
|
||||
def _case1(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 1: Optimal Zone (PZ1) — P ≤ A, 점수 99 고정."""
|
||||
if anchoring_price >= current_price:
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=99,
|
||||
indicator_range=IndicatorRangeEnum.PZ1,
|
||||
)
|
||||
return None
|
||||
|
||||
def _case2(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 2: Negotiable Zone (PZ2) — A < P < T, 99→80 선형 보간."""
|
||||
if anchoring_price < current_price < target_price:
|
||||
percent = int(math.floor(
|
||||
99 - ((current_price - anchoring_price)
|
||||
/ (target_price - anchoring_price) * 19)))
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=percent,
|
||||
indicator_range=IndicatorRangeEnum.PZ2,
|
||||
)
|
||||
return None
|
||||
|
||||
def _case3(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
"""Case 3: Target Exceeded Zone (PZ3) — P ≥ T, 79에서 지수 감쇠."""
|
||||
if target_price <= current_price:
|
||||
scale_exponent = int(math.floor(math.log10(target_price)))
|
||||
k = math.pow(10, -scale_exponent)
|
||||
exponent = -k * (current_price - target_price)
|
||||
raw_score = 79 * math.exp(exponent)
|
||||
percent = max(1, int(math.floor(raw_score)))
|
||||
return IndicatorResponse(
|
||||
indicator_type=IndicatorType.PERCENT_DETAIL,
|
||||
indicator_value=percent,
|
||||
indicator_range=IndicatorRangeEnum.PZ3,
|
||||
)
|
||||
return None
|
||||
|
||||
def calculate(self, anchoring_price: int, current_price: int,
|
||||
target_price: int) -> Optional[IndicatorResponse]:
|
||||
ret = [
|
||||
self._case1(anchoring_price, current_price, target_price),
|
||||
self._case2(anchoring_price, current_price, target_price),
|
||||
self._case3(anchoring_price, current_price, target_price),
|
||||
]
|
||||
return next((r for r in ret if r is not None), None)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""숫자 → 한국어 표기 변환 (예: 1234 → 천이백삼십사)."""
|
||||
|
||||
|
||||
def number_to_korean(number: int) -> str:
|
||||
"""정수를 한국어 표기로 변환한다. 조 단위까지 지원."""
|
||||
if number == 0:
|
||||
return "영"
|
||||
|
||||
big_units = ["", "만", "억", "조"]
|
||||
digits = ["", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구"]
|
||||
|
||||
chunks = []
|
||||
temp_num = number
|
||||
while temp_num > 0:
|
||||
chunks.append(temp_num % 10000)
|
||||
temp_num //= 10000
|
||||
|
||||
res_str = ""
|
||||
for i, chunk in enumerate(chunks):
|
||||
if chunk == 0:
|
||||
continue
|
||||
|
||||
chunk_str = ""
|
||||
digit_1000 = chunk // 1000
|
||||
if digit_1000 > 0:
|
||||
chunk_str += (digits[digit_1000] if digit_1000 > 1 else "") + "천"
|
||||
|
||||
digit_100 = (chunk % 1000) // 100
|
||||
if digit_100 > 0:
|
||||
chunk_str += (digits[digit_100] if digit_100 > 1 else "") + "백"
|
||||
|
||||
digit_10 = (chunk % 100) // 10
|
||||
if digit_10 > 0:
|
||||
chunk_str += (digits[digit_10] if digit_10 > 1 else "") + "십"
|
||||
|
||||
digit_1 = chunk % 10
|
||||
if digit_1 > 0:
|
||||
chunk_str += digits[digit_1]
|
||||
|
||||
res_str = chunk_str + big_units[i] + res_str
|
||||
|
||||
return res_str
|
||||
@@ -0,0 +1,91 @@
|
||||
"""협상 오케스트레이터 — Q-Table·정책·카드 저장소를 조립해 카드를 선택한다.
|
||||
|
||||
Q-Table은 resources/policy/q_table.json (휴리스틱 초기값)에서 로드한다. DB 없음.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from common.paths import RESOURCES_DIR
|
||||
from services.cards.mapper import ActionCardMapper
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from services.policy.q_table import QTable
|
||||
from services.policy.selector import CardSelector
|
||||
from services.policy.state import State
|
||||
from services.policy.ucb import UCBPolicy
|
||||
from services.policy.visit_table import VisitTable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATE_SPACE_SIZE = 162
|
||||
|
||||
|
||||
class NegotiationOrchestrator:
|
||||
def __init__(self):
|
||||
self.mapper = ActionCardMapper()
|
||||
self.script_repo = CardScriptRepository()
|
||||
self.action_space_size = self.mapper.get_action_space_size()
|
||||
|
||||
self.q_table = self._load_q_table()
|
||||
self.visit_table = VisitTable(
|
||||
state_space_size=STATE_SPACE_SIZE,
|
||||
action_space_size=self.action_space_size,
|
||||
)
|
||||
|
||||
self.policy = UCBPolicy(visit_table=self.visit_table)
|
||||
self.selector = CardSelector(
|
||||
q_table=self.q_table,
|
||||
policy=self.policy,
|
||||
action_card_mapper=self.mapper,
|
||||
)
|
||||
|
||||
def _load_q_table(self) -> QTable:
|
||||
q_json = RESOURCES_DIR / "policy" / "q_table.json"
|
||||
if q_json.exists():
|
||||
with open(q_json, "r", encoding="utf-8") as f:
|
||||
q_table = QTable.from_dict(json.load(f))
|
||||
logger.info(f"Q-Table 로드: {q_json} "
|
||||
f"({q_table.state_space_size}×{q_table.action_space_size})")
|
||||
return q_table
|
||||
|
||||
logger.warning("q_table.json 없음 — 빈 Q-Table로 기동")
|
||||
return QTable(
|
||||
state_space_size=STATE_SPACE_SIZE,
|
||||
action_space_size=self.action_space_size,
|
||||
)
|
||||
|
||||
def select_card(self, state: State, excluded_cards: list = None,
|
||||
isolate_learning: bool = False) -> dict:
|
||||
"""
|
||||
Args:
|
||||
excluded_cards: 제외할 card_id 리스트
|
||||
isolate_learning: True면 UCB 격리(방문수 미증가, argmax) — 신규견적 등
|
||||
"""
|
||||
logger.info(f"[Input State] {state}")
|
||||
|
||||
excluded_actions = []
|
||||
if excluded_cards:
|
||||
for card_id in excluded_cards:
|
||||
action_id = self.mapper.get_action_id(card_id)
|
||||
if action_id is not None:
|
||||
excluded_actions.append(action_id)
|
||||
|
||||
result = self.selector.execute(
|
||||
state,
|
||||
use_policy=not isolate_learning,
|
||||
excluded_actions=excluded_actions,
|
||||
)
|
||||
|
||||
if result.get("card_id"):
|
||||
card = self.script_repo.find_by_id(result["card_id"])
|
||||
if card:
|
||||
result["card_name"] = card.get("card_name")
|
||||
result["script"] = card.get("script")
|
||||
else:
|
||||
result["script"] = "Script not found in repository."
|
||||
|
||||
return result
|
||||
|
||||
def reset_episode(self):
|
||||
"""협상 세션 경계에서 정책의 에피소드 상태 초기화"""
|
||||
self.selector.reset_episode()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""스텝 후처리 — 응답 확정 직전의 스텝별 비즈니스 로직."""
|
||||
|
||||
from router.v1.nego.protocol import ChatMetadata, NegotiationRequest, NegotiationResponse
|
||||
|
||||
|
||||
class StepActionHandler:
|
||||
"""스텝 처리 후, 응답 확정 전에 실행되는 부수 로직 (가격 갱신 등)."""
|
||||
|
||||
def execute_post_step_actions(self, request: NegotiationRequest,
|
||||
response: NegotiationResponse):
|
||||
"""response 객체를 in-place로 수정한다."""
|
||||
if request.step == "추가할인요청":
|
||||
self._handle_requote_additional_discount(request, response)
|
||||
|
||||
def _handle_requote_additional_discount(self, request: NegotiationRequest,
|
||||
response: NegotiationResponse):
|
||||
"""재견적 추가할인: 사용자가 [예]를 선택하면 1% 할인 적용."""
|
||||
if response.step not in ["결과안내", "협상완료"]:
|
||||
return
|
||||
|
||||
try:
|
||||
input_price = float(request.input or 0)
|
||||
|
||||
if response.chat_metadata is None:
|
||||
response.chat_metadata = ChatMetadata()
|
||||
|
||||
if request.user_input == "예":
|
||||
response.chat_metadata.price = int(input_price * 0.99)
|
||||
else:
|
||||
response.chat_metadata.price = int(input_price)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
@@ -0,0 +1,64 @@
|
||||
"""협상 긴장도(Tension) 추정 + 페르소나 선택 (지표 ⑩).
|
||||
|
||||
계획서 정의:
|
||||
- 협상 단계마다 0~1 백분위 환산 가능한 수치를 협상 긴장도로 정의하여 활용
|
||||
- 단계별 변수를 수치화 후 수치에 따라 페르소나를 적용 — 적용된 페르소나의 정확도 측정
|
||||
|
||||
설계 (2026-08-28 확정):
|
||||
- 실제 긴장도(사후 정의) = clip((제안가 − 목표가) / (초기제안가 − 목표가), 0, 1)
|
||||
- 예측 긴장도(서버 실시간) = 단계 변수인 지표점수(ThreeSegIndicator, 정수 1~99)로부터
|
||||
역산한 추정치 — 정수 양자화·스케일 의존 손실이 있어 실제값과 독립적으로 검증 가능
|
||||
- 페르소나 = 예측 긴장도 3구간(저/중/고)으로 선택, profiling 활성 시 스크립트 톤에 적용
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def clip01(v: float) -> float:
|
||||
return max(0.0, min(1.0, v))
|
||||
|
||||
|
||||
def actual_tension(initial: float, target: float, price: float) -> float:
|
||||
"""실제 긴장도 정의 (사후 산출용 — 하네스/집계기가 사용하는 기준 정의)."""
|
||||
if initial <= target:
|
||||
raise ValueError("initial must exceed target")
|
||||
return clip01((price - target) / (initial - target))
|
||||
|
||||
|
||||
def estimate_tension(indicator_value: int, target: float, initial: float) -> float:
|
||||
"""지표점수(1~99) → 긴장도 추정 (모델 변수 경유 역산).
|
||||
|
||||
PZ1/PZ2(80~99, 제안가 ≤ 목표가 구간) → 긴장도 0.
|
||||
PZ3(1~79)는 지표 산식 79·exp(−k(P−T))의 역함수로 (P−T)를 복원해 정규화한다.
|
||||
지표가 정수로 절사되어 있어 실제 긴장도와 양자화 오차가 존재한다 (독립 검증 근거).
|
||||
"""
|
||||
if initial <= target:
|
||||
return 0.0
|
||||
if indicator_value >= 80:
|
||||
return 0.0
|
||||
k = math.pow(10, -int(math.floor(math.log10(target))))
|
||||
p_minus_t = -math.log(indicator_value / 79) / k
|
||||
return clip01(p_minus_t / (initial - target))
|
||||
|
||||
|
||||
# 페르소나 프리셋 — 예측 긴장도 3구간
|
||||
PERSONAS = [
|
||||
# (하한, 이름, profiling 톤 지시문)
|
||||
(2 / 3, "단호한 압박형",
|
||||
"Firm and assertive negotiation stance. Emphasize competition, alternatives, "
|
||||
"and deadlines. Keep it professional but apply clear pressure in Korean."),
|
||||
(1 / 3, "균형 협상형",
|
||||
"Balanced, data-driven negotiation stance. Emphasize mutual benefit and "
|
||||
"objective grounds. Professional and persuasive in Korean."),
|
||||
(0.0, "우호적 마무리형",
|
||||
"Warm, appreciative closing stance. The deal is close — emphasize partnership "
|
||||
"and a smooth finish. Polite and collaborative in Korean."),
|
||||
]
|
||||
|
||||
|
||||
def select_persona(tension: float) -> dict:
|
||||
"""예측 긴장도 → 페르소나 (저/중/고 3구간)."""
|
||||
for lower_bound, name, tone in PERSONAS:
|
||||
if tension >= lower_bound:
|
||||
return {"name": name, "tone": tone}
|
||||
return {"name": PERSONAS[-1][1], "tone": PERSONAS[-1][2]}
|
||||
Whitespace-only changes.
@@ -0,0 +1,63 @@
|
||||
"""Q-Table 모델 — 추론 전용 (학습 경로는 이 프로젝트에서 제외)."""
|
||||
|
||||
import numpy as np
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class QTable:
|
||||
"""
|
||||
Q-Table은 추상적인 action_id만 다루며,
|
||||
실제 협상 카드(card_id)는 ActionCardMapper에서 매핑한다.
|
||||
"""
|
||||
|
||||
def __init__(self, state_space_size: int, action_space_size: int):
|
||||
self.state_space_size = state_space_size
|
||||
self.action_space_size = action_space_size
|
||||
self.q_values = np.zeros((state_space_size, action_space_size))
|
||||
|
||||
def get_q_value(self, state_index: int, action_id: int) -> float:
|
||||
self._validate_indices(state_index, action_id)
|
||||
return float(self.q_values[state_index, action_id])
|
||||
|
||||
def get_q_values_for_state(self, state_index: int) -> np.ndarray:
|
||||
self._validate_state(state_index)
|
||||
return self.q_values[state_index, :].copy()
|
||||
|
||||
def get_best_action(self, state_index: int) -> int:
|
||||
self._validate_state(state_index)
|
||||
return int(np.argmax(self.q_values[state_index, :]))
|
||||
|
||||
def to_dict(self) -> Dict:
|
||||
return {
|
||||
"state_space_size": self.state_space_size,
|
||||
"action_space_size": self.action_space_size,
|
||||
"q_values": self.q_values.tolist(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict) -> "QTable":
|
||||
q_table = cls(
|
||||
state_space_size=data["state_space_size"],
|
||||
action_space_size=data["action_space_size"],
|
||||
)
|
||||
q_table.q_values = np.array(data["q_values"])
|
||||
return q_table
|
||||
|
||||
def _validate_state(self, state_index: int):
|
||||
if state_index < 0 or state_index >= self.state_space_size:
|
||||
raise ValueError(
|
||||
f"state_index {state_index} out of range [0, {self.state_space_size})"
|
||||
)
|
||||
|
||||
def _validate_indices(self, state_index: int, action_id: int):
|
||||
self._validate_state(state_index)
|
||||
if action_id < 0 or action_id >= self.action_space_size:
|
||||
raise ValueError(
|
||||
f"action_id {action_id} out of range [0, {self.action_space_size})"
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"QTable(state_space_size={self.state_space_size}, "
|
||||
f"action_space_size={self.action_space_size})"
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""카드 선택기 — State → action_id → card_id 추론."""
|
||||
|
||||
import logging
|
||||
from typing import Dict, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from services.cards.mapper import ActionCardMapper
|
||||
from services.policy.q_table import QTable
|
||||
from services.policy.state import State
|
||||
from services.policy.ucb import UCBPolicy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CardSelector:
|
||||
"""
|
||||
Q_Table은 추상적인 action_id만 반환하고,
|
||||
ActionCardMapper를 통해 구체적인 card_id로 변환한다.
|
||||
"""
|
||||
|
||||
def __init__(self, q_table: QTable, policy: UCBPolicy,
|
||||
action_card_mapper: ActionCardMapper):
|
||||
self.q_table = q_table
|
||||
self.policy = policy
|
||||
self.action_card_mapper = action_card_mapper
|
||||
|
||||
def execute(
|
||||
self,
|
||||
state: State,
|
||||
use_policy: bool = True,
|
||||
excluded_actions: Optional[list] = None,
|
||||
) -> Dict:
|
||||
"""
|
||||
현재 상태에서 최적의 협상 카드 선택.
|
||||
|
||||
Args:
|
||||
use_policy: True면 UCB 정책(방문수 증가 + 에피소드 중복 방지),
|
||||
False면 순수 Q-value argmax (학습 격리 — 신규견적 등)
|
||||
excluded_actions: 선택에서 제외할 action_id 리스트
|
||||
"""
|
||||
state_index = state.to_index()
|
||||
q_values = self.q_table.get_q_values_for_state(state_index)
|
||||
|
||||
available_mask = None
|
||||
if excluded_actions is not None:
|
||||
action_space_size = len(q_values)
|
||||
available_mask = np.ones(action_space_size, dtype=int)
|
||||
for action_id in excluded_actions:
|
||||
if 0 <= action_id < action_space_size:
|
||||
available_mask[action_id] = 0
|
||||
logger.info(f"[CardSelector] excluded actions: {excluded_actions}")
|
||||
|
||||
if use_policy:
|
||||
action_id = self.policy.select_action(
|
||||
state_index, q_values, available_mask=available_mask
|
||||
)
|
||||
else:
|
||||
if available_mask is not None:
|
||||
masked_q = q_values.copy()
|
||||
masked_q[available_mask == 0] = -np.inf
|
||||
action_id = int(np.argmax(masked_q))
|
||||
if masked_q[action_id] == -np.inf:
|
||||
action_id = None
|
||||
else:
|
||||
action_id = self.q_table.get_best_action(state_index)
|
||||
|
||||
if action_id is None:
|
||||
return {
|
||||
"action_id": None,
|
||||
"card_id": None,
|
||||
"q_value": None,
|
||||
"state_index": state_index,
|
||||
"message": "No available actions (all actions used in this episode)",
|
||||
}
|
||||
|
||||
card_id = self.action_card_mapper.get_card_id(action_id)
|
||||
if card_id is None:
|
||||
return {
|
||||
"action_id": action_id,
|
||||
"card_id": None,
|
||||
"q_value": float(q_values[action_id]),
|
||||
"state_index": state_index,
|
||||
"visit_count": 0,
|
||||
"message": f"action_id {action_id} has no card mapping",
|
||||
}
|
||||
|
||||
q_value = self.q_table.get_q_value(state_index, action_id)
|
||||
|
||||
# 학습 격리 경로는 정책을 거치지 않으므로 정책 통계가 무의미 → None
|
||||
if use_policy:
|
||||
visit_count = self.policy.visit_table.get_action_count(state_index, action_id)
|
||||
selection_info = self.policy._last_selection_info
|
||||
else:
|
||||
visit_count = None
|
||||
selection_info = {}
|
||||
|
||||
return {
|
||||
"action_id": action_id,
|
||||
"card_id": card_id,
|
||||
"q_value": float(q_value),
|
||||
"state_index": state_index,
|
||||
"visit_count": visit_count,
|
||||
"visit_count_at_selection": selection_info.get("visit_count"),
|
||||
"total_visits_at_selection": selection_info.get("total_visits"),
|
||||
"ucb_score_at_selection": selection_info.get("ucb_score"),
|
||||
}
|
||||
|
||||
def reset_episode(self):
|
||||
"""협상 세션 종료/시작 시 정책 초기화"""
|
||||
self.policy.reset_episode()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""협상 스냅샷 → Q-Table State 변환."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from services.policy.state import (
|
||||
AcceptanceRate,
|
||||
DistributionStructure,
|
||||
InputPriceZone,
|
||||
PartnerType,
|
||||
RevenueRange,
|
||||
State,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NegotiationSnapshot:
|
||||
"""협상 스냅샷 — 실제 비즈니스 데이터"""
|
||||
|
||||
revenue_amount: float # 매출액 (원)
|
||||
distribution_code: str # "M" 제조 / "W" 총판 / "R" 유통
|
||||
partner_count: int
|
||||
anchor_price: float
|
||||
target_price: float
|
||||
input_price: float
|
||||
acceptance_ratio: Optional[float] = None # 0~1, 없으면 initial_price로 계산
|
||||
initial_price: Optional[float] = None
|
||||
|
||||
|
||||
def build_state(snapshot: NegotiationSnapshot) -> State:
|
||||
revenue_range = RevenueRange.from_amount(snapshot.revenue_amount)
|
||||
distribution = DistributionStructure.from_code(snapshot.distribution_code)
|
||||
partner_type = PartnerType.from_count(snapshot.partner_count)
|
||||
|
||||
if snapshot.acceptance_ratio is not None:
|
||||
acceptance_rate = AcceptanceRate.from_ratio(snapshot.acceptance_ratio)
|
||||
elif snapshot.initial_price is not None:
|
||||
if snapshot.initial_price <= 0:
|
||||
raise ValueError("initial_price must be positive")
|
||||
ratio = (snapshot.initial_price - snapshot.input_price) / snapshot.initial_price
|
||||
acceptance_rate = AcceptanceRate.from_ratio(ratio)
|
||||
else:
|
||||
raise ValueError("Either acceptance_ratio or initial_price must be provided")
|
||||
|
||||
input_price_zone = InputPriceZone.from_prices(
|
||||
input_price=snapshot.input_price,
|
||||
anchor_price=snapshot.anchor_price,
|
||||
target_price=snapshot.target_price,
|
||||
)
|
||||
|
||||
return State(
|
||||
revenue_range=revenue_range,
|
||||
distribution=distribution,
|
||||
partner_type=partner_type,
|
||||
acceptance_rate=acceptance_rate,
|
||||
input_price_zone=input_price_zone,
|
||||
)
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Q-Learning State 표현 (162 states = 3×3×3×3×2)."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import IntEnum
|
||||
from typing import List
|
||||
|
||||
_REVENUE_DESCRIPTIONS = ("Low (≤1,000만원)", "Mid (1,000~3,000만원)", "High (>3,000만원)")
|
||||
_DISTRIBUTION_DESCRIPTIONS = ("제조", "총판", "유통")
|
||||
_PARTNER_DESCRIPTIONS = ("Single (단독)", "Multiple (다수)", "None (없음)")
|
||||
_ACCEPTANCE_DESCRIPTIONS = ("Low (<3%)", "Mid (3~9%)", "High (>9%)")
|
||||
_PRICE_ZONE_DESCRIPTIONS = ("PZ1 (A≤P≤T)", "PZ2 (P>T)")
|
||||
|
||||
|
||||
class RevenueRange(IntEnum):
|
||||
"""매출액 가격구간"""
|
||||
|
||||
LOW = 0 # ≤ 1,000만원
|
||||
MID = 1 # 1,000만원 ~ 3,000만원
|
||||
HIGH = 2 # > 3,000만원
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _REVENUE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_amount(cls, amount: float) -> "RevenueRange":
|
||||
if amount <= 10_000_000:
|
||||
return cls.LOW
|
||||
elif amount <= 30_000_000:
|
||||
return cls.MID
|
||||
return cls.HIGH
|
||||
|
||||
|
||||
class DistributionStructure(IntEnum):
|
||||
"""유통 구조"""
|
||||
|
||||
MANUFACTURER = 0 # 제조 (M)
|
||||
WHOLESALER = 1 # 총판 (W)
|
||||
RETAILER = 2 # 유통 (R)
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _DISTRIBUTION_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_code(cls, code: str) -> "DistributionStructure":
|
||||
normalized = (code or "").strip().upper()
|
||||
mapping = {"M": cls.MANUFACTURER, "W": cls.WHOLESALER, "R": cls.RETAILER}
|
||||
if normalized not in mapping:
|
||||
raise ValueError(f"unknown distribution code: {code}")
|
||||
return mapping[normalized]
|
||||
|
||||
|
||||
class PartnerType(IntEnum):
|
||||
"""파트너사 종류"""
|
||||
|
||||
SINGLE = 0 # 단독
|
||||
MULTIPLE = 1 # 다수
|
||||
NONE = 2 # 없음
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _PARTNER_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_count(cls, count: int) -> "PartnerType":
|
||||
if count == 0:
|
||||
return cls.NONE
|
||||
elif count == 1:
|
||||
return cls.SINGLE
|
||||
return cls.MULTIPLE
|
||||
|
||||
|
||||
class AcceptanceRate(IntEnum):
|
||||
"""가격 수용률 구간"""
|
||||
|
||||
LOW = 0 # < 3%
|
||||
MID = 1 # 3% ~ 9%
|
||||
HIGH = 2 # > 9%
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _ACCEPTANCE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_ratio(cls, ratio: float) -> "AcceptanceRate":
|
||||
if ratio < 0.03:
|
||||
return cls.LOW
|
||||
elif ratio <= 0.09:
|
||||
return cls.MID
|
||||
return cls.HIGH
|
||||
|
||||
|
||||
class InputPriceZone(IntEnum):
|
||||
"""입력 금액 구간"""
|
||||
|
||||
PZ1 = 0 # A ≤ P ≤ T
|
||||
PZ2 = 1 # P > T
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return _PRICE_ZONE_DESCRIPTIONS[self.value]
|
||||
|
||||
@classmethod
|
||||
def from_prices(cls, input_price: float, anchor_price: float,
|
||||
target_price: float) -> "InputPriceZone":
|
||||
if anchor_price <= 0 or target_price <= 0:
|
||||
raise ValueError("anchor_price and target_price must be positive")
|
||||
if anchor_price > target_price:
|
||||
raise ValueError("anchor_price must not exceed target_price")
|
||||
if anchor_price <= input_price <= target_price:
|
||||
return cls.PZ1
|
||||
return cls.PZ2
|
||||
|
||||
|
||||
@dataclass
|
||||
class State:
|
||||
"""State = (매출구간, 유통구조, 파트너, 수용률, 가격구간) — 3×3×3×3×2 = 162"""
|
||||
|
||||
revenue_range: RevenueRange
|
||||
distribution: DistributionStructure
|
||||
partner_type: PartnerType
|
||||
acceptance_rate: AcceptanceRate
|
||||
input_price_zone: InputPriceZone
|
||||
|
||||
def to_array(self) -> List[int]:
|
||||
return [
|
||||
self.revenue_range.value,
|
||||
self.distribution.value,
|
||||
self.partner_type.value,
|
||||
self.acceptance_rate.value,
|
||||
self.input_price_zone.value,
|
||||
]
|
||||
|
||||
def to_index(self) -> int:
|
||||
"""State를 1차원 인덱스(0~161)로 변환"""
|
||||
return (
|
||||
self.revenue_range.value * 54
|
||||
+ self.distribution.value * 18
|
||||
+ self.partner_type.value * 6
|
||||
+ self.acceptance_rate.value * 2
|
||||
+ self.input_price_zone.value
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_index(cls, index: int) -> "State":
|
||||
if index < 0 or index >= 162:
|
||||
raise ValueError(f"index {index} out of range [0, 162)")
|
||||
revenue_value, remainder = divmod(index, 54)
|
||||
dist_value, remainder = divmod(remainder, 18)
|
||||
partner_value, remainder = divmod(remainder, 6)
|
||||
accept_value, pricezone_value = divmod(remainder, 2)
|
||||
return cls(
|
||||
revenue_range=RevenueRange(revenue_value),
|
||||
distribution=DistributionStructure(dist_value),
|
||||
partner_type=PartnerType(partner_value),
|
||||
acceptance_rate=AcceptanceRate(accept_value),
|
||||
input_price_zone=InputPriceZone(pricezone_value),
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return (
|
||||
f"State("
|
||||
f"revenue={self.revenue_range.description}, "
|
||||
f"distribution={self.distribution.description}, "
|
||||
f"partner={self.partner_type.description}, "
|
||||
f"acceptance={self.acceptance_rate.description}, "
|
||||
f"price_zone={self.input_price_zone.description})"
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""UCB 액션 선택 정책 — 에피소드 내 카드 중복 방지 포함."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from services.policy.visit_table import VisitTable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UCBPolicy:
|
||||
"""Upper Confidence Bound policy with per-episode action masking.
|
||||
|
||||
UCB = Q(s,a) + c * sqrt(ln(N(s)) / N(s,a))
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
visit_table: VisitTable,
|
||||
exploration_constant: float = float(np.sqrt(2.0)),
|
||||
epsilon: float = 1e-6,
|
||||
rng: Optional[np.random.Generator] = None,
|
||||
) -> None:
|
||||
self.visit_table = visit_table
|
||||
self.action_space_size = visit_table.action_space_size
|
||||
self.exploration_constant = exploration_constant
|
||||
self.epsilon = epsilon
|
||||
self._rng = rng or np.random.default_rng()
|
||||
self._episode_actions: set[int] = set()
|
||||
self._last_selection_info: dict = {}
|
||||
|
||||
def select_action(
|
||||
self,
|
||||
state_index: int,
|
||||
q_values: np.ndarray,
|
||||
available_mask: Optional[np.ndarray] = None,
|
||||
) -> Optional[int]:
|
||||
mask = self._prepare_mask(available_mask)
|
||||
if not mask.any():
|
||||
self.reset_episode()
|
||||
mask = self._prepare_mask(available_mask)
|
||||
if not mask.any():
|
||||
return None
|
||||
|
||||
counts = self.visit_table.get_state_counts(state_index)
|
||||
masked_counts = np.where(mask, counts, 0)
|
||||
total = max(masked_counts.sum(), 1)
|
||||
|
||||
# N(s,a)=0인 액션은 epsilon으로 대체 → UCB 보너스가 매우 커져 자연스럽게 우선 선택
|
||||
denom = np.where(counts > 0, counts.astype(float), self.epsilon)
|
||||
bonus = self.exploration_constant * np.sqrt(np.log(total + 1.0) / denom)
|
||||
scores = q_values + bonus
|
||||
scores[~mask] = -np.inf
|
||||
action = int(np.argmax(scores))
|
||||
|
||||
self._last_selection_info = {
|
||||
"visit_count": int(counts[action]),
|
||||
"total_visits": int(total),
|
||||
"ucb_score": float(scores[action]),
|
||||
}
|
||||
|
||||
logger.info(
|
||||
f"[UCB Policy - State {state_index}] "
|
||||
f"q={[f'{q:.3f}' for q in q_values]} visits={counts.tolist()} "
|
||||
f"mask={mask.astype(int).tolist()} => action {action}"
|
||||
)
|
||||
|
||||
self.visit_table.increment(state_index, action)
|
||||
self._episode_actions.add(action)
|
||||
return action
|
||||
|
||||
def reset_episode(self) -> None:
|
||||
"""에피소드(협상 세션) 내 사용된 액션 기록 초기화 — 세션 경계마다 호출할 것"""
|
||||
self._episode_actions.clear()
|
||||
|
||||
def get_action_mask(self) -> np.ndarray:
|
||||
mask = np.ones(self.action_space_size, dtype=int)
|
||||
for action in self._episode_actions:
|
||||
mask[action] = 0
|
||||
return mask
|
||||
|
||||
def _prepare_mask(self, available_mask: Optional[np.ndarray]) -> np.ndarray:
|
||||
if available_mask is None:
|
||||
mask = np.ones(self.action_space_size, dtype=bool)
|
||||
else:
|
||||
mask = np.asarray(available_mask, dtype=bool).copy()
|
||||
for action in self._episode_actions:
|
||||
mask[action] = False
|
||||
return mask
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Visit (N) table — UCB 정책의 방문 횟수 추적."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisitTable:
|
||||
state_space_size: int
|
||||
action_space_size: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._counts = np.zeros(
|
||||
(self.state_space_size, self.action_space_size), dtype=np.int64
|
||||
)
|
||||
|
||||
def increment(self, state_index: int, action_id: int, count: int = 1) -> None:
|
||||
self._validate_indices(state_index, action_id)
|
||||
if count < 0:
|
||||
raise ValueError("count must be non-negative")
|
||||
self._counts[state_index, action_id] += count
|
||||
|
||||
def get_action_count(self, state_index: int, action_id: int) -> int:
|
||||
self._validate_indices(state_index, action_id)
|
||||
return int(self._counts[state_index, action_id])
|
||||
|
||||
def get_state_counts(self, state_index: int) -> np.ndarray:
|
||||
self._validate_state(state_index)
|
||||
return self._counts[state_index, :].copy()
|
||||
|
||||
def total_visits(self, state_index: int) -> int:
|
||||
self._validate_state(state_index)
|
||||
return int(self._counts[state_index, :].sum())
|
||||
|
||||
def reset_state(self, state_index: int) -> None:
|
||||
self._validate_state(state_index)
|
||||
self._counts[state_index, :] = 0
|
||||
|
||||
def to_dict(self) -> Dict:
|
||||
return {
|
||||
"state_space_size": self.state_space_size,
|
||||
"action_space_size": self.action_space_size,
|
||||
"counts": self._counts.tolist(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict) -> "VisitTable":
|
||||
table = cls(
|
||||
state_space_size=data["state_space_size"],
|
||||
action_space_size=data["action_space_size"],
|
||||
)
|
||||
table._counts = np.array(data["counts"], dtype=np.int64)
|
||||
return table
|
||||
|
||||
def _validate_state(self, state_index: int) -> None:
|
||||
if state_index < 0 or state_index >= self.state_space_size:
|
||||
raise ValueError(
|
||||
f"state_index {state_index} out of range [0, {self.state_space_size})"
|
||||
)
|
||||
|
||||
def _validate_indices(self, state_index: int, action_id: int) -> None:
|
||||
self._validate_state(state_index)
|
||||
if action_id < 0 or action_id >= self.action_space_size:
|
||||
raise ValueError(
|
||||
f"action_id {action_id} out of range [0, {self.action_space_size})"
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""N-profiling — LLM 기반 스크립트 톤 변환 (on/off 가능).
|
||||
|
||||
off이거나 API 키가 없으면 프로파일러가 생성되지 않으며,
|
||||
협상 엔진은 원문 스크립트를 그대로 사용한다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Profiler:
|
||||
"""modifier + verifier 묶음. rewrite()가 검증 실패 시 None을 반환한다."""
|
||||
|
||||
def __init__(self, api_key: str, model: str):
|
||||
# openai 의존성은 profiling 활성 시에만 로드
|
||||
from services.profiling.modifier import ScriptModifier
|
||||
from services.profiling.verifier import ScriptVerifier
|
||||
|
||||
self.modifier = ScriptModifier(api_key=api_key, model=model)
|
||||
self.verifier = ScriptVerifier()
|
||||
|
||||
def rewrite(self, script: str, context: dict = None) -> Optional[str]:
|
||||
modified = self.modifier.modify_script(script, context)
|
||||
if modified is None:
|
||||
return None
|
||||
if not self.verifier.verify_script(script, modified):
|
||||
return None
|
||||
return modified
|
||||
|
||||
|
||||
def build_profiler(api_key: str, model: str, enabled: bool) -> Optional[Profiler]:
|
||||
"""설정에 따라 Profiler를 생성한다. 비활성/키 없음이면 None."""
|
||||
if not enabled:
|
||||
logger.info("[profiling] 비활성 (config)")
|
||||
return None
|
||||
if not api_key:
|
||||
logger.warning("[profiling] OPENAI_API_KEY 없음 — 프로파일링 비활성으로 기동")
|
||||
return None
|
||||
try:
|
||||
profiler = Profiler(api_key=api_key, model=model)
|
||||
logger.info(f"[profiling] 활성 (model={model})")
|
||||
return profiler
|
||||
except Exception as e:
|
||||
logger.warning(f"[profiling] 초기화 실패 — 비활성으로 기동: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,61 @@
|
||||
"""ScriptModifier — LLM으로 협상 스크립트의 톤을 상황·상대 성향에 맞게 재작성한다.
|
||||
|
||||
평문 입출력. {변수} 플레이스홀더는 보존해야 하며, 검증은 verifier가 담당한다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SYSTEM_PROMPT = """You are an expert Negotiation Script Editor.
|
||||
Rewrite the provided Korean negotiation script to match the requested tone/context.
|
||||
|
||||
Rules:
|
||||
1. **Preserve Variables**: Do NOT change, remove, or add any {placeholder} variables. \
|
||||
Only use variables that exist in the input.
|
||||
2. **Preserve Meaning**: Keep every factual statement and number intact. \
|
||||
Only adjust tone, phrasing, and flow.
|
||||
3. **Language**: The output MUST be in Korean (Hangul).
|
||||
4. **Plain Text Only**: Output ONLY the rewritten script text. \
|
||||
No markdown, no code fences, no explanations.
|
||||
5. Keep the line structure similar to the input (one thought per line)."""
|
||||
|
||||
_USER_TEMPLATE = """Original Script:
|
||||
{script}
|
||||
|
||||
Context/Instructions:
|
||||
{context}
|
||||
|
||||
Rewritten script:"""
|
||||
|
||||
|
||||
class ScriptModifier:
|
||||
def __init__(self, api_key: str, model: str = "gpt-4o"):
|
||||
self.client = OpenAI(api_key=api_key)
|
||||
self.model = model
|
||||
|
||||
def modify_script(self, script: str, context: dict = None) -> Optional[str]:
|
||||
"""스크립트 톤 재작성. 실패 시 None을 반환한다 (호출측에서 원문 유지)."""
|
||||
if not script or not script.strip():
|
||||
return None
|
||||
try:
|
||||
response = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
temperature=0,
|
||||
messages=[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": _USER_TEMPLATE.format(
|
||||
script=script, context=str(context or {}))},
|
||||
],
|
||||
)
|
||||
text = (response.choices[0].message.content or "").strip()
|
||||
# 혹시 모를 코드펜스 제거
|
||||
if text.startswith("```"):
|
||||
text = text.strip("`").strip()
|
||||
return text or None
|
||||
except Exception as e:
|
||||
logger.error(f"[ScriptModifier] LLM 호출 실패: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,31 @@
|
||||
"""ScriptVerifier — LLM이 재작성한 스크립트의 데이터 무결성 검증."""
|
||||
|
||||
import logging
|
||||
|
||||
from common.textutil import extract_placeholders
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ScriptVerifier:
|
||||
"""재작성된 스크립트가 원문의 {변수}를 그대로 보존했는지 검증한다."""
|
||||
|
||||
def verify_script(self, original: str, modified: str) -> bool:
|
||||
if not isinstance(modified, str) or not modified.strip():
|
||||
logger.warning("[ScriptVerifier] 검증 실패: 결과가 비어있음")
|
||||
return False
|
||||
|
||||
original_params = extract_placeholders(original)
|
||||
modified_params = extract_placeholders(modified)
|
||||
|
||||
missing = original_params - modified_params
|
||||
if missing:
|
||||
logger.warning(f"[ScriptVerifier] 검증 실패: 누락된 변수 {missing}")
|
||||
return False
|
||||
|
||||
added = modified_params - original_params
|
||||
if added:
|
||||
logger.warning(f"[ScriptVerifier] 검증 실패: 추가된 미지 변수 {added}")
|
||||
return False
|
||||
|
||||
return True
|
||||
Whitespace-only changes.
@@ -0,0 +1,76 @@
|
||||
"""계측 기능 테스트 — ⑩ 긴장도·페르소나, ⑦ 계약 데이터화."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from config.config_models import AppConfig, InstrumentConfig, ProfilingConfig
|
||||
from router.v1.nego.protocol import NegotiationRequest
|
||||
from services.negotiation.engine import ChatEngine
|
||||
from services.negotiation.tension import estimate_tension, select_persona
|
||||
|
||||
SNAP = {"rq_type": "재협상", "session_id": "T-1", "index": 5, "user_input": "예",
|
||||
"item_price": 163600.0, "revenue": 163600.0, "dist": "R", "partners_yn": "없음",
|
||||
"partners": 0, "anchor": 8099.0, "target": 8180.0, "initial": 9000.0,
|
||||
"input": 9000.0, "iteration": 0, "is_new_quote": True, "profiling": False}
|
||||
|
||||
|
||||
def make_engine(tmp_path):
|
||||
config = AppConfig(
|
||||
profiling=ProfilingConfig(enabled=False),
|
||||
instrument=InstrumentConfig(
|
||||
tension_log=str(tmp_path / "tension.jsonl"),
|
||||
response_time_log="",
|
||||
contracts_log=str(tmp_path / "contracts.jsonl"),
|
||||
),
|
||||
)
|
||||
return ChatEngine(config), tmp_path
|
||||
|
||||
|
||||
def test_persona_bands():
|
||||
assert select_persona(0.9)["name"] == "단호한 압박형"
|
||||
assert select_persona(0.5)["name"] == "균형 협상형"
|
||||
assert select_persona(0.1)["name"] == "우호적 마무리형"
|
||||
|
||||
|
||||
def test_estimate_tension_zones():
|
||||
# PZ1/PZ2(지표 ≥ 80) → 0, 초기제안가 = 최대 긴장 근사
|
||||
assert estimate_tension(99, 8180, 9000) == 0.0
|
||||
assert estimate_tension(34, 8180, 9000) > 0.5
|
||||
|
||||
|
||||
def test_tension_log_has_persona(tmp_path):
|
||||
engine, tmp = make_engine(tmp_path)
|
||||
req = NegotiationRequest(**dict(SNAP, step="가격협상_확인"))
|
||||
res = engine.process_request(req)
|
||||
assert res.step == "가격협상"
|
||||
rows = [json.loads(x) for x in (tmp / "tension.jsonl").read_text().splitlines()]
|
||||
assert rows, "긴장도 로그 미기록"
|
||||
row = rows[-1]
|
||||
assert 0.0 <= row["predicted"] <= 1.0
|
||||
assert row["persona"] in ("단호한 압박형", "균형 협상형", "우호적 마무리형")
|
||||
assert isinstance(row["indicator"], int)
|
||||
|
||||
|
||||
def test_contract_logged_on_completion(tmp_path):
|
||||
engine, tmp = make_engine(tmp_path)
|
||||
# 1% 와일드카드 수락 → 협상완료 (입력가 8000 ≤ 앵커 8099로 진입)
|
||||
req = NegotiationRequest(**dict(SNAP, step="wild_card_1pct", user_input="예",
|
||||
input=8000.0))
|
||||
res = engine.process_request(req)
|
||||
assert res.step == "협상완료"
|
||||
rows = [json.loads(x) for x in (tmp / "contracts.jsonl").read_text().splitlines()]
|
||||
assert len(rows) == 1
|
||||
rec = rows[0]
|
||||
assert rec["final_price"] == 7920 # 8000 × 0.99
|
||||
assert rec["reduction_pct"] is not None
|
||||
assert rec["rq_type"] == "재협상"
|
||||
|
||||
|
||||
def test_contract_not_logged_midway(tmp_path):
|
||||
engine, tmp = make_engine(tmp_path)
|
||||
engine.process_request(NegotiationRequest(**dict(SNAP, step="시작", index=0)))
|
||||
assert not (tmp / "contracts.jsonl").exists() or \
|
||||
not (tmp / "contracts.jsonl").read_text().strip()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""서버 스모크 테스트 — 엔진 기동, 고정/동적 스텝, 계측 응답."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
# 04 bench와 동일 형태의 가격협상 진입 요청
|
||||
HEAVY_BODY = {
|
||||
"rq_type": "재협상", "session_id": "TEST-01", "step": "가격협상_확인", "index": 5,
|
||||
"user_input": "예", "item_price": 163600, "revenue": 163600, "dist": "R",
|
||||
"partners_yn": "없음", "partners": 0, "anchor": 8099, "target": 8180,
|
||||
"initial": 9000, "input": 9000, "iteration": 0, "is_new_quote": True,
|
||||
"profiling": False,
|
||||
}
|
||||
|
||||
|
||||
def test_health():
|
||||
res = client.get("/health")
|
||||
assert res.status_code == 200
|
||||
assert res.json()["status"] == "OK"
|
||||
|
||||
|
||||
def test_config_endpoint():
|
||||
res = client.get("/v1/nego/config")
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["server"] == "NEGO_AGENT"
|
||||
assert body["cards"] > 0
|
||||
|
||||
|
||||
def test_fixed_step_start():
|
||||
res = client.post("/v1/nego/chat", json={
|
||||
"rq_type": "재협상", "session_id": "TEST-00", "step": "시작", "index": 0,
|
||||
})
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["step"] == "서비스안내"
|
||||
assert body["script"]
|
||||
# KT 지칭이 응답에 없어야 한다
|
||||
assert "kt" not in body["script"].lower()
|
||||
|
||||
|
||||
def test_dynamic_step_price_negotiation():
|
||||
"""가격협상_확인 [예] + 입력가 ≤ 앵커 → 와일드카드(1% 추가 네고) 진입."""
|
||||
body = dict(HEAVY_BODY, user_input="8000", step="가격협상_재입력", index=4)
|
||||
res = client.post("/v1/nego/chat", json=body)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["step"] == "가격협상_확인"
|
||||
|
||||
res2 = client.post("/v1/nego/chat", json=dict(HEAVY_BODY, input=8000))
|
||||
assert res2.status_code == 200
|
||||
out = res2.json()
|
||||
# 입력가(8000) ≤ 앵커(8099) + 유형 A → wild_card_1pct 스텝으로 전이
|
||||
assert out["step"] == "wild_card_1pct"
|
||||
assert out["script"]
|
||||
|
||||
|
||||
def test_dynamic_step_card_selection():
|
||||
"""입력가 > 앵커 상태의 가격협상_확인 [예] → '가격협상' 동적 스텝 — 카드 선택 + 지표 계산."""
|
||||
res = client.post("/v1/nego/chat", json=HEAVY_BODY)
|
||||
assert res.status_code == 200
|
||||
out = res.json()
|
||||
assert out["chat_metadata"]["card_id"]
|
||||
assert out["script"]
|
||||
assert out["chat_metadata"]["indicator_value"] is not None
|
||||
|
||||
|
||||
def test_response_time_header():
|
||||
res = client.get("/health")
|
||||
assert "x-response-time-ms" in res.headers
|
||||
|
||||
|
||||
def test_cards_are_plain_text():
|
||||
"""카드 정본은 평문 script만 갖는다 — Slate(editor_script)·KT 종속 변수 없음."""
|
||||
import json
|
||||
from common.paths import RESOURCES_DIR
|
||||
|
||||
nego = json.load(open(RESOURCES_DIR / "cards" / "nego_card.json", encoding="utf-8"))
|
||||
for card in nego["cards"]:
|
||||
assert set(card.keys()) == {"card_id", "card_name", "script"}
|
||||
assert "dss_count" not in card["script"]
|
||||
assert "kt" not in card["script"].lower()
|
||||
assert "그룹사" not in card["script"]
|
||||
|
||||
wild = json.load(open(RESOURCES_DIR / "cards" / "wild_card.json", encoding="utf-8"))
|
||||
for config in wild.values():
|
||||
assert "editor_script" not in config
|
||||
|
||||
|
||||
def test_card_variable_substitution_and_hidden():
|
||||
"""card_data 값은 치환되고, 값이 없는 변수 문장은 숨겨진다."""
|
||||
from services.cards.completer import CardScriptCompleter
|
||||
from services.cards.repository import CardScriptRepository
|
||||
from router.v1.nego.protocol import NegotiationCardData
|
||||
|
||||
completer = CardScriptCompleter(CardScriptRepository())
|
||||
|
||||
# 값이 있으면 치환
|
||||
out = completer.execute("NC26-007", NegotiationCardData(payment_terms="입고 후 30일 이내 현금 지급"))
|
||||
assert "입고 후 30일 이내 현금 지급" in out
|
||||
assert "{payment_terms}" not in out
|
||||
|
||||
# 값이 없으면 해당 문장 Hidden — 나머지 문장은 유지
|
||||
out2 = completer.execute("NC26-007", None)
|
||||
assert "payment_terms" not in out2
|
||||
assert "공급 가능한 가격" in out2
|
||||
|
||||
|
||||
def test_session_invalidate():
|
||||
res = client.post("/v1/nego/session/invalidate",
|
||||
json={"session_id": "TEST-01", "reason": "테스트"})
|
||||
assert res.status_code == 200
|
||||
assert res.json()["status"] == "ok"
|
||||
@@ -0,0 +1,20 @@
|
||||
# 실행 방법
|
||||
# pip install -r requirements.txt
|
||||
# python web_main.py
|
||||
#
|
||||
# 또는 uvicorn 직접 실행:
|
||||
# uvicorn router.router:app --host 0.0.0.0 --port 53117
|
||||
|
||||
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