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 - FreewritingCleanupData 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
+294
-22
No files matched your search
+34
-5
@@ -2,11 +2,12 @@
|
||||
// ABOUTME: Handles API requests, error handling, retry logic, and response parsing
|
||||
|
||||
import { requestUrl } from 'obsidian';
|
||||
import { AnthropicRequest, AnthropicResponse, AnthropicModel, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS } from '../types';
|
||||
import { AnthropicRequest, AnthropicResponse, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS, ModelsListResponse } from '../types';
|
||||
|
||||
export class AnthropicClient {
|
||||
private apiKey: string;
|
||||
private baseUrl = 'https://api.anthropic.com/v1/messages';
|
||||
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
||||
private modelsUrl = 'https://api.anthropic.com/v1/models';
|
||||
private readonly MAX_RETRIES = 3;
|
||||
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
||||
|
||||
@@ -18,7 +19,7 @@ export class AnthropicClient {
|
||||
|
||||
async cleanupText(
|
||||
text: string,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
cleanupPrompt: string,
|
||||
enableCommentary = false,
|
||||
commentaryStyle: CommentaryStyle = 'constructive',
|
||||
@@ -77,7 +78,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
return this.parseStructuredResponse(response, enableCommentary);
|
||||
}
|
||||
|
||||
async testConnection(model: AnthropicModel): Promise<{
|
||||
async testConnection(model: string): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: {
|
||||
@@ -174,10 +175,38 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
return { cleanedText, commentary };
|
||||
}
|
||||
|
||||
async fetchModels(): Promise<ModelsListResponse> {
|
||||
if (!this.apiKey) {
|
||||
throw new Error('API key is required');
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await requestUrl({
|
||||
url: this.modelsUrl,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'x-api-key': this.apiKey,
|
||||
'anthropic-version': '2023-06-01'
|
||||
}
|
||||
});
|
||||
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw new Error(`Models API request failed: ${response.status}\n${response.text}`);
|
||||
}
|
||||
|
||||
return response.json as ModelsListResponse;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Network request failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||
try {
|
||||
const response = await requestUrl({
|
||||
url: this.baseUrl,
|
||||
url: this.messagesUrl,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
||||
|
||||
import { Editor, MarkdownView, Plugin } from 'obsidian';
|
||||
import { FreewritingCleanupSettings } from './types';
|
||||
import { FreewritingCleanupSettings, FreewritingCleanupData } from './types';
|
||||
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
|
||||
import { CleanupService } from './services/cleanupService';
|
||||
import { ModelService } from './services/modelService';
|
||||
import { CleanupCommand } from './commands/cleanupCommand';
|
||||
|
||||
export default class FreewritingCleanupPlugin extends Plugin {
|
||||
settings: FreewritingCleanupSettings;
|
||||
cleanupService: CleanupService;
|
||||
modelService: ModelService;
|
||||
cleanupCommand: CleanupCommand;
|
||||
|
||||
async onload() {
|
||||
@@ -17,8 +19,15 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
||||
|
||||
// Initialize services
|
||||
this.cleanupService = new CleanupService(this.settings.apiKey);
|
||||
this.modelService = new ModelService(this.cleanupService.anthropicClient);
|
||||
this.cleanupCommand = new CleanupCommand(this.cleanupService);
|
||||
|
||||
// Load model cache
|
||||
const data = await this.loadData() as FreewritingCleanupData | null;
|
||||
if (data?.modelCache) {
|
||||
this.modelService.loadCache(data.modelCache);
|
||||
}
|
||||
|
||||
// Register command
|
||||
this.registerCommand();
|
||||
|
||||
@@ -37,7 +46,12 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
||||
}
|
||||
|
||||
async saveSettings() {
|
||||
await this.saveData(this.settings);
|
||||
// Save settings with model cache
|
||||
const data: FreewritingCleanupData = {
|
||||
...this.settings,
|
||||
modelCache: this.modelService?.getCache() || undefined
|
||||
};
|
||||
await this.saveData(data);
|
||||
|
||||
// Update the cleanup service with new settings
|
||||
if (this.cleanupService) {
|
||||
|
||||
@@ -6,10 +6,15 @@ import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||
|
||||
export class CleanupService {
|
||||
private anthropicClient: AnthropicClient;
|
||||
private client: AnthropicClient;
|
||||
|
||||
// Expose client for ModelService
|
||||
get anthropicClient(): AnthropicClient {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
constructor(apiKey: string) {
|
||||
this.anthropicClient = new AnthropicClient(apiKey);
|
||||
this.client = new AnthropicClient(apiKey);
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
@@ -20,7 +25,7 @@ export class CleanupService {
|
||||
throw new Error('No text selected for cleanup');
|
||||
}
|
||||
|
||||
if (!this.anthropicClient.validateApiKey()) {
|
||||
if (!this.client.validateApiKey()) {
|
||||
throw new Error('API key is not configured. Please check your plugin settings.');
|
||||
}
|
||||
|
||||
@@ -32,7 +37,7 @@ export class CleanupService {
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
const { cleanedText, commentary } = await this.anthropicClient.cleanupText(
|
||||
const { cleanedText, commentary } = await this.client.cleanupText(
|
||||
text,
|
||||
settings.model,
|
||||
settings.cleanupPrompt,
|
||||
@@ -74,7 +79,7 @@ export class CleanupService {
|
||||
outputTokens?: number;
|
||||
};
|
||||
}> {
|
||||
if (!this.anthropicClient.validateApiKey()) {
|
||||
if (!this.client.validateApiKey()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'API key is not configured'
|
||||
@@ -82,7 +87,7 @@ export class CleanupService {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.anthropicClient.testConnection(settings.model);
|
||||
const result = await this.client.testConnection(settings.model);
|
||||
return result;
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -105,7 +110,7 @@ export class CleanupService {
|
||||
// MARK: - Configuration Methods
|
||||
|
||||
updateApiKey(apiKey: string): void {
|
||||
this.anthropicClient.updateApiKey(apiKey);
|
||||
this.client.updateApiKey(apiKey);
|
||||
}
|
||||
|
||||
validateSettings(settings: FreewritingCleanupSettings): {
|
||||
|
||||
@@ -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
|
||||
}));
|
||||
}
|
||||
}
|
||||
+79
-7
@@ -1,9 +1,10 @@
|
||||
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin
|
||||
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization
|
||||
|
||||
import { App, ButtonComponent, Notice, PluginSettingTab, Setting } from 'obsidian';
|
||||
import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, Setting } from 'obsidian';
|
||||
import FreewritingCleanupPlugin from './main';
|
||||
import { FreewritingCleanupSettings, ANTHROPIC_MODELS, AnthropicModel, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
||||
import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
||||
import { ModelOption } from './services/modelService';
|
||||
|
||||
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||
apiKey: '',
|
||||
@@ -16,18 +17,23 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||
|
||||
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
plugin: FreewritingCleanupPlugin;
|
||||
private modelDropdown: DropdownComponent | null = null;
|
||||
private availableModels: ModelOption[] = [];
|
||||
|
||||
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
display(): void {
|
||||
async display(): Promise<void> {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
|
||||
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
|
||||
|
||||
// Load models asynchronously
|
||||
await this.loadModels();
|
||||
|
||||
// MARK: - API Configuration
|
||||
|
||||
containerEl.createEl('h3', { text: 'API Configuration' });
|
||||
@@ -42,6 +48,11 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
this.plugin.settings.apiKey = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.cleanupService.updateApiKey(value);
|
||||
|
||||
// Trigger model refresh when API key is entered
|
||||
if (value.trim().length > 0) {
|
||||
await this.refreshModels();
|
||||
}
|
||||
}))
|
||||
.then(setting => {
|
||||
// Make it a password field
|
||||
@@ -61,13 +72,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setName('Claude Model')
|
||||
.setDesc('Which Claude model to use for text cleanup')
|
||||
.addDropdown(dropdown => {
|
||||
ANTHROPIC_MODELS.forEach(model => {
|
||||
dropdown.addOption(model, model);
|
||||
});
|
||||
this.modelDropdown = dropdown;
|
||||
this.populateModelDropdown(dropdown);
|
||||
dropdown
|
||||
.setValue(this.plugin.settings.model)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.model = value as AnthropicModel;
|
||||
this.plugin.settings.model = value;
|
||||
await this.plugin.saveSettings();
|
||||
});
|
||||
});
|
||||
@@ -191,6 +201,68 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
}));
|
||||
}
|
||||
|
||||
// MARK: - Model Loading
|
||||
|
||||
private async loadModels(): Promise<void> {
|
||||
try {
|
||||
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
||||
} catch (error) {
|
||||
console.error('Error loading models:', error);
|
||||
// Error already shown by ModelService via Notice
|
||||
}
|
||||
}
|
||||
|
||||
private populateModelDropdown(dropdown: DropdownComponent): void {
|
||||
if (this.availableModels.length === 0) {
|
||||
// No models available yet, disable dropdown
|
||||
dropdown.addOption('', 'Loading models...');
|
||||
dropdown.setDisabled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear existing options
|
||||
dropdown.selectEl.empty();
|
||||
|
||||
// Add all available models
|
||||
this.availableModels.forEach(model => {
|
||||
dropdown.addOption(model.id, model.displayName);
|
||||
});
|
||||
|
||||
dropdown.setDisabled(false);
|
||||
}
|
||||
|
||||
private async refreshModels(): Promise<void> {
|
||||
try {
|
||||
// Disable dropdown during refresh
|
||||
if (this.modelDropdown) {
|
||||
this.modelDropdown.setDisabled(true);
|
||||
this.modelDropdown.selectEl.empty();
|
||||
this.modelDropdown.addOption('', 'Refreshing models...');
|
||||
}
|
||||
|
||||
// Fetch new models
|
||||
this.availableModels = await this.plugin.modelService.refreshModels();
|
||||
|
||||
// Update dropdown
|
||||
if (this.modelDropdown) {
|
||||
this.populateModelDropdown(this.modelDropdown);
|
||||
|
||||
// Restore selected model if it still exists
|
||||
const currentModel = this.plugin.settings.model;
|
||||
const modelExists = this.availableModels.some(m => m.id === currentModel);
|
||||
if (modelExists) {
|
||||
this.modelDropdown.setValue(currentModel);
|
||||
}
|
||||
}
|
||||
|
||||
// Save updated cache
|
||||
await this.plugin.saveSettings();
|
||||
} catch (error) {
|
||||
console.error('Error refreshing models:', error);
|
||||
// Error already shown by ModelService via Notice
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
|
||||
export interface FreewritingCleanupSettings {
|
||||
apiKey: string;
|
||||
model: AnthropicModel;
|
||||
model: string; // Changed from AnthropicModel to string to support dynamic models
|
||||
cleanupPrompt: string;
|
||||
enableCommentary: boolean;
|
||||
commentaryStyle: CommentaryStyle;
|
||||
customCommentaryPrompt: string;
|
||||
}
|
||||
|
||||
export interface FreewritingCleanupData extends FreewritingCleanupSettings {
|
||||
modelCache?: ModelCache;
|
||||
}
|
||||
|
||||
export interface AnthropicMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: Array<{
|
||||
@@ -57,6 +61,25 @@ export interface CleanupResult {
|
||||
};
|
||||
}
|
||||
|
||||
export interface ModelInfo {
|
||||
id: string;
|
||||
display_name?: string;
|
||||
created_at: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface ModelsListResponse {
|
||||
data: ModelInfo[];
|
||||
first_id: string;
|
||||
has_more: boolean;
|
||||
last_id: string;
|
||||
}
|
||||
|
||||
export interface ModelCache {
|
||||
models: ModelInfo[];
|
||||
fetchedAt: number;
|
||||
}
|
||||
|
||||
export const ANTHROPIC_MODELS = [
|
||||
'claude-opus-4-1-20250805',
|
||||
'claude-opus-4-20250514',
|
||||
|
||||
Reference in new issue
Block a user