구글 429 막힘을 모델별로 분리(3.6 Flash 429가 Flash-Lite로 번지지 않게), 기본 한도 500은 유지
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
feeed87f47
commit
b2ebd9beec
7 files changed
+58
-24
No files matched your search
@@ -80,9 +80,10 @@ def chat_once(token, model, sid, message, timeout=240):
|
||||
return {"tools": tools, "reply": reply or tokens, "sec": round(time.time() - t0, 1), "error": err}
|
||||
|
||||
|
||||
def run_model(token, model, tag):
|
||||
def run_model(token, model, tag, delay=0.0):
|
||||
out = []
|
||||
for i, (label, q) in enumerate(QUESTIONS):
|
||||
if delay and i: time.sleep(delay) # 무료 등급 분당 제한용
|
||||
sid = f"ab_{tag}_{i}"
|
||||
r = chat_once(token, model, sid, q)
|
||||
r.update(label=label, q=q, model=model, sid=sid,
|
||||
@@ -96,6 +97,7 @@ def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--models", default="gemma4:31b-cloud,glm-5.3-flash:cloud,kimi-k3:cloud,kimi-k2.6:cloud")
|
||||
ap.add_argument("--out", default="ab.json")
|
||||
ap.add_argument("--delay", type=float, default=0.0, help="질문 사이 대기(초)")
|
||||
a = ap.parse_args()
|
||||
models = [m for m in a.models.split(",") if m]
|
||||
|
||||
@@ -111,7 +113,7 @@ def main():
|
||||
results = []
|
||||
try:
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futs = [ex.submit(run_model, token, m, re.sub(r"\W", "", m.split(":")[0])) for m in models]
|
||||
futs = [ex.submit(run_model, token, m, re.sub(r"\W", "", m.split(":")[0]), a.delay) for m in models]
|
||||
for f in futs:
|
||||
results += f.result()
|
||||
finally:
|
||||
|
||||
@@ -3121,7 +3121,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,
|
||||
googleUsage: provider === 'google' ? getGoogleUsageToday(String(activeModel || '')) : null,
|
||||
orchestration: orchCfg ? {
|
||||
enabled: orchCfg.enabled,
|
||||
secondary: orchCfg.secondary,
|
||||
|
||||
@@ -65,7 +65,7 @@ function getProviderConfig(): { active: ProviderID; providers: any } {
|
||||
*/
|
||||
function getEffectiveProviderConfig(): { active: ProviderID; providers: any } {
|
||||
const resolved = getProviderConfig();
|
||||
if (resolved.active === 'google' && isGoogleNearLimit()) {
|
||||
if (resolved.active === 'google' && isGoogleNearLimit(String(resolved.providers?.google?.model || ''))) {
|
||||
log.warn(`[Provider] Google daily request limit reached — falling back to ${GOOGLE_FALLBACK_MODEL} (ollama)`);
|
||||
return {
|
||||
active: 'ollama',
|
||||
|
||||
@@ -16,7 +16,9 @@ const RPD_LIMIT = 500;
|
||||
// limit doesn't land the one call that actually gets rejected.
|
||||
const SAFETY_MARGIN = 20;
|
||||
|
||||
interface UsageRecord { date: string; count: number; blockedUntil?: number; learnedLimit?: number }
|
||||
// 구글 무료 한도는 모델별 통이다(quotaId …PerProjectPerModel) — 3.6 Flash가 막혀도 3.5 Flash-Lite는 멀쩡하므로
|
||||
// 막힘 시각과 배운 한도는 모델 이름을 키로 따로 보관한다.
|
||||
interface UsageRecord { date: string; count: number; blocked?: Record<string, number>; learnedLimits?: Record<string, number> }
|
||||
|
||||
function usageFilePath(): string {
|
||||
return path.join(getConfig().getConfigDir(), 'google-usage.json');
|
||||
@@ -31,7 +33,7 @@ function readUsage(): UsageRecord {
|
||||
const raw = JSON.parse(fs.readFileSync(usageFilePath(), 'utf-8')) as UsageRecord;
|
||||
if (raw.date === todayKey()) return raw;
|
||||
// 날짜가 바뀌어도 막힘 시각이 남아 있으면 유지한다(자정 직후에도 429 구간일 수 있음)
|
||||
if (raw.blockedUntil && raw.blockedUntil > Date.now()) return { date: todayKey(), count: 0, blockedUntil: raw.blockedUntil, learnedLimit: raw.learnedLimit };
|
||||
if (raw.blocked && Object.values(raw.blocked).some(t => t > Date.now())) return { date: todayKey(), count: 0, blocked: raw.blocked, learnedLimits: raw.learnedLimits };
|
||||
} catch { /* missing/corrupt/stale — start fresh below */ }
|
||||
return { date: todayKey(), count: 0 };
|
||||
}
|
||||
@@ -46,21 +48,22 @@ function writeUsage(u: UsageRecord): void {
|
||||
try { fs.writeFileSync(usageFilePath(), JSON.stringify(u)); } catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
/** 설정(llm.providers.google.rpd_limit) > 429 응답에서 배운 값 > 기본 추정치 순으로 하루 한도를 정한다. */
|
||||
function effectiveLimit(u: UsageRecord): number {
|
||||
/** 설정(llm.providers.google.rpd_limit) > 그 모델의 429에서 배운 값 > 기본 추정치(500, 7월 사용자 관측) 순. */
|
||||
function effectiveLimit(u: UsageRecord, model?: string): number {
|
||||
try {
|
||||
const cfg = Number(((getConfig().getConfig() as any)?.llm?.providers?.google?.rpd_limit));
|
||||
if (cfg > 0) return cfg;
|
||||
} catch { /* 설정 없음 */ }
|
||||
return u.learnedLimit && u.learnedLimit > 0 ? u.learnedLimit : RPD_LIMIT;
|
||||
const learned = model ? u.learnedLimits?.[model] : undefined;
|
||||
return learned && learned > 0 ? learned : RPD_LIMIT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Google이 429를 돌려줬을 때 호출한다. 하드코딩한 한도(500)는 7월 관측값이라 무료 등급이 바뀌면 어긋난다
|
||||
* (2026-10-17 실측: 하루 20회 / 분당 제한으로 429). 추정치를 믿지 않고, 429 본문에서 재시도 대기 시간과
|
||||
* 한도 값을 읽어 그 시간 동안은 곧바로 대체 모델로 돌린다.
|
||||
* Google이 429를 돌려줬을 때 호출한다. 429 본문에서 재시도 대기 시간과 일일 한도를 읽어, **그 모델에 한해**
|
||||
* 대기 시간 동안 곧바로 대체 모델로 돌린다. 요청한 모델명과 응답이 가리키는 모델명이 다를 수 있어(별칭:
|
||||
* 2026-10-17 gemini-3.5-flash 요청이 3.6-flash 한도로 집계됨) 둘 다 막는다.
|
||||
*/
|
||||
export function parseGoogle429(body: string): { delayMs: number; dailyLimit?: number } {
|
||||
export function parseGoogle429(body: string): { delayMs: number; dailyLimit?: number; model?: string } {
|
||||
const text = String(body || '');
|
||||
let delayMs = 60_000; // 분당 제한이면 보통 이 정도면 풀린다
|
||||
const secs = /retryDelay"?:\s*"?(\d+(?:\.\d+)?)s/i.exec(text);
|
||||
@@ -69,24 +72,32 @@ export function parseGoogle429(body: string): { delayMs: number; dailyLimit?: nu
|
||||
else if (hms && (hms[1] || hms[2] || hms[3])) delayMs = (Number(hms[1] || 0) * 3600 + Number(hms[2] || 0) * 60 + Number(hms[3] || 0)) * 1000;
|
||||
delayMs = Math.min(Math.max(delayMs, 30_000), 24 * 3600_000);
|
||||
const lim = /limit:\s*(\d+)/i.exec(text);
|
||||
return { delayMs, dailyLimit: lim && /PerDay|per day/i.test(text) ? Number(lim[1]) : undefined };
|
||||
const model = /model:\s*([\w.\-]+)/i.exec(text)?.[1];
|
||||
return { delayMs, dailyLimit: lim && /PerDay|per day/i.test(text) ? Number(lim[1]) : undefined, model };
|
||||
}
|
||||
|
||||
export function recordGoogle429(body: string): void {
|
||||
export function recordGoogle429(body: string, requestedModel?: string): void {
|
||||
const u = readUsage();
|
||||
const { delayMs, dailyLimit } = parseGoogle429(body);
|
||||
u.blockedUntil = Date.now() + delayMs;
|
||||
if (dailyLimit) u.learnedLimit = dailyLimit;
|
||||
const { delayMs, dailyLimit, model } = parseGoogle429(body);
|
||||
const until = Date.now() + delayMs;
|
||||
u.blocked = u.blocked || {};
|
||||
u.learnedLimits = u.learnedLimits || {};
|
||||
for (const m of new Set([requestedModel, model].filter(Boolean) as string[])) {
|
||||
u.blocked[m] = until;
|
||||
if (dailyLimit) u.learnedLimits[m] = dailyLimit;
|
||||
}
|
||||
writeUsage(u);
|
||||
}
|
||||
|
||||
export function getGoogleUsageToday(): { date: string; count: number; limit: number; blockedUntil?: number } {
|
||||
export function getGoogleUsageToday(model?: string): { date: string; count: number; limit: number; blockedUntil?: number } {
|
||||
const usage = readUsage();
|
||||
return { date: usage.date, count: usage.count, limit: effectiveLimit(usage), blockedUntil: usage.blockedUntil };
|
||||
return { date: usage.date, count: usage.count, limit: effectiveLimit(usage, model), blockedUntil: model ? usage.blocked?.[model] : undefined };
|
||||
}
|
||||
|
||||
export function isGoogleNearLimit(): boolean {
|
||||
/** model: 지금 쓰려는 구글 모델명. 주면 그 모델의 막힘만 본다(다른 모델의 429가 번지지 않게). */
|
||||
export function isGoogleNearLimit(model?: string): boolean {
|
||||
const u = readUsage();
|
||||
if (u.blockedUntil && u.blockedUntil > Date.now()) return true; // 429 직후에는 대기 시간 동안 대체 모델 사용
|
||||
return u.count >= (effectiveLimit(u) - SAFETY_MARGIN);
|
||||
const blockedUntil = model ? u.blocked?.[model] : Math.max(0, ...Object.values(u.blocked || {}));
|
||||
if (blockedUntil && blockedUntil > Date.now()) return true; // 429 직후에는 대기 시간 동안 대체 모델 사용
|
||||
return u.count >= (effectiveLimit(u, model) - SAFETY_MARGIN);
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export class OpenAICompatAdapter implements LLMProvider {
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => '');
|
||||
if (this.id === 'google' && response.status === 429) recordGoogle429(text);
|
||||
if (this.id === 'google' && response.status === 429) recordGoogle429(text, String((body as any)?.model || ''));
|
||||
throw new Error(`${this.id} API error ${response.status}: ${text.slice(0, 200)}`);
|
||||
}
|
||||
return response.json();
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* google-usage — 429 막힘은 해당 모델에만. 3.6 Flash가 막혀도 Flash-Lite는 계속 구글로 간다.
|
||||
*/
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { getConfig } from '../src/config/config';
|
||||
import { recordGoogle429, isGoogleNearLimit } from '../src/providers/google-usage';
|
||||
|
||||
test('한 모델의 429가 다른 구글 모델로 번지지 않는다', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gusage-'));
|
||||
(getConfig() as any).getConfigDir = () => dir; // 시험용 임시 폴더로 격리
|
||||
const body = 'limit: 20, model: gemini-3.6-flash\nPlease retry in 1h. "quotaId": "GenerateRequestsPerDayPerProjectPerModel-FreeTier"';
|
||||
recordGoogle429(body, 'gemini-3.5-flash'); // 별칭: 요청명과 응답명이 다름
|
||||
assert.equal(isGoogleNearLimit('gemini-3.6-flash'), true);
|
||||
assert.equal(isGoogleNearLimit('gemini-3.5-flash'), true);
|
||||
assert.equal(isGoogleNearLimit('gemini-3.5-flash-lite'), false); // 별도 통은 영향 없음
|
||||
});
|
||||
@@ -12,6 +12,7 @@ describe('parseGoogle429', () => {
|
||||
const r = parseGoogle429(body);
|
||||
assert.equal(r.delayMs, 49_014_000);
|
||||
assert.equal(r.dailyLimit, 20);
|
||||
assert.equal(r.model, 'gemini-3.6-flash'); // 막힘은 이 모델에만 적용해야 한다(Flash-Lite는 별도 통)
|
||||
});
|
||||
test('retryDelay 없이 "retry in 13h36m"만 있어도 읽는다', () => {
|
||||
assert.equal(parseGoogle429('Please retry in 13h36m54s.').delayMs, (13 * 3600 + 36 * 60 + 54) * 1000);
|
||||
|
||||
Reference in new issue
Block a user