From 3d1227dc45124a22f8d7d206752430791fa5bff6 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:03:30 +0200 Subject: [PATCH] Improves model fallback and caching strategy Adds API key validation before fetching models Ensures consistent fallback model caching on API errors or missing key Reduces redundant code by centralizing fallback model caching logic Relates to dynamic-models branch --- services/modelService.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 6329102..579def9 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -24,7 +24,7 @@ export class ModelService { /** * Get available models with caching and fallback logic * Returns models from cache if valid, otherwise fetches from API - * Falls back to hardcoded list if API fails + * Falls back to hardcoded list if API fails or API key is missing */ async getAvailableModels(): Promise { // Check if we have a valid cache @@ -32,6 +32,19 @@ export class ModelService { return this.formatModels(this.modelCache.models); } + // If no API key, immediately return and cache fallback (no Notice needed) + if (!this.anthropicClient.validateApiKey()) { + const fallback = this.getFallbackModels(); + // Cache fallback models as ModelInfo for consistency + this.updateCache(fallback.map(f => ({ + id: f.id, + display_name: f.displayName, + created_at: '', + type: 'model' + } as ModelInfo))); + return fallback; + } + // Try to fetch from API try { const response = await this.anthropicClient.fetchModels(); @@ -40,7 +53,15 @@ export class ModelService { } catch (error) { console.error('Failed to fetch models from API:', error); new Notice('Fetching current models failed. Using hardcoded fallback list.'); - return this.getFallbackModels(); + const fallback = this.getFallbackModels(); + // Cache fallback models as ModelInfo for consistency + this.updateCache(fallback.map(f => ({ + id: f.id, + display_name: f.displayName, + created_at: '', + type: 'model' + } as ModelInfo))); + return fallback; } }