From 0a46e76065ff36c2428db228877f352dc1454bc9 Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 17 Oct 2026 22:39:19 +0900 Subject: [PATCH] =?UTF-8?q?=EC=82=AC=EC=9A=A9=20=EB=B9=84=EC=9A=A9=20?= =?UTF-8?q?=EC=B6=94=EC=82=B0=20=ED=8C=A8=EB=84=90:=20=ED=86=A0=ED=81=B0?= =?UTF-8?q?=20=EA=B8=B0=EB=A1=9D=C3=97=EA=B3=B5=EC=8B=9D=20=EB=8B=A8?= =?UTF-8?q?=EA=B0=80=EB=A1=9C=20=EC=98=A4=EB=8A=98/7=EC=9D=BC/=EC=9B=94=20?= =?UTF-8?q?=EC=A7=80=EC=B6=9C=EA=B3=BC=20=EB=AA=A8=EB=8D=B8=EB=B3=84=20?= =?UTF-8?q?=ED=91=9C,=20=EC=95=A4=ED=8A=B8=EB=A1=9C=ED=94=BD=20=EC=BD=98?= =?UTF-8?q?=EC=86=94=20=EC=9E=94=EC=95=A1=20=EA=B8=B0=EC=A4=80=20=EC=B6=94?= =?UTF-8?q?=EC=A0=95=20=EC=9E=94=EC=95=A1=C2=B7=EA=B2=BD=EA=B3=A0=20(/api/?= =?UTF-8?q?usage/cost,=20/api/settings/billing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/routes/settings.ts | 28 +++++++++ src/providers/cost-estimate.ts | 96 ++++++++++++++++++++++++++++++ tests/cost-estimate.test.ts | 60 +++++++++++++++++++ web-ui/html/index.html | 14 +++++ web-ui/js/app/settings-provider.js | 50 +++++++++++++++- 5 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 src/providers/cost-estimate.ts create mode 100644 tests/cost-estimate.test.ts diff --git a/src/gateway/routes/settings.ts b/src/gateway/routes/settings.ts index 1235b05..49d9d10 100644 --- a/src/gateway/routes/settings.ts +++ b/src/gateway/routes/settings.ts @@ -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 = { ...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) => { diff --git a/src/providers/cost-estimate.ts b/src/providers/cost-estimate.ts new file mode 100644 index 0000000..2671991 --- /dev/null +++ b/src/providers/cost-estimate.ts @@ -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, daily: {} as Record }; + 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 }; +} diff --git a/tests/cost-estimate.test.ts b/tests/cost-estimate.test.ts new file mode 100644 index 0000000..2edf511 --- /dev/null +++ b/tests/cost-estimate.test.ts @@ -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); + }); +}); diff --git a/web-ui/html/index.html b/web-ui/html/index.html index 6e07aaf..db7be40 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -1123,6 +1123,20 @@
날씨·뉴스 등 실시간/사실 조회, 모델을 직접 고른 대화, 이미지가 있는 대화는 항상 기본 모델이 처리합니다. 이 항목은 아래 전체 저장 버튼과 별개로 이 버튼에서 바로 저장됩니다.
+ +
+
사용 비용 (추산)
+
불러오는 중…
+
+
+ + + +
+
기록된 토큰 × 공식 단가로 계산한 추산입니다. 올라마(정액)·로컬 모델은 0원으로, 구글은 무료 등급이면 실제로는 0원이지만 유료 가정 값을 보여 줍니다. 앱을 거치지 않은 호출(시험 스크립트 등)은 빠지며, 캐시 할인은 반영하지 않아 실제보다 약간 높게 나옵니다. 정확한 잔액은 콘솔(platform.claude.com/settings/billing)에서 확인하세요.
+
+
diff --git a/web-ui/js/app/settings-provider.js b/web-ui/js/app/settings-provider.js index 99d883d..d8e8df5 100644 --- a/web-ui/js/app/settings-provider.js +++ b/web-ui/js/app/settings-provider.js @@ -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 '' + label + ' ' + _fmtUsd(d[k].usd) + ' · ' + d[k].calls + '회'; }).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 = '모델 (최근 7일·이번 달)호출입력출력추산' + + rows.map(([m, b]) => '' + escHtml(m) + '' + b.calls + '' + _fmtTok(b.promptTokens) + '' + _fmtTok(b.completionTokens) + '' + + (b.priced ? _fmtUsd(b.usd) : '정액/로컬') + '').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 = '추정 잔액 ' + _fmtUsd(a.estimated_balance) + ' (기록 $' + a.balance_usd.toFixed(2) + ' − 이후 지출 ' + _fmtUsd(a.spent_since) + ')' + + (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; } + } +}