Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화

This commit is contained in:
HyeongBaeYang committed 2026-06-17 11:10:03 +09:00
1 parent 212725e5f9
commit 951d6eab84
140 files changed
+6689 -214

No files matched your search

View File
Whitespace-only changes.
+56
View File
@@ -0,0 +1,56 @@
"""비교용 baseline 정책 (NegotiationPolicy 구현). 학습 정책과 같은 인터페이스로 하네스에 등록."""
import numpy as np
from negotiation.policies.base import ActionDecision, NegotiationPolicy, PolicyContext, Transition
class RandomPolicy(NegotiationPolicy):
"""가용 액션 중 무작위 선택. 학습하지 않음(update no-op). 학습 정책의 하한 비교군."""
name = "random"
def __init__(self, seed: int = 0):
self.rng = np.random.default_rng(seed)
def _available(self, ctx: PolicyContext):
used = ctx.episode.used_action_ids if ctx.episode else set()
avail = [a for a in range(ctx.action_space_size) if a not in used]
return avail or list(range(ctx.action_space_size))
def select(self, ctx: PolicyContext) -> ActionDecision:
avail = self._available(ctx)
a = int(self.rng.choice(avail))
if ctx.episode:
ctx.episode.mark_used(a)
return ActionDecision(action_id=a, propensity=1.0 / len(avail), available_actions=avail)
def update(self, transition: Transition) -> None:
pass
def predict_action_dist(self, ctx: PolicyContext) -> np.ndarray:
avail = self._available(ctx)
dist = np.zeros(ctx.action_space_size)
for a in avail:
dist[a] = 1.0 / len(avail)
return dist
class StaticPolicy(NegotiationPolicy):
"""항상 고정 카드(기본 action 0). '정적 운영'(학습 없음) 비교군."""
name = "static"
def __init__(self, fixed_action: int = 0):
self.fixed = fixed_action
def select(self, ctx: PolicyContext) -> ActionDecision:
used = ctx.episode.used_action_ids if ctx.episode else set()
a = self.fixed if self.fixed not in used else next(
(x for x in range(ctx.action_space_size) if x not in used), self.fixed)
if ctx.episode:
ctx.episode.mark_used(a)
return ActionDecision(action_id=a, propensity=1.0, available_actions=[a])
def update(self, transition: Transition) -> None:
pass
+79
View File
@@ -0,0 +1,79 @@
"""시뮬레이션 구매자 (계획서 G, H5).
PoC 본체의 핵심: **카드(action) 선택에 따라 협상 결과가 달라지는** 환경. 그래야 에이전트가
"어떤 카드가 좋은가"를 보상으로 학습할 수 있고, 학습 정책이 random 보다 성과가 오르는지 검증 가능.
- HeuristicBuyer: LLM 없이 결정론적(seed)으로 동작. 각 카드에 숨은 효과(effectiveness)를 부여해
수락확률·타결가에 반영. 에이전트는 이를 모르고 보상으로만 추정한다.
- LLMBuyer(옵션): Azure OpenAI 가상 구매자(페르소나/예산). 자격증명(llm.enabled) 있을 때만.
"""
from dataclasses import dataclass
from typing import Dict, List, Optional
import numpy as np
@dataclass
class Scenario:
"""KT 구매자 관점. anchor=협력사 기준가(높음) ≥ target=KT 목표 매입가(낮음)."""
anchor_price: float # 협력사 기준가(앵커). 제시가 ≤ anchor → 우선협상
target_price: float # KT 목표 매입가(낮음). 낮게 타결할수록 보상↑
revenue_amount: float = 20_000_000
distribution_code: str = "A"
partner_count: int = 1
acceptance_ratio: float = 0.05
@dataclass
class BuyerResponse:
accept: bool
new_price: float # 협력사가 양보한 새 제시가(이번 턴 후)
walked: bool = False # 협상 이탈(결렬)
class HeuristicBuyer:
"""카드 효과 기반 결정론적 '협력사(판매자)' 모델 (KT 구매자가 상대).
card_effectiveness[action] ∈ [0,1] 가 클수록: 협력사가 더 크게 양보(가격 인하)하고 수락확률↑
→ KT 에게 유리(낮은 타결가). 효과는 비공개이며 에이전트는 보상으로만 추정.
"""
def __init__(self, card_effectiveness: Dict[int, float], seed: int = 0,
accept_base: float = 0.10, accept_gain: float = 0.75, max_turns: int = 5):
self.eff = card_effectiveness
self.rng = np.random.default_rng(seed)
self.accept_base = accept_base
self.accept_gain = accept_gain
self.max_turns = max_turns
def reseed(self, seed: int):
self.rng = np.random.default_rng(seed)
def respond(self, action_id: int, scenario: Scenario, turn: int, current_price: float) -> BuyerResponse:
eff = float(self.eff.get(action_id, 0.1))
# 협력사 양보: 효과 클수록 앵커가 쪽으로 더 많이 내려온다(KT 이득). 앵커가 이하까지 도달 가능.
floor = scenario.anchor_price * 0.95
concession = (current_price - floor) * (0.15 + 0.55 * eff)
new_price = max(floor, current_price - concession)
# 수락(현 가격에 합의)확률: 효과 + 후반 라운드 압박.
p_accept = min(0.97, self.accept_base + self.accept_gain * eff + 0.06 * (turn - 1))
accept = bool(self.rng.random() < p_accept)
walked = (not accept) and (turn >= self.max_turns)
return BuyerResponse(accept=accept, new_price=new_price, walked=walked)
def make_card_effectiveness(action_space_size: int, seed: int = 0,
n_good: int = 3) -> Dict[int, float]:
"""카드 효과 벡터 생성: n_good 개의 '좋은 카드'(0.75~0.95) + 나머지 약효(0.05~0.35)."""
rng = np.random.default_rng(seed)
eff = {a: float(rng.uniform(0.05, 0.35)) for a in range(action_space_size)}
good = rng.choice(action_space_size, size=min(n_good, action_space_size), replace=False)
for a in good:
eff[int(a)] = float(rng.uniform(0.75, 0.95))
return eff
def best_actions(card_effectiveness: Dict[int, float], k: int = 3) -> List[int]:
return [a for a, _ in sorted(card_effectiveness.items(), key=lambda kv: -kv[1])[:k]]
@@ -0,0 +1,18 @@
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
episodes: 400 # 정책당 협상 에피소드 수
seed: 42 # 재현용 (구매자 randomness 페어드)
max_turns: 5 # 협상 라운드 상한
n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수
curve_buckets: 10 # 학습곡선 구간 수
policies: # 비교 대상 (random/static = 비학습 비교군, qtable_ucb = 학습)
- random
- static
- qtable_ucb
scenario: # KT 구매자(갑): anchor(앵커링) < target(목표 매입가). 갑이 직접 입력.
target_price: 10000 # KT 목표 매입가
anchor_price: 8000 # KT 앵커링가(공격적으로 낮게 설정). 제시가 ≤ 8000 → 우선협상
# ↑ 0.99×target(9900)도 가능하나, 카드 효과가 드러나려면 협상 여지(갭)가 있어야 함
revenue_amount: 20000000
distribution_code: A
partner_count: 1
acceptance_ratio: 0.05
+77
View File
@@ -0,0 +1,77 @@
"""지표 집계 + 학습곡선 (H5, 계획서 G 지표)."""
import math
from dataclasses import dataclass
from typing import List
from eval_harness.simulator import EpisodeResult
@dataclass
class Aggregate:
n: int
success_rate: float
mean_settled_ratio: float # 평균 타결가 / 목표가
mean_turns: float
mean_reward: float
reward_ci95: float # 평균보상 95% 신뢰구간 반폭
def as_row(self) -> dict:
return {
"n": self.n,
"success_rate": round(self.success_rate, 3),
"mean_settled_ratio": round(self.mean_settled_ratio, 3),
"mean_turns": round(self.mean_turns, 2),
"mean_reward": round(self.mean_reward, 4),
"reward_ci95": round(self.reward_ci95, 4),
}
def aggregate(results: List[EpisodeResult]) -> Aggregate:
n = len(results)
if n == 0:
return Aggregate(0, 0, 0, 0, 0, 0)
succ = sum(1 for r in results if r.success) / n
settled = sum(r.settled_ratio for r in results) / n
turns = sum(r.turns for r in results) / n
rewards = [r.total_reward for r in results]
mean_r = sum(rewards) / n
var = sum((x - mean_r) ** 2 for x in rewards) / n if n > 1 else 0.0
ci = 1.96 * math.sqrt(var / n) if n > 1 else 0.0
return Aggregate(n, succ, settled, turns, mean_r, ci)
def learning_curve(results: List[EpisodeResult], buckets: int = 10) -> List[float]:
"""에피소드를 buckets 구간으로 나눠 구간별 평균 보상 (우상향이면 학습)."""
n = len(results)
if n == 0:
return []
size = max(1, n // buckets)
curve = []
for i in range(0, n, size):
chunk = results[i:i + size]
curve.append(round(sum(r.total_reward for r in chunk) / len(chunk), 4))
return curve
def good_card_hit_rate(first_actions: List[int], good_actions: List[int], last_frac: float = 0.3) -> float:
"""후반 구간에서 첫 카드가 '좋은 카드'였던 비율 (학습 수렴 지표)."""
if not first_actions:
return 0.0
tail = first_actions[max(0, int(len(first_actions) * (1 - last_frac))):]
good = set(good_actions)
return sum(1 for a in tail if a in good) / len(tail)
def hit_curve(first_actions: List[int], good_actions: List[int], buckets: int = 10) -> List[float]:
"""구간별 '좋은 카드 선택' 비율 (학습 전/후 개선곡선 — 세일즈용)."""
n = len(first_actions)
if n == 0:
return []
good = set(good_actions)
size = max(1, n // buckets)
curve = []
for i in range(0, n, size):
chunk = first_actions[i:i + size]
curve.append(round(sum(1 for a in chunk if a in good) / len(chunk), 3))
return curve
+33
View File
@@ -0,0 +1,33 @@
"""정책 레지스트리 — 하네스에서 비교할 정책 인스턴스 팩토리 (H5).
현재: random / static / qtable_ucb. LinUCB(H3)·CQL(H6)은 같은 NegotiationPolicy 로 추후 등록.
"""
import math
from eval_harness.baselines import RandomPolicy, StaticPolicy
from negotiation.policies.qtable_policy import UCBQTablePolicy
from negotiation.qtable.domain.model.q_table import QTable
from tenancy.config import PolicyConfig, StateConfig
def build_policy(name: str, state_cfg: StateConfig, action_space_size: int,
policy_cfg: PolicyConfig, seed: int = 0):
"""이름으로 새 정책 인스턴스 생성 (메모리 QTable, DB 미사용 — 시뮬 속도/격리)."""
if name == "random":
return RandomPolicy(seed=seed)
if name == "static":
return StaticPolicy(fixed_action=0)
if name in ("qtable_ucb", "qtable", "ucb"):
qt = QTable(state_cfg.state_space_size, action_space_size,
learning_rate=policy_cfg.learning_rate, discount_factor=policy_cfg.gamma)
params = policy_cfg.params or {}
return UCBQTablePolicy(
qt,
exploration_constant=params.get("exploration_constant", math.sqrt(2.0)),
epsilon=params.get("propensity_epsilon", 0.1),
)
raise ValueError(f"unknown policy: {name} (지원: random|static|qtable_ucb; LinUCB/CQL 은 H3/H6)")
AVAILABLE = ["random", "static", "qtable_ucb"]
+162
View File
@@ -0,0 +1,162 @@
"""eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체).
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효".
구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다.
"""
import argparse
import json
import os
from typing import Dict, List
import yaml
from eval_harness.buyer import HeuristicBuyer, Scenario, best_actions, make_card_effectiveness
from eval_harness.metrics import aggregate, good_card_hit_rate, hit_curve, learning_curve
from eval_harness.registry import build_policy
from eval_harness.simulator import run_episode
from tenancy.config_loader import TenantConfigLoader
_HERE = os.path.dirname(os.path.abspath(__file__))
def _resolve_config(path: str) -> str:
if os.path.isabs(path) and os.path.exists(path):
return path
for cand in (path, os.path.join(_HERE, path), os.path.join(_HERE, "configs", os.path.basename(path))):
if os.path.exists(cand):
return cand
raise FileNotFoundError(f"config not found: {path}")
def run(config_path: str, tenant_id: str) -> dict:
with open(_resolve_config(config_path), "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f)
tcfg = TenantConfigLoader().load(tenant_id)
A = tcfg.action_mapping.action_space_size
if A == 0:
raise ValueError(f"tenant {tenant_id} 에 action 매핑이 없습니다 (action_space_size=0)")
scn_raw = cfg.get("scenario", {})
scenario = Scenario(
anchor_price=scn_raw.get("anchor_price", 8000), target_price=scn_raw.get("target_price", 10000),
revenue_amount=scn_raw.get("revenue_amount", 20_000_000),
distribution_code=scn_raw.get("distribution_code", "A"),
partner_count=scn_raw.get("partner_count", 1), acceptance_ratio=scn_raw.get("acceptance_ratio", 0.05),
)
episodes = int(cfg.get("episodes", 400))
seed = int(cfg.get("seed", 42))
max_turns = int(cfg.get("max_turns", 5))
buckets = int(cfg.get("curve_buckets", 10))
n_good = int(cfg.get("n_good_cards", 3))
policy_names = cfg.get("policies", ["random", "qtable_ucb"])
# 카드 효과(숨김) + 좋은 카드 — 구매자는 테넌트/seed 로 고정. 정책은 모른다.
eff = make_card_effectiveness(A, seed=seed, n_good=n_good)
good = best_actions(eff, k=n_good)
report = {"tenant": tenant_id, "episodes": episodes, "seed": seed,
"action_space_size": A, "good_cards": good, "policies": {}}
for name in policy_names:
policy = build_policy(name, tcfg.state, A, tcfg.policy, seed=seed)
buyer = HeuristicBuyer(eff, seed=seed, max_turns=max_turns)
results = []
for i in range(episodes):
buyer.reseed(seed * 100_000 + i) # 페어드: 정책 간 동일 구매자 randomness
learn = name in ("qtable_ucb", "qtable", "ucb")
results.append(run_episode(policy, buyer, scenario, tcfg.state, tcfg.reward, A,
max_turns=max_turns, learn=learn))
agg = aggregate(results)
firsts = [r.first_action for r in results]
# 초반 구간 미세 곡선(첫 50 에피소드, 5개씩) — 빠른 수렴 시 cold→warm 상승을 드러냄.
early = hit_curve(firsts[:50], good, buckets=10)
report["policies"][name] = {
**agg.as_row(),
"learning_curve": learning_curve(results, buckets=buckets),
"good_card_hit_rate": round(good_card_hit_rate(firsts, good), 3),
"hit_curve": hit_curve(firsts, good, buckets=buckets),
"early_hit_curve": early,
}
report["verdict"] = _verdict(report)
return report
def _verdict(report: dict) -> dict:
pols = report["policies"]
learner = pols.get("qtable_ucb")
baseline = pols.get("random") or pols.get("static")
if not learner or not baseline:
return {"pass": None, "note": "학습/비교군 부재"}
# PoC 판정(계획서 G): 학습형이 random/정적 대비 성과 우상향.
# - 평균보상 우위 + 95%CI 비중첩(통계적 분리)
# - '좋은 카드' 적중 우위(학습으로 카드 우열을 알아냄)
# - cold→warm: 초반 미세곡선이 baseline 수준에서 상승
beats_reward = learner["mean_reward"] - learner["reward_ci95"] > baseline["mean_reward"] + baseline["reward_ci95"]
beats_hit = learner["good_card_hit_rate"] >= baseline["good_card_hit_rate"] + 0.2
ec = learner.get("early_hit_curve") or [0, 0]
cold_warm = len(ec) >= 2 and ec[-1] > ec[0]
passed = beats_reward and beats_hit
return {
"pass": bool(passed),
"ci_separated": bool(beats_reward),
"learner_mean_reward": learner["mean_reward"],
"baseline_mean_reward": baseline["mean_reward"],
"reward_uplift": round(learner["mean_reward"] - baseline["mean_reward"], 4),
"learner_good_hit": learner["good_card_hit_rate"],
"baseline_good_hit": baseline["good_card_hit_rate"],
"early_cold_to_warm": [ec[0], ec[-1]] if ec else [],
"cold_warm_rising": bool(cold_warm),
"note": ("학습형이 baseline 대비 평균보상 우위(95%CI 분리) + '좋은 카드' 적중 우위 → 학습 루프 유효"
if passed else "개선 미확인"),
}
def _print(report: dict):
print("=" * 70)
print(f" 알고리즘 비교 — tenant={report['tenant']} episodes={report['episodes']} seed={report['seed']}")
print(f" (숨은) 좋은 카드 action: {report['good_cards']} / 총 {report['action_space_size']}개")
print("=" * 70)
hdr = f"{'policy':<12} {'success':>8} {'settled/tgt':>12} {'turns':>7} {'mean_rwd':>10} {'±95%CI':>9} {'good_hit':>9}"
print(hdr); print("-" * len(hdr))
for name, p in report["policies"].items():
print(f"{name:<12} {p['success_rate']:>8.3f} {p['mean_settled_ratio']:>12.3f} "
f"{p['mean_turns']:>7.2f} {p['mean_reward']:>10.4f} {p['reward_ci95']:>9.4f} {p['good_card_hit_rate']:>9.3f}")
print("-" * len(hdr))
print("\n학습 개선곡선 ('좋은 카드' 선택률 구간별, 세일즈용):")
for name, p in report["policies"].items():
print(f" {name:<12} 전구간 {p.get('hit_curve')}")
print(f"\n qtable_ucb 초반 cold→warm (첫 50ep, 5개씩): {report['policies'].get('qtable_ucb', {}).get('early_hit_curve')}")
v = report["verdict"]
flag = "✅ PASS" if v.get("pass") else ("— " if v.get("pass") is None else "❌ FAIL")
print(f"\n판정 {flag}: {v.get('note')}")
if v.get("pass") is not None:
print(f" 평균보상 학습형 {v['learner_mean_reward']} vs baseline {v['baseline_mean_reward']} "
f"(uplift {v['reward_uplift']}, 95%CI 분리={v['ci_separated']})")
print(f" 좋은카드 적중 학습형 {v['learner_good_hit']} vs baseline {v['baseline_good_hit']} · "
f"cold→warm {v['early_cold_to_warm']}")
def main():
ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)")
ap.add_argument("--config", default="configs/exp_default.yaml")
ap.add_argument("--tenant", default="ktcommerce")
ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장")
args = ap.parse_args()
report = run(args.config, args.tenant)
_print(report)
if args.save:
out_dir = os.path.join(_HERE, "reports")
os.makedirs(out_dir, exist_ok=True)
out = os.path.join(out_dir, f"report_{args.tenant}.json")
with open(out, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print(f"\n[저장] {out}")
if __name__ == "__main__":
main()
+83
View File
@@ -0,0 +1,83 @@
"""에피소드 시뮬레이터 — 정책 vs 구매자의 한 협상 시퀀스 (H5).
한 에피소드: 앵커에서 시작, 매 턴 정책이 카드 선택 → 구매자 반응(수락/계속/이탈) → 보상.
수락 시 타결가로 성공 종료, 마지막 턴까지 미수락이면 결렬. 보상은 RewardCalculator(테넌트 config)로 채점.
정책의 update(Transition)로 온라인 학습(시퀀스 보상). 동일 seed 시 재현 가능(페어드 비교).
"""
from dataclasses import dataclass
from eval_harness.buyer import HeuristicBuyer, Scenario
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
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 state_index
from tenancy.config import RewardConfig, StateConfig
@dataclass
class EpisodeResult:
success: bool
settled_price: float
turns: int
total_reward: float
target_price: float
first_action: int = -1 # 첫 턴 선택 카드(학습 수렴 측정용)
@property
def settled_ratio(self) -> float:
return self.settled_price / self.target_price if self.target_price else 0.0
def run_episode(policy, buyer: HeuristicBuyer, scenario: Scenario,
state_cfg: StateConfig, reward_cfg: RewardConfig, action_space_size: int,
max_turns: int = 5, learn: bool = True) -> EpisodeResult:
rc = RewardCalculator(reward_cfg)
episode = EpisodeState()
total_r = 0.0
# 협력사는 목표가보다 높게 시작(협상 여지). KT 가 카드로 앵커가 이하까지 끌어내린다.
price = scenario.target_price * 1.15
last_idx = last_action = None
first_action = -1
def snap(p, turn, outcome):
return NegotiationSnapshot(
revenue_amount=scenario.revenue_amount, distribution_code=scenario.distribution_code,
partner_count=scenario.partner_count, acceptance_ratio=scenario.acceptance_ratio,
input_price=p, anchor_price=scenario.anchor_price, target_price=scenario.target_price,
round_number=turn, outcome=outcome,
)
for turn in range(1, max_turns + 1):
s = snap(price, turn, NegotiationOutcome.ONGOING)
idx = state_index(s, state_cfg)
ctx = PolicyContext(state_index=idx, snapshot=s, action_space_size=action_space_size, episode=episode)
decision = policy.select(ctx)
last_idx, last_action = idx, decision.action_id
if turn == 1:
first_action = decision.action_id
resp = buyer.respond(decision.action_id, scenario, turn, price)
price = resp.new_price # 협력사가 양보한 새 가격
# 우선협상(제시가 ≤ anchor) 또는 협력사 수락 → 타결
if resp.accept or price <= scenario.anchor_price:
fs = snap(price, turn, NegotiationOutcome.SUCCESS)
r = rc.calculate(fs).total # 낮은 타결가일수록 보상↑
if learn:
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=r, done=True))
total_r += r
return EpisodeResult(True, price, turn, total_r, scenario.target_price, first_action)
# 미타결: 진행 보상 후 다음 턴(가격은 계속 내려간 상태)
r = rc.calculate(s).total
if learn:
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=r, done=False))
total_r += r
# 카드 소진/라운드 종료까지 우선협상 미달 → 결렬
fs = snap(price, max_turns, NegotiationOutcome.FAILURE)
r = rc.calculate(fs).total
if learn and last_idx is not None:
policy.update(Transition(state_index=last_idx, action_id=last_action, reward=r, done=True))
total_r += r
return EpisodeResult(False, price, max_turns, total_r, scenario.target_price, first_action)