구글 한도: 429 응답에서 대기시간·일일한도를 읽어 즉시 대체 모델로 전환(하드코딩 500회 가정 제거), 시스템 프롬프트에 현재 백엔드 모델명 주입
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ea2f9dccc4
commit
feeed87f47
6 files changed
+101
-7
No files matched your search
@@ -179,8 +179,11 @@ def _chat_openai_compat(base, key, model, messages, timeout):
|
||||
tcs.append(item)
|
||||
return {"content": msg.get("content") or "", "tool_calls": tcs}
|
||||
|
||||
CALL_DELAY = 0.0 # --delay: 분당 호출 제한(RPM)이 있는 무료 등급용
|
||||
|
||||
def chat(endpoint, model, messages, timeout=150):
|
||||
"""model 표기: 'anthropic:claude-...' / 'google:gemini-...' / 그 외는 Ollama."""
|
||||
if CALL_DELAY: time.sleep(CALL_DELAY)
|
||||
t = time.time()
|
||||
if model.startswith("anthropic:"):
|
||||
msg = _chat_anthropic(model.split(":", 1)[1], messages, timeout)
|
||||
@@ -240,7 +243,10 @@ def main():
|
||||
ap.add_argument("--out", default="")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--repeat", type=int, default=2)
|
||||
ap.add_argument("--delay", type=float, default=0.0, help="호출 사이 대기(초)")
|
||||
a = ap.parse_args()
|
||||
global CALL_DELAY
|
||||
CALL_DELAY = a.delay
|
||||
models = [m for m in a.models.split(",") if m]
|
||||
results = []
|
||||
with cf.ThreadPoolExecutor(max_workers=a.workers) as ex:
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
* and skill context and passes them in.
|
||||
*/
|
||||
|
||||
import { getActiveBackendLabel } from '../../providers/factory';
|
||||
|
||||
export interface SystemPromptInput {
|
||||
/** '' for normal chat; background_task / heartbeat / cron get an autonomy preamble. */
|
||||
executionMode?: string;
|
||||
@@ -70,6 +72,7 @@ export function groundingResultReadingRule(dateStr: string): string {
|
||||
}
|
||||
|
||||
export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
const backendLabel = getActiveBackendLabel();
|
||||
const executionMode = String(input.executionMode || '');
|
||||
const dateStr = input.dateStr;
|
||||
const timeStr = input.timeStr;
|
||||
@@ -266,7 +269,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
const packageInstallRuleBlock = (toolNames.has('shell') || toolNames.has('run_command'))
|
||||
? '\nPACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.'
|
||||
: '';
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. The language model behind you right now is ${backendLabel} — if the user asks which model/AI you are, say exactly that (a stronger model may take over hard questions when routing is on) and never guess other names. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.${verifyFactsRule}
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${routeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph.${newsFormatRule}${weatherFormatRule}${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
|
||||
|
||||
@@ -271,3 +271,18 @@ export function getFallbackModel(): string {
|
||||
const raw = getConfig().getConfig() as any;
|
||||
return String(raw.models?.fallback || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 지금 대화가 실제로 쓰는 백엔드 표기("google / gemini-3.5-flash-lite" 등). 시스템 프롬프트에 넣어
|
||||
* "모델은?" 같은 질문에 모델이 지어내지 않고 답하게 한다(2026-10-17: Gemini로 돌면서 "오픈소스 Ollama 모델"이라고 오답).
|
||||
* 구글 한도 때문에 대체 모델로 돌고 있으면 그 사실대로 반영한다.
|
||||
*/
|
||||
export function getActiveBackendLabel(): string {
|
||||
try {
|
||||
const { active, providers } = getEffectiveProviderConfig();
|
||||
const model = String(providers?.[active]?.model || getModelForRole('executor') || '').trim();
|
||||
return model ? `${active} / ${model}` : String(active);
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ 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 }
|
||||
interface UsageRecord { date: string; count: number; blockedUntil?: number; learnedLimit?: number }
|
||||
|
||||
function usageFilePath(): string {
|
||||
return path.join(getConfig().getConfigDir(), 'google-usage.json');
|
||||
@@ -30,6 +30,8 @@ function readUsage(): UsageRecord {
|
||||
try {
|
||||
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 };
|
||||
} catch { /* missing/corrupt/stale — start fresh below */ }
|
||||
return { date: todayKey(), count: 0 };
|
||||
}
|
||||
@@ -37,14 +39,54 @@ function readUsage(): UsageRecord {
|
||||
export function recordGoogleRequest(): void {
|
||||
const usage = readUsage();
|
||||
usage.count += 1;
|
||||
try { fs.writeFileSync(usageFilePath(), JSON.stringify(usage)); } catch { /* non-fatal */ }
|
||||
writeUsage(usage);
|
||||
}
|
||||
|
||||
export function getGoogleUsageToday(): { date: string; count: number; limit: number } {
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Google이 429를 돌려줬을 때 호출한다. 하드코딩한 한도(500)는 7월 관측값이라 무료 등급이 바뀌면 어긋난다
|
||||
* (2026-10-17 실측: 하루 20회 / 분당 제한으로 429). 추정치를 믿지 않고, 429 본문에서 재시도 대기 시간과
|
||||
* 한도 값을 읽어 그 시간 동안은 곧바로 대체 모델로 돌린다.
|
||||
*/
|
||||
export function parseGoogle429(body: string): { delayMs: number; dailyLimit?: number } {
|
||||
const text = String(body || '');
|
||||
let delayMs = 60_000; // 분당 제한이면 보통 이 정도면 풀린다
|
||||
const secs = /retryDelay"?:\s*"?(\d+(?:\.\d+)?)s/i.exec(text);
|
||||
const hms = /retry in\s+(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?/i.exec(text);
|
||||
if (secs) delayMs = Math.ceil(Number(secs[1]) * 1000);
|
||||
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 };
|
||||
}
|
||||
|
||||
export function recordGoogle429(body: string): void {
|
||||
const u = readUsage();
|
||||
const { delayMs, dailyLimit } = parseGoogle429(body);
|
||||
u.blockedUntil = Date.now() + delayMs;
|
||||
if (dailyLimit) u.learnedLimit = dailyLimit;
|
||||
writeUsage(u);
|
||||
}
|
||||
|
||||
export function getGoogleUsageToday(): { date: string; count: number; limit: number; blockedUntil?: number } {
|
||||
const usage = readUsage();
|
||||
return { date: usage.date, count: usage.count, limit: RPD_LIMIT };
|
||||
return { date: usage.date, count: usage.count, limit: effectiveLimit(usage), blockedUntil: usage.blockedUntil };
|
||||
}
|
||||
|
||||
export function isGoogleNearLimit(): boolean {
|
||||
return readUsage().count >= (RPD_LIMIT - SAFETY_MARGIN);
|
||||
const u = readUsage();
|
||||
if (u.blockedUntil && u.blockedUntil > Date.now()) return true; // 429 직후에는 대기 시간 동안 대체 모델 사용
|
||||
return u.count >= (effectiveLimit(u) - SAFETY_MARGIN);
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import type { LLMProvider, ChatMessage, ChatOptions, ChatResult, GenerateOptions, GenerateResult, ModelInfo, ProviderID } from './LLMProvider';
|
||||
import { contentToString } from './content-utils';
|
||||
import { recordGoogleRequest } from './google-usage';
|
||||
import { recordGoogleRequest, recordGoogle429 } from './google-usage';
|
||||
import { logUsage, parseOpenAiUsage } from './usage-log';
|
||||
|
||||
export interface OpenAICompatConfig {
|
||||
@@ -63,6 +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);
|
||||
throw new Error(`${this.id} API error ${response.status}: ${text.slice(0, 200)}`);
|
||||
}
|
||||
return response.json();
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* google-usage — 429 본문에서 대기 시간·일일 한도 읽기
|
||||
* 표본: 2026-10-17 실제 응답(무료 등급 하루 20회, "Please retry in 13h36m54.56s", retryDelay "49014s").
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseGoogle429 } from '../src/providers/google-usage';
|
||||
|
||||
describe('parseGoogle429', () => {
|
||||
test('일일 한도 429: retryDelay 초 단위와 limit 값을 읽는다', () => {
|
||||
const body = 'Quota exceeded for metric: generate_content_free_tier_requests, limit: 20, model: gemini-3.6-flash\nPlease retry in 13h36m54.561904137s. "quotaId": "GenerateRequestsPerDayPerProjectPerModel-FreeTier" "retryDelay": "49014s"';
|
||||
const r = parseGoogle429(body);
|
||||
assert.equal(r.delayMs, 49_014_000);
|
||||
assert.equal(r.dailyLimit, 20);
|
||||
});
|
||||
test('retryDelay 없이 "retry in 13h36m"만 있어도 읽는다', () => {
|
||||
assert.equal(parseGoogle429('Please retry in 13h36m54s.').delayMs, (13 * 3600 + 36 * 60 + 54) * 1000);
|
||||
});
|
||||
test('분당 제한(대기 시간 없음)은 60초로 본다', () => {
|
||||
const r = parseGoogle429('You exceeded your current quota (requests per minute)');
|
||||
assert.equal(r.delayMs, 60_000);
|
||||
assert.equal(r.dailyLimit, undefined);
|
||||
});
|
||||
test('대기 시간은 24시간을 넘기지 않는다', () => {
|
||||
assert.equal(parseGoogle429('"retryDelay": "999999s"').delayMs, 24 * 3600_000);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user