초기 커밋 — 협상 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:
민헌andClaude Fable 5 committed 2026-08-31 13:09:52 +09:00
commit dfb9ad6e66
268 files changed
+164241

No files matched your search

View File
Whitespace-only changes.
+75
View File
@@ -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)
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+33
View File
@@ -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(),
}
+38
View File
@@ -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}
+103
View File
@@ -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] = "세션종료"