Adds dynamic Claude model fetching and management #1
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',
|
||||
|
⚠️ Potential issue | 🟠 Major Keep pagination metadata in sync after sorting Sorting the collected models before returning them means the original 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ 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: {
|
||||
'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?: {
|
||||
|
||||
@@ -2,15 +2,17 @@
|
||||
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
||||
|
||||
import { Editor, MarkdownView, Notice, Plugin } from 'obsidian';
|
||||
import { FreewritingPromptsSettings } from './types';
|
||||
import { FreewritingPromptsSettings, FreewritingPromptsData } from './types';
|
||||
import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings';
|
||||
import { PromptGeneratorService } from './services/promptGenerator';
|
||||
import { ModelService } from './services/modelService';
|
||||
import { TimedPromptsCommand } from './commands/timedPrompts';
|
||||
import { NotePromptsCommand } from './commands/notePrompts';
|
||||
|
||||
export default class FreewritingPromptsPlugin extends Plugin {
|
||||
settings: FreewritingPromptsSettings;
|
||||
promptGenerator: PromptGeneratorService;
|
||||
modelService: ModelService;
|
||||
timedCommand: TimedPromptsCommand;
|
||||
noteCommand: NotePromptsCommand;
|
||||
|
||||
@@ -19,9 +21,16 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
||||
|
||||
// Initialize services
|
||||
this.promptGenerator = new PromptGeneratorService(this.settings);
|
||||
this.modelService = new ModelService(this.promptGenerator.anthropicClient);
|
||||
this.timedCommand = new TimedPromptsCommand(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
|
||||
this.registerCommands();
|
||||
|
||||
@@ -48,7 +57,12 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
||||
}
|
||||
|
||||
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
|
||||
if (this.promptGenerator) {
|
||||
|
||||
@@ -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,7 +3,7 @@
|
||||
|
||||
import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types';
|
||||
import { FreewritingPromptsSettings, GeneratedPrompt } from '../types';
|
||||
|
||||
export class PromptGeneratorService {
|
||||
private client: AnthropicClient;
|
||||
@@ -54,7 +54,7 @@ export class PromptGeneratorService {
|
||||
|
||||
private async generatePrompts(
|
||||
count: number,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
systemPrompt: string,
|
||||
examplePrompt: string,
|
||||
type: 'timed' | 'note'
|
||||
@@ -97,7 +97,7 @@ export class PromptGeneratorService {
|
||||
|
||||
private createCacheKey(
|
||||
count: number,
|
||||
model: AnthropicModel,
|
||||
model: string,
|
||||
systemPrompt: string,
|
||||
examplePrompt: string,
|
||||
type: string
|
||||
|
||||
+80
-7
@@ -1,9 +1,10 @@
|
||||
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin
|
||||
// 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 { FreewritingPromptsSettings, ANTHROPIC_MODELS, AnthropicModel } from './types';
|
||||
import { FreewritingPromptsSettings } from './types';
|
||||
import { ModelOption } from './services/modelService';
|
||||
|
||||
export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
|
||||
apiKey: '',
|
||||
@@ -18,18 +19,23 @@ export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
|
||||
|
||||
export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
||||
plugin: FreewritingPromptsPlugin;
|
||||
private modelDropdown: DropdownComponent | null = null;
|
||||
private availableModels: ModelOption[] = [];
|
||||
|
||||
constructor(app: App, plugin: FreewritingPromptsPlugin) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
display(): void {
|
||||
async display(): Promise<void> {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
|
||||
containerEl.createEl('h2', { text: 'Freewriting Prompts' });
|
||||
|
||||
// Load models asynchronously
|
||||
await this.loadModels();
|
||||
|
||||
// MARK: - API Configuration
|
||||
|
||||
containerEl.createEl('h3', { text: 'API Configuration' });
|
||||
@@ -44,6 +50,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
||||
this.plugin.settings.apiKey = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.promptGenerator.updateApiKey(value);
|
||||
|
||||
// Trigger model refresh when API key is entered
|
||||
if (value.trim().length > 0) {
|
||||
await this.refreshModels();
|
||||
}
|
||||
}))
|
||||
.then(setting => {
|
||||
// Make it a password field
|
||||
@@ -63,13 +74,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
||||
.setName('Claude Model')
|
||||
.setDesc('Which Claude model to use for generating prompts')
|
||||
.addDropdown(dropdown => {
|
||||
ANTHROPIC_MODELS.forEach(model => {
|
||||
dropdown.addOption(model, model);
|
||||
});
|
||||
this.modelDropdown = dropdown;
|
||||
this.populateModelDropdown(dropdown);
|
||||
dropdown
|
||||
.setValue(this.plugin.settings.model)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.model = value as AnthropicModel;
|
||||
this.plugin.settings.model = value;
|
||||
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
|
||||
|
||||
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
export interface FreewritingPromptsSettings {
|
||||
apiKey: string;
|
||||
model: AnthropicModel;
|
||||
model: string; // Changed from AnthropicModel to string to support dynamic models
|
||||
timedCount: number;
|
||||
delaySeconds: number;
|
||||
noteCount: number;
|
||||
@@ -12,6 +12,10 @@ export interface FreewritingPromptsSettings {
|
||||
freewritingExamplePrompt: string;
|
||||
}
|
||||
|
||||
export interface FreewritingPromptsData extends FreewritingPromptsSettings {
|
||||
modelCache?: ModelCache;
|
||||
}
|
||||
|
||||
export interface AnthropicMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
@@ -46,6 +50,25 @@ export interface GeneratedPrompt {
|
||||
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 = [
|
||||
'claude-opus-4-1-20250805',
|
||||
'claude-opus-4-20250514',
|
||||
|
||||
Reference in new issue
Block a user
🛠️ 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:
🤖 Prompt for AI Agents
✅ Addressed in commits
afa725dto3f53bb5