From 21417078fca8eda9f47b58ac89640a95f04717ec Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 17 Oct 2026 23:55:19 +0900 Subject: [PATCH] =?UTF-8?q?Anthropic=20=ED=81=AC=EB=A0=88=EB=94=A7=20?= =?UTF-8?q?=EC=86=8C=EC=A7=84=C2=B7=EA=B3=BC=EB=B6=80=ED=95=98(400=20credi?= =?UTF-8?q?t=20balance,=20429/5xx)=20=EC=8B=9C=20=EC=A7=80=EC=84=9C?= =?UTF-8?q?=EB=B2=84=20=EB=A1=9C=EC=BB=AC=20=EC=98=AC=EB=9D=BC=EB=A7=88(ol?= =?UTF-8?q?lama=5Flocal)=EB=A1=9C=20=EC=9E=90=EB=8F=99=20=EC=A0=84?= =?UTF-8?q?=ED=99=98=20=E2=80=94=2030=EB=B6=84(=EC=9E=94=EC=95=A1)/3?= =?UTF-8?q?=EB=B6=84(=EA=B3=BC=EB=B6=80=ED=95=98)=20=EB=92=A4=20=EC=9E=AC?= =?UTF-8?q?=EC=8B=9C=EB=8F=84,=20=EC=A7=84=ED=96=89=20=EC=A4=91=20?= =?UTF-8?q?=ED=84=B4=EB=8F=84=20=ED=95=9C=20=EB=B2=88=20=EC=9E=AC=EC=8B=9C?= =?UTF-8?q?=EB=8F=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/agents/ollama-client.ts | 14 +++++++++- src/providers/anthropic-adapter.ts | 2 ++ src/providers/anthropic-usage.ts | 43 ++++++++++++++++++++++++++++++ src/providers/factory.ts | 6 +++++ tests/anthropic-outage.test.ts | 16 +++++++++++ 5 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 src/providers/anthropic-usage.ts create mode 100644 tests/anthropic-outage.test.ts diff --git a/src/agents/ollama-client.ts b/src/agents/ollama-client.ts index 70b0963..d060324 100644 --- a/src/agents/ollama-client.ts +++ b/src/agents/ollama-client.ts @@ -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); diff --git a/src/providers/anthropic-adapter.ts b/src/providers/anthropic-adapter.ts index 7526afe..f81edfa 100644 --- a/src/providers/anthropic-adapter.ts +++ b/src/providers/anthropic-adapter.ts @@ -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(); diff --git a/src/providers/anthropic-usage.ts b/src/providers/anthropic-usage.ts new file mode 100644 index 0000000..6099706 --- /dev/null +++ b/src/providers/anthropic-usage.ts @@ -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 = ''; } diff --git a/src/providers/factory.ts b/src/providers/factory.ts index f2ce73d..ce7e6ab 100644 --- a/src/providers/factory.ts +++ b/src/providers/factory.ts @@ -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; } diff --git a/tests/anthropic-outage.test.ts b/tests/anthropic-outage.test.ts new file mode 100644 index 0000000..506a947 --- /dev/null +++ b/tests/anthropic-outage.test.ts @@ -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); +});