feat: add dynamic model fetching from Anthropic API #2

Merged
AlexKucera merged 10 commits from dynamic-models into master 2025-10-24 11:14:13 +02:00
2 changed files with 36 additions and 4 deletions
Showing only changes of commit fcc495aa8f - Show all commits

No files matched your search

+35 -3
View File
1
@@ -49,6 +49,19 @@ export class ModelService {
* Used when user changes API key
*/
async refreshModels(): Promise<ModelOption[]> {
// If no API key, immediately return and cache fallback
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 {
const response = await this.anthropicClient.fetchModels();
this.updateCache(response.data);
@@ -56,7 +69,15 @@ export class ModelService {
} catch (error) {
console.error('Failed to refresh 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;
}
}
@@ -81,6 +102,14 @@ export class ModelService {
this.modelCache = null;
}
/**
* Get fallback model options (public API for UI components)
* Returns hardcoded model list as ModelOption array
*/
getFallbackOptions(): ModelOption[] {
return this.getFallbackModels();
}
// MARK: - Private Methods
/**
@@ -109,12 +138,15 @@ export class ModelService {
/**
* Format ModelInfo array to ModelOption array for dropdown
* Uses display_name if available, otherwise falls back to id
* Sorted by displayName for consistent UX across cache/API ordering
*/
private formatModels(models: ModelInfo[]): ModelOption[] {
return models.map(model => ({
return models
.map(model => ({
id: model.id,
displayName: model.display_name || model.id
}));
}))
.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
/**
+1 -1
View File
1
@@ -55,7 +55,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
await this.refreshModels();
} else if (this.modelDropdown) {
// Show fallback immediately when key is cleared
this.availableModels = await this.plugin.modelService.getAvailableModels();
this.availableModels = this.plugin.modelService.getFallbackOptions();
this.populateModelDropdown(this.modelDropdown);
}
}))
1