Implements freewriting prompts plugin

Initial implementation of the Freewriting Prompts plugin.

This commit introduces the core functionality for generating
AI-powered writing prompts using Anthropic's Claude API.

It includes:
- API client for interacting with the Anthropic API
- Services for generating and caching prompts
- Commands for displaying staggered prompts and appending prompts to notes
- Settings tab for configuring the plugin
This commit is contained in:
AlexKucera committed 2025-09-19 18:51:48 +02:00
1 parent e204a9998c
commit 44936775cd
10 files changed
+1095 -143

No files matched your search

+254
View File
@@ -0,0 +1,254 @@
// 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';
export class AnthropicClient {
private apiKey: string;
private baseUrl = 'https://api.anthropic.com/v1/messages';
constructor(apiKey: string) {
this.apiKey = apiKey;
}
// MARK: - Public Methods
async generatePrompts(
count: number,
model: AnthropicModel,
systemPrompt: string,
examplePrompt: string
): Promise<string[]> {
if (!this.apiKey) {
throw new Error('API key is required');
}
try {
const userMessage = this.createUserMessage(count, examplePrompt);
const request: AnthropicRequest = {
model,
max_tokens: 1000,
messages: [{ role: 'user', content: userMessage }],
system: systemPrompt
};
const response = await this.makeRequest(request);
return this.parsePromptsFromResponse(response);
} catch (error) {
console.error('Error generating prompts:', error);
if (error instanceof Error) {
new Notice(`Failed to generate prompts: ${error.message}`);
throw error;
}
throw new Error('Unknown error occurred while generating prompts');
}
}
// MARK: - Private Methods
private createUserMessage(count: number, examplePrompt: string): string {
const baseMessage = `Please generate ${count} creative writing prompts.`;
if (examplePrompt.trim()) {
return `${baseMessage} Here's an example of the style I'm looking for:\n\n"${examplePrompt}"\n\nPlease provide ${count} similar prompts, each on a new line, numbered 1-${count}.`;
}
return `${baseMessage} Please provide ${count} diverse and engaging writing prompts, each on a new line, numbered 1-${count}.`;
}
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
try {
const response = await requestUrl({
url: this.baseUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify(request)
});
if (response.status < 200 || response.status >= 300) {
throw new Error(`API request failed: ${response.status}\n${response.text}`);
}
return response.json as AnthropicResponse;
} catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error(`Network request failed: ${String(error)}`);
}
}
private parsePromptsFromResponse(response: AnthropicResponse): string[] {
if (!response.content || response.content.length === 0) {
throw new Error('No content received from API');
}
const text = response.content[0].text;
const lines = text.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
const prompts: string[] = [];
for (const line of lines) {
// Remove numbering (1., 2., etc.) and clean up the prompt
const cleaned = line.replace(/^\d+\.\s*/, '').trim();
if (cleaned.length > 0) {
prompts.push(cleaned);
}
}
if (prompts.length === 0) {
throw new Error('No valid prompts found in API response');
}
return prompts;
}
// MARK: - Configuration Methods
updateApiKey(apiKey: string): void {
this.apiKey = apiKey;
}
validateApiKey(): boolean {
return !!(this.apiKey && this.apiKey.trim().length > 0);
}
async testApiKey(model: AnthropicModel): Promise<{
success: boolean;
message: string;
details?: {
model?: string;
responseTime: number;
inputTokens?: number;
outputTokens?: number;
};
error?: string;
}> {
if (!this.validateApiKey()) {
return {
success: false,
message: 'API key is empty or invalid format',
error: 'INVALID_KEY_FORMAT'
};
}
const startTime = Date.now();
try {
const testRequest: AnthropicRequest = {
model,
max_tokens: 10,
messages: [{ role: 'user', content: 'Please respond with just the word "ping"' }],
system: 'You are a test assistant. Respond only with the exact word requested.'
};
const response = await this.makeRequest(testRequest);
const responseTime = Date.now() - startTime;
return {
success: true,
message: 'API key is valid and working correctly',
details: {
model: response.model,
responseTime,
inputTokens: response.usage?.input_tokens,
outputTokens: response.usage?.output_tokens
}
};
} catch (error) {
const responseTime = Date.now() - startTime;
return this.parseTestError(error, responseTime);
}
}
private parseTestError(error: unknown, responseTime: number): {
success: boolean;
message: string;
details?: {
model?: string;
responseTime: number;
inputTokens?: number;
outputTokens?: number;
};
error: string;
} {
const baseResult = {
success: false,
details: { responseTime }
};
if (error instanceof Error) {
const errorMessage = error.message.toLowerCase();
// Check for specific error types
if (errorMessage.includes('401') || errorMessage.includes('unauthorized')) {
return {
...baseResult,
message: 'API key is invalid or unauthorized',
error: 'UNAUTHORIZED'
};
}
if (errorMessage.includes('429') || errorMessage.includes('rate limit')) {
return {
...baseResult,
message: 'Rate limit exceeded. Please try again later.',
error: 'RATE_LIMITED'
};
}
if (errorMessage.includes('403') || errorMessage.includes('forbidden')) {
return {
...baseResult,
message: 'API access forbidden. Check your account status and billing.',
error: 'FORBIDDEN'
};
}
if (errorMessage.includes('400') || errorMessage.includes('bad request')) {
return {
...baseResult,
message: 'Invalid request format. This may indicate a plugin bug.',
error: 'BAD_REQUEST'
};
}
if (errorMessage.includes('500') || errorMessage.includes('internal server')) {
return {
...baseResult,
message: 'Anthropic server error. Please try again later.',
error: 'SERVER_ERROR'
};
}
if (errorMessage.includes('network') || errorMessage.includes('fetch')) {
return {
...baseResult,
message: 'Network error. Check your internet connection.',
error: 'NETWORK_ERROR'
};
}
// Generic error with the actual message
return {
...baseResult,
message: `API test failed: ${error.message}`,
error: 'UNKNOWN_ERROR'
};
}
return {
...baseResult,
message: 'Unknown error occurred during API test',
error: 'UNKNOWN_ERROR'
};
}
}
+122
View File
@@ -0,0 +1,122 @@
// ABOUTME: Note prompts command implementation that appends prompts to the current note
// ABOUTME: Handles editor interaction, cursor positioning, and prompt formatting
import { Editor, MarkdownView, Notice } from 'obsidian';
import { PromptGeneratorService } from '../services/promptGenerator';
import { FreewritingPromptsSettings } from '../types';
export class NotePromptsCommand {
constructor(private promptGenerator: PromptGeneratorService) {}
// MARK: - Public Methods
async execute(
settings: FreewritingPromptsSettings,
editor: Editor,
view: MarkdownView
): Promise<void> {
if (!editor || !view) {
new Notice('No active note found. Please open a note first.');
return;
}
try {
// Generate prompts
const prompts = await this.promptGenerator.generateNotePrompts(settings);
if (prompts.length === 0) {
new Notice('No prompts were generated');
return;
}
// Format and insert prompts into the note
this.insertPromptsIntoNote(editor, prompts);
new Notice(`Added ${prompts.length} writing prompts to your note`);
} catch (error) {
console.error('Error executing note prompts command:', error);
// Error handling is done in the service layer
}
}
// MARK: - Private Methods
private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
const cursor = editor.getCursor();
const currentLine = editor.getLine(cursor.line);
// Determine if we need to add a newline before our content
const needsNewlineBefore = currentLine.trim().length > 0;
// Format the prompts
const formattedPrompts = this.formatPrompts(prompts);
// Prepare the content to insert
let contentToInsert = '';
if (needsNewlineBefore) {
contentToInsert += '\n';
}
contentToInsert += formattedPrompts;
// If we're not at the end of the document, add a trailing newline
const lastLine = editor.lastLine();
if (cursor.line < lastLine) {
contentToInsert += '\n';
}
// Insert the content at the cursor position
editor.replaceSelection(contentToInsert);
// Position cursor at the end of the inserted content
const lines = contentToInsert.split('\n');
const newCursorLine = cursor.line + lines.length - 1;
const newCursorCh = lines[lines.length - 1].length;
if (cursor.line === lastLine && !needsNewlineBefore) {
// If we were at the last line and didn't add a newline before, adjust
editor.setCursor(cursor.line, cursor.ch + contentToInsert.length);
} else {
editor.setCursor(newCursorLine, newCursorCh);
}
}
private formatPrompts(prompts: string[]): string {
const timestamp = new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
let formatted = `## Writing Prompts (${timestamp})\n\n`;
prompts.forEach((prompt, index) => {
formatted += `${index + 1}. ${prompt}\n\n`;
});
return formatted;
}
// MARK: - Utility Methods
static canExecute(editor: Editor, view: MarkdownView): boolean {
return !!(editor && view && view.file);
}
static getExecutionContext(app: any): { editor: Editor | null; view: MarkdownView | null } {
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) {
return { editor: null, view: null };
}
return {
editor: activeView.editor,
view: activeView
};
}
}
+117
View File
@@ -0,0 +1,117 @@
// ABOUTME: Staggered prompts command implementation that shows prompts as timed notifications
// ABOUTME: Manages interval-based prompt display with proper cleanup and error handling
import { Notice } from 'obsidian';
import { PromptGeneratorService } from '../services/promptGenerator';
import { FreewritingPromptsSettings } from '../types';
export class StaggeredPromptsCommand {
private activeInterval: number | null = null;
private promptQueue: string[] = [];
private currentIndex = 0;
constructor(private promptGenerator: PromptGeneratorService) {}
// MARK: - Public Methods
async execute(settings: FreewritingPromptsSettings): Promise<void> {
// Stop any existing staggered sequence
this.stop();
try {
// Generate prompts
const prompts = await this.promptGenerator.generateStaggeredPrompts(settings);
if (prompts.length === 0) {
new Notice('No prompts were generated');
return;
}
// Initialize the prompt queue
this.promptQueue = prompts;
this.currentIndex = 0;
// Show the first prompt immediately
this.showCurrentPrompt();
// If there are more prompts, start the interval
if (prompts.length > 1) {
this.startInterval(settings.delaySeconds);
}
} catch (error) {
console.error('Error executing staggered prompts command:', error);
// Error handling is done in the service layer
}
}
stop(): void {
if (this.activeInterval !== null) {
clearInterval(this.activeInterval);
this.activeInterval = null;
}
this.promptQueue = [];
this.currentIndex = 0;
}
isRunning(): boolean {
return this.activeInterval !== null;
}
// MARK: - Private Methods
private startInterval(delaySeconds: number): void {
this.activeInterval = window.setInterval(() => {
this.currentIndex++;
if (this.currentIndex < this.promptQueue.length) {
this.showCurrentPrompt();
} else {
// We've shown all prompts, stop the interval
this.stop();
new Notice('All prompts have been shown');
}
}, delaySeconds * 1000);
}
private showCurrentPrompt(): void {
if (this.currentIndex < this.promptQueue.length) {
const prompt = this.promptQueue[this.currentIndex];
const promptNumber = this.currentIndex + 1;
const totalPrompts = this.promptQueue.length;
// Create a longer-lasting notice for the prompt
const notice = new Notice(
`Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`,
8000 // Show for 8 seconds
);
// Add some styling to make it more prominent
const noticeEl = notice.noticeEl;
if (noticeEl) {
noticeEl.style.maxWidth = '400px';
noticeEl.style.whiteSpace = 'pre-wrap';
noticeEl.style.fontSize = '14px';
noticeEl.style.lineHeight = '1.4';
noticeEl.addClass('freewriting-prompt-notice');
}
}
}
// MARK: - Status Methods
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
return {
isRunning: this.isRunning(),
currentPrompt: this.currentIndex + 1,
totalPrompts: this.promptQueue.length
};
}
getRemainingPrompts(): string[] {
if (this.currentIndex >= this.promptQueue.length) {
return [];
}
return this.promptQueue.slice(this.currentIndex + 1);
}
}
+153 -131
View File
@@ -1,134 +1,156 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// ABOUTME: Main plugin file for Freewriting Prompts - generates AI-powered writing prompts
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
// Remember to rename these classes and interfaces!
import { Editor, MarkdownView, Notice, Plugin } from 'obsidian';
import { FreewritingPromptsSettings } from './types';
import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings';
import { PromptGeneratorService } from './services/promptGenerator';
import { StaggeredPromptsCommand } from './commands/staggeredPrompts';
import { NotePromptsCommand } from './commands/notePrompts';
interface MyPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (_evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, _view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
export default class FreewritingPromptsPlugin extends Plugin {
settings: FreewritingPromptsSettings;
promptGenerator: PromptGeneratorService;
staggeredCommand: StaggeredPromptsCommand;
noteCommand: NotePromptsCommand;
async onload() {
console.log('Loading Freewriting Prompts plugin');
await this.loadSettings();
// Initialize services
this.promptGenerator = new PromptGeneratorService(this.settings);
this.staggeredCommand = new StaggeredPromptsCommand(this.promptGenerator);
this.noteCommand = new NotePromptsCommand(this.promptGenerator);
// Register commands
this.registerCommands();
// Add settings tab
this.addSettingTab(new FreewritingPromptsSettingTab(this.app, this));
console.log('Freewriting Prompts plugin loaded');
}
onunload() {
console.log('Unloading Freewriting Prompts plugin');
// Stop any running staggered prompts
if (this.staggeredCommand) {
this.staggeredCommand.stop();
}
// Clear prompt cache
if (this.promptGenerator) {
this.promptGenerator.clearCache();
}
}
// MARK: - Settings Management
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
// Update the prompt generator with new settings
if (this.promptGenerator) {
this.promptGenerator.updateApiKey(this.settings.apiKey);
}
}
// MARK: - Command Registration
private registerCommands() {
// Staggered Freewriting Prompts command
this.addCommand({
id: 'staggered-freewriting-prompts',
name: 'Staggered Freewriting Prompts',
callback: async () => {
await this.executeStaggeredPrompts();
}
});
// Freewriting Prompt command (editor-based)
this.addCommand({
id: 'freewriting-prompt',
name: 'Freewriting Prompt',
editorCallback: async (editor: Editor, view: MarkdownView) => {
await this.executeNotePrompts(editor, view);
}
});
// Stop staggered prompts command
this.addCommand({
id: 'stop-staggered-prompts',
name: 'Stop Staggered Prompts',
callback: () => {
this.stopStaggeredPrompts();
}
});
}
// MARK: - Command Implementations
private async executeStaggeredPrompts(): Promise<void> {
// Check if staggered prompts are already running
if (this.staggeredCommand.isRunning()) {
new Notice('Staggered prompts are already running. Use "Stop Staggered Prompts" to stop them first.');
return;
}
// Validate settings
const validation = this.promptGenerator.validateSettings(this.settings);
if (!validation.isValid) {
new Notice(`Settings validation failed: ${validation.errors.join(', ')}`);
return;
}
try {
await this.staggeredCommand.execute(this.settings);
} catch (error) {
console.error('Error executing staggered prompts:', error);
// Error handling is done in the command layer
}
}
private async executeNotePrompts(editor: Editor, view: MarkdownView): Promise<void> {
// Check if we can execute the command
if (!NotePromptsCommand.canExecute(editor, view)) {
new Notice('Please open a note and place your cursor where you want to insert prompts.');
return;
}
// Validate settings
const validation = this.promptGenerator.validateSettings(this.settings);
if (!validation.isValid) {
new Notice(`Settings validation failed: ${validation.errors.join(', ')}`);
return;
}
try {
await this.noteCommand.execute(this.settings, editor, view);
} catch (error) {
console.error('Error executing note prompts:', error);
// Error handling is done in the command layer
}
}
private stopStaggeredPrompts(): void {
if (this.staggeredCommand.isRunning()) {
this.staggeredCommand.stop();
new Notice('Staggered prompts stopped');
} else {
new Notice('No staggered prompts are currently running');
}
}
// MARK: - Public API for Settings
getStaggeredStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
return this.staggeredCommand.getStatus();
}
}
+5 -6
View File
@@ -1,11 +1,10 @@
{
"id": "sample-plugin",
"name": "Sample Plugin",
"id": "freewriting-prompts",
"name": "Freewriting Prompts",
"version": "1.0.0",
"minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
"author": "Alexander",
"authorUrl": "",
"isDesktopOnly": false
}
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "obsidian-sample-plugin",
"name": "obsidian-freewriting-prompts",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "obsidian-sample-plugin",
"name": "obsidian-freewriting-prompts",
"version": "1.0.0",
"license": "MIT",
"devDependencies": {
+4 -4
View File
@@ -1,15 +1,15 @@
{
"name": "obsidian-sample-plugin",
"name": "obsidian-freewriting-prompts",
"version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "",
"keywords": ["obsidian", "plugin", "writing", "prompts", "ai", "claude", "freewriting"],
"author": "Alexander",
"license": "MIT",
"devDependencies": {
"@types/node": "^16.11.6",
+158
View File
@@ -0,0 +1,158 @@
// ABOUTME: Service layer for generating writing prompts with caching and error handling
// ABOUTME: Coordinates between the Anthropic API client and plugin commands
import { Notice } from 'obsidian';
import { AnthropicClient } from '../api/anthropicClient';
import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types';
export class PromptGeneratorService {
private client: AnthropicClient;
private cache: Map<string, GeneratedPrompt[]> = new Map();
private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes
// Expose client for API testing in settings
get anthropicClient(): AnthropicClient {
return this.client;
}
constructor(settings: FreewritingPromptsSettings) {
this.client = new AnthropicClient(settings.apiKey);
}
// MARK: - Public Methods
async generateStaggeredPrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
return this.generatePrompts(
settings.staggeredCount,
settings.model as AnthropicModel,
settings.systemPrompt,
settings.staggeredExamplePrompt,
'staggered'
);
}
async generateNotePrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
return this.generatePrompts(
settings.noteCount,
settings.model as AnthropicModel,
settings.systemPrompt,
settings.freewritingExamplePrompt,
'note'
);
}
updateApiKey(apiKey: string): void {
this.client.updateApiKey(apiKey);
this.clearCache(); // Clear cache when API key changes
}
clearCache(): void {
this.cache.clear();
}
// MARK: - Private Methods
private async generatePrompts(
count: number,
model: AnthropicModel,
systemPrompt: string,
examplePrompt: string,
type: 'staggered' | 'note'
): Promise<string[]> {
if (!this.client.validateApiKey()) {
new Notice('Please configure your Anthropic API key in settings');
throw new Error('API key not configured');
}
const cacheKey = this.createCacheKey(count, model, systemPrompt, examplePrompt, type);
const cachedPrompts = this.getCachedPrompts(cacheKey);
if (cachedPrompts) {
return cachedPrompts.map(p => p.text);
}
try {
new Notice('Generating prompts...');
const prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt);
const generatedPrompts: GeneratedPrompt[] = prompts.map(text => ({
text,
timestamp: new Date()
}));
this.cache.set(cacheKey, generatedPrompts);
new Notice(`Generated ${prompts.length} writing prompts`);
return prompts;
} catch (error) {
console.error('Error in PromptGeneratorService:', error);
if (error instanceof Error) {
new Notice(`Error generating prompts: ${error.message}`);
} else {
new Notice('Unknown error occurred while generating prompts');
}
throw error;
}
}
private createCacheKey(
count: number,
model: AnthropicModel,
systemPrompt: string,
examplePrompt: string,
type: string
): string {
const keyData = {
count,
model,
systemPrompt: systemPrompt.trim(),
examplePrompt: examplePrompt.trim(),
type
};
return JSON.stringify(keyData);
}
private getCachedPrompts(cacheKey: string): GeneratedPrompt[] | null {
const cached = this.cache.get(cacheKey);
if (!cached) {
return null;
}
const now = new Date().getTime();
const cacheTime = cached[0].timestamp.getTime();
if (now - cacheTime > this.cacheExpiryMs) {
this.cache.delete(cacheKey);
return null;
}
return cached;
}
// MARK: - Validation Methods
validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } {
const errors: string[] = [];
if (!settings.apiKey || settings.apiKey.trim().length === 0) {
errors.push('API key is required');
}
if (settings.staggeredCount < 1 || settings.staggeredCount > 50) {
errors.push('Staggered count must be between 1 and 50');
}
if (settings.delaySeconds < 1 || settings.delaySeconds > 300) {
errors.push('Delay seconds must be between 1 and 300');
}
if (settings.noteCount < 1 || settings.noteCount > 20) {
errors.push('Note count must be between 1 and 20');
}
return {
isValid: errors.length === 0,
errors
};
}
}
+223
View File
@@ -0,0 +1,223 @@
// 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, Notice, PluginSettingTab, Setting } from 'obsidian';
import FreewritingPromptsPlugin from './main';
import { FreewritingPromptsSettings, ANTHROPIC_MODELS } from './types';
export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
apiKey: '',
model: 'claude-3-haiku-20240307',
staggeredCount: 10,
delaySeconds: 6,
noteCount: 3,
systemPrompt: 'You are a creative writing assistant. Generate engaging, thought-provoking writing prompts that inspire creativity and help writers overcome blocks. Focus on variety, originality, and emotional depth.',
staggeredExamplePrompt: 'Write about a character who discovers they can see the last thing a person touched before they died.',
freewritingExamplePrompt: 'Describe a world where colors have been outlawed and only exist in secret underground galleries.'
};
export class FreewritingPromptsSettingTab extends PluginSettingTab {
plugin: FreewritingPromptsPlugin;
constructor(app: App, plugin: FreewritingPromptsPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Freewriting Prompts Settings' });
// MARK: - API Configuration
containerEl.createEl('h3', { text: 'API Configuration' });
new Setting(containerEl)
.setName('Anthropic API Key')
.setDesc('Your Anthropic API key for Claude. Get one at https://console.anthropic.com/')
.addText(text => text
.setPlaceholder('sk-ant-...')
.setValue(this.plugin.settings.apiKey)
.onChange(async (value) => {
this.plugin.settings.apiKey = value;
await this.plugin.saveSettings();
this.plugin.promptGenerator.updateApiKey(value);
}))
.then(setting => {
// Make it a password field
setting.controlEl.querySelector('input')?.setAttribute('type', 'password');
});
new Setting(containerEl)
.setName('Test API Key')
.setDesc('Test your API key to verify it works correctly')
.addButton(button => button
.setButtonText('Test Connection')
.onClick(async () => {
await this.testApiKey(button);
}));
new Setting(containerEl)
.setName('Claude Model')
.setDesc('Which Claude model to use for generating prompts')
.addDropdown(dropdown => {
ANTHROPIC_MODELS.forEach(model => {
dropdown.addOption(model, model);
});
dropdown
.setValue(this.plugin.settings.model)
.onChange(async (value) => {
this.plugin.settings.model = value;
await this.plugin.saveSettings();
});
});
// MARK: - Command Configuration
containerEl.createEl('h3', { text: 'Command Configuration' });
new Setting(containerEl)
.setName('Staggered Prompts Count')
.setDesc('Number of prompts to generate for staggered notifications (1-50)')
.addText(text => text
.setPlaceholder('10')
.setValue(this.plugin.settings.staggeredCount.toString())
.onChange(async (value) => {
const count = parseInt(value);
if (!isNaN(count) && count >= 1 && count <= 50) {
this.plugin.settings.staggeredCount = count;
await this.plugin.saveSettings();
}
}));
new Setting(containerEl)
.setName('Delay Between Prompts')
.setDesc('Seconds to wait between each staggered prompt notification (1-300)')
.addText(text => text
.setPlaceholder('6')
.setValue(this.plugin.settings.delaySeconds.toString())
.onChange(async (value) => {
const delay = parseInt(value);
if (!isNaN(delay) && delay >= 1 && delay <= 300) {
this.plugin.settings.delaySeconds = delay;
await this.plugin.saveSettings();
}
}));
new Setting(containerEl)
.setName('Note Prompts Count')
.setDesc('Number of prompts to append to the current note (1-20)')
.addText(text => text
.setPlaceholder('3')
.setValue(this.plugin.settings.noteCount.toString())
.onChange(async (value) => {
const count = parseInt(value);
if (!isNaN(count) && count >= 1 && count <= 20) {
this.plugin.settings.noteCount = count;
await this.plugin.saveSettings();
}
}));
// MARK: - Prompt Customization
containerEl.createEl('h3', { text: 'Prompt Customization' });
new Setting(containerEl)
.setName('System Prompt')
.setDesc('Instructions for the AI on how to generate prompts')
.addTextArea(text => text
.setPlaceholder('You are a creative writing assistant...')
.setValue(this.plugin.settings.systemPrompt)
.onChange(async (value) => {
this.plugin.settings.systemPrompt = value;
await this.plugin.saveSettings();
}))
.then(setting => {
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '3');
});
new Setting(containerEl)
.setName('Staggered Prompts Example')
.setDesc('Example prompt to guide the style for staggered notifications')
.addTextArea(text => text
.setPlaceholder('Write about a character who...')
.setValue(this.plugin.settings.staggeredExamplePrompt)
.onChange(async (value) => {
this.plugin.settings.staggeredExamplePrompt = value;
await this.plugin.saveSettings();
}))
.then(setting => {
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
});
new Setting(containerEl)
.setName('Note Prompts Example')
.setDesc('Example prompt to guide the style for note prompts')
.addTextArea(text => text
.setPlaceholder('Describe a world where...')
.setValue(this.plugin.settings.freewritingExamplePrompt)
.onChange(async (value) => {
this.plugin.settings.freewritingExamplePrompt = value;
await this.plugin.saveSettings();
}))
.then(setting => {
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
});
// MARK: - Actions
containerEl.createEl('h3', { text: 'Actions' });
new Setting(containerEl)
.setName('Clear Cache')
.setDesc('Clear the cached prompts to force regeneration')
.addButton(button => button
.setButtonText('Clear Cache')
.onClick(() => {
this.plugin.promptGenerator.clearCache();
// Show a temporary notice
const notice = new Notice('Cache cleared');
setTimeout(() => notice.hide(), 2000);
}));
}
// MARK: - API Testing
private async testApiKey(button: any): Promise<void> {
const originalText = button.buttonEl.textContent;
// Update button to show loading state
button.setButtonText('Testing...');
button.setDisabled(true);
try {
const client = this.plugin.promptGenerator.anthropicClient;
const result = await client.testApiKey(this.plugin.settings.model as any);
if (result.success) {
// Success - show detailed information
const details = result.details;
const detailText = details ?
`\n\nDetails:\n• Model: ${details.model}\n• Response time: ${details.responseTime}ms\n• Input tokens: ${details.inputTokens || 'N/A'}\n• Output tokens: ${details.outputTokens || 'N/A'}` : '';
new Notice(`✅ ${result.message}${detailText}`, 8000);
} else {
// Error - show detailed error information
const errorDetails = result.details ?
`\n\nTroubleshooting:\n• Response time: ${result.details.responseTime}ms\n• Error type: ${result.error}` : '';
new Notice(`❌ ${result.message}${errorDetails}`, 10000);
}
} catch (error) {
console.error('Unexpected error during API test:', error);
new Notice('❌ Unexpected error during API test. Check console for details.', 5000);
} finally {
// Restore button state
button.setButtonText(originalText);
button.setDisabled(false);
}
}
}
+57
View File
@@ -0,0 +1,57 @@
// ABOUTME: Type definitions for the Freewriting Prompts plugin
// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration
export interface FreewritingPromptsSettings {
apiKey: string;
model: string;
staggeredCount: number;
delaySeconds: number;
noteCount: number;
systemPrompt: string;
staggeredExamplePrompt: string;
freewritingExamplePrompt: string;
}
export interface AnthropicMessage {
role: 'user' | 'assistant' | 'system';
content: string;
}
export interface AnthropicRequest {
model: string;
max_tokens: number;
messages: AnthropicMessage[];
system?: string;
}
export interface AnthropicResponse {
content: Array<{
text: string;
type: 'text';
}>;
id: string;
model: string;
role: 'assistant';
stop_reason: string;
stop_sequence: null;
type: 'message';
usage: {
input_tokens: number;
output_tokens: number;
};
}
export interface GeneratedPrompt {
text: string;
timestamp: Date;
}
export const ANTHROPIC_MODELS = [
'claude-3-haiku-20240307',
'claude-3-sonnet-20240229',
'claude-3-opus-20240229',
'claude-3-5-sonnet-20241022',
'claude-3-5-haiku-20241022'
] as const;
export type AnthropicModel = typeof ANTHROPIC_MODELS[number];