Merge pull request #2 from AlexKucera/dynamic-models
feat: add dynamic model fetching from Anthropic API
This commit was merged in pull request #2.
This commit is contained in:
7 files changed
+412
-65
No files matched your search
@@ -75,7 +75,7 @@ Settings use the `FreewritingCleanupSettings` interface with modular defaults:
|
|||||||
```typescript
|
```typescript
|
||||||
interface FreewritingCleanupSettings {
|
interface FreewritingCleanupSettings {
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
model: AnthropicModel;
|
model: string; // Dynamic model ID fetched from Anthropic API
|
||||||
cleanupPrompt: string;
|
cleanupPrompt: string;
|
||||||
enableCommentary: boolean;
|
enableCommentary: boolean;
|
||||||
commentaryStyle: CommentaryStyle;
|
commentaryStyle: CommentaryStyle;
|
||||||
|
|||||||
+44
-9
@@ -2,11 +2,12 @@
|
|||||||
// ABOUTME: Handles API requests, error handling, retry logic, and response parsing
|
// ABOUTME: Handles API requests, error handling, retry logic, and response parsing
|
||||||
|
|
||||||
import { requestUrl } from 'obsidian';
|
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 {
|
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 MAX_RETRIES = 3;
|
private readonly MAX_RETRIES = 3;
|
||||||
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
||||||
|
|
||||||
@@ -18,12 +19,12 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
async cleanupText(
|
async cleanupText(
|
||||||
text: string,
|
text: string,
|
||||||
model: AnthropicModel,
|
model: string,
|
||||||
cleanupPrompt: string,
|
cleanupPrompt: string,
|
||||||
enableCommentary = false,
|
enableCommentary = false,
|
||||||
commentaryStyle: CommentaryStyle = 'constructive',
|
commentaryStyle: CommentaryStyle = 'constructive',
|
||||||
customCommentaryPrompt?: string
|
customCommentaryPrompt?: string
|
||||||
): Promise<{ cleanedText: string; commentary?: string }> {
|
): Promise<{ cleanedText: string; commentary?: string; usage?: { input_tokens: number; output_tokens: number } }> {
|
||||||
if (!this.apiKey) {
|
if (!this.apiKey) {
|
||||||
throw new Error('API key is required');
|
throw new Error('API key is required');
|
||||||
}
|
}
|
||||||
@@ -74,10 +75,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
};
|
};
|
||||||
|
|
||||||
const response = await this.makeRequestWithRetry(request);
|
const response = await this.makeRequestWithRetry(request);
|
||||||
return this.parseStructuredResponse(response, enableCommentary);
|
const responseText = this.extractTextFromResponse(response);
|
||||||
|
const parsed = this.parseStructuredResponse(responseText, enableCommentary);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...parsed,
|
||||||
|
usage: response.usage
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async testConnection(model: AnthropicModel): Promise<{
|
async testConnection(model: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
details?: {
|
details?: {
|
||||||
@@ -129,13 +136,13 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
private async makeRequestWithRetry(request: AnthropicRequest): Promise<string> {
|
private async makeRequestWithRetry(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||||
let lastError: Error = new Error('No attempts made');
|
let lastError: Error = new Error('No attempts made');
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) {
|
for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) {
|
||||||
try {
|
try {
|
||||||
const response = await this.makeRequest(request);
|
const response = await this.makeRequest(request);
|
||||||
return this.extractTextFromResponse(response);
|
return response;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error instanceof Error ? error : new Error('Unknown error');
|
lastError = error instanceof Error ? error : new Error('Unknown error');
|
||||||
|
|
||||||
@@ -174,10 +181,38 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
return { cleanedText, commentary };
|
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> {
|
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',
|
||||||
|
|||||||
@@ -2,23 +2,32 @@
|
|||||||
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
||||||
|
|
||||||
import { Editor, MarkdownView, Plugin } from 'obsidian';
|
import { Editor, MarkdownView, Plugin } from 'obsidian';
|
||||||
import { FreewritingCleanupSettings } from './types';
|
import { FreewritingCleanupSettings, FreewritingCleanupData } from './types';
|
||||||
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
|
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
|
||||||
import { CleanupService } from './services/cleanupService';
|
import { CleanupService } from './services/cleanupService';
|
||||||
|
import { ModelService } from './services/modelService';
|
||||||
import { CleanupCommand } from './commands/cleanupCommand';
|
import { CleanupCommand } from './commands/cleanupCommand';
|
||||||
|
|
||||||
export default class FreewritingCleanupPlugin extends Plugin {
|
export default class FreewritingCleanupPlugin extends Plugin {
|
||||||
settings: FreewritingCleanupSettings;
|
settings: FreewritingCleanupSettings;
|
||||||
cleanupService: CleanupService;
|
cleanupService: CleanupService;
|
||||||
|
modelService: ModelService;
|
||||||
cleanupCommand: CleanupCommand;
|
cleanupCommand: CleanupCommand;
|
||||||
|
|
||||||
async onload() {
|
async onload() {
|
||||||
await this.loadSettings();
|
// Load settings and reuse the data to avoid double loadData() call
|
||||||
|
const data = await this.loadSettings();
|
||||||
|
|
||||||
// Initialize services
|
// Initialize services
|
||||||
this.cleanupService = new CleanupService(this.settings.apiKey);
|
this.cleanupService = new CleanupService(this.settings.apiKey);
|
||||||
|
this.modelService = new ModelService(this.cleanupService.anthropicClient);
|
||||||
this.cleanupCommand = new CleanupCommand(this.cleanupService);
|
this.cleanupCommand = new CleanupCommand(this.cleanupService);
|
||||||
|
|
||||||
|
// Load model cache from already-loaded data
|
||||||
|
if (data?.modelCache) {
|
||||||
|
this.modelService.loadCache(data.modelCache);
|
||||||
|
}
|
||||||
|
|
||||||
// Register command
|
// Register command
|
||||||
this.registerCommand();
|
this.registerCommand();
|
||||||
|
|
||||||
@@ -32,12 +41,19 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Settings Management
|
// MARK: - Settings Management
|
||||||
|
|
||||||
async loadSettings() {
|
async loadSettings(): Promise<FreewritingCleanupData | null> {
|
||||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
const data = await this.loadData() as FreewritingCleanupData | null;
|
||||||
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveSettings() {
|
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
|
// Update the cleanup service with new settings
|
||||||
if (this.cleanupService) {
|
if (this.cleanupService) {
|
||||||
|
|||||||
@@ -6,10 +6,15 @@ import { AnthropicClient } from '../api/anthropicClient';
|
|||||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||||
|
|
||||||
export class CleanupService {
|
export class CleanupService {
|
||||||
private anthropicClient: AnthropicClient;
|
private client: AnthropicClient;
|
||||||
|
|
||||||
|
// Expose client for ModelService
|
||||||
|
get anthropicClient(): AnthropicClient {
|
||||||
|
return this.client;
|
||||||
|
}
|
||||||
|
|
||||||
constructor(apiKey: string) {
|
constructor(apiKey: string) {
|
||||||
this.anthropicClient = new AnthropicClient(apiKey);
|
this.client = new AnthropicClient(apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
@@ -20,7 +25,7 @@ export class CleanupService {
|
|||||||
throw new Error('No text selected for cleanup');
|
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.');
|
throw new Error('API key is not configured. Please check your plugin settings.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,7 +37,7 @@ export class CleanupService {
|
|||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { cleanedText, commentary } = await this.anthropicClient.cleanupText(
|
const { cleanedText, commentary, usage } = await this.client.cleanupText(
|
||||||
text,
|
text,
|
||||||
settings.model,
|
settings.model,
|
||||||
settings.cleanupPrompt,
|
settings.cleanupPrompt,
|
||||||
@@ -48,8 +53,8 @@ export class CleanupService {
|
|||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
model: settings.model,
|
model: settings.model,
|
||||||
tokensUsed: {
|
tokensUsed: {
|
||||||
input: 0, // We don't have access to this from the response
|
input: usage?.input_tokens ?? 0,
|
||||||
output: 0 // We don't have access to this from the response
|
output: usage?.output_tokens ?? 0
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -74,7 +79,7 @@ export class CleanupService {
|
|||||||
outputTokens?: number;
|
outputTokens?: number;
|
||||||
};
|
};
|
||||||
}> {
|
}> {
|
||||||
if (!this.anthropicClient.validateApiKey()) {
|
if (!this.client.validateApiKey()) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'API key is not configured'
|
message: 'API key is not configured'
|
||||||
@@ -82,7 +87,7 @@ export class CleanupService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await this.anthropicClient.testConnection(settings.model);
|
const result = await this.client.testConnection(settings.model);
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return {
|
return {
|
||||||
@@ -105,7 +110,7 @@ export class CleanupService {
|
|||||||
// MARK: - Configuration Methods
|
// MARK: - Configuration Methods
|
||||||
|
|
||||||
updateApiKey(apiKey: string): void {
|
updateApiKey(apiKey: string): void {
|
||||||
this.anthropicClient.updateApiKey(apiKey);
|
this.client.updateApiKey(apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
validateSettings(settings: FreewritingCleanupSettings): {
|
validateSettings(settings: FreewritingCleanupSettings): {
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
// 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 or API key is missing
|
||||||
|
*/
|
||||||
|
async getAvailableModels(): Promise<ModelOption[]> {
|
||||||
|
// Check if we have a valid cache
|
||||||
|
if (this.isCacheValid() && this.modelCache) {
|
||||||
|
return this.formatModels(this.modelCache.models);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no API key, immediately return and cache fallback (no Notice needed)
|
||||||
|
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 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.');
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force refresh the model list from API
|
||||||
|
* 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);
|
||||||
|
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.');
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get fallback model options (public API for UI components)
|
||||||
|
* Returns hardcoded model list as ModelOption array
|
||||||
|
*/
|
||||||
|
getFallbackOptions(): ModelOption[] {
|
||||||
|
return this.getFallbackModels();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 from API for user-friendly model names
|
||||||
|
* Sorted by displayName for consistent UX across cache/API ordering
|
||||||
|
*/
|
||||||
|
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||||
|
return models
|
||||||
|
.map(model => ({
|
||||||
|
id: model.id,
|
||||||
|
displayName: model.display_name
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.displayName.localeCompare(b.displayName));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get fallback models from hardcoded list
|
||||||
|
*/
|
||||||
|
private getFallbackModels(): ModelOption[] {
|
||||||
|
return ANTHROPIC_MODELS.map(id => ({
|
||||||
|
id,
|
||||||
|
displayName: id
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
+123
-36
@@ -1,9 +1,10 @@
|
|||||||
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin
|
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup 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, Modal, Notice, PluginSettingTab, Setting } from 'obsidian';
|
||||||
import FreewritingCleanupPlugin from './main';
|
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 = {
|
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
@@ -16,6 +17,8 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
|||||||
|
|
||||||
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||||
plugin: FreewritingCleanupPlugin;
|
plugin: FreewritingCleanupPlugin;
|
||||||
|
private modelDropdown: DropdownComponent | null = null;
|
||||||
|
private availableModels: ModelOption[] = [];
|
||||||
|
|
||||||
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
||||||
super(app, plugin);
|
super(app, plugin);
|
||||||
@@ -28,6 +31,18 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
|
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
|
||||||
|
|
||||||
|
// Load models asynchronously in the background
|
||||||
|
this.loadModels()
|
||||||
|
.then(() => {
|
||||||
|
// Update dropdown UI when models are loaded
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.populateModelDropdown(this.modelDropdown);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Error loading models in background:', error);
|
||||||
|
});
|
||||||
|
|
||||||
// MARK: - API Configuration
|
// MARK: - API Configuration
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'API Configuration' });
|
containerEl.createEl('h3', { text: 'API Configuration' });
|
||||||
@@ -42,6 +57,16 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
this.plugin.settings.apiKey = value;
|
this.plugin.settings.apiKey = value;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
this.plugin.cleanupService.updateApiKey(value);
|
this.plugin.cleanupService.updateApiKey(value);
|
||||||
|
|
||||||
|
// Refresh when key is entered; revert to fallback when cleared
|
||||||
|
const hasKey = value.trim().length > 0;
|
||||||
|
if (hasKey) {
|
||||||
|
await this.refreshModels();
|
||||||
|
} else if (this.modelDropdown) {
|
||||||
|
// Show fallback immediately when key is cleared
|
||||||
|
this.availableModels = this.plugin.modelService.getFallbackOptions();
|
||||||
|
this.populateModelDropdown(this.modelDropdown);
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
// Make it a password field
|
// Make it a password field
|
||||||
@@ -61,13 +86,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
.setName('Claude Model')
|
.setName('Claude Model')
|
||||||
.setDesc('Which Claude model to use for text cleanup')
|
.setDesc('Which Claude model to use for text cleanup')
|
||||||
.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();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -191,6 +215,75 @@ 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, otherwise use first available
|
||||||
|
const currentModel = this.plugin.settings.model;
|
||||||
|
const modelExists = this.availableModels.some(m => m.id === currentModel);
|
||||||
|
|
||||||
|
if (modelExists) {
|
||||||
|
this.modelDropdown.setValue(currentModel);
|
||||||
|
} else if (this.availableModels.length > 0) {
|
||||||
|
// Model no longer available - update to first available model
|
||||||
|
const newModel = this.availableModels[0].id;
|
||||||
|
this.plugin.settings.model = newModel;
|
||||||
|
this.modelDropdown.setValue(newModel);
|
||||||
|
console.log(`Model '${currentModel}' no longer available, switched to '${newModel}'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save updated cache and any model changes
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error refreshing models:', error);
|
||||||
|
// Error already shown by ModelService via Notice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
private async testApiKey(button: ButtonComponent): Promise<void> {
|
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||||
@@ -248,53 +341,47 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simple confirmation modal
|
// Confirmation modal using Obsidian's Modal class for consistent styling and accessibility
|
||||||
class ConfirmModal {
|
class ConfirmModal extends Modal {
|
||||||
private app: App;
|
|
||||||
private title: string;
|
private title: string;
|
||||||
private message: string;
|
private message: string;
|
||||||
private callback: (result: boolean) => void;
|
private callback: (result: boolean) => void;
|
||||||
private modalEl: HTMLElement | null = null;
|
|
||||||
|
|
||||||
constructor(app: App, title: string, message: string, callback: (result: boolean) => void) {
|
constructor(app: App, title: string, message: string, callback: (result: boolean) => void) {
|
||||||
this.app = app;
|
super(app);
|
||||||
this.title = title;
|
this.title = title;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
}
|
}
|
||||||
|
|
||||||
open(): void {
|
onOpen(): void {
|
||||||
// Create modal backdrop
|
const { contentEl } = this;
|
||||||
this.modalEl = document.createElement('div');
|
|
||||||
this.modalEl.className = 'modal-container mod-dim';
|
|
||||||
|
|
||||||
// Create modal content
|
contentEl.createEl('h2', { text: this.title });
|
||||||
const modal = this.modalEl.createDiv('modal');
|
contentEl.createEl('p', { text: this.message });
|
||||||
const header = modal.createDiv('modal-header');
|
|
||||||
header.createEl('h3', { text: this.title });
|
|
||||||
|
|
||||||
const content = modal.createDiv('modal-content');
|
const buttonContainer = contentEl.createDiv({ cls: 'modal-button-container' });
|
||||||
content.createEl('p', { text: this.message });
|
|
||||||
|
|
||||||
const buttons = modal.createDiv('modal-button-container');
|
const cancelButton = buttonContainer.createEl('button', { text: 'Cancel' });
|
||||||
|
cancelButton.addEventListener('click', () => {
|
||||||
|
this.close();
|
||||||
|
this.callback(false);
|
||||||
|
});
|
||||||
|
|
||||||
const cancelButton = buttons.createEl('button', { text: 'Cancel' });
|
const confirmButton = buttonContainer.createEl('button', {
|
||||||
cancelButton.onclick = () => this.close(false);
|
text: 'Confirm',
|
||||||
|
cls: 'mod-warning'
|
||||||
|
});
|
||||||
|
confirmButton.addEventListener('click', () => {
|
||||||
|
this.close();
|
||||||
|
this.callback(true);
|
||||||
|
});
|
||||||
|
|
||||||
const confirmButton = buttons.createEl('button', { text: 'Confirm', cls: 'mod-warning' });
|
|
||||||
confirmButton.onclick = () => this.close(true);
|
|
||||||
|
|
||||||
if (this.modalEl) {
|
|
||||||
document.body.appendChild(this.modalEl);
|
|
||||||
}
|
|
||||||
confirmButton.focus();
|
confirmButton.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
private close(result: boolean): void {
|
onClose(): void {
|
||||||
if (this.modalEl && this.modalEl.parentNode) {
|
const { contentEl } = this;
|
||||||
this.modalEl.parentNode.removeChild(this.modalEl);
|
contentEl.empty();
|
||||||
}
|
|
||||||
this.modalEl = null;
|
|
||||||
this.callback(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,17 @@
|
|||||||
|
|
||||||
export interface FreewritingCleanupSettings {
|
export interface FreewritingCleanupSettings {
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
model: AnthropicModel;
|
model: string; // Changed from AnthropicModel to string to support dynamic models
|
||||||
cleanupPrompt: string;
|
cleanupPrompt: string;
|
||||||
enableCommentary: boolean;
|
enableCommentary: boolean;
|
||||||
commentaryStyle: CommentaryStyle;
|
commentaryStyle: CommentaryStyle;
|
||||||
customCommentaryPrompt: string;
|
customCommentaryPrompt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface FreewritingCleanupData extends FreewritingCleanupSettings {
|
||||||
|
modelCache?: ModelCache;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AnthropicMessage {
|
export interface AnthropicMessage {
|
||||||
role: 'user' | 'assistant' | 'system';
|
role: 'user' | 'assistant' | 'system';
|
||||||
content: Array<{
|
content: Array<{
|
||||||
@@ -57,16 +61,34 @@ export interface CleanupResult {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ANTHROPIC_MODELS = [
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback model list used when API key is not set or API fetch fails
|
||||||
|
export const ANTHROPIC_MODELS: readonly string[] = [
|
||||||
'claude-opus-4-1-20250805',
|
'claude-opus-4-1-20250805',
|
||||||
'claude-opus-4-20250514',
|
'claude-opus-4-20250514',
|
||||||
'claude-sonnet-4-20250514',
|
'claude-sonnet-4-20250514',
|
||||||
'claude-3-7-sonnet-latest',
|
'claude-3-7-sonnet-latest',
|
||||||
'claude-3-5-haiku-latest',
|
'claude-3-5-haiku-latest',
|
||||||
'claude-3-haiku-20240307'
|
'claude-3-haiku-20240307'
|
||||||
] as const;
|
];
|
||||||
|
|
||||||
export type AnthropicModel = typeof ANTHROPIC_MODELS[number];
|
|
||||||
|
|
||||||
// Commentary style options
|
// Commentary style options
|
||||||
export const COMMENTARY_STYLES = [
|
export const COMMENTARY_STYLES = [
|
||||||
|
|||||||
Reference in new issue
Block a user