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.
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