diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 9027771..b8bbaad 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -1,12 +1,13 @@ // ABOUTME: Anthropic API client for generating writing prompts using Claude // ABOUTME: Handles API requests, error handling, and response parsing -import { Notice, requestUrl } from 'obsidian'; -import { AnthropicRequest, AnthropicResponse, AnthropicModel } from '../types'; +import { requestUrl } from 'obsidian'; +import { AnthropicRequest, AnthropicResponse, 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 SYSTEM_PROMPT_SUFFIX = '\n\nIMPORTANT OUTPUT REQUIREMENTS:\n- Return ONLY the numbered writing prompts, nothing else\n- Do not include any explanations, questions, or additional commentary\n- Do not ask if the user wants more prompts or different styles\n- Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)'; private readonly TIMED_PROMPT_MODIFIER = '\n\nFOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT:\n- Each prompt should be answerable in 1-5 words or a single sentence\n- Focus on immediate, concrete observations or quick thoughts\n- Avoid complex scenarios or deep philosophical questions\n- Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft"\n- Keep prompts simple, immediate, and concrete'; @@ -19,7 +20,7 @@ export class AnthropicClient { async generatePrompts( count: number, - model: AnthropicModel, + model: string, systemPrompt: string, examplePrompt: string, type: 'timed' | 'note' @@ -56,6 +57,34 @@ export class AnthropicClient { } } + async fetchModels(): Promise { + 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)}`); + } + } + // MARK: - Private Methods private createUserMessage(count: number, examplePrompt: string): string { @@ -71,7 +100,7 @@ export class AnthropicClient { private async makeRequest(request: AnthropicRequest): Promise { try { const response = await requestUrl({ - url: this.baseUrl, + url: this.messagesUrl, method: 'POST', headers: { 'Content-Type': 'application/json', @@ -131,7 +160,7 @@ export class AnthropicClient { return !!(this.apiKey && this.apiKey.trim().length > 0); } - async testApiKey(model: AnthropicModel): Promise<{ + async testApiKey(model: string): Promise<{ success: boolean; message: string; details?: { diff --git a/main.ts b/main.ts index 1ec931b..7a9969e 100644 --- a/main.ts +++ b/main.ts @@ -2,15 +2,17 @@ // ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle import { Editor, MarkdownView, Notice, Plugin } from 'obsidian'; -import { FreewritingPromptsSettings } from './types'; +import { FreewritingPromptsSettings, FreewritingPromptsData } from './types'; import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings'; import { PromptGeneratorService } from './services/promptGenerator'; +import { ModelService } from './services/modelService'; import { TimedPromptsCommand } from './commands/timedPrompts'; import { NotePromptsCommand } from './commands/notePrompts'; export default class FreewritingPromptsPlugin extends Plugin { settings: FreewritingPromptsSettings; promptGenerator: PromptGeneratorService; + modelService: ModelService; timedCommand: TimedPromptsCommand; noteCommand: NotePromptsCommand; @@ -19,9 +21,16 @@ export default class FreewritingPromptsPlugin extends Plugin { // Initialize services this.promptGenerator = new PromptGeneratorService(this.settings); + this.modelService = new ModelService(this.promptGenerator.anthropicClient); this.timedCommand = new TimedPromptsCommand(this.promptGenerator); this.noteCommand = new NotePromptsCommand(this.promptGenerator); + // Load model cache + const data = await this.loadData() as FreewritingPromptsData | null; + if (data?.modelCache) { + this.modelService.loadCache(data.modelCache); + } + // Register commands this.registerCommands(); @@ -48,7 +57,12 @@ export default class FreewritingPromptsPlugin extends Plugin { } async saveSettings() { - await this.saveData(this.settings); + // Save settings with model cache + const data: FreewritingPromptsData = { + ...this.settings, + modelCache: this.modelService?.getCache() || undefined + }; + await this.saveData(data); // Update the prompt generator with new settings if (this.promptGenerator) { diff --git a/services/modelService.ts b/services/modelService.ts new file mode 100644 index 0000000..44ebf63 --- /dev/null +++ b/services/modelService.ts @@ -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 { + // 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 { + 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 + })); + } +} diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index fc7f792..5b3f3fd 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -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 diff --git a/settings.ts b/settings.ts index bfb1ef3..803f532 100644 --- a/settings.ts +++ b/settings.ts @@ -1,9 +1,10 @@ // ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts 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 FreewritingPromptsPlugin from './main'; -import { FreewritingPromptsSettings, ANTHROPIC_MODELS, AnthropicModel } from './types'; +import { FreewritingPromptsSettings } from './types'; +import { ModelOption } from './services/modelService'; export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { apiKey: '', @@ -18,18 +19,23 @@ export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { export class FreewritingPromptsSettingTab extends PluginSettingTab { plugin: FreewritingPromptsPlugin; + private modelDropdown: DropdownComponent | null = null; + private availableModels: ModelOption[] = []; constructor(app: App, plugin: FreewritingPromptsPlugin) { super(app, plugin); this.plugin = plugin; } - display(): void { + async display(): Promise { const { containerEl } = this; containerEl.empty(); containerEl.createEl('h2', { text: 'Freewriting Prompts' }); + // Load models asynchronously + await this.loadModels(); + // MARK: - API Configuration containerEl.createEl('h3', { text: 'API Configuration' }); @@ -44,6 +50,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); this.plugin.promptGenerator.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 @@ -63,13 +74,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .setName('Claude Model') .setDesc('Which Claude model to use for generating prompts') .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(); }); }); @@ -183,6 +193,69 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { })); } + // MARK: - Model Loading + + private async loadModels(): Promise { + try { + this.availableModels = await this.plugin.modelService.getAvailableModels(); + } catch (error) { + console.error('Error loading models:', error); + // Error already shown by ModelService via Notice + // availableModels will be empty array, dropdown will be disabled + } + } + + 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 { + 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: - API Testing private async testApiKey(button: ButtonComponent): Promise { diff --git a/types.ts b/types.ts index 8319552..b83c723 100644 --- a/types.ts +++ b/types.ts @@ -3,7 +3,7 @@ export interface FreewritingPromptsSettings { apiKey: string; - model: AnthropicModel; + model: string; // Changed from AnthropicModel to string to support dynamic models timedCount: number; delaySeconds: number; noteCount: number; @@ -12,6 +12,10 @@ export interface FreewritingPromptsSettings { freewritingExamplePrompt: string; } +export interface FreewritingPromptsData extends FreewritingPromptsSettings { + modelCache?: ModelCache; +} + export interface AnthropicMessage { role: 'user' | 'assistant' | 'system'; content: string; @@ -46,6 +50,25 @@ export interface GeneratedPrompt { timestamp: Date; } +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',