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:
6 files changed
+287
-19
No files matched your search
+35
-6
@@ -1,12 +1,13 @@
|
||||
// ABOUTME: Anthropic API client for generating writing prompts using Claude
|
||||
// ABOUTME: Handles API requests, error handling, and response parsing
|
||||
|
||||
import { Notice, requestUrl } from 'obsidian';
|
||||
import { AnthropicRequest, AnthropicResponse, AnthropicModel } from '../types';
|
||||
import { requestUrl } from 'obsidian';
|
||||
import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types';
|
||||
|
||||
export class AnthropicClient {
|
||||
private apiKey: string;
|
||||
private baseUrl = 'https://api.anthropic.com/v1/messages';
|
||||
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
||||
private modelsUrl = 'https://api.anthropic.com/v1/models';
|
||||
private readonly SYSTEM_PROMPT_SUFFIX = '\n\nIMPORTANT OUTPUT REQUIREMENTS:\n- Return ONLY the numbered writing prompts, nothing else\n- Do not include any explanations, questions, or additional commentary\n- Do not ask if the user wants more prompts or different styles\n- Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)';
|
||||
|
||||
private readonly TIMED_PROMPT_MODIFIER = '\n\nFOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT:\n- Each prompt should be answerable in 1-5 words or a single sentence\n- Focus on immediate, concrete observations or quick thoughts\n- Avoid complex scenarios or deep philosophical questions\n- Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft"\n- Keep prompts simple, immediate, and concrete';
|
||||
@@ -19,7 +20,7 @@ export class AnthropicClient {
|
||||
|
||||
async generatePrompts(
|
||||
count: number,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
systemPrompt: string,
|
||||
examplePrompt: string,
|
||||
type: 'timed' | 'note'
|
||||
@@ -56,6 +57,34 @@ export class AnthropicClient {
|
||||
}
|
||||
}
|
||||
|
||||
async fetchModels(): Promise<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
|
||||
|
||||
private createUserMessage(count: number, examplePrompt: string): string {
|
||||
@@ -71,7 +100,7 @@ export class AnthropicClient {
|
||||
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||
try {
|
||||
const response = await requestUrl({
|
||||
url: this.baseUrl,
|
||||
url: this.messagesUrl,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -131,7 +160,7 @@ export class AnthropicClient {
|
||||
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
||||
}
|
||||
|
||||
async testApiKey(model: AnthropicModel): Promise<{
|
||||
async testApiKey(model: string): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: {
|
||||
|
||||
Reference in new issue
Block a user