사용 비용 추산 패널: 토큰 기록×공식 단가로 오늘/7일/월 지출과 모델별 표, 앤트로픽 콘솔 잔액 기준 추정 잔액·경고 (/api/usage/cost, /api/settings/billing)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-17 22:39:19 +09:00
1 parent 70534638ab
commit 0a46e76065
5 files changed
+247 -1

No files matched your search

+28
View File
@@ -3,6 +3,7 @@ import fs from 'fs';
import path from 'path';
import { getConfig, ConfigManager } from '../../config/config.js';
import { resetProvider } from '../../providers/factory.js';
import { readUsageRows, summarize } from '../../providers/cost-estimate.js';
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -191,6 +192,33 @@ export function registerSettingsRoutes(app: Express): void {
res.json({ success: true, model: cm.getConfig().models.primary });
});
// ── 사용 비용 추산 (token-usage.jsonl × 단가표) + 앤트로픽 잔액 추산 ─────────────────────
app.get('/api/usage/cost', (_req, res) => {
const billing = ((cm.getConfig() as any).billing?.anthropic) || {};
res.json({ success: true, ...summarize(readUsageRows(), billing) });
});
// 콘솔에서 확인한 현재 잔액($)을 기준 시점과 함께 저장 → 이후 지출을 빼서 잔액을 추산한다
app.post('/api/settings/billing', (req, res) => {
const b = req.body || {};
const current = cm.getConfig() as any;
const prev = current.billing?.anthropic || {};
const next: Record<string, any> = { ...prev };
if (b.balance_usd !== undefined) {
const v = Number(b.balance_usd);
if (!Number.isFinite(v) || v < 0 || v > 100000) { res.status(400).json({ success: false, error: 'balance_usd must be a non-negative number' }); return; }
next.balance_usd = v;
next.as_of = new Date().toISOString();
}
if (b.warn_below_usd !== undefined) {
const w = Number(b.warn_below_usd);
if (!Number.isFinite(w) || w < 0) { res.status(400).json({ success: false, error: 'warn_below_usd must be a non-negative number' }); return; }
next.warn_below_usd = w;
}
cm.updateConfig({ billing: { ...(current.billing || {}), anthropic: next } } as any);
res.json({ success: true, ...summarize(readUsageRows(), next) });
});
// ── Model routing (어려운 질문만 hard_model로) ────────────────────────────────
app.get('/api/settings/routing', (_req, res) => {
+96
View File
@@ -0,0 +1,96 @@
/**
* cost-estimate.ts — 토큰 사용 기록(token-usage.jsonl)으로 지출을 추산한다.
*
* Anthropic은 선불 잔액을 읽는 API가 없고(문서 확인 2026-10-17), 사용량·비용 API는 조직용 Admin 키가 필요해
* 개인 계정에서는 쓸 수 없다. 그래서 우리가 기록한 호출별 토큰 × 공식 단가표로 추산한다.
*
* 추산이 실제보다 높게 나오도록(보수적으로) 한 부분: 캐시 적중 입력도 일반 입력 단가로 센다.
* 추산에서 빠지는 것: 앱을 거치지 않은 호출(벤치마크 스크립트 등), 기록을 고치기 전 호출.
* 올라마 클라우드(정액 구독)·로컬 모델은 호출당 비용이 없으므로 0원.
* 구글은 무료 등급이면 실제로는 0원이지만 기록에는 등급이 없어서, "유료 등급이라면"의 값을 보여 준다.
*/
import fs from 'fs';
import path from 'path';
import { getConfig } from '../config/config';
export interface Price { in: number; out: number } // USD per 1M tokens
/** 단가표(2026-10-17 공식 가격 페이지). 모르는 모델은 null → 비용 계산에서 제외. */
export function priceFor(model: string, promptTokens: number, isoDate: string): Price | null {
const m = String(model || '');
if (/^claude-haiku-5-5/.test(m)) return promptTokens > 100_000 ? { in: 0.5, out: 2.5 } : { in: 0.1, out: 0.5 };
if (/^claude-sonnet-5-5/.test(m)) return { in: 2, out: 10 };
if (/^claude-opus-5-5/.test(m)) return { in: 4, out: 20 };
if (/^claude-haiku-4-5/.test(m)) return { in: 1, out: 5 };
if (/^claude-sonnet-4/.test(m)) return { in: 3, out: 15 };
if (/^claude-opus-4/.test(m)) return { in: 5, out: 25 };
if (/^gemini-3\.5-flash-lite/.test(m)) return { in: 0.3, out: 2.5 };
if (/^gemini-3\.[68]-flash/.test(m)) return isoDate >= '2027-01-01' ? { in: 1.5, out: 7.5 } : { in: 0.75, out: 3.75 };
if (/^gemini-3\.1-pro/.test(m)) return promptTokens > 200_000 ? { in: 4, out: 18 } : { in: 2, out: 12 };
return null;
}
export interface UsageRow { ts: string; model: string; promptTokens: number; completionTokens: number }
export function costOf(row: UsageRow): number | null {
const p = priceFor(row.model, row.promptTokens, row.ts.slice(0, 10));
if (!p) return null;
return (row.promptTokens * p.in + row.completionTokens * p.out) / 1_000_000;
}
const KST_MS = 9 * 3600_000;
export const kstDay = (ts: string | number | Date) => new Date(new Date(ts).getTime() + KST_MS).toISOString().slice(0, 10);
export function readUsageRows(file?: string): UsageRow[] {
let p = file;
if (!p) { try { p = path.join(getConfig().getConfigDir(), 'logs', 'token-usage.jsonl'); } catch { return []; } }
let text = '';
try { text = fs.readFileSync(p, 'utf-8'); } catch { return []; }
const rows: UsageRow[] = [];
for (const line of text.split('\n')) {
if (!line.trim()) continue;
try {
const r = JSON.parse(line);
if (r?.ts && r?.model) rows.push({ ts: String(r.ts), model: String(r.model), promptTokens: Number(r.promptTokens) || 0, completionTokens: Number(r.completionTokens) || 0 });
} catch { /* 깨진 줄은 건너뜀 */ }
}
return rows;
}
export interface CostBucket { calls: number; promptTokens: number; completionTokens: number; usd: number }
const empty = (): CostBucket => ({ calls: 0, promptTokens: 0, completionTokens: 0, usd: 0 });
function add(b: CostBucket, r: UsageRow, usd: number | null) {
b.calls++; b.promptTokens += r.promptTokens; b.completionTokens += r.completionTokens; b.usd += usd ?? 0;
}
export interface BillingState { balance_usd?: number; as_of?: string; warn_below_usd?: number }
export function summarize(rows: UsageRow[], billing: BillingState = {}, now: Date = new Date()) {
const today = kstDay(now);
const monthPrefix = today.slice(0, 7);
const weekAgo = kstDay(now.getTime() - 6 * 86400_000);
const out = { today: empty(), last7: empty(), month: empty(), byModel: {} as Record<string, CostBucket & { priced: boolean }>, daily: {} as Record<string, number> };
for (const r of rows) {
const usd = costOf(r);
const day = kstDay(r.ts);
const bm = out.byModel[r.model] || (out.byModel[r.model] = { ...empty(), priced: usd !== null });
if (day >= monthPrefix + '-01' && day.startsWith(monthPrefix)) add(out.month, r, usd);
if (day === today) add(out.today, r, usd);
if (day >= weekAgo) { add(out.last7, r, usd); out.daily[day] = (out.daily[day] || 0) + (usd ?? 0); }
if (day.startsWith(monthPrefix) || day >= weekAgo) add(bm, r, usd);
}
// 앤트로픽 잔액 추산: 사용자가 콘솔에서 확인해 입력한 잔액 − 그 시점 이후 claude 호출의 추산 지출
let anthropic: null | { balance_usd: number; as_of: string; spent_since: number; estimated_balance: number; warn_below_usd: number; low: boolean } = null;
if (typeof billing.balance_usd === 'number' && billing.as_of) {
const since = new Date(billing.as_of).getTime();
let spent = 0;
for (const r of rows) {
if (!/^claude-/.test(r.model) || new Date(r.ts).getTime() < since) continue;
spent += costOf(r) ?? 0;
}
const warn = typeof billing.warn_below_usd === 'number' ? billing.warn_below_usd : 1;
const est = billing.balance_usd - spent;
anthropic = { balance_usd: billing.balance_usd, as_of: billing.as_of, spent_since: spent, estimated_balance: est, warn_below_usd: warn, low: est <= warn };
}
return { ...out, anthropic };
}
+60
View File
@@ -0,0 +1,60 @@
/**
* cost-estimate — 토큰 기록 × 단가표 추산, 앤트로픽 잔액 추산.
* 표본 단가: 2026-10-17 공식 가격 페이지(Haiku 5.5 $0.10/$0.50, Sonnet 5.5 $2/$10, Flash-Lite $0.30/$2.50).
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { priceFor, costOf, summarize, kstDay } from '../src/providers/cost-estimate';
const row = (model: string, p: number, c: number, ts = '2026-10-17T05:00:00Z') => ({ ts, model, promptTokens: p, completionTokens: c });
describe('단가·비용', () => {
test('Haiku 5.5: 입력 8,000 + 출력 500 토큰', () => {
assert.ok(Math.abs(costOf(row('claude-haiku-5-5', 8000, 500))! - (8000 * 0.1 + 500 * 0.5) / 1e6) < 1e-12);
});
test('Haiku 5.5는 프롬프트 10만 토큰을 넘으면 비싼 단가', () => {
assert.deepEqual(priceFor('claude-haiku-5-5', 150_000, '2026-10-17'), { in: 0.5, out: 2.5 });
});
test('Sonnet 5.5는 Haiku의 20배 입력 단가', () => {
assert.equal(priceFor('claude-sonnet-5-5', 1, '2026-10-17')!.in / priceFor('claude-haiku-5-5', 1, '2026-10-17')!.in, 20);
});
test('Gemini Flash는 2027년부터 단가 2배', () => {
assert.equal(priceFor('gemini-3.6-flash', 1, '2026-12-31')!.in, 0.75);
assert.equal(priceFor('gemini-3.6-flash', 1, '2027-01-01')!.in, 1.5);
});
test('올라마·로컬 모델은 비용 없음(null)', () => {
assert.equal(costOf(row('gemma4:31b-cloud', 7000, 150)), null);
assert.equal(costOf(row('kimi-k2.6:cloud', 7000, 150)), null);
});
});
describe('summarize', () => {
const now = new Date('2026-10-17T10:00:00Z'); // KST 19:00
test('KST 날짜 경계: UTC 15시 이후는 다음 날로 센다', () => {
assert.equal(kstDay('2026-10-17T14:59:59Z'), '2026-10-17');
assert.equal(kstDay('2026-10-17T15:00:00Z'), '2026-10-18');
});
test('오늘·최근 7일·이번 달 합산, 단가 없는 모델은 호출 수만', () => {
const rows = [row('claude-haiku-5-5', 10_000, 1_000), row('gemma4:31b-cloud', 7000, 100), row('claude-haiku-5-5', 10_000, 1_000, '2026-10-10T05:00:00Z')];
const s = summarize(rows, {}, now);
assert.equal(s.today.calls, 2);
assert.equal(s.last7.calls, 2); // 10/10은 7일 창(10/11~10/17) 밖
assert.equal(s.month.calls, 3);
assert.ok(Math.abs(s.today.usd - (10_000 * 0.1 + 1_000 * 0.5) / 1e6) < 1e-12);
assert.equal(s.byModel['gemma4:31b-cloud'].priced, false);
});
test('잔액 추산: 기준 시점 이후 claude 지출만 뺀다', () => {
const rows = [row('claude-sonnet-5-5', 1_000_000, 0, '2026-10-17T01:00:00Z'), row('claude-sonnet-5-5', 1_000_000, 0, '2026-10-17T06:00:00Z'), row('gemma4:31b-cloud', 9_000_000, 0, '2026-10-17T06:00:00Z')];
const s = summarize(rows, { balance_usd: 5, as_of: '2026-10-17T03:00:00Z', warn_below_usd: 1 }, now);
assert.equal(s.anthropic!.spent_since, 2); // 기준 시점 이후 Sonnet 100만 입력 = $2
assert.equal(s.anthropic!.estimated_balance, 3);
assert.equal(s.anthropic!.low, false);
});
test('잔액이 경고선 이하면 low', () => {
const s = summarize([row('claude-sonnet-5-5', 2_000_000, 0, '2026-10-17T06:00:00Z')], { balance_usd: 4.5, as_of: '2026-10-17T03:00:00Z', warn_below_usd: 1 }, now);
assert.equal(s.anthropic!.low, true);
});
test('잔액 기록이 없으면 anthropic은 null', () => {
assert.equal(summarize([], {}, now).anthropic, null);
});
});
+14
View File
@@ -1123,6 +1123,20 @@
<div style="font-size:11px;color:var(--muted);margin-top:8px;line-height:1.6">날씨·뉴스 등 실시간/사실 조회, 모델을 직접 고른 대화, 이미지가 있는 대화는 항상 기본 모델이 처리합니다. 이 항목은 아래 전체 저장 버튼과 별개로 이 버튼에서 바로 저장됩니다.</div>
</div>
<!-- 사용 비용 추산 -->
<div style="border:1px solid var(--line);border-radius:12px;padding:12px;margin-bottom:14px">
<div class="right-section-title" style="margin-bottom:8px">사용 비용 (추산)</div>
<div id="cost-totals" style="display:flex;gap:16px;flex-wrap:wrap;font-size:13px;margin-bottom:8px">불러오는 중…</div>
<div style="overflow-x:auto"><table id="cost-table" style="border-collapse:collapse;font-size:11px;width:100%"></table></div>
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:10px">
<label style="font-size:12px;color:var(--muted)">Anthropic 콘솔 잔액 $
<input id="cost-balance-input" type="number" min="0" step="0.01" placeholder="예: 5.00" style="width:90px;margin-left:6px;border:1px solid var(--line);border-radius:8px;padding:5px;font-size:12px"></label>
<button class="btn btn-sm" onclick="saveCostBalance()">이 잔액으로 기록</button>
<span id="cost-balance-note" style="font-size:12px"></span>
</div>
<div style="font-size:11px;color:var(--muted);margin-top:8px;line-height:1.6">기록된 토큰 × 공식 단가로 계산한 <b>추산</b>입니다. 올라마(정액)·로컬 모델은 0원으로, 구글은 무료 등급이면 실제로는 0원이지만 유료 가정 값을 보여 줍니다. 앱을 거치지 않은 호출(시험 스크립트 등)은 빠지며, 캐시 할인은 반영하지 않아 실제보다 약간 높게 나옵니다. 정확한 잔액은 콘솔(platform.claude.com/settings/billing)에서 확인하세요.</div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
<!-- Left col: provider-specific connection fields -->
+49 -1
View File
@@ -188,7 +188,7 @@ function setSettingsTab(tab) {
if (t === tab) {
panel.style.display = 'block';
if (t === 'channels') loadChannelsStatus();
if (t === 'models') { loadModelSettings().finally(() => { try { loadRoutingSettings(); } catch {} }); }
if (t === 'models') { loadModelSettings().finally(() => { try { loadRoutingSettings(); loadCostPanel(); } catch {} }); }
if (t === 'agents') loadAgentsTab();
if (t === 'integrations') loadIntegrationsTab();
if (t === 'credentials') loadCredentialsTab();
@@ -1583,3 +1583,51 @@ async function saveRoutingSettings() {
if (st) st.textContent = '저장 실패: ' + e.message;
}
}
// ── 사용 비용(추산) 패널 ─────────────────────────────────────────────────────────
const _USD_KRW = 1400; // 표시용 대략 환율
function _fmtUsd(v) { return '$' + (v || 0).toFixed(v >= 10 ? 1 : 2) + ' (≈₩' + Math.round((v || 0) * _USD_KRW).toLocaleString() + ')'; }
function _fmtTok(n) { return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'K' : String(n); }
async function loadCostPanel() {
const totals = document.getElementById('cost-totals');
const table = document.getElementById('cost-table');
if (!totals || !table) return;
try {
const d = await api('/api/usage/cost');
totals.innerHTML = ['today:오늘', 'last7:최근 7일', 'month:이번 달']
.map(x => { const [k, label] = x.split(':'); return '<span><span style="color:var(--muted)">' + label + '</span> <b>' + _fmtUsd(d[k].usd) + '</b> · ' + d[k].calls + '회</span>'; }).join('');
const rows = Object.entries(d.byModel).sort((a, b) => b[1].usd - a[1].usd || b[1].calls - a[1].calls).slice(0, 12);
table.innerHTML = '<tr style="color:var(--muted);text-align:left"><th>모델 (최근 7일·이번 달)</th><th>호출</th><th>입력</th><th>출력</th><th>추산</th></tr>' +
rows.map(([m, b]) => '<tr style="border-top:1px solid var(--line)"><td style="padding:3px 6px 3px 0">' + escHtml(m) + '</td><td>' + b.calls + '</td><td>' + _fmtTok(b.promptTokens) + '</td><td>' + _fmtTok(b.completionTokens) + '</td><td>' +
(b.priced ? _fmtUsd(b.usd) : '<span style="color:var(--muted)">정액/로컬</span>') + '</td></tr>').join('');
const note = document.getElementById('cost-balance-note');
if (note) {
if (d.anthropic) {
const a = d.anthropic;
note.style.color = a.low ? '#c0392b' : 'var(--text)';
note.innerHTML = '추정 잔액 <b>' + _fmtUsd(a.estimated_balance) + '</b> <span style="color:var(--muted)">(기록 $' + a.balance_usd.toFixed(2) + ' − 이후 지출 ' + _fmtUsd(a.spent_since) + ')</span>' +
(a.low ? ' ⚠ 잔액이 $' + a.warn_below_usd + ' 이하입니다 — 충전을 확인하세요' : '');
} else {
note.style.color = 'var(--muted)';
note.textContent = '콘솔의 현재 잔액을 입력하면 이후 지출을 빼서 잔액을 추산합니다';
}
}
} catch (e) {
totals.textContent = '불러오기 실패: ' + e.message;
}
}
async function saveCostBalance() {
const v = document.getElementById('cost-balance-input')?.value;
if (v === '' || v == null) return;
try {
await api('/api/settings/billing', { method: 'POST', body: JSON.stringify({ balance_usd: Number(v) }) });
document.getElementById('cost-balance-input').value = '';
await loadCostPanel();
} catch (e) {
const note = document.getElementById('cost-balance-note');
if (note) { note.style.color = '#c0392b'; note.textContent = '저장 실패: ' + e.message; }
}
}