v4.3.19-6: Google 일일 사용량 표시 + 한도 도달시 자동 폴백
- google-usage.ts: Gemini 무료티어 RPD(하루 500회 추정치) 대비 요청 카운트를 날짜별로 추적(.smallclaw/google-usage.json, 자정 자동 리셋) - openai-compat-adapter.ts: google provider일 때 post() 호출마다 카운트 - factory.ts: getProvider()/getModelForRole() 둘 다 getEffectiveProviderConfig() 경유하도록 통일 — 카운트가 480(여유분 20 적용) 넘으면 자동으로 ollama+deepseek-v4-flash:cloud로 전환(429 맞고 반응하는 게 아니라 사전 차단). provider/model 선택이 별도 함수라 따로 고치면 불일치 날 수 있어서 공유 헬퍼로 묶음 - 메인 채팅 사이드바 모델 pill에 "N/500" 뱃지 추가(Google일 때만 표시, 70%↑ 노랑/90%↑ 빨강), 기존 10초 폴링(checkStatus)에 얹어서 실시간 반영 - 실사용 확인: 배포 직후 실제 채팅으로 카운트 0→1 증가 확인, 480 시뮬레이션 으로 폴백 전환/복귀 양쪽 다 확인 Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
814f32a63e
commit
a80ad9e809
6 files changed
+107
-2
No files matched your search
@@ -2985,6 +2985,7 @@ app.get('/api/status', async (_req, res) => {
|
||||
currentModel: activeModel,
|
||||
workspace: (config as any).workspace?.path || '',
|
||||
search: rawCfg.search?.google_api_key ? 'google' : (rawCfg.search?.tavily_api_key ? 'tavily' : (rawCfg.search?.searxng_url ? 'searxng' : 'none')),
|
||||
googleUsage: provider === 'google' ? getGoogleUsageToday() : null,
|
||||
orchestration: orchCfg ? {
|
||||
enabled: orchCfg.enabled,
|
||||
secondary: orchCfg.secondary,
|
||||
@@ -3869,6 +3870,7 @@ app.post('/api/open-path', requireGatewayAuth, async (req, res) => {
|
||||
// trigger the OpenAI OAuth flow.
|
||||
|
||||
import { getProvider, resetProvider, buildProviderForLLM, getModelForRole } from '../providers/factory';
|
||||
import { getGoogleUsageToday } from '../providers/google-usage';
|
||||
import { buildWebhookRouter, resolveHookConfig } from './channels/webhook-handler';
|
||||
import { getMCPManager } from './infra/mcp-manager';
|
||||
import { startOAuthFlow, isConnected, clearTokens, loadTokens, exchangeManualCodeFromPending } from '../auth/openai-oauth';
|
||||
|
||||
@@ -22,6 +22,13 @@ import { OllamaAdapter } from './ollama-adapter';
|
||||
import { OpenAICompatAdapter } from './openai-compat-adapter';
|
||||
import { OpenAICodexAdapter } from './openai-codex-adapter';
|
||||
import { AnthropicAdapter } from './anthropic-adapter';
|
||||
import { isGoogleNearLimit } from './google-usage';
|
||||
|
||||
// Model to use when Google's daily request limit is reached — proactive, not
|
||||
// reactive to a 429 (see google-usage.ts). Hardcoded rather than reusing
|
||||
// models.fallback: that field is a separate, more general "provider errored
|
||||
// mid-turn" mechanism (see handle-chat.ts) and may be tuned independently.
|
||||
const GOOGLE_FALLBACK_MODEL = 'deepseek-v4-flash:cloud';
|
||||
|
||||
const LEGACY_BLOCKED_MODELS = new Set(['codex-davinci-002']);
|
||||
const DEFAULT_OPENAI_MODEL = 'gpt-4o';
|
||||
@@ -49,6 +56,32 @@ function getProviderConfig(): { active: ProviderID; providers: any } {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as getProviderConfig(), but swaps 'google' for the Ollama fallback model
|
||||
* once today's request count is near the free-tier RPD limit. Both getProvider()
|
||||
* (which model instance to talk to) and getModelForRole() (which model name to
|
||||
* ask for) call this instead of the raw config, so they can't drift apart into
|
||||
* a provider/model mismatch (e.g. an Ollama connection asked for a Gemini name).
|
||||
*/
|
||||
function getEffectiveProviderConfig(): { active: ProviderID; providers: any } {
|
||||
const resolved = getProviderConfig();
|
||||
if (resolved.active === 'google' && isGoogleNearLimit()) {
|
||||
log.warn(`[Provider] Google daily request limit reached — falling back to ${GOOGLE_FALLBACK_MODEL} (ollama)`);
|
||||
return {
|
||||
active: 'ollama',
|
||||
providers: {
|
||||
...resolved.providers,
|
||||
ollama: {
|
||||
...(resolved.providers.ollama || {}),
|
||||
endpoint: resolved.providers.ollama?.endpoint || 'http://localhost:11434',
|
||||
model: GOOGLE_FALLBACK_MODEL,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function getConfigDir(): string {
|
||||
const PROJECT_CONFIG = path.join(process.cwd(), '.smallclaw');
|
||||
const HOME_CONFIG = path.join(os.homedir(), '.smallclaw');
|
||||
@@ -64,7 +97,7 @@ let cachedProviderId: ProviderID | null = null;
|
||||
* Returns the active provider. Re-creates it if the config changed.
|
||||
*/
|
||||
export function getProvider(): LLMProvider {
|
||||
const { active, providers } = getProviderConfig();
|
||||
const { active, providers } = getEffectiveProviderConfig();
|
||||
|
||||
if (cachedProvider && cachedProviderId === active) {
|
||||
// For Ollama, update endpoint in case it changed in settings
|
||||
@@ -201,7 +234,7 @@ export function getModelForRole(role: 'manager' | 'executor' | 'verifier' | 'bac
|
||||
}
|
||||
|
||||
// New-style per-provider model
|
||||
const { active, providers } = getProviderConfig();
|
||||
const { active, providers } = getEffectiveProviderConfig();
|
||||
const providerCfg = providers[active] || {};
|
||||
if (providerCfg.model) {
|
||||
const model = String(providerCfg.model).trim();
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* google-usage.ts
|
||||
* Tracks daily request count against Gemini's free-tier RPD (requests/day) limit,
|
||||
* so the app can proactively fall back before Google starts rejecting calls
|
||||
* (rather than reacting to a 429 mid-turn).
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { getConfig } from '../config/config';
|
||||
|
||||
// User-observed free-tier RPD for gemini-3.5-flash-lite (2026-07-26). Google can
|
||||
// change this without notice — this is a practical estimate, not a guarantee.
|
||||
const RPD_LIMIT = 500;
|
||||
// Trip the fallback a bit before the hard wall so a burst of requests near the
|
||||
// limit doesn't land the one call that actually gets rejected.
|
||||
const SAFETY_MARGIN = 20;
|
||||
|
||||
interface UsageRecord { date: string; count: number }
|
||||
|
||||
function usageFilePath(): string {
|
||||
return path.join(getConfig().getConfigDir(), 'google-usage.json');
|
||||
}
|
||||
|
||||
function todayKey(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function readUsage(): UsageRecord {
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(usageFilePath(), 'utf-8')) as UsageRecord;
|
||||
if (raw.date === todayKey()) return raw;
|
||||
} catch { /* missing/corrupt/stale — start fresh below */ }
|
||||
return { date: todayKey(), count: 0 };
|
||||
}
|
||||
|
||||
export function recordGoogleRequest(): void {
|
||||
const usage = readUsage();
|
||||
usage.count += 1;
|
||||
try { fs.writeFileSync(usageFilePath(), JSON.stringify(usage)); } catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
export function getGoogleUsageToday(): { date: string; count: number; limit: number } {
|
||||
const usage = readUsage();
|
||||
return { date: usage.date, count: usage.count, limit: RPD_LIMIT };
|
||||
}
|
||||
|
||||
export function isGoogleNearLimit(): boolean {
|
||||
return readUsage().count >= (RPD_LIMIT - SAFETY_MARGIN);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import type { LLMProvider, ChatMessage, ChatOptions, ChatResult, GenerateOptions, GenerateResult, ModelInfo, ProviderID } from './LLMProvider';
|
||||
import { contentToString } from './content-utils';
|
||||
import { recordGoogleRequest } from './google-usage';
|
||||
|
||||
export interface OpenAICompatConfig {
|
||||
endpoint: string;
|
||||
@@ -41,6 +42,10 @@ export class OpenAICompatAdapter implements LLMProvider {
|
||||
}
|
||||
|
||||
private async post(path: string, body: object): Promise<any> {
|
||||
// Count every attempt (not just successes) — Google's RPD counts issued
|
||||
// requests, and a proactive count lets getProvider() fall back before we
|
||||
// ever hit an actual 429 mid-turn.
|
||||
if (this.id === 'google') recordGoogleRequest();
|
||||
const auth = await this.getAuthHeader();
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (auth) headers['Authorization'] = auth;
|
||||
|
||||
@@ -136,6 +136,7 @@
|
||||
<span style="font-size:11px;color:var(--muted);font-weight:700">모델</span>
|
||||
<span id="current-provider-badge" style="font-size:11px;font-weight:800;color:var(--muted)"></span>
|
||||
<span id="current-model" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">-</span>
|
||||
<span id="google-usage-badge" title="Gemini 무료 티어 일일 요청 한도(대략치, 예고없이 바뀔 수 있음)" style="display:none;font-size:10px;font-weight:700;font-family:'IBM Plex Mono',monospace;color:var(--muted);padding:2px 6px;border-radius:6px;background:var(--panel);flex-shrink:0"></span>
|
||||
<span class="status-pill" style="margin-left:auto;flex-shrink:0;padding:4px 9px;font-size:11px">
|
||||
<span class="dot" id="ollama-dot"></span>
|
||||
<span id="ollama-status" style="font-weight:700">확인 중...</span>
|
||||
|
||||
@@ -855,6 +855,20 @@ async function checkStatus() {
|
||||
if (badge) badge.textContent = isCloud ? providerLabel.toUpperCase() : '';
|
||||
const cpn = document.getElementById('chat-provider-name');
|
||||
if (cpn) cpn.textContent = providerLabel;
|
||||
|
||||
// Google-only: daily request usage against the free-tier RPD limit
|
||||
const gub = document.getElementById('google-usage-badge');
|
||||
if (gub) {
|
||||
const gu = status.googleUsage;
|
||||
if (provider === 'google' && gu) {
|
||||
const pct = gu.limit > 0 ? (gu.count / gu.limit) : 0;
|
||||
gub.style.display = 'inline-block';
|
||||
gub.textContent = `${gu.count}/${gu.limit}`;
|
||||
gub.style.color = pct >= 0.9 ? 'var(--err)' : pct >= 0.7 ? 'var(--warn)' : 'var(--muted)';
|
||||
} else {
|
||||
gub.style.display = 'none';
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
document.getElementById('ollama-dot').className = 'dot offline';
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user