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,183 @@
|
||||
"""콘솔 데모 — 현재까지 구현된(P0~P4) 협상 의사결정 루프를 화면 없이 콘솔에서 돌린다.
|
||||
|
||||
흐름: TenantConfig 로드 → 엔진 조립 → (협상 관측치) → build_state/state_index
|
||||
→ 카드 선택(※임시 placeholder 정책) → reward 계산 → learning.experience_logs 로깅.
|
||||
|
||||
주의: 실제 Q-Table UCB 정책/대화 step 체계는 아직 미구현(H1/P5/P7).
|
||||
여기 카드선택은 '가용 액션 중 최소 인덱스' 임시 정책이며 학습하지 않는다.
|
||||
이 데모의 목적은 "테넌트별 config 주입·상태분류·보상·DB 격리"를 눈으로 확인하는 것.
|
||||
|
||||
실행:
|
||||
cd agent
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 시나리오
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from negotiation.policies.base import ActionDecision, EpisodeState
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from negotiation.qtable.domain.service.state_calculator import build_state, state_index
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
|
||||
def _placeholder_select(engine, ctx_state_index, episode: EpisodeState) -> ActionDecision:
|
||||
"""임시 정책: 가용(미사용) 액션 중 최소 인덱스. propensity 는 균등분포 가정.
|
||||
(실제 UCB Q-Table 정책은 H1/P5 에서 대체된다.)
|
||||
"""
|
||||
mask = engine.mapper.available_mask(episode.used_action_ids)
|
||||
available = [a for a in engine.mapper.action_ids() if mask[a]]
|
||||
if not available:
|
||||
available = engine.mapper.action_ids() # 다 썼으면 리셋
|
||||
action_id = available[0]
|
||||
propensity = 1.0 / len(available)
|
||||
return ActionDecision(
|
||||
action_id=action_id,
|
||||
propensity=propensity,
|
||||
card_id=engine.mapper.get_card_id(action_id),
|
||||
available_actions=available,
|
||||
)
|
||||
|
||||
|
||||
def _print_turn(turn, snap, st, idx, decision, reward):
|
||||
print(f"\n── turn {turn} " + "─" * 40)
|
||||
print(f" 관측: 매출={snap.revenue_amount:,.0f} 유통={snap.distribution_code} 파트너={snap.partner_count} "
|
||||
f"수용률={snap.acceptance_ratio:.2f} 입력가={snap.input_price:,.0f} (앵커 {snap.anchor_price:,.0f}~목표 {snap.target_price:,.0f})")
|
||||
print(f" 상태: revenue={st.revenue_idx} dist={st.distribution_idx} partner={st.partner_idx} "
|
||||
f"accept={st.acceptance_idx} pricezone={st.price_zone_idx} → state_index={idx}")
|
||||
print(f" 선택: action={decision.action_id} card={decision.card_id} "
|
||||
f"propensity={decision.propensity:.3f} (가용 {decision.available_actions})")
|
||||
print(f" 보상: total={reward.total:+.4f} (price={reward.price_reward:.3f} end={reward.end_reward:+.2f} "
|
||||
f"penalty={reward.penalty:.3f} weight={reward.weight:.2f}) outcome={snap.outcome.value}")
|
||||
|
||||
|
||||
def _scenario():
|
||||
"""기본 3턴 시나리오 (KT 구매자: 협력사 제시가가 11000→10200→9800 으로 내려와 앵커가(9900) 이하에서 타결)."""
|
||||
return [
|
||||
dict(input_price=11000, acceptance_ratio=0.02, round_number=1, outcome=NegotiationOutcome.ONGOING),
|
||||
dict(input_price=10200, acceptance_ratio=0.05, round_number=2, outcome=NegotiationOutcome.ONGOING),
|
||||
dict(input_price=9800, acceptance_ratio=0.11, round_number=3, outcome=NegotiationOutcome.SUCCESS),
|
||||
]
|
||||
|
||||
|
||||
async def run(tenant_id: str, use_db: bool, interactive: bool):
|
||||
loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)
|
||||
if not loader.is_registered(tenant_id):
|
||||
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: ktcommerce, imarketkorea, _base")
|
||||
return
|
||||
registry = TenantEngineRegistry(loader=loader)
|
||||
engine = await registry.get_engine(tenant_id)
|
||||
reward_calc = RewardCalculator(engine.config.reward)
|
||||
repo = LearningRepository(engine.company_id)
|
||||
episode = EpisodeState()
|
||||
session_id = uuid.uuid4()
|
||||
|
||||
print("=" * 56)
|
||||
print(f" 콘솔 데모 — tenant={tenant_id} company_id={engine.company_id}")
|
||||
print(f" state_space={engine.state_space_size} action_space={engine.action_space_size}")
|
||||
print(f" 카드셋 예: action0={engine.mapper.get_card_id(0)} ... action{engine.action_space_size-1}={engine.mapper.get_card_id(engine.action_space_size-1)}")
|
||||
print(f" DB 로깅: {'ON (learning.experience_logs)' if use_db else 'OFF'}")
|
||||
print(" ※ 카드선택은 임시 placeholder 정책 (실제 UCB Q-Table 은 H1/P5)")
|
||||
print("=" * 56)
|
||||
|
||||
turns = _interactive_turns() if interactive else _scenario()
|
||||
logged = 0
|
||||
for i, params in enumerate(turns, start=1):
|
||||
snap = NegotiationSnapshot(
|
||||
revenue_amount=params.get("revenue_amount", 20_000_000),
|
||||
distribution_code=params.get("distribution_code", "A"),
|
||||
partner_count=params.get("partner_count", 1),
|
||||
acceptance_ratio=params["acceptance_ratio"],
|
||||
input_price=params["input_price"],
|
||||
anchor_price=params.get("anchor_price", 9900),
|
||||
target_price=params.get("target_price", 10000),
|
||||
round_number=params["round_number"],
|
||||
outcome=params["outcome"],
|
||||
)
|
||||
try:
|
||||
st = build_state(snap, engine.config.state)
|
||||
idx = state_index(snap, engine.config.state)
|
||||
except ValueError as ex:
|
||||
print(f"[!] 상태 산출 실패: {ex}")
|
||||
continue
|
||||
decision = _placeholder_select(engine, idx, episode)
|
||||
episode.mark_used(decision.action_id)
|
||||
reward = reward_calc.calculate(snap)
|
||||
_print_turn(i, snap, st, idx, decision, reward)
|
||||
|
||||
if use_db:
|
||||
data = {
|
||||
"session_id": session_id,
|
||||
"state_index": idx,
|
||||
"action_id": decision.action_id,
|
||||
"card_id": decision.card_id,
|
||||
"snapshot": snap.to_dict(),
|
||||
"propensity": decision.propensity,
|
||||
"turn": snap.round_number,
|
||||
"available_actions": decision.available_actions,
|
||||
"reward": reward.total,
|
||||
"done": snap.outcome != NegotiationOutcome.ONGOING,
|
||||
"settled_price": int(snap.input_price) if snap.outcome == NegotiationOutcome.SUCCESS else None,
|
||||
}
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [lambda s: repo.log_transition(s, data)])
|
||||
logged += 1 if err == ErrorType.SUCCESS else 0
|
||||
|
||||
if use_db:
|
||||
err, cnt = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: repo.count_experience(s)
|
||||
)
|
||||
print(f"\n[DB] 이번 실행에서 {logged}건 로깅. company_id={engine.company_id} 누적 experience={cnt}건")
|
||||
print(" (다른 테넌트로 실행해도 서로 섞이지 않음 — company_id 논리격리 확인용)")
|
||||
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
|
||||
|
||||
def _interactive_turns():
|
||||
print("\n[대화형] 빈 줄(엔터)이면 기본값. outcome: o(ongoing)/s(success)/f(failure). 'q' 입력 시 종료.\n")
|
||||
turns = []
|
||||
rnd = 1
|
||||
while True:
|
||||
raw = input(f"turn {rnd} - 입력가(예 930) [q종료]: ").strip()
|
||||
if raw.lower() == "q":
|
||||
break
|
||||
try:
|
||||
input_price = float(raw) if raw else 900
|
||||
except ValueError:
|
||||
print(" 숫자를 입력하세요."); continue
|
||||
acc = input(" 수용률(0~1, 예 0.05): ").strip()
|
||||
oc = input(" 결과 o/s/f: ").strip().lower()
|
||||
outcome = {"s": NegotiationOutcome.SUCCESS, "f": NegotiationOutcome.FAILURE}.get(oc, NegotiationOutcome.ONGOING)
|
||||
turns.append(dict(
|
||||
input_price=input_price,
|
||||
acceptance_ratio=float(acc) if acc else 0.05,
|
||||
round_number=rnd,
|
||||
outcome=outcome,
|
||||
))
|
||||
rnd += 1
|
||||
if outcome != NegotiationOutcome.ONGOING:
|
||||
break
|
||||
return turns
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)")
|
||||
ap.add_argument("--tenant", default="ktcommerce", help="테넌트 id (ktcommerce|imarketkorea)")
|
||||
ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화")
|
||||
ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력")
|
||||
args = ap.parse_args()
|
||||
asyncio.run(run(args.tenant, use_db=not args.no_db, interactive=args.interactive))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""init_base — 공유 베이스 정책(_base) 시드 (P5, 계획서 D).
|
||||
|
||||
시뮬레이터로 UCB Q-Table 을 학습시켜 learning 스키마의 _base(scope=base) 버전에 저장한다.
|
||||
신규 테넌트는 cold-start 시 이 베이스를 warm-start 복제해 어느 정도 학습된 상태로 시작한다.
|
||||
|
||||
실행: cd agent && APP_ENV=local python -m tools.init_base [--action-space 9] [--episodes 500]
|
||||
차원(state×action)은 신규 테넌트와 호환돼야 복제된다(데모 테넌트=162×9).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import BASE_COMPANY_ID
|
||||
from common.logger import LOG
|
||||
from eval_harness.buyer import HeuristicBuyer, Scenario, best_actions, make_card_effectiveness
|
||||
from eval_harness.registry import build_policy
|
||||
from eval_harness.simulator import run_episode
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
|
||||
async def seed_base(action_space: int = 9, episodes: int = 500, seed: int = 123,
|
||||
anchor: float = 8000, target: float = 10000) -> dict:
|
||||
cfg = TenantConfigLoader().load(BASE_COMPANY_ID) # _base: state 162
|
||||
S = cfg.state.state_space_size
|
||||
A = action_space
|
||||
lr, gamma = cfg.policy.learning_rate, cfg.policy.gamma
|
||||
|
||||
# 시뮬레이터로 베이스 학습
|
||||
policy = build_policy("qtable_ucb", cfg.state, A, cfg.policy, seed=seed)
|
||||
eff = make_card_effectiveness(A, seed=seed)
|
||||
buyer = HeuristicBuyer(eff, seed=seed)
|
||||
scenario = Scenario(anchor_price=anchor, target_price=target)
|
||||
for i in range(episodes):
|
||||
buyer.reseed(seed * 100_000 + i)
|
||||
run_episode(policy, buyer, scenario, cfg.state, cfg.reward, A, learn=True)
|
||||
|
||||
# _base 버전(scope=base)에 저장 (재시드 시 기존 셀 비우고 갱신)
|
||||
repo = LearningRepository(BASE_COMPANY_ID)
|
||||
vid = await repo.get_or_create_active_version(
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
|
||||
scope=1, version_name="base_v000")
|
||||
await repo.reset_learning() # 이전 셀 정리(버전은 유지)
|
||||
cells = policy.qtable.nonzero_cells()
|
||||
for st, a, q, c in cells:
|
||||
await repo.upsert_cell(vid, st, a, q, c)
|
||||
|
||||
return {"version_id": str(vid), "state_space": S, "action_space": A,
|
||||
"episodes": episodes, "cells": len(cells), "good_cards": best_actions(eff)}
|
||||
|
||||
|
||||
async def _main(args):
|
||||
info = await seed_base(action_space=args.action_space, episodes=args.episodes)
|
||||
print("=" * 56)
|
||||
print(" 베이스 정책 시드 완료 (_base, scope=base)")
|
||||
print(f" 버전: {info['version_id']} 차원: {info['state_space']}x{info['action_space']}")
|
||||
print(f" 학습 에피소드: {info['episodes']} 저장 셀: {info['cells']}")
|
||||
print(f" (숨은) 좋은 카드: {info['good_cards']}")
|
||||
print(" → 이제 신규 테넌트 첫 협상 시 warm-start 로 이 베이스를 복제합니다.")
|
||||
print("=" * 56)
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="공유 베이스 정책 시드 (P5)")
|
||||
ap.add_argument("--action-space", type=int, default=9)
|
||||
ap.add_argument("--episodes", type=int, default=500)
|
||||
args = ap.parse_args()
|
||||
asyncio.run(_main(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""learning.experience_logs 를 company_id 별로 집계 출력 (DB 격리 확인용).
|
||||
|
||||
실행: cd agent && APP_ENV=local python -m tools.show_logs
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import ExperienceLog
|
||||
from common.enums import DBType, DBWRType
|
||||
|
||||
|
||||
async def main():
|
||||
def q(s):
|
||||
stmt = (
|
||||
select(ExperienceLog.company_id, func.count().label("n"), func.max(ExperienceLog.reward).label("max_reward"))
|
||||
.group_by(ExperienceLog.company_id)
|
||||
.order_by(ExperienceLog.company_id)
|
||||
)
|
||||
return DB_SESSION_MNG.execute(s, stmt)
|
||||
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, q)
|
||||
print("company_id count max_reward")
|
||||
print("-" * 44)
|
||||
for company_id, n, max_reward in rows:
|
||||
mr = f"{max_reward:+.4f}" if max_reward is not None else " n/a "
|
||||
print(f"{company_id:<20} {n:>6} {mr}")
|
||||
if not rows:
|
||||
print("(비어있음 — 먼저 tools.console_demo 를 실행하세요)")
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in new issue
Block a user