Adds dynamic Claude model fetching and management #1

Merged
AlexKucera merged 60 commits from dynamic-models into master 2025-10-31 13:42:04 +01:00
6 changed files with 287 additions and 19 deletions
Showing only changes of commit 20530142e4 - Show all commits

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'
1
@@ -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> {
coderabbitai[bot] commented 2025-10-24 13:55:13 +02:00 (Migrated from github.com)
Review

🛠️ Refactor suggestion | 🟠 Major

Add loop‑safety guard and de‑duplication for models pagination.

Defensive guards prevent runaway loops and duplicate model ids if the API misbehaves or cursors don’t advance.

Apply this diff:

-            // Fetch all pages
-            while (hasMore) {
+            // Fetch all pages with safety guards
+            const seen = new Set<string>();
+            let pageCount = 0;
+            const MAX_PAGES = 100;
+            while (hasMore) {
+                if (pageCount++ > MAX_PAGES) {
+                    throw new Error(`Models pagination exceeded ${MAX_PAGES} pages (cursor did not converge)`);
+                }
@@
-                const pageResponse = data as ModelsListResponse;
+                const pageResponse = data as ModelsListResponse;
@@
-                allModels.push(...pageResponse.data);
+                for (const m of pageResponse.data) {
+                    if (!seen.has(m.id)) {
+                        seen.add(m.id);
+                        allModels.push(m);
+                    }
+                }
@@
-                // Set up for next iteration
-                if (hasMore) {
-                    afterId = lastId;
-                }
+                // Set up for next iteration; break if cursor didn’t advance
+                if (hasMore) {
+                    if (afterId === lastId) {
+                        throw new Error('Models pagination cursor did not advance (after_id equals last_id)');
+                    }
+                    afterId = lastId;
+                }
🤖 Prompt for AI Agents
In api/anthropicClient.ts around lines 134 to 190, the pagination loop lacks
protections against runaway loops and duplicate models if the API returns the
same cursor or repeated items; add a loop-safety guard (e.g., maxIterations =
1000 and increment a counter each loop, throw if exceeded), track seen model ids
with a Set to filter out duplicates before pushing into allModels, detect lack
of cursor progress by checking if lastId is falsy or equals the previous afterId
and break to avoid infinite looping, and ensure afterId is only updated to
lastId when it advances.

✅ Addressed in commits afa725d to 3f53bb5

_🛠️ Refactor suggestion_ | _🟠 Major_ **Add loop‑safety guard and de‑duplication for models pagination.** Defensive guards prevent runaway loops and duplicate model ids if the API misbehaves or cursors don’t advance. Apply this diff: ```diff - // Fetch all pages - while (hasMore) { + // Fetch all pages with safety guards + const seen = new Set<string>(); + let pageCount = 0; + const MAX_PAGES = 100; + while (hasMore) { + if (pageCount++ > MAX_PAGES) { + throw new Error(`Models pagination exceeded ${MAX_PAGES} pages (cursor did not converge)`); + } @@ - const pageResponse = data as ModelsListResponse; + const pageResponse = data as ModelsListResponse; @@ - allModels.push(...pageResponse.data); + for (const m of pageResponse.data) { + if (!seen.has(m.id)) { + seen.add(m.id); + allModels.push(m); + } + } @@ - // Set up for next iteration - if (hasMore) { - afterId = lastId; - } + // Set up for next iteration; break if cursor didn’t advance + if (hasMore) { + if (afterId === lastId) { + throw new Error('Models pagination cursor did not advance (after_id equals last_id)'); + } + afterId = lastId; + } ``` <details> <summary>🤖 Prompt for AI Agents</summary> ``` In api/anthropicClient.ts around lines 134 to 190, the pagination loop lacks protections against runaway loops and duplicate models if the API returns the same cursor or repeated items; add a loop-safety guard (e.g., maxIterations = 1000 and increment a counter each loop, throw if exceeded), track seen model ids with a Set to filter out duplicates before pushing into allModels, detect lack of cursor progress by checking if lastId is falsy or equals the previous afterId and break to avoid infinite looping, and ensure afterId is only updated to lastId when it advances. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits afa725d to 3f53bb5
try { try {
const response = await requestUrl({ const response = await requestUrl({
url: this.baseUrl, url: this.messagesUrl,
method: 'POST', method: 'POST',
coderabbitai[bot] commented 2025-10-31 13:29:42 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Keep pagination metadata in sync after sorting

Sorting the collected models before returning them means the original first_id/last_id no longer describe the first and last entries in data. Any consumer that trusts those fields for cache validation or pagination deltas will now read inconsistent state. Recompute the IDs from the sorted array (or skip the sort) before returning.

             const sorted = allModels.slice().sort((a, b) =>
                 (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id)
             );
 
             // Return combined response with all models
             return {
-                data: sorted,
-                first_id: firstId,
-                has_more: false, // We've fetched all pages
-                last_id: lastId
+                data: sorted,
+                first_id: sorted[0]?.id ?? firstId ?? '',
+                has_more: false, // We've fetched all pages
+                last_id: sorted[sorted.length - 1]?.id ?? lastId ?? ''
             };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            const sorted = allModels.slice().sort((a, b) =>
                (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id)
            );

            // Return combined response with all models
            return {
                data: sorted,
                first_id: sorted[0]?.id ?? firstId ?? '',
                has_more: false, // We've fetched all pages
                last_id: sorted[sorted.length - 1]?.id ?? lastId ?? ''
            };
🤖 Prompt for AI Agents
In api/anthropicClient.ts around lines 221 to 231, sorting the collected models
before returning makes the previously computed first_id/last_id inconsistent
with the returned data; recompute the pagination IDs from the sorted array (or
avoid sorting) so they match the response: after creating sorted, set first_id
to sorted[0].id and last_id to sorted[sorted.length-1].id (guard for empty array
and use null/undefined as appropriate), keep has_more as before, and return
those recomputed IDs so consumers see consistent pagination metadata.

✅ Addressed in commits 5bf804b to 4cb2308

_⚠️ Potential issue_ | _🟠 Major_ **Keep pagination metadata in sync after sorting** Sorting the collected models before returning them means the original `first_id`/`last_id` no longer describe the first and last entries in `data`. Any consumer that trusts those fields for cache validation or pagination deltas will now read inconsistent state. Recompute the IDs from the sorted array (or skip the sort) before returning. ```diff const sorted = allModels.slice().sort((a, b) => (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id) ); // Return combined response with all models return { - data: sorted, - first_id: firstId, - has_more: false, // We've fetched all pages - last_id: lastId + data: sorted, + first_id: sorted[0]?.id ?? firstId ?? '', + has_more: false, // We've fetched all pages + last_id: sorted[sorted.length - 1]?.id ?? lastId ?? '' }; ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const sorted = allModels.slice().sort((a, b) => (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id) ); // Return combined response with all models return { data: sorted, first_id: sorted[0]?.id ?? firstId ?? '', has_more: false, // We've fetched all pages last_id: sorted[sorted.length - 1]?.id ?? lastId ?? '' }; ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In api/anthropicClient.ts around lines 221 to 231, sorting the collected models before returning makes the previously computed first_id/last_id inconsistent with the returned data; recompute the pagination IDs from the sorted array (or avoid sorting) so they match the response: after creating sorted, set first_id to sorted[0].id and last_id to sorted[sorted.length-1].id (guard for empty array and use null/undefined as appropriate), keep has_more as before, and return those recomputed IDs so consumers see consistent pagination metadata. ``` </details> <!-- fingerprinting:phantom:medusa:sabertoothed --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 5bf804b to 4cb2308
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?: {
1
+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' });
1
@@ -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',