feat: Clawdbot Gateway 모니터링 페이지 + API 클라이언트
- /admin/ai-gw: 토큰 사용량/비용 실시간 모니터링 대시보드 - clawdbot_client.py: Gateway HTTP API 클라이언트 (세션 상태, 사용량 조회) - 세션별 토큰/비용 통계, 모델별 breakdown - API 문서 추가 (docs/clawdbot-gateway-api.md)
This commit is contained in:
parent
ccb0067a1c
commit
2a090c9704
@ -321,6 +321,122 @@ def generate_upsell_real(user_name, current_items, recent_products, available_pr
|
||||
return _parse_upsell_response(response_text)
|
||||
|
||||
|
||||
# ===== Claude 상태 조회 =====
|
||||
|
||||
async def _get_gateway_status():
|
||||
"""
|
||||
Clawdbot Gateway에서 세션 목록 조회
|
||||
토큰 차감 없음 (AI 호출 아님)
|
||||
"""
|
||||
config = _load_gateway_config()
|
||||
url = f"ws://127.0.0.1:{config['port']}"
|
||||
token = config['token']
|
||||
|
||||
try:
|
||||
async with websockets.connect(url, max_size=25 * 1024 * 1024,
|
||||
close_timeout=5) as ws:
|
||||
# 1. connect.challenge 대기
|
||||
challenge_msg = await asyncio.wait_for(ws.recv(), timeout=10)
|
||||
challenge = json.loads(challenge_msg)
|
||||
nonce = None
|
||||
if challenge.get('event') == 'connect.challenge':
|
||||
nonce = challenge.get('payload', {}).get('nonce')
|
||||
|
||||
# 2. connect 요청
|
||||
connect_id = str(uuid.uuid4())
|
||||
connect_frame = {
|
||||
'type': 'req',
|
||||
'id': connect_id,
|
||||
'method': 'connect',
|
||||
'params': {
|
||||
'minProtocol': 3,
|
||||
'maxProtocol': 3,
|
||||
'client': {
|
||||
'id': 'gateway-client',
|
||||
'displayName': 'Pharmacy Status',
|
||||
'version': '1.0.0',
|
||||
'platform': 'win32',
|
||||
'mode': 'backend',
|
||||
'instanceId': str(uuid.uuid4()),
|
||||
},
|
||||
'caps': [],
|
||||
'auth': {'token': token},
|
||||
'role': 'operator',
|
||||
'scopes': ['operator.read'],
|
||||
}
|
||||
}
|
||||
await ws.send(json.dumps(connect_frame))
|
||||
|
||||
# 3. connect 응답 대기
|
||||
while True:
|
||||
msg = await asyncio.wait_for(ws.recv(), timeout=10)
|
||||
data = json.loads(msg)
|
||||
if data.get('id') == connect_id:
|
||||
if not data.get('ok'):
|
||||
error = data.get('error', {}).get('message', 'connect failed')
|
||||
logger.warning(f"[Clawdbot] connect 실패: {error}")
|
||||
return {'error': error, 'connected': False}
|
||||
break
|
||||
|
||||
# 4. sessions.list 요청
|
||||
list_id = str(uuid.uuid4())
|
||||
list_frame = {
|
||||
'type': 'req',
|
||||
'id': list_id,
|
||||
'method': 'sessions.list',
|
||||
'params': {
|
||||
'limit': 10
|
||||
}
|
||||
}
|
||||
await ws.send(json.dumps(list_frame))
|
||||
|
||||
# 5. 응답 대기
|
||||
while True:
|
||||
msg = await asyncio.wait_for(ws.recv(), timeout=10)
|
||||
data = json.loads(msg)
|
||||
|
||||
# 이벤트 무시
|
||||
if data.get('event'):
|
||||
continue
|
||||
|
||||
if data.get('id') == list_id:
|
||||
if data.get('ok'):
|
||||
return {
|
||||
'connected': True,
|
||||
'sessions': data.get('payload', {})
|
||||
}
|
||||
else:
|
||||
error = data.get('error', {}).get('message', 'unknown')
|
||||
return {'error': error, 'connected': True}
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("[Clawdbot] Gateway 타임아웃")
|
||||
return {'error': 'timeout', 'connected': False}
|
||||
except (ConnectionRefusedError, OSError) as e:
|
||||
logger.warning(f"[Clawdbot] Gateway 연결 실패: {e}")
|
||||
return {'error': str(e), 'connected': False}
|
||||
except Exception as e:
|
||||
logger.warning(f"[Clawdbot] 상태 조회 실패: {e}")
|
||||
return {'error': str(e), 'connected': False}
|
||||
|
||||
|
||||
def get_claude_status():
|
||||
"""
|
||||
동기 래퍼: Claude 상태 조회
|
||||
|
||||
Returns:
|
||||
dict: 상태 정보
|
||||
"""
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
result = loop.run_until_complete(_get_gateway_status())
|
||||
loop.close()
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning(f"[Clawdbot] 상태 조회 실패: {e}")
|
||||
return {'error': str(e), 'connected': False}
|
||||
|
||||
|
||||
def _parse_upsell_response(text):
|
||||
"""AI 응답에서 JSON 추출"""
|
||||
import re
|
||||
|
||||
559
backend/templates/admin_ai_gw.html
Normal file
559
backend/templates/admin_ai_gw.html
Normal file
@ -0,0 +1,559 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AI Gateway 모니터 - 청춘약국</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: #0f172a;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: #e2e8f0;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* ── 헤더 ── */
|
||||
.header {
|
||||
background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
|
||||
padding: 28px 32px 24px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
.header-nav {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.header-nav a {
|
||||
color: rgba(255,255,255,0.6);
|
||||
text-decoration: none;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
.header-nav a:hover { color: #fff; }
|
||||
.header h1 {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.5px;
|
||||
margin-bottom: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.header h1 .live-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: #22c55e;
|
||||
border-radius: 50%;
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
.header h1 .live-dot.offline { background: #ef4444; animation: none; }
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.4); }
|
||||
50% { opacity: 0.8; box-shadow: 0 0 0 8px rgba(34, 197, 94, 0); }
|
||||
}
|
||||
.header p {
|
||||
font-size: 14px;
|
||||
color: rgba(255,255,255,0.5);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* ── 컨텐츠 ── */
|
||||
.content {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 20px 60px;
|
||||
}
|
||||
|
||||
/* ── 메인 카드 ── */
|
||||
.main-card {
|
||||
background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
|
||||
border-radius: 20px;
|
||||
padding: 32px;
|
||||
margin-bottom: 24px;
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
.main-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.main-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: rgba(255,255,255,0.5);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.main-model {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: #a78bfa;
|
||||
}
|
||||
.refresh-btn {
|
||||
background: rgba(255,255,255,0.1);
|
||||
border: none;
|
||||
color: rgba(255,255,255,0.7);
|
||||
padding: 10px 18px;
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.refresh-btn:hover {
|
||||
background: rgba(255,255,255,0.15);
|
||||
color: #fff;
|
||||
}
|
||||
.refresh-btn.loading { opacity: 0.6; pointer-events: none; }
|
||||
|
||||
/* 컨텍스트 표시 */
|
||||
.context-display {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.context-numbers {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.context-used {
|
||||
font-size: 64px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -3px;
|
||||
line-height: 1;
|
||||
}
|
||||
.context-max {
|
||||
font-size: 24px;
|
||||
font-weight: 500;
|
||||
color: rgba(255,255,255,0.3);
|
||||
}
|
||||
.context-percent {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: #22c55e;
|
||||
margin-left: 16px;
|
||||
}
|
||||
.context-percent.warning { color: #fbbf24; }
|
||||
.context-percent.danger { color: #ef4444; }
|
||||
|
||||
/* 프로그레스 바 */
|
||||
.progress-wrap {
|
||||
background: rgba(255,255,255,0.1);
|
||||
border-radius: 100px;
|
||||
height: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
border-radius: 100px;
|
||||
background: linear-gradient(90deg, #22c55e, #84cc16);
|
||||
transition: width 0.6s ease;
|
||||
}
|
||||
.progress-bar.warning { background: linear-gradient(90deg, #f59e0b, #fbbf24); }
|
||||
.progress-bar.danger { background: linear-gradient(90deg, #ef4444, #f97316); }
|
||||
|
||||
/* 통계 그리드 */
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 16px;
|
||||
margin-top: 28px;
|
||||
}
|
||||
.stat-item {
|
||||
background: rgba(0,0,0,0.2);
|
||||
border-radius: 14px;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: rgba(255,255,255,0.4);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.stat-value.purple { color: #a78bfa; }
|
||||
.stat-value.blue { color: #38bdf8; }
|
||||
.stat-value.yellow { color: #fbbf24; }
|
||||
.stat-value.green { color: #34d399; }
|
||||
|
||||
/* ── 세션 목록 ── */
|
||||
.sessions-card {
|
||||
background: #1e293b;
|
||||
border-radius: 20px;
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
overflow: hidden;
|
||||
}
|
||||
.sessions-header {
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.05);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.sessions-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sessions-count {
|
||||
font-size: 13px;
|
||||
color: rgba(255,255,255,0.4);
|
||||
}
|
||||
.sessions-list {
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.session-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.03);
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.session-item:hover { background: rgba(255,255,255,0.02); }
|
||||
.session-item:last-child { border-bottom: none; }
|
||||
.session-info { flex: 1; }
|
||||
.session-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.session-meta {
|
||||
font-size: 12px;
|
||||
color: rgba(255,255,255,0.4);
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
.session-model {
|
||||
color: #a78bfa;
|
||||
}
|
||||
.session-usage {
|
||||
text-align: right;
|
||||
}
|
||||
.session-percent {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.session-percent.low { color: #22c55e; }
|
||||
.session-percent.mid { color: #fbbf24; }
|
||||
.session-percent.high { color: #ef4444; }
|
||||
.session-tokens {
|
||||
font-size: 12px;
|
||||
color: rgba(255,255,255,0.4);
|
||||
}
|
||||
.session-bar-wrap {
|
||||
width: 100px;
|
||||
height: 4px;
|
||||
background: rgba(255,255,255,0.1);
|
||||
border-radius: 100px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.session-bar {
|
||||
height: 100%;
|
||||
border-radius: 100px;
|
||||
background: #22c55e;
|
||||
}
|
||||
.session-bar.mid { background: #fbbf24; }
|
||||
.session-bar.high { background: #ef4444; }
|
||||
|
||||
/* ── 모델별 통계 ── */
|
||||
.model-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.model-stat-card {
|
||||
background: #1e293b;
|
||||
border-radius: 14px;
|
||||
padding: 18px 20px;
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
.model-stat-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.model-stat-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
color: rgba(255,255,255,0.6);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.model-stat-row span:last-child {
|
||||
font-weight: 600;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
/* ── 에러 상태 ── */
|
||||
.error-state {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #f87171;
|
||||
}
|
||||
.error-icon { font-size: 48px; margin-bottom: 12px; }
|
||||
.error-text { font-size: 16px; font-weight: 500; margin-bottom: 8px; }
|
||||
.error-sub { font-size: 13px; color: rgba(255,255,255,0.4); }
|
||||
|
||||
/* ── 타임스탬프 ── */
|
||||
.timestamp {
|
||||
text-align: center;
|
||||
padding: 16px;
|
||||
font-size: 12px;
|
||||
color: rgba(255,255,255,0.3);
|
||||
}
|
||||
|
||||
/* ── 반응형 ── */
|
||||
@media (max-width: 768px) {
|
||||
.stats-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.context-used { font-size: 48px; }
|
||||
.context-max { font-size: 18px; }
|
||||
.context-percent { font-size: 18px; }
|
||||
.header { padding: 20px 16px 18px; }
|
||||
.content { padding: 16px 12px 40px; }
|
||||
.main-card { padding: 24px 20px; }
|
||||
.session-bar-wrap { display: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div class="header-nav">
|
||||
<a href="/admin">← 관리자 홈</a>
|
||||
<div>
|
||||
<a href="/admin/ai-crm" style="margin-right: 16px;">AI 업셀링</a>
|
||||
<a href="/admin/alimtalk">알림톡 로그</a>
|
||||
</div>
|
||||
</div>
|
||||
<h1>
|
||||
<span class="live-dot" id="statusDot"></span>
|
||||
AI Gateway 모니터
|
||||
</h1>
|
||||
<p>Clawdbot Gateway 실시간 상태 · Claude / GPT 토큰 사용량</p>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div id="mainContent">
|
||||
<!-- 메인 카드 -->
|
||||
<div class="main-card">
|
||||
<div class="main-header">
|
||||
<div>
|
||||
<div class="main-title">현재 모델</div>
|
||||
<div class="main-model" id="currentModel">로딩중...</div>
|
||||
</div>
|
||||
<button class="refresh-btn" id="refreshBtn" onclick="refresh()">
|
||||
<span>↻</span> 새로고침
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="context-display">
|
||||
<div class="context-numbers">
|
||||
<span class="context-used" id="contextUsed">--</span>
|
||||
<span class="context-max" id="contextMax">/ 200k</span>
|
||||
<span class="context-percent" id="contextPercent">0%</span>
|
||||
</div>
|
||||
<div class="progress-wrap">
|
||||
<div class="progress-bar" id="progressBar" style="width: 0%"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid">
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">입력 토큰</div>
|
||||
<div class="stat-value purple" id="inputTokens">-</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">출력 토큰</div>
|
||||
<div class="stat-value blue" id="outputTokens">-</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">전체 토큰 (모든 세션)</div>
|
||||
<div class="stat-value yellow" id="totalTokens">-</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">활성 세션</div>
|
||||
<div class="stat-value green" id="sessionCount">-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 모델별 통계 -->
|
||||
<div class="model-stats" id="modelStats"></div>
|
||||
|
||||
<!-- 세션 목록 -->
|
||||
<div class="sessions-card">
|
||||
<div class="sessions-header">
|
||||
<div class="sessions-title">세션별 상세</div>
|
||||
<div class="sessions-count" id="sessionsCount">-</div>
|
||||
</div>
|
||||
<div class="sessions-list" id="sessionsList"></div>
|
||||
</div>
|
||||
|
||||
<div class="timestamp" id="timestamp">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function formatNumber(num) {
|
||||
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
|
||||
if (num >= 1000) return Math.round(num / 1000) + 'k';
|
||||
return num.toString();
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
return str.replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));
|
||||
}
|
||||
|
||||
function getPercentClass(percent) {
|
||||
if (percent >= 70) return 'high';
|
||||
if (percent >= 40) return 'mid';
|
||||
return 'low';
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
const btn = document.getElementById('refreshBtn');
|
||||
btn.classList.add('loading');
|
||||
btn.innerHTML = '<span>⟳</span> 로딩중...';
|
||||
|
||||
fetch('/api/claude-status?detail=true')
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
btn.classList.remove('loading');
|
||||
btn.innerHTML = '<span>↻</span> 새로고침';
|
||||
|
||||
if (!data.ok || !data.connected) {
|
||||
document.getElementById('statusDot').classList.add('offline');
|
||||
document.getElementById('mainContent').innerHTML = `
|
||||
<div class="main-card">
|
||||
<div class="error-state">
|
||||
<div class="error-icon">⚠️</div>
|
||||
<div class="error-text">Gateway 연결 실패</div>
|
||||
<div class="error-sub">${data.error || 'Clawdbot이 실행 중인지 확인하세요'}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('statusDot').classList.remove('offline');
|
||||
updateUI(data);
|
||||
})
|
||||
.catch(err => {
|
||||
btn.classList.remove('loading');
|
||||
btn.innerHTML = '<span>↻</span> 새로고침';
|
||||
console.error(err);
|
||||
});
|
||||
}
|
||||
|
||||
function updateUI(data) {
|
||||
const ctx = data.context;
|
||||
const main = data.mainSession || {};
|
||||
const summary = data.summary;
|
||||
|
||||
// 모델
|
||||
document.getElementById('currentModel').textContent = data.model;
|
||||
|
||||
// 컨텍스트
|
||||
document.getElementById('contextUsed').textContent = formatNumber(ctx.used);
|
||||
document.getElementById('contextMax').textContent = '/ ' + formatNumber(ctx.max);
|
||||
|
||||
const percentEl = document.getElementById('contextPercent');
|
||||
percentEl.textContent = ctx.percent + '%';
|
||||
percentEl.className = 'context-percent';
|
||||
if (ctx.percent >= 70) percentEl.classList.add('danger');
|
||||
else if (ctx.percent >= 40) percentEl.classList.add('warning');
|
||||
|
||||
// 프로그레스 바
|
||||
const bar = document.getElementById('progressBar');
|
||||
bar.style.width = ctx.percent + '%';
|
||||
bar.className = 'progress-bar';
|
||||
if (ctx.percent >= 70) bar.classList.add('danger');
|
||||
else if (ctx.percent >= 40) bar.classList.add('warning');
|
||||
|
||||
// 통계
|
||||
document.getElementById('inputTokens').textContent = formatNumber(main.inputTokens || 0);
|
||||
document.getElementById('outputTokens').textContent = formatNumber(main.outputTokens || 0);
|
||||
document.getElementById('totalTokens').textContent = formatNumber(summary.totalTokens);
|
||||
document.getElementById('sessionCount').textContent = summary.totalSessions + '개';
|
||||
|
||||
// 모델별 통계
|
||||
if (data.modelStats) {
|
||||
const statsHtml = Object.entries(data.modelStats).map(([model, stat]) => `
|
||||
<div class="model-stat-card">
|
||||
<div class="model-stat-name">${escapeHtml(model)}</div>
|
||||
<div class="model-stat-row">
|
||||
<span>세션 수</span>
|
||||
<span>${stat.sessions}개</span>
|
||||
</div>
|
||||
<div class="model-stat-row">
|
||||
<span>총 토큰</span>
|
||||
<span>${formatNumber(stat.tokens)}</span>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
document.getElementById('modelStats').innerHTML = statsHtml;
|
||||
}
|
||||
|
||||
// 세션 목록
|
||||
if (data.sessions) {
|
||||
document.getElementById('sessionsCount').textContent =
|
||||
`토큰 사용량 순 · ${data.sessions.length}개`;
|
||||
|
||||
const sessionsHtml = data.sessions.map(s => {
|
||||
const pct = s.tokens.contextPercent;
|
||||
const pctClass = getPercentClass(pct);
|
||||
return `
|
||||
<div class="session-item">
|
||||
<div class="session-info">
|
||||
<div class="session-name">${escapeHtml(s.displayName || s.name)}</div>
|
||||
<div class="session-meta">
|
||||
<span class="session-model">${escapeHtml(s.model)}</span>
|
||||
<span>${s.channel || '-'}</span>
|
||||
<span>${s.updatedAt || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="session-usage">
|
||||
<div class="session-percent ${pctClass}">${pct}%</div>
|
||||
<div class="session-tokens">${s.tokens.display}</div>
|
||||
<div class="session-bar-wrap">
|
||||
<div class="session-bar ${pctClass}" style="width: ${pct}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
document.getElementById('sessionsList').innerHTML = sessionsHtml;
|
||||
}
|
||||
|
||||
// 타임스탬프
|
||||
const ts = new Date(data.timestamp);
|
||||
document.getElementById('timestamp').textContent =
|
||||
`마지막 업데이트: ${ts.toLocaleTimeString('ko-KR')}`;
|
||||
}
|
||||
|
||||
// 초기 로드 & 30초 자동 갱신
|
||||
refresh();
|
||||
setInterval(refresh, 30000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
342
docs/clawdbot-gateway-api.md
Normal file
342
docs/clawdbot-gateway-api.md
Normal file
@ -0,0 +1,342 @@
|
||||
# Clawdbot Gateway WebSocket API 가이드
|
||||
|
||||
> 외부 애플리케이션에서 Clawdbot Gateway에 연결하여 AI 호출 또는 상태 조회하는 방법
|
||||
|
||||
## 개요
|
||||
|
||||
Clawdbot Gateway는 WebSocket API를 제공합니다. 이를 통해:
|
||||
- **AI 호출** (`agent` 메서드) — Claude/GPT 등 모델에 질문 (토큰 소비)
|
||||
- **상태 조회** (`sessions.list` 등) — 세션 정보 조회 (토큰 무소비)
|
||||
- **세션 설정** (`sessions.patch`) — 모델 오버라이드 등
|
||||
|
||||
## 아키텍처
|
||||
|
||||
```
|
||||
┌─────────────────┐ WebSocket ┌─────────────────┐
|
||||
│ Flask 서버 │ ◄─────────────────► │ Clawdbot Gateway│
|
||||
│ (pharmacy-pos) │ Port 18789 │ (localhost) │
|
||||
└─────────────────┘ └────────┬────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ Claude / GPT │
|
||||
│ (Providers) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
## 설정 파일 위치
|
||||
|
||||
Gateway 설정은 `~/.clawdbot/clawdbot.json`에 있음:
|
||||
```json
|
||||
{
|
||||
"gateway": {
|
||||
"port": 18789,
|
||||
"auth": {
|
||||
"mode": "token",
|
||||
"token": "your-gateway-token"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 연결 프로토콜 (Python)
|
||||
|
||||
### 1. 기본 연결 흐름
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
import websockets
|
||||
|
||||
async def connect_to_gateway():
|
||||
config = load_gateway_config() # ~/.clawdbot/clawdbot.json 읽기
|
||||
url = f"ws://127.0.0.1:{config['port']}"
|
||||
token = config['token']
|
||||
|
||||
async with websockets.connect(url) as ws:
|
||||
# 1단계: challenge 수신
|
||||
challenge = json.loads(await ws.recv())
|
||||
# {'event': 'connect.challenge', 'payload': {'nonce': '...'}}
|
||||
|
||||
# 2단계: connect 요청
|
||||
connect_frame = {
|
||||
'type': 'req',
|
||||
'id': str(uuid.uuid4()),
|
||||
'method': 'connect',
|
||||
'params': {
|
||||
'minProtocol': 3,
|
||||
'maxProtocol': 3,
|
||||
'client': {
|
||||
'id': 'gateway-client', # 고정값
|
||||
'displayName': 'My App',
|
||||
'version': '1.0.0',
|
||||
'platform': 'win32',
|
||||
'mode': 'backend', # 고정값
|
||||
'instanceId': str(uuid.uuid4()),
|
||||
},
|
||||
'caps': [],
|
||||
'auth': {'token': token},
|
||||
'role': 'operator',
|
||||
'scopes': ['operator.admin'], # 또는 ['operator.read']
|
||||
}
|
||||
}
|
||||
await ws.send(json.dumps(connect_frame))
|
||||
|
||||
# 3단계: connect 응답 대기
|
||||
while True:
|
||||
msg = json.loads(await ws.recv())
|
||||
if msg.get('id') == connect_frame['id']:
|
||||
if msg.get('ok'):
|
||||
print("연결 성공!")
|
||||
break
|
||||
else:
|
||||
print(f"연결 실패: {msg.get('error')}")
|
||||
return
|
||||
|
||||
# 이제 다른 메서드 호출 가능
|
||||
# ...
|
||||
```
|
||||
|
||||
### 2. 주의사항: client 파라미터
|
||||
|
||||
⚠️ **중요**: `client.id`와 `client.mode`는 Gateway 스키마에 정의된 값만 허용됨
|
||||
|
||||
| 필드 | 허용되는 값 | 설명 |
|
||||
|------|-------------|------|
|
||||
| `client.id` | `'gateway-client'` | 백엔드 클라이언트용 |
|
||||
| `client.mode` | `'backend'` | 백엔드 모드 |
|
||||
| `role` | `'operator'` | 제어 클라이언트 |
|
||||
| `scopes` | `['operator.admin']` 또는 `['operator.read']` | 권한 범위 |
|
||||
|
||||
잘못된 값 사용 시 에러:
|
||||
```
|
||||
invalid connect params: at /client/id: must be equal to constant
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 메서드 종류
|
||||
|
||||
### 토큰 소비 없는 메서드 (관리용)
|
||||
|
||||
| 메서드 | 용도 | 파라미터 |
|
||||
|--------|------|----------|
|
||||
| `sessions.list` | 세션 목록 조회 | `{limit: 10}` |
|
||||
| `sessions.patch` | 세션 설정 변경 | `{key: '...', model: '...'}` |
|
||||
|
||||
### 토큰 소비하는 메서드 (AI 호출)
|
||||
|
||||
| 메서드 | 용도 | 파라미터 |
|
||||
|--------|------|----------|
|
||||
| `agent` | AI에게 질문 | `{message: '...', sessionId: '...'}` |
|
||||
|
||||
---
|
||||
|
||||
## 실제 구현 예제
|
||||
|
||||
### 예제 1: 상태 조회 (토큰 0)
|
||||
|
||||
```python
|
||||
# services/clawdbot_client.py 참고
|
||||
|
||||
async def _get_gateway_status():
|
||||
"""세션 목록 조회 — 토큰 소비 없음"""
|
||||
# ... (연결 코드 생략)
|
||||
|
||||
# sessions.list 요청
|
||||
list_frame = {
|
||||
'type': 'req',
|
||||
'id': str(uuid.uuid4()),
|
||||
'method': 'sessions.list',
|
||||
'params': {'limit': 10}
|
||||
}
|
||||
await ws.send(json.dumps(list_frame))
|
||||
|
||||
# 응답 대기
|
||||
while True:
|
||||
msg = json.loads(await ws.recv())
|
||||
if msg.get('event'): # 이벤트는 무시
|
||||
continue
|
||||
if msg.get('id') == list_frame['id']:
|
||||
return msg.get('payload', {})
|
||||
```
|
||||
|
||||
**응답 예시:**
|
||||
```json
|
||||
{
|
||||
"sessions": [
|
||||
{
|
||||
"key": "agent:main:main",
|
||||
"totalTokens": 30072,
|
||||
"contextTokens": 200000,
|
||||
"model": "claude-opus-4-5"
|
||||
}
|
||||
],
|
||||
"defaults": {
|
||||
"model": "claude-opus-4-5",
|
||||
"contextTokens": 200000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 예제 2: AI 호출 (토큰 소비)
|
||||
|
||||
```python
|
||||
async def ask_ai(message, session_id='my-session', model=None):
|
||||
"""AI에게 질문 — 토큰 소비함"""
|
||||
# ... (연결 코드)
|
||||
|
||||
# 모델 오버라이드 (선택)
|
||||
if model:
|
||||
patch_frame = {
|
||||
'type': 'req',
|
||||
'id': str(uuid.uuid4()),
|
||||
'method': 'sessions.patch',
|
||||
'params': {'key': session_id, 'model': model}
|
||||
}
|
||||
await ws.send(json.dumps(patch_frame))
|
||||
# 응답 대기...
|
||||
|
||||
# agent 요청
|
||||
agent_frame = {
|
||||
'type': 'req',
|
||||
'id': str(uuid.uuid4()),
|
||||
'method': 'agent',
|
||||
'params': {
|
||||
'message': message,
|
||||
'sessionId': session_id,
|
||||
'sessionKey': session_id,
|
||||
'timeout': 60,
|
||||
}
|
||||
}
|
||||
await ws.send(json.dumps(agent_frame))
|
||||
|
||||
# 응답 대기 (accepted → final)
|
||||
while True:
|
||||
msg = json.loads(await ws.recv())
|
||||
if msg.get('event'):
|
||||
continue
|
||||
if msg.get('id') == agent_frame['id']:
|
||||
if msg.get('payload', {}).get('status') == 'accepted':
|
||||
continue # 아직 처리 중
|
||||
# 최종 응답
|
||||
payloads = msg.get('payload', {}).get('result', {}).get('payloads', [])
|
||||
return '\n'.join(p.get('text', '') for p in payloads)
|
||||
```
|
||||
|
||||
### 예제 3: 모델 오버라이드
|
||||
|
||||
비싼 Opus 대신 저렴한 Sonnet 사용:
|
||||
|
||||
```python
|
||||
UPSELL_MODEL = 'anthropic/claude-sonnet-4-5'
|
||||
|
||||
response = await ask_ai(
|
||||
message="추천 멘트 만들어줘",
|
||||
session_id='upsell-customer1',
|
||||
model=UPSELL_MODEL # Sonnet으로 오버라이드
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Flask API 엔드포인트 예제
|
||||
|
||||
```python
|
||||
# app.py
|
||||
|
||||
@app.route('/api/claude-status')
|
||||
def api_claude_status():
|
||||
"""토큰 차감 없이 상태 조회"""
|
||||
from services.clawdbot_client import get_claude_status
|
||||
|
||||
status = get_claude_status()
|
||||
|
||||
if not status.get('connected'):
|
||||
return jsonify({'ok': False, 'error': status.get('error')}), 503
|
||||
|
||||
sessions = status.get('sessions', {})
|
||||
# ... 데이터 가공
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'context': {'used': 30000, 'max': 200000, 'percent': 15},
|
||||
'model': 'claude-opus-4-5'
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 토큰 관리 전략
|
||||
|
||||
### 모델별 용도 분리
|
||||
|
||||
| 용도 | 모델 | 이유 |
|
||||
|------|------|------|
|
||||
| 메인 컨트롤러 | Claude Opus | 복잡한 추론, 도구 사용 |
|
||||
| 단순 생성 (업셀링 등) | Claude Sonnet | 빠르고 저렴 |
|
||||
| 코딩 작업 | GPT-5 Codex | 정식 지원, 안정적 |
|
||||
|
||||
### 세션 분리
|
||||
|
||||
```python
|
||||
# 용도별 세션 ID 분리
|
||||
ask_ai("...", session_id='upsell-고객명') # 업셀링 전용
|
||||
ask_ai("...", session_id='analysis-daily') # 분석 전용
|
||||
ask_ai("...", session_id='chat-main') # 일반 대화
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 트러블슈팅
|
||||
|
||||
### 1. "invalid connect params" 에러
|
||||
|
||||
```
|
||||
at /client/id: must be equal to constant
|
||||
at /client/mode: must be equal to constant
|
||||
```
|
||||
|
||||
**해결**: `client.id`는 `'gateway-client'`, `client.mode`는 `'backend'` 사용
|
||||
|
||||
### 2. Gateway 연결 실패
|
||||
|
||||
```python
|
||||
ConnectionRefusedError: [WinError 10061]
|
||||
```
|
||||
|
||||
**해결**: Clawdbot Gateway가 실행 중인지 확인
|
||||
```bash
|
||||
clawdbot gateway status
|
||||
```
|
||||
|
||||
### 3. CLI 명령어가 hang됨
|
||||
|
||||
Clawdbot 내부(agent 세션)에서 `clawdbot status` 같은 CLI 호출하면 충돌.
|
||||
→ WebSocket API 직접 사용할 것
|
||||
|
||||
---
|
||||
|
||||
## 파일 위치
|
||||
|
||||
```
|
||||
pharmacy-pos-qr-system/
|
||||
└── backend/
|
||||
└── services/
|
||||
└── clawdbot_client.py # Gateway 클라이언트 구현
|
||||
└── app.py # Flask API (/api/claude-status)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 참고 자료
|
||||
|
||||
- Clawdbot 문서: `C:\Users\청춘약국\AppData\Roaming\npm\node_modules\clawdbot\docs\`
|
||||
- Gateway 프로토콜: `docs/gateway/protocol.md`
|
||||
- 설정 예제: `docs/gateway/configuration-examples.md`
|
||||
|
||||
---
|
||||
|
||||
*작성: 2026-02-27 | 용림 🐉*
|
||||
Loading…
Reference in New Issue
Block a user