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:
Jarvis committed 2025-10-23 10:17:30 +02:00
1 parent a79dcec18f
commit 20530142e4
6 files changed
+287 -19

No files matched your search

+35 -6
View File
@@ -1,12 +1,13 @@
// ABOUTME: Anthropic API client for generating writing prompts using Claude // ABOUTME: Anthropic API client for generating writing prompts using Claude
// ABOUTME: Handles API requests, error handling, and response parsing // ABOUTME: Handles API requests, error handling, and response parsing
import { Notice, requestUrl } from 'obsidian'; import { requestUrl } from 'obsidian';
import { AnthropicRequest, AnthropicResponse, AnthropicModel } from '../types'; import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types';
export class AnthropicClient { export class AnthropicClient {
private apiKey: string; 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 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'; 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( async generatePrompts(
count: number, count: number,
model: AnthropicModel, model: string,
systemPrompt: string, systemPrompt: string,
examplePrompt: string, examplePrompt: string,
type: 'timed' | 'note' type: 'timed' | 'note'
@@ -56,6 +57,34 @@ export class AnthropicClient {
} }
} }
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)}`);
}
}
// MARK: - Private Methods // MARK: - Private Methods
private createUserMessage(count: number, examplePrompt: string): string { private createUserMessage(count: number, examplePrompt: string): string {
@@ -71,7 +100,7 @@ export class AnthropicClient {
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> { private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
try { try {
const response = await requestUrl({ const response = await requestUrl({
url: this.baseUrl, url: this.messagesUrl,
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -131,7 +160,7 @@ export class AnthropicClient {
return !!(this.apiKey && this.apiKey.trim().length > 0); return !!(this.apiKey && this.apiKey.trim().length > 0);
} }
async testApiKey(model: AnthropicModel): Promise<{ async testApiKey(model: string): Promise<{
success: boolean; success: boolean;
message: string; message: string;
details?: { details?: {
+16 -2
View File
@@ -2,15 +2,17 @@
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle // ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
import { Editor, MarkdownView, Notice, Plugin } from 'obsidian'; import { Editor, MarkdownView, Notice, Plugin } from 'obsidian';
import { FreewritingPromptsSettings } from './types'; import { FreewritingPromptsSettings, FreewritingPromptsData } from './types';
import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings'; import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings';
import { PromptGeneratorService } from './services/promptGenerator'; import { PromptGeneratorService } from './services/promptGenerator';
import { ModelService } from './services/modelService';
import { TimedPromptsCommand } from './commands/timedPrompts'; import { TimedPromptsCommand } from './commands/timedPrompts';
import { NotePromptsCommand } from './commands/notePrompts'; import { NotePromptsCommand } from './commands/notePrompts';
export default class FreewritingPromptsPlugin extends Plugin { export default class FreewritingPromptsPlugin extends Plugin {
settings: FreewritingPromptsSettings; settings: FreewritingPromptsSettings;
promptGenerator: PromptGeneratorService; promptGenerator: PromptGeneratorService;
modelService: ModelService;
timedCommand: TimedPromptsCommand; timedCommand: TimedPromptsCommand;
noteCommand: NotePromptsCommand; noteCommand: NotePromptsCommand;
@@ -19,9 +21,16 @@ export default class FreewritingPromptsPlugin extends Plugin {
// Initialize services // Initialize services
this.promptGenerator = new PromptGeneratorService(this.settings); this.promptGenerator = new PromptGeneratorService(this.settings);
this.modelService = new ModelService(this.promptGenerator.anthropicClient);
this.timedCommand = new TimedPromptsCommand(this.promptGenerator); this.timedCommand = new TimedPromptsCommand(this.promptGenerator);
this.noteCommand = new NotePromptsCommand(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 // Register commands
this.registerCommands(); this.registerCommands();
@@ -48,7 +57,12 @@ export default class FreewritingPromptsPlugin extends Plugin {
} }
async saveSettings() { 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 // Update the prompt generator with new settings
if (this.promptGenerator) { if (this.promptGenerator) {
+129
View File
@@ -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 -3
View File
@@ -3,7 +3,7 @@
import { Notice } from 'obsidian'; import { Notice } from 'obsidian';
import { AnthropicClient } from '../api/anthropicClient'; import { AnthropicClient } from '../api/anthropicClient';
import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types'; import { FreewritingPromptsSettings, GeneratedPrompt } from '../types';
export class PromptGeneratorService { export class PromptGeneratorService {
private client: AnthropicClient; private client: AnthropicClient;
@@ -54,7 +54,7 @@ export class PromptGeneratorService {
private async generatePrompts( private async generatePrompts(
count: number, count: number,
model: AnthropicModel, model: string,
systemPrompt: string, systemPrompt: string,
examplePrompt: string, examplePrompt: string,
type: 'timed' | 'note' type: 'timed' | 'note'
@@ -97,7 +97,7 @@ export class PromptGeneratorService {
private createCacheKey( private createCacheKey(
count: number, count: number,
model: AnthropicModel, model: string,
systemPrompt: string, systemPrompt: string,
examplePrompt: string, examplePrompt: string,
type: string type: string
+80 -7
View File
@@ -1,9 +1,10 @@
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin // ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization // 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 FreewritingPromptsPlugin from './main';
import { FreewritingPromptsSettings, ANTHROPIC_MODELS, AnthropicModel } from './types'; import { FreewritingPromptsSettings } from './types';
import { ModelOption } from './services/modelService';
export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
apiKey: '', apiKey: '',
@@ -18,18 +19,23 @@ export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
export class FreewritingPromptsSettingTab extends PluginSettingTab { export class FreewritingPromptsSettingTab extends PluginSettingTab {
plugin: FreewritingPromptsPlugin; plugin: FreewritingPromptsPlugin;
private modelDropdown: DropdownComponent | null = null;
private availableModels: ModelOption[] = [];
constructor(app: App, plugin: FreewritingPromptsPlugin) { constructor(app: App, plugin: FreewritingPromptsPlugin) {
super(app, plugin); super(app, plugin);
this.plugin = plugin; this.plugin = plugin;
} }
display(): void { async display(): Promise<void> {
const { containerEl } = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
containerEl.createEl('h2', { text: 'Freewriting Prompts' }); containerEl.createEl('h2', { text: 'Freewriting Prompts' });
// Load models asynchronously
await this.loadModels();
// MARK: - API Configuration // MARK: - API Configuration
containerEl.createEl('h3', { text: 'API Configuration' }); containerEl.createEl('h3', { text: 'API Configuration' });
@@ -44,6 +50,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
this.plugin.settings.apiKey = value; this.plugin.settings.apiKey = value;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
this.plugin.promptGenerator.updateApiKey(value); this.plugin.promptGenerator.updateApiKey(value);
// Trigger model refresh when API key is entered
if (value.trim().length > 0) {
await this.refreshModels();
}
})) }))
.then(setting => { .then(setting => {
// Make it a password field // Make it a password field
@@ -63,13 +74,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
.setName('Claude Model') .setName('Claude Model')
.setDesc('Which Claude model to use for generating prompts') .setDesc('Which Claude model to use for generating prompts')
.addDropdown(dropdown => { .addDropdown(dropdown => {
ANTHROPIC_MODELS.forEach(model => { this.modelDropdown = dropdown;
dropdown.addOption(model, model); this.populateModelDropdown(dropdown);
});
dropdown dropdown
.setValue(this.plugin.settings.model) .setValue(this.plugin.settings.model)
.onChange(async (value) => { .onChange(async (value) => {
this.plugin.settings.model = value as AnthropicModel; this.plugin.settings.model = value;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
}); });
}); });
@@ -183,6 +193,69 @@ export class FreewritingPromptsSettingTab 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
// 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<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: - API Testing // MARK: - API Testing
private async testApiKey(button: ButtonComponent): Promise<void> { private async testApiKey(button: ButtonComponent): Promise<void> {
+24 -1
View File
@@ -3,7 +3,7 @@
export interface FreewritingPromptsSettings { export interface FreewritingPromptsSettings {
apiKey: string; apiKey: string;
model: AnthropicModel; model: string; // Changed from AnthropicModel to string to support dynamic models
timedCount: number; timedCount: number;
delaySeconds: number; delaySeconds: number;
noteCount: number; noteCount: number;
@@ -12,6 +12,10 @@ export interface FreewritingPromptsSettings {
freewritingExamplePrompt: string; freewritingExamplePrompt: string;
} }
export interface FreewritingPromptsData extends FreewritingPromptsSettings {
modelCache?: ModelCache;
}
export interface AnthropicMessage { export interface AnthropicMessage {
role: 'user' | 'assistant' | 'system'; role: 'user' | 'assistant' | 'system';
content: string; content: string;
@@ -46,6 +50,25 @@ export interface GeneratedPrompt {
timestamp: Date; 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 = [ export const ANTHROPIC_MODELS = [
'claude-opus-4-1-20250805', 'claude-opus-4-1-20250805',
'claude-opus-4-20250514', 'claude-opus-4-20250514',