Anthropic 크레딧 소진·과부하(400 credit balance, 429/5xx) 시 지서버 로컬 올라마(ollama_local)로 자동 전환 — 30분(잔액)/3분(과부하) 뒤 재시도, 진행 중 턴도 한 번 재시도
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f53ca1aab9
commit
21417078fc
5 files changed
+80
-1
No files matched your search
@@ -9,6 +9,7 @@
|
||||
* resetProvider() from the settings API). No other files need touching.
|
||||
*/
|
||||
|
||||
import { isAnthropicOutageError } from '../providers/anthropic-usage';
|
||||
import { getProvider, getModelForRole, getPrimaryModel, getFallbackModel, resetProvider } from '../providers/factory';
|
||||
import type { LLMProvider, TokenUsage } from '../providers/LLMProvider';
|
||||
import { AgentRole } from '../types';
|
||||
@@ -70,6 +71,13 @@ export class OllamaClient {
|
||||
const result = await this.provider.chat(messages, model, chatOpts);
|
||||
return { message: result.message, thinking: result.thinking };
|
||||
} catch (err: any) {
|
||||
if (isAnthropicOutageError(err) && !options?.model) {
|
||||
// 막힘이 기록됐으니 getProvider()/getModelForRole()은 이제 지서버 올라마를 가리킨다
|
||||
const alt = getModelForRole(role);
|
||||
console.warn(`[OllamaClient] Anthropic unavailable — retrying on ${alt}`);
|
||||
const result = await this.provider.chat(messages, alt, chatOpts);
|
||||
return { message: result.message, thinking: result.thinking };
|
||||
}
|
||||
const fallback = getFallbackModel();
|
||||
if (fallback && fallback !== model && isRetryableModelError(err)) {
|
||||
console.warn(`[OllamaClient] ${model} unavailable (quota or retirement), retrying with fallback model ${fallback}`);
|
||||
@@ -128,7 +136,11 @@ export class OllamaClient {
|
||||
try {
|
||||
result = await this.provider.chat(messages, modelToUse, chatOpts);
|
||||
} catch (err: any) {
|
||||
if (fallbackModel && fallbackModel !== modelToUse && isRetryableModelError(err)) {
|
||||
if (isAnthropicOutageError(err) && !options?.model) {
|
||||
modelToUse = getModelForRole(role);
|
||||
console.warn(`[OllamaClient] Anthropic unavailable — retrying on ${modelToUse}`);
|
||||
result = await this.provider.chat(messages, modelToUse, chatOpts);
|
||||
} else if (fallbackModel && fallbackModel !== modelToUse && isRetryableModelError(err)) {
|
||||
console.warn(`[OllamaClient] ${modelToUse} unavailable (quota or retirement), retrying with fallback model ${fallbackModel}`);
|
||||
modelToUse = fallbackModel;
|
||||
result = await this.provider.chat(messages, modelToUse, chatOpts);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* Converts between the server's OpenAI-style ChatMessage format and Anthropic's format.
|
||||
*/
|
||||
|
||||
import { recordAnthropicFailure } from './anthropic-usage';
|
||||
import { logUsage } from './usage-log';
|
||||
import type {
|
||||
LLMProvider, ChatMessage, ContentPart, ChatOptions, ChatResult,
|
||||
@@ -52,6 +53,7 @@ export class AnthropicAdapter implements LLMProvider {
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => '');
|
||||
recordAnthropicFailure(response.status, text);
|
||||
throw new Error(`Anthropic API error ${response.status}: ${text.slice(0, 300)}`);
|
||||
}
|
||||
return response.json();
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* anthropic-usage.ts — Anthropic API가 "쓸 수 없는 상태"(크레딧 소진·과부하·한도)로 응답하면 잠시 막힘으로 기록한다.
|
||||
* factory.getEffectiveProviderConfig()가 막힘 동안 활성 provider를 지서버 로컬 올라마(ollama_local)로 바꿔,
|
||||
* 크레딧이 바닥나도 채팅이 계속되게 한다(구글 일일 한도 대체와 같은 구조). 막힘이 풀리면 다시 Anthropic을 시도한다.
|
||||
*/
|
||||
|
||||
const CREDIT_BLOCK_MS = 30 * 60_000; // 잔액 부족: 충전 전엔 계속 실패하므로 길게, 30분마다 한 번 재시도
|
||||
const BUSY_BLOCK_MS = 3 * 60_000; // 429·529·5xx: 잠깐
|
||||
|
||||
let blockedUntil = 0;
|
||||
let blockedReason = '';
|
||||
|
||||
/** Anthropic이 "이 요청은 지금 처리 못 한다"고 말한 종류의 오류인가(잘못된 요청 400 등은 해당 없음). */
|
||||
export function classifyAnthropicOutage(status: number, body: string): 'credit' | 'busy' | null {
|
||||
const t = String(body || '');
|
||||
if (status === 400 && /credit balance|billing|purchase credits/i.test(t)) return 'credit';
|
||||
if (status === 402) return 'credit';
|
||||
if (status === 429 || status === 529 || status === 503 || status === 502 || status === 500) return 'busy';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function recordAnthropicFailure(status: number, body: string): void {
|
||||
const kind = classifyAnthropicOutage(status, body);
|
||||
if (!kind) return;
|
||||
blockedUntil = Date.now() + (kind === 'credit' ? CREDIT_BLOCK_MS : BUSY_BLOCK_MS);
|
||||
blockedReason = `${kind} (HTTP ${status})`;
|
||||
}
|
||||
|
||||
export function isAnthropicBlocked(): boolean {
|
||||
return Date.now() < blockedUntil;
|
||||
}
|
||||
|
||||
export function anthropicBlockReason(): string {
|
||||
return isAnthropicBlocked() ? blockedReason : '';
|
||||
}
|
||||
|
||||
/** 어댑터가 던진 오류 메시지가 위 종류인가("Anthropic API error 400: …credit balance…"). */
|
||||
export function isAnthropicOutageError(err: any): boolean {
|
||||
const m = /Anthropic API error (\d{3}): ([\s\S]*)/.exec(String(err?.message || err || ''));
|
||||
return !!m && classifyAnthropicOutage(Number(m[1]), m[2]) !== null;
|
||||
}
|
||||
|
||||
export function resetAnthropicBlock(): void { blockedUntil = 0; blockedReason = ''; }
|
||||
@@ -23,6 +23,7 @@ import { OpenAICompatAdapter } from './openai-compat-adapter';
|
||||
import { OpenAICodexAdapter } from './openai-codex-adapter';
|
||||
import { AnthropicAdapter } from './anthropic-adapter';
|
||||
import { isGoogleNearLimit } from './google-usage';
|
||||
import { isAnthropicBlocked, anthropicBlockReason } from './anthropic-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
|
||||
@@ -79,6 +80,11 @@ function getEffectiveProviderConfig(): { active: ProviderID; providers: any } {
|
||||
},
|
||||
};
|
||||
}
|
||||
// Anthropic 크레딧 소진·과부하 동안은 지서버 로컬 올라마(gemma4)로 — 검색은 별도로 시어엔진 체인으로 넘어간다.
|
||||
if (resolved.active === 'anthropic' && isAnthropicBlocked() && resolved.providers?.ollama_local?.endpoint) {
|
||||
log.warn(`[Provider] Anthropic unavailable (${anthropicBlockReason()}) — falling back to ollama_local (${resolved.providers.ollama_local.model || 'default'})`);
|
||||
return { active: 'ollama_local', providers: resolved.providers };
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyAnthropicOutage, isAnthropicOutageError, recordAnthropicFailure, isAnthropicBlocked, resetAnthropicBlock } from '../src/providers/anthropic-usage';
|
||||
|
||||
test('크레딧 부족 400 → credit', () => assert.equal(classifyAnthropicOutage(400, '{"error":{"message":"Your credit balance is too low to access the Anthropic API"}}'), 'credit'));
|
||||
test('일반 잘못된 요청 400은 대상 아님', () => assert.equal(classifyAnthropicOutage(400, 'max_tokens: must be > 0'), null));
|
||||
test('429·529 → busy', () => { assert.equal(classifyAnthropicOutage(429, ''), 'busy'); assert.equal(classifyAnthropicOutage(529, 'overloaded'), 'busy'); });
|
||||
test('오류 메시지 판별', () => {
|
||||
assert.equal(isAnthropicOutageError(new Error('Anthropic API error 400: credit balance is too low')), true);
|
||||
assert.equal(isAnthropicOutageError(new Error('Anthropic API error 400: invalid tool schema')), false);
|
||||
});
|
||||
test('기록 후 막힘, 초기화하면 풀림', () => {
|
||||
resetAnthropicBlock(); assert.equal(isAnthropicBlocked(), false);
|
||||
recordAnthropicFailure(400, 'credit balance is too low'); assert.equal(isAnthropicBlocked(), true);
|
||||
resetAnthropicBlock(); assert.equal(isAnthropicBlocked(), false);
|
||||
});
|
||||
Reference in new issue
Block a user