feat: add dynamic model fetching from Anthropic API
Replace hardcoded model list with dynamic API-based model fetching that queries the Anthropic models endpoint. Implements 24-hour caching with automatic fallback to hardcoded models if API is unavailable. Changes: - Add ModelService to fetch and cache available models from API - Implement 24-hour TTL cache persisted in plugin data - Update AnthropicClient with fetchModels() method - Modify settings UI to load models asynchronously with loading states - Auto-refresh models when API key is entered or changed - Display model names using display_name field from API - Preserve user's selected model across updates and restarts - Show notice when falling back to hardcoded model list - Change model type from strict enum to string for dynamic support Technical details: - New ModelInfo and ModelsListResponse interfaces for API response - ModelCache interface with timestamp for TTL validation - FreewritingPromptsData extends settings to include cache - Settings dropdown disabled during model fetch/refresh - Fallback to ANTHROPIC_MODELS constant on API failure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
6 files changed
+287
-19
No files matched your search
@@ -0,0 +1,129 @@
|
||||
// ABOUTME: Service for managing Claude model list from Anthropic API
|
||||
// ABOUTME: Handles fetching, caching with 24-hour TTL, and fallback to hardcoded list
|
||||
|
||||
import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||
|
||||
export interface ModelOption {
|
||||
id: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export class ModelService {
|
||||
private anthropicClient: AnthropicClient;
|
||||
private modelCache: ModelCache | null = null;
|
||||
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
constructor(anthropicClient: AnthropicClient) {
|
||||
this.anthropicClient = anthropicClient;
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
async getAvailableModels(): Promise<ModelOption[]> {
|
||||
// Check if we have a valid cache
|
||||
if (this.isCacheValid() && this.modelCache) {
|
||||
return this.formatModels(this.modelCache.models);
|
||||
}
|
||||
|
||||
// Try to fetch from API
|
||||
try {
|
||||
const response = await this.anthropicClient.fetchModels();
|
||||
this.updateCache(response.data);
|
||||
return this.formatModels(response.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch models from API:', error);
|
||||
new Notice('Fetching current models failed. Using hardcoded fallback list.');
|
||||
return this.getFallbackModels();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Force refresh the model list from API
|
||||
* Used when user changes API key
|
||||
*/
|
||||
async refreshModels(): Promise<ModelOption[]> {
|
||||
try {
|
||||
const response = await this.anthropicClient.fetchModels();
|
||||
this.updateCache(response.data);
|
||||
return this.formatModels(response.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh models from API:', error);
|
||||
new Notice('Fetching current models failed. Using hardcoded fallback list.');
|
||||
return this.getFallbackModels();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cache from plugin data
|
||||
*/
|
||||
loadCache(cache: ModelCache | null): void {
|
||||
this.modelCache = cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current cache for saving to plugin data
|
||||
*/
|
||||
getCache(): ModelCache | null {
|
||||
return this.modelCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cache (for testing or manual refresh)
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.modelCache = null;
|
||||
}
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
/**
|
||||
* Check if the current cache is still valid (within TTL)
|
||||
*/
|
||||
private isCacheValid(): boolean {
|
||||
if (!this.modelCache) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const age = now - this.modelCache.fetchedAt;
|
||||
return age < this.CACHE_TTL_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update cache with new model data
|
||||
*/
|
||||
private updateCache(models: ModelInfo[]): void {
|
||||
this.modelCache = {
|
||||
models,
|
||||
fetchedAt: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Format ModelInfo array to ModelOption array for dropdown
|
||||
* Uses display_name if available, otherwise falls back to id
|
||||
*/
|
||||
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||
return models.map(model => ({
|
||||
id: model.id,
|
||||
displayName: model.display_name || model.id
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fallback models from hardcoded list
|
||||
*/
|
||||
private getFallbackModels(): ModelOption[] {
|
||||
return ANTHROPIC_MODELS.map(id => ({
|
||||
id,
|
||||
displayName: id
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types';
|
||||
import { FreewritingPromptsSettings, GeneratedPrompt } from '../types';
|
||||
|
||||
export class PromptGeneratorService {
|
||||
private client: AnthropicClient;
|
||||
@@ -54,7 +54,7 @@ export class PromptGeneratorService {
|
||||
|
||||
private async generatePrompts(
|
||||
count: number,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
systemPrompt: string,
|
||||
examplePrompt: string,
|
||||
type: 'timed' | 'note'
|
||||
@@ -97,7 +97,7 @@ export class PromptGeneratorService {
|
||||
|
||||
private createCacheKey(
|
||||
count: number,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
systemPrompt: string,
|
||||
examplePrompt: string,
|
||||
type: string
|
||||
|
||||
Reference in new issue
Block a user