Added DocStrings

This commit is contained in:
AlexKucera committed 2025-10-24 13:09:10 +02:00
1 parent 03d2b1c93d
commit e96ef65200
8 files changed
+797 -17

No files matched your search

+85 -13
View File
@@ -5,16 +5,41 @@ import { Notice } from 'obsidian';
import { AnthropicClient } from '../api/anthropicClient';
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
/**
* Simplified model representation for UI display purposes.
* Used to populate dropdown menus with user-friendly model names.
*/
export interface ModelOption {
/** Model identifier (e.g., 'claude-3-5-haiku-latest') */
id: string;
/** Human-readable display name for the UI */
displayName: string;
}
/**
* Service responsible for managing the list of available Claude models.
*
* Key responsibilities:
* - Fetches current model list from Anthropic API
* - Caches results for 24 hours to minimize API calls
* - Provides fallback to hardcoded model list when API is unavailable
* - Handles graceful degradation when API key is not configured
*
* The 24-hour cache TTL balances freshness with API efficiency - models don't
* change frequently enough to warrant more aggressive polling, but we want
* users to see new models within a reasonable timeframe.
*/
export class ModelService {
private anthropicClient: AnthropicClient;
private modelCache: ModelCache | null = null;
/** Cache time-to-live in milliseconds (24 hours) */
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
/**
* Creates a new model service instance.
*
* @param anthropicClient - Client for making API requests to Anthropic
*/
constructor(anthropicClient: AnthropicClient) {
this.anthropicClient = anthropicClient;
}
@@ -22,9 +47,17 @@ export class ModelService {
// 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
* Retrieves available Claude models with intelligent caching and fallback.
*
* This method implements a three-tier strategy:
* 1. Return cached models if valid (within 24-hour TTL)
* 2. Fetch fresh models from API if cache is stale or empty
* 3. Fall back to hardcoded ANTHROPIC_MODELS if API fails
*
* If no API key is configured, quietly returns fallback without showing errors,
* since this is expected during initial plugin setup.
*
* @returns Array of model options formatted for UI display
*/
async getAvailableModels(): Promise<ModelOption[]> {
// Check if we have a valid cache
@@ -50,8 +83,13 @@ export class ModelService {
}
/**
* Force refresh the model list from API
* Used when user changes API key
* Forces a refresh of the model list from the API, bypassing cache.
*
* This is called when the user enters a new API key in settings, ensuring
* they immediately see the correct models available for their account.
* Falls back to hardcoded models if the API request fails.
*
* @returns Array of current available models
*/
async refreshModels(): Promise<ModelOption[]> {
// If no API key, quietly return fallback
@@ -71,21 +109,33 @@ export class ModelService {
}
/**
* Load cache from plugin data
* Loads cached model data from plugin persistent storage.
*
* Called during plugin initialization to restore the previous session's
* model list, avoiding an immediate API call on every startup.
*
* @param cache - Previously saved cache data, or null if none exists
*/
loadCache(cache: ModelCache | null): void {
this.modelCache = cache;
}
/**
* Get current cache for saving to plugin data
* Retrieves current cache for persistence to disk.
*
* Called during plugin save operations to preserve the model cache
* across Obsidian restarts, maintaining the 24-hour TTL.
*
* @returns Current cache state, or null if no cache exists
*/
getCache(): ModelCache | null {
return this.modelCache;
}
/**
* Clear the cache (for testing or manual refresh)
* Clears the cached model list, forcing a fresh fetch on next access.
*
* Useful for testing or troubleshooting cache-related issues.
*/
clearCache(): void {
this.modelCache = null;
@@ -94,7 +144,13 @@ export class ModelService {
// MARK: - Private Methods
/**
* Check if the current cache is still valid (within TTL)
* Checks whether the current cache is still valid based on TTL.
*
* Cache is considered valid if it exists and was fetched less than
* 24 hours ago. This prevents excessive API calls while ensuring
* reasonable freshness of model data.
*
* @returns true if cache exists and is within TTL, false otherwise
*/
private isCacheValid(): boolean {
if (!this.modelCache) {
@@ -107,7 +163,11 @@ export class ModelService {
}
/**
* Update cache with new model data
* Updates the cache with freshly fetched model data.
*
* Sets the fetchedAt timestamp to now, starting the 24-hour TTL countdown.
*
* @param models - Array of model information from the API
*/
private updateCache(models: ModelInfo[]): void {
this.modelCache = {
@@ -117,8 +177,14 @@ export class ModelService {
}
/**
* Format ModelInfo array to ModelOption array for dropdown
* Uses display_name if available, otherwise falls back to id
* Transforms API model data into UI-friendly format.
*
* Prefers display_name when available for better UX, falls back to
* model ID if display_name is missing. Results are sorted alphabetically
* for easier scanning in the dropdown.
*
* @param models - Raw model info from API
* @returns Formatted options ready for dropdown display
*/
private formatModels(models: ModelInfo[]): ModelOption[] {
return models.map(model => ({
@@ -128,7 +194,13 @@ export class ModelService {
}
/**
* Get fallback models from hardcoded list
* Provides fallback model list when API is unavailable.
*
* Uses the hardcoded ANTHROPIC_MODELS constant which should be periodically
* updated to include newly released models. This ensures the plugin remains
* functional even during API outages or when no API key is configured.
*
* @returns Array of fallback model options
*/
private getFallbackModels(): ModelOption[] {
return ANTHROPIC_MODELS.map(id => ({
+125 -1
View File
@@ -5,22 +5,58 @@ import { Notice } from 'obsidian';
import { AnthropicClient } from '../api/anthropicClient';
import { FreewritingPromptsSettings, GeneratedPrompt } from '../types';
/**
* Service that coordinates prompt generation between commands and the API client.
*
* This service layer provides:
* - High-level methods for different prompt types (timed vs note)
* - In-memory caching with 10-minute TTL to avoid redundant API calls
* - Settings validation before attempting generation
* - User feedback via Obsidian notices
* - Error handling and propagation
*
* The 10-minute cache is relatively short because:
* 1. Users expect fresh prompts when they explicitly request them
* 2. The cache prevents rapid-fire duplicate requests during a single session
* 3. Memory usage is minimal (cache is just strings with timestamps)
*/
export class PromptGeneratorService {
private client: AnthropicClient;
/** In-memory cache mapping request parameters to generated prompts */
private cache: Map<string, GeneratedPrompt[]> = new Map();
/** Cache expiry time in milliseconds (10 minutes) */
private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes
// Expose client for API testing in settings
/**
* Exposes the underlying API client for direct access.
* Used by settings tab to test API key connectivity.
*/
get anthropicClient(): AnthropicClient {
return this.client;
}
/**
* Creates a new prompt generator service.
*
* @param settings - Plugin settings containing API key and configuration
*/
constructor(settings: FreewritingPromptsSettings) {
this.client = new AnthropicClient(settings.apiKey);
}
// MARK: - Public Methods
/**
* Generates prompts optimized for timed notifications.
*
* These prompts are short and answerable quickly since they appear as
* timed notifications during freewriting sessions. Uses the timedExamplePrompt
* to guide style and applies special system instructions for brevity.
*
* @param settings - Current plugin settings
* @returns Array of short, focused prompts for rapid response
* @throws Error if API key is invalid or generation fails
*/
async generateTimedPrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
return this.generatePrompts(
settings.timedCount,
@@ -31,6 +67,17 @@ export class PromptGeneratorService {
);
}
/**
* Generates prompts for insertion into notes.
*
* These prompts can be more elaborate and creative since they're inserted
* as text into a note rather than appearing as brief notifications. Uses
* the freewritingExamplePrompt to guide style.
*
* @param settings - Current plugin settings
* @returns Array of creative prompts suitable for note insertion
* @throws Error if API key is invalid or generation fails
*/
async generateNotePrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
return this.generatePrompts(
settings.noteCount,
@@ -41,17 +88,52 @@ export class PromptGeneratorService {
);
}
/**
* Updates the API key for the underlying client.
*
* Called when the user changes their API key in settings. Clears the cache
* since previous cached prompts may have been generated with a different key.
*
* @param apiKey - New Anthropic API key
*/
updateApiKey(apiKey: string): void {
this.client.updateApiKey(apiKey);
this.clearCache(); // Clear cache when API key changes
}
/**
* Clears all cached prompts.
*
* Forces fresh generation on next request. Useful when users want to
* ensure they're getting completely new prompts rather than cached ones.
*/
clearCache(): void {
this.cache.clear();
}
// MARK: - Private Methods
/**
* Core prompt generation method with caching logic.
*
* Implements the full generation flow:
* 1. Validates API key configuration
* 2. Checks cache for matching prompts within TTL
* 3. Calls API if cache miss or expired
* 4. Stores results in cache with timestamp
* 5. Shows user feedback via notices
*
* The cache key is derived from all generation parameters to ensure
* cached prompts match the current settings exactly.
*
* @param count - Number of prompts to generate
* @param model - Claude model ID to use
* @param systemPrompt - Base system instructions
* @param examplePrompt - Example to guide style
* @param type - Prompt type ('timed' or 'note') affecting format and length
* @returns Array of generated prompt strings
* @throws Error if API key is missing or API call fails
*/
private async generatePrompts(
count: number,
model: string,
@@ -95,6 +177,20 @@ export class PromptGeneratorService {
}
}
/**
* Creates a unique cache key from generation parameters.
*
* The key is a JSON string containing all parameters that affect output.
* This ensures we only serve cached prompts when ALL settings match,
* preventing incorrect reuse when the user changes any configuration.
*
* @param count - Number of prompts
* @param model - Model ID
* @param systemPrompt - System instructions
* @param examplePrompt - Example prompt
* @param type - Prompt type
* @returns JSON string uniquely identifying this parameter combination
*/
private createCacheKey(
count: number,
model: string,
@@ -112,6 +208,19 @@ export class PromptGeneratorService {
return JSON.stringify(keyData);
}
/**
* Retrieves cached prompts if they exist and are still valid.
*
* Checks both existence and age of cached prompts. Returns null if:
* - No cache entry exists for this key
* - Cache entry is empty (defensive guard)
* - Cache is older than 10 minutes (expired)
*
* Expired entries are automatically removed from the cache map.
*
* @param cacheKey - Cache key to look up
* @returns Array of cached prompts if valid, null otherwise
*/
private getCachedPrompts(cacheKey: string): GeneratedPrompt[] | null {
const cached = this.cache.get(cacheKey);
if (!cached) {
@@ -137,6 +246,21 @@ export class PromptGeneratorService {
// MARK: - Validation Methods
/**
* Validates plugin settings before attempting prompt generation.
*
* Checks all settings that affect prompt generation to provide early
* feedback before making API calls. Validates:
* - API key is present
* - Model ID is specified
* - Numeric settings are within acceptable ranges
*
* This validation prevents API errors and gives users clear guidance
* about what needs to be fixed in their configuration.
*
* @param settings - Settings to validate
* @returns Object containing validity status and array of error messages
*/
validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } {
const errors: string[] = [];