Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화
This commit is contained in:
1 parent
212725e5f9
commit
951d6eab84
140 files changed
+6689
-214
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,27 @@
|
||||
"""FastAPI 의존성 — 요청에서 테넌트 엔진을 해석한다 (계획서 B).
|
||||
|
||||
미들웨어가 검증/주입한 request.state.tenant_id 로 레지스트리에서 엔진을 가져온다.
|
||||
요청 본문엔 tenant 가 없다(위조 방지) — 항상 헤더 경로로만 결정된다.
|
||||
"""
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from common.enums import EXCEPTION_TENANT_HEADER_MISSING, EXCEPTION_TENANT_NOT_REGISTERED
|
||||
from tenancy.registry import TenantEngine, tenant_registry
|
||||
|
||||
|
||||
async def get_tenant_engine(request: Request) -> TenantEngine:
|
||||
tenant_id = getattr(request.state, "tenant_id", None)
|
||||
if not tenant_id:
|
||||
raise EXCEPTION_TENANT_HEADER_MISSING
|
||||
try:
|
||||
return await tenant_registry.get_engine(tenant_id)
|
||||
except KeyError:
|
||||
raise EXCEPTION_TENANT_NOT_REGISTERED
|
||||
|
||||
|
||||
def new_episode_state():
|
||||
"""요청 스코프 EpisodeState 생성 (정책 인스턴스에 두지 않기 위함)."""
|
||||
from negotiation.policies.base import EpisodeState
|
||||
|
||||
return EpisodeState()
|
||||
Whitespace-only changes.
@@ -0,0 +1,64 @@
|
||||
"""테넌트 라우팅 미들웨어.
|
||||
|
||||
규약 (계획서 B):
|
||||
- 헤더 `X-Tenant-ID`(1순위) / 경로 `/t/{id}/...`(폴백)로 테넌트 식별.
|
||||
- 부재 시 400(TENANT_HEADER_MISSING), 미등록 404(TENANT_NOT_REGISTERED).
|
||||
- default tenant 금지 (KT 사고 방지) — allow_default_tenant=false.
|
||||
- 요청 본문엔 tenant 미포함(위조 방지). 식별된 tenant_id 는 request.state.tenant_id 로만 전달.
|
||||
|
||||
NOTE(P0): 여기서는 헤더 추출 + 부재 검증까지만 한다.
|
||||
미등록 404 판정(레지스트리 조회)·company_id 매핑·엔진 resolve 는 P4(TenantEngineRegistry)에서 채운다.
|
||||
health/docs 등 화이트리스트 경로는 검사를 건너뛴다.
|
||||
"""
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from common.enums import ErrorType
|
||||
from config.server_configs import agent_config
|
||||
|
||||
_TENANT_HEADER = "X-Tenant-ID"
|
||||
|
||||
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI).
|
||||
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo")
|
||||
|
||||
|
||||
class TenantMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# CORS preflight(OPTIONS)는 테넌트 헤더 없이 오므로 통과시킨다(CORSMiddleware 가 처리).
|
||||
if request.method == "OPTIONS":
|
||||
return await call_next(request)
|
||||
|
||||
path = request.url.path
|
||||
if any(path.startswith(p) for p in _WHITELIST_PREFIXES):
|
||||
return await call_next(request)
|
||||
|
||||
tenant_id = request.headers.get(_TENANT_HEADER)
|
||||
|
||||
# 경로 폴백: /t/{tenant_id}/...
|
||||
if not tenant_id and path.startswith("/t/"):
|
||||
parts = path.split("/", 3)
|
||||
if len(parts) >= 3 and parts[2]:
|
||||
tenant_id = parts[2]
|
||||
|
||||
if not tenant_id:
|
||||
if agent_config.allow_default_tenant:
|
||||
tenant_id = "_base"
|
||||
else:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"result": {"success": False, "code": ErrorType.TENANT_HEADER_MISSING.value, "desc": ErrorType.TENANT_HEADER_MISSING.name}},
|
||||
)
|
||||
|
||||
# 미등록 테넌트는 404 (default tenant 금지 — KT 사고 방지).
|
||||
from tenancy.registry import tenant_registry
|
||||
|
||||
if not tenant_registry.is_registered(tenant_id):
|
||||
return JSONResponse(
|
||||
status_code=404,
|
||||
content={"result": {"success": False, "code": ErrorType.TENANT_NOT_REGISTERED.value, "desc": ErrorType.TENANT_NOT_REGISTERED.name}},
|
||||
)
|
||||
|
||||
request.state.tenant_id = tenant_id
|
||||
return await call_next(request)
|
||||
@@ -0,0 +1,77 @@
|
||||
import os
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from router.middleware.tenant_middleware import TenantMiddleware
|
||||
import router.v1.health.health
|
||||
import router.v1.negotiation.negotiation
|
||||
import router.v1.chat.chat
|
||||
import router.v1.learning.learning
|
||||
import router.v1.card.card
|
||||
|
||||
API_SERVER_START_TIME = GTime.UTCStr()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# startup: 공유 베이스(_base) 없으면 자동 시드 (운영 자동화, P5)
|
||||
from bootstrap.lifespan import ensure_base_seeded
|
||||
await ensure_base_seeded()
|
||||
yield
|
||||
# shutdown: DB 엔진 커넥션 풀 정리
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
|
||||
|
||||
app = FastAPI(title="Negosium Agent Server", lifespan=lifespan)
|
||||
|
||||
# Accept-Encoding: gzip 요청에 대해 1000 bytes 이상 응답을 압축.
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
||||
# 테넌트 라우팅 미들웨어 (헤더 X-Tenant-ID → request.state.tenant_id).
|
||||
app.add_middleware(TenantMiddleware)
|
||||
# 데모 HTML(file:// 또는 타 출처)에서 호출 가능하도록 CORS 허용 (개발용 — 운영은 출처 제한 권장).
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def log_time(request: Request, call_next):
|
||||
start_time = time.time()
|
||||
response = await call_next(request)
|
||||
elapsed = time.time() - start_time
|
||||
LOG.d(f"took: {elapsed:.4f} - {request.url.path}")
|
||||
return response
|
||||
|
||||
|
||||
@app.get(path="/healthz", responses={404: {"description": "Not found"}})
|
||||
async def healthz():
|
||||
return API_SERVER_START_TIME
|
||||
|
||||
|
||||
# 간단 테스트 프론트 (tests/negotiation_demo.html). 같은 출처로 서빙 → CORS 불필요.
|
||||
_DEMO_HTML = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tests", "negotiation_demo.html")
|
||||
|
||||
|
||||
@app.get(path="/demo", include_in_schema=False)
|
||||
async def demo():
|
||||
return FileResponse(_DEMO_HTML)
|
||||
|
||||
|
||||
# 각 도메인 라우터 등록. 새 기능 추가 시 router.v1.<domain>.<file> import 후 include.
|
||||
# (chat / card / learning / qtable 라우터는 P7 에서 Chat_server 14개 API 이식하며 추가)
|
||||
app.include_router(router.v1.health.health.router)
|
||||
app.include_router(router.v1.negotiation.negotiation.router)
|
||||
app.include_router(router.v1.chat.chat.router)
|
||||
app.include_router(router.v1.learning.learning.router)
|
||||
app.include_router(router.v1.card.card.router)
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
"""카드 매핑 API (card-update / card-search, tenant 스코프).
|
||||
|
||||
PoC: action_id ↔ card_id 매핑을 learning.tenant_action_cards 에 둔다(config 기본 + DB override).
|
||||
카드 스크립트 본문은 ScriptRepository(tenants/<id>/resources)가 담당 — 여기선 매핑만.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import ErrorType
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from router.deps import get_tenant_engine
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
async def _merged_mapping(engine: TenantEngine) -> dict:
|
||||
"""config 기본 매핑 위에 DB override 를 얹은 action→card 최종 매핑."""
|
||||
mapping = {int(a): c for a, c in engine.config.action_mapping.action_to_card.items()}
|
||||
overrides = await LearningRepository(engine.company_id).get_action_cards()
|
||||
for o in overrides:
|
||||
mapping[o["action_id"]] = o["card_id"]
|
||||
return mapping
|
||||
|
||||
|
||||
class CardUpdateReq(BaseModel):
|
||||
action_id: int
|
||||
card_id: str
|
||||
|
||||
|
||||
@router.post("/card-update", summary="카드 매핑 갱신(action→card)")
|
||||
async def card_update(req: CardUpdateReq, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
if not (0 <= req.action_id < engine.action_space_size):
|
||||
return {"success": False, "desc": "action_id out of range",
|
||||
"action_space_size": engine.action_space_size}
|
||||
err = await LearningRepository(engine.company_id).upsert_action_card(req.action_id, req.card_id)
|
||||
return {"success": err == ErrorType.SUCCESS, "company_id": engine.company_id,
|
||||
"action_id": req.action_id, "card_id": req.card_id, "desc": err.name}
|
||||
|
||||
|
||||
@router.get("/card-search", summary="카드 검색(전체 매핑 또는 card_id 조회)")
|
||||
async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
mapping = await _merged_mapping(engine)
|
||||
if card_id:
|
||||
hits = [a for a, c in mapping.items() if c == card_id]
|
||||
return {"company_id": engine.company_id, "card_id": card_id, "action_ids": hits, "found": bool(hits)}
|
||||
return {"company_id": engine.company_id,
|
||||
"mapping": [{"action_id": a, "card_id": c} for a, c in sorted(mapping.items())]}
|
||||
Whitespace-only changes.
@@ -0,0 +1,24 @@
|
||||
"""chat 라우터 (대화형 협상, P7 슬라이스). 엔진 주입(헤더→레지스트리) → ChatService."""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from router.deps import get_tenant_engine
|
||||
from router.v1.chat.protocol import Req_Chat, Res_Chat
|
||||
from services.chat_service import ChatService
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
router = APIRouter(prefix="/v1/chat", tags=["Chat (negotiation)"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
response_model=Res_Chat,
|
||||
summary="협상 대화 한 턴",
|
||||
description="session_id 없으면 새 협상 시작. user_input 으로 진행(버튼 텍스트/가격). X-Tenant-ID 헤더 필수.",
|
||||
)
|
||||
async def chat(
|
||||
req: Req_Chat,
|
||||
engine: TenantEngine = Depends(get_tenant_engine),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return await service.chat(engine, req)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""chat 라우터 프로토콜 (대화형 /chat, P7 슬라이스)."""
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol
|
||||
|
||||
|
||||
class Req_Chat(Req_WebPacketProtocol):
|
||||
"""대화 한 턴. session_id 없으면 새 협상 시작(아래 컨텍스트로). tenant 는 헤더로만."""
|
||||
|
||||
session_id: Optional[str] = Field(None, description="없으면 새 세션 생성")
|
||||
rq_type: str = Field("재협상", description="재협상 | 재견적")
|
||||
user_input: Optional[str] = Field(None, description="버튼 선택 텍스트 또는 가격(price 모드)")
|
||||
# 새 세션 시작 시 협상 컨텍스트 (옵션, 기본값 제공)
|
||||
revenue_amount: float = 20_000_000
|
||||
distribution_code: str = "A"
|
||||
partner_count: int = 1
|
||||
acceptance_ratio: float = 0.05
|
||||
# 갑(KT/iMK)이 직접 입력. anchor < target. anchor 기본 제안값 = target*(1-0.01).
|
||||
target_price: float = 10000 # KT 목표 매입가
|
||||
anchor_price: float = 9900 # KT 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
||||
|
||||
|
||||
class Res_Chat(Res_WebPacketProtocol):
|
||||
session_id: Optional[str] = None
|
||||
step: Optional[str] = None
|
||||
client_step: Optional[str] = None
|
||||
script: Optional[str] = None
|
||||
input_mode: Optional[str] = None
|
||||
input_options: Optional[List[str]] = None
|
||||
chat_end: bool = False
|
||||
outcome: Optional[str] = None
|
||||
# 가격협상 턴에서 선택된 협상 카드 + 학습 메타
|
||||
card_id: Optional[str] = None
|
||||
policy: Optional[str] = None
|
||||
q_value: Optional[float] = None
|
||||
updated_q: Optional[float] = None
|
||||
visit_count: Optional[int] = None
|
||||
reward_total: Optional[float] = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,9 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
# 협상 엔진 헬스체크 (Chat_server /health 이식). MVC 컨벤션: 라우터는 얇게.
|
||||
router = APIRouter(prefix="/v1", tags=["Health"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(path="/health", summary="협상 에이전트 헬스체크")
|
||||
async def health():
|
||||
return {"status": "ok", "service": "negosium-agent"}
|
||||
Whitespace-only changes.
@@ -0,0 +1,149 @@
|
||||
"""learning/qtable 관리 API (Chat_server 14개 API 보존, tenant 스코프).
|
||||
|
||||
엔드포인트: /q-table/versions·switch·current, /experience-logs, /reset-learning, /reset-all,
|
||||
/invalidate-session, /train. 모두 X-Tenant-ID 헤더로 company_id 격리.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import ErrorType
|
||||
from negotiation.policies.base import Transition
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.policy.model_store import QTablePolicyStore
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from router.deps import get_tenant_engine
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["Learning / Q-Table"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
def _repo(engine: TenantEngine) -> LearningRepository:
|
||||
return LearningRepository(engine.company_id)
|
||||
|
||||
|
||||
@router.get("/q-table/versions", summary="Q-Table 버전 목록")
|
||||
async def list_versions(engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
err, versions = await repo.read(lambda s: repo.list_versions(s))
|
||||
return {"company_id": engine.company_id, "versions": [
|
||||
{"version_name": v.version_name, "is_active": v.is_active, "scope": v.scope,
|
||||
"state_space_size": v.state_space_size, "action_space_size": v.action_space_size,
|
||||
"epochs": v.epochs, "created_at": str(v.created_at)} for v in (versions or [])]}
|
||||
|
||||
|
||||
class SwitchReq(BaseModel):
|
||||
version_name: str
|
||||
|
||||
|
||||
@router.post("/q-table/switch", summary="활성 Q-Table 버전 전환")
|
||||
async def switch_version(req: SwitchReq, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
err = await _repo(engine).set_active_version(req.version_name)
|
||||
ok = err == ErrorType.SUCCESS
|
||||
return {"success": ok, "active_version": req.version_name if ok else None,
|
||||
"desc": err.name}
|
||||
|
||||
|
||||
@router.get("/q-table/current", summary="현재 활성 Q-Table 상태")
|
||||
async def current_qtable(engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
if not active:
|
||||
return {"company_id": engine.company_id, "active_version": None, "q_value_rows": 0}
|
||||
rows = await repo.qvalue_count(active.version_id)
|
||||
return {"company_id": engine.company_id, "active_version": active.version_name,
|
||||
"state_space_size": active.state_space_size, "action_space_size": active.action_space_size,
|
||||
"q_value_rows": rows}
|
||||
|
||||
|
||||
@router.get("/experience-logs", summary="최근 경험 로그")
|
||||
async def experience_logs(limit: int = 50, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
err, total = await repo.read(lambda s: repo.count_experience(s))
|
||||
logs = await repo.recent_experience(limit=min(limit, 500))
|
||||
return {"company_id": engine.company_id, "total": total, "logs": logs}
|
||||
|
||||
|
||||
@router.post("/reset-learning", summary="[관리] 학습 데이터 초기화(자사 스코프)")
|
||||
async def reset_learning(engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
err = await _repo(engine).reset_learning()
|
||||
return {"success": err == ErrorType.SUCCESS, "company_id": engine.company_id, "desc": err.name}
|
||||
|
||||
|
||||
@router.post("/reset-all", summary="[관리] 완전 초기화(자사 스코프, 타테넌트 무영향)")
|
||||
async def reset_all(engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
err = await _repo(engine).reset_all()
|
||||
return {"success": err == ErrorType.SUCCESS, "company_id": engine.company_id, "desc": err.name}
|
||||
|
||||
|
||||
class InvalidateReq(BaseModel):
|
||||
session_id: str
|
||||
reason: Optional[str] = "invalidated"
|
||||
|
||||
|
||||
@router.post("/invalidate-session", summary="세션 학습 데이터 무효화")
|
||||
async def invalidate_session(req: InvalidateReq, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
err = await repo.write_one(lambda s: repo.invalidate_by_session(s, req.session_id, req.reason))
|
||||
return {"success": err == ErrorType.SUCCESS, "session_id": req.session_id, "desc": err.name}
|
||||
|
||||
|
||||
class TrainReq(BaseModel):
|
||||
epochs: int = 1
|
||||
|
||||
|
||||
@router.post("/train", summary="오프라인 Q-Learning 학습(경험로그 기반)")
|
||||
async def train(req: TrainReq, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
transitions = await repo.load_transitions()
|
||||
if not transitions:
|
||||
return {"success": True, "trained_transitions": 0, "note": "경험 로그 없음 (먼저 /chat 진행)"}
|
||||
|
||||
S, A = engine.state_space_size, engine.action_space_size
|
||||
qt = QTable(S, A, learning_rate=engine.config.policy.learning_rate, discount_factor=engine.config.policy.gamma)
|
||||
# 활성 버전에서 현재 Q 적재
|
||||
version_id = await repo.get_or_create_active_version(
|
||||
state_space_size=S, action_space_size=A,
|
||||
learning_rate=engine.config.policy.learning_rate, discount_factor=engine.config.policy.gamma)
|
||||
qrows, vrows = await repo.load_cells(version_id)
|
||||
for st, a, q in qrows:
|
||||
if 0 <= st < S and 0 <= a < A:
|
||||
qt.q[st, a] = q
|
||||
policy = UCBQTablePolicy(qt, mark_visits=False)
|
||||
|
||||
updates = 0
|
||||
touched = set()
|
||||
for _ in range(max(1, req.epochs)):
|
||||
for st, a, r, ns, done in transitions:
|
||||
if st is None or a is None or not (0 <= st < S and 0 <= a < A):
|
||||
continue
|
||||
policy.update(Transition(state_index=st, action_id=a, reward=r, next_state_index=ns, done=bool(done)))
|
||||
touched.add((st, a))
|
||||
updates += 1
|
||||
# 갱신된 셀 영속화
|
||||
for (st, a) in touched:
|
||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, st, a)
|
||||
|
||||
return {"success": True, "trained_transitions": len(transitions), "epochs": req.epochs,
|
||||
"updates": updates, "cells_persisted": len(touched), "company_id": engine.company_id}
|
||||
|
||||
|
||||
@router.get("/verification-report", summary="Q-Table 검증 리포트(요약)")
|
||||
async def verification_report(engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
repo = _repo(engine)
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
err, total_exp = await repo.read(lambda s: repo.count_experience(s))
|
||||
if not active:
|
||||
return {"company_id": engine.company_id, "active_version": None, "experience_total": total_exp}
|
||||
qrows, vrows = await repo.load_cells(active.version_id)
|
||||
nonzero = [(s, a, q) for s, a, q in qrows if q != 0]
|
||||
top = sorted(nonzero, key=lambda x: -x[2])[:10]
|
||||
return {
|
||||
"company_id": engine.company_id, "active_version": active.version_name,
|
||||
"experience_total": total_exp, "q_value_rows": len(qrows), "nonzero_q": len(nonzero),
|
||||
"visited_cells": len(vrows),
|
||||
"top_q": [{"state_index": s, "action_id": a, "q_value": round(q, 4)} for s, a, q in top],
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,28 @@
|
||||
"""negotiation 라우터 (컨트롤러). 엔진 주입(헤더→레지스트리) → service 호출만 담당.
|
||||
|
||||
NOTE: 현재는 P2 의사결정 루프의 HTTP 프리뷰(/v1/negotiation/step).
|
||||
실제 대화 /chat + 14개 API + step 체계는 P7 에서 이식한다.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from router.deps import get_tenant_engine
|
||||
from router.v1.negotiation.protocol import Req_NegotiationStep, Res_NegotiationStep
|
||||
from services.negotiation_service import NegotiationService
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation (preview)"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/step",
|
||||
response_model=Res_NegotiationStep,
|
||||
summary="협상 한 라운드 (프리뷰)",
|
||||
description="관측치 → 상태분류 → (임시)카드선택 → 보상 → DB로깅. X-Tenant-ID 헤더 필수. 실제 학습/대화는 미구현.",
|
||||
)
|
||||
async def step(
|
||||
req: Req_NegotiationStep,
|
||||
engine: TenantEngine = Depends(get_tenant_engine),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return await service.step(engine, req)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""negotiation 라우터 프로토콜 (backend Protocol 규약: Req_/Res_ + result: ErrorInfo)."""
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol
|
||||
|
||||
|
||||
class Req_NegotiationStep(Req_WebPacketProtocol):
|
||||
"""한 협상 라운드 관측치. tenant 는 본문에 없음(헤더 X-Tenant-ID 로만, 위조 방지)."""
|
||||
|
||||
# 이산 상태 산출 입력
|
||||
revenue_amount: float = Field(..., description="매출액(원)")
|
||||
distribution_code: str = Field("A", description="유통 구조 외부 코드 (테넌트 code_map)")
|
||||
partner_count: int = Field(1, description="파트너사 수")
|
||||
acceptance_ratio: float = Field(..., description="가격 수용률 0~1")
|
||||
input_price: float = Field(..., description="현재 제시/입력 가격")
|
||||
anchor_price: float = Field(..., description="앵커(시작) 가격")
|
||||
target_price: float = Field(..., description="목표 가격")
|
||||
# 시퀀스/보상
|
||||
round_number: int = Field(1, description="협상 라운드(turn)")
|
||||
outcome: str = Field("ongoing", description="ongoing | success | failure")
|
||||
# 세션/에피소드 (HTTP 무상태 — 클라이언트가 사용한 action 을 전달해 중복 방지)
|
||||
session_id: Optional[str] = Field(None, description="협상 세션 uuid (없으면 생성)")
|
||||
used_action_ids: Optional[List[int]] = Field(None, description="이미 제시한 action(중복방지 마스킹)")
|
||||
log: bool = Field(True, description="learning.experience_logs 에 기록할지")
|
||||
learn: bool = Field(True, description="Q-Table 온라인 갱신 + 영속화 여부")
|
||||
|
||||
|
||||
# 중첩 뷰는 result/msg 가 필요 없으므로 순수 BaseModel.
|
||||
class StateView(BaseModel):
|
||||
revenue_idx: int = 0
|
||||
distribution_idx: int = 0
|
||||
partner_idx: int = 0
|
||||
acceptance_idx: int = 0
|
||||
price_zone_idx: int = 0
|
||||
|
||||
|
||||
class RewardView(BaseModel):
|
||||
price_reward: float = 0.0
|
||||
end_reward: float = 0.0
|
||||
penalty: float = 0.0
|
||||
weight: float = 0.0
|
||||
total: float = 0.0
|
||||
|
||||
|
||||
class Res_NegotiationStep(Res_WebPacketProtocol):
|
||||
tenant_id: Optional[str] = None
|
||||
company_id: Optional[str] = None
|
||||
session_id: Optional[str] = None
|
||||
state_index: Optional[int] = None
|
||||
state: Optional[StateView] = None
|
||||
action_id: Optional[int] = None
|
||||
card_id: Optional[str] = None
|
||||
propensity: Optional[float] = None
|
||||
available_actions: Optional[List[int]] = None
|
||||
reward: Optional[RewardView] = None
|
||||
logged: bool = False
|
||||
# 학습 가시화: 선택 시점 Q, UCB 점수, 갱신 후 Q, 이 state-action 누적 방문수, 정책명
|
||||
policy: Optional[str] = None
|
||||
q_value: Optional[float] = None
|
||||
ucb_score: Optional[float] = None
|
||||
updated_q: Optional[float] = None
|
||||
visit_count: Optional[int] = None
|
||||
learned: bool = False
|
||||
Reference in new issue
Block a user