dralkh_spaceforge/api/openai-service.ts
dralkh e80dfda20d release: v1.0.5
JS/TS:
- Replace builtin-modules with node:module (esbuild.config.mjs)
- Replace fs-extra with native fs (install.js), remove from deps
- Fix createEl deprecation: use createDiv/createSpan
- Remove unnecessary type assertions, fix unsafe casts
- Bind event handlers with arrow functions

CSS:
- Remove all !important declarations (~30 instances) — replace with
  chained selectors (.class.class) for equal specificity
- Merge all duplicate selectors across 7 CSS files (~50+ instances)
- Convert 3-digit hex to 6-digit format (_variables.css)
- Fix duplicate CSS properties (overflow-y in mcq.css)
- Delete leftover display:none suppression rule in calendar.css

Meta:
- Bump version to 1.0.5
- Update minAppVersion to 1.8.7
- Add versions.json entry for 1.0.5
2026-05-20 11:02:54 +03:00

188 lines
8.8 KiB
TypeScript

import { Notice, requestUrl } from 'obsidian';
import { OPENAI, API } from '../ui/constants';
import SpaceforgePlugin from '../main';
import { MCQQuestion, MCQSet } from '../models/mcq';
import { IMCQGenerationService } from './mcq-generation-service';
import { SpaceforgeSettings, MCQQuestionAmountMode, MCQDifficulty } from '../models/settings';
interface OpenAIResponse {
choices: Array<{ message: { content: string } }>;
}
interface OpenAIErrorResponse {
error?: { message?: string };
message?: string;
}
export class OpenAIService implements IMCQGenerationService {
plugin: SpaceforgePlugin;
constructor(plugin: SpaceforgePlugin) {
this.plugin = plugin;
}
async generateMCQs(notePath: string, noteContent: string, settings: SpaceforgeSettings): Promise<MCQSet | null> {
if (!settings.openaiApiKey) {
new Notice(`${OPENAI} ${API} key not set in settings.`);
return null;
}
if (!settings.openaiModel) {
new Notice(`${OPENAI} model not set in settings.`);
return null;
}
try {
new Notice(`Generating questions using ${OPENAI}...`);
// Determine the number of questions to generate
let numQuestionsToGenerate: number;
if (settings.mcqQuestionAmountMode === MCQQuestionAmountMode.WordsPerQuestion) {
const wordCount = noteContent.split(/\s+/).filter(Boolean).length;
numQuestionsToGenerate = Math.max(1, Math.ceil(wordCount / settings.mcqWordsPerQuestion));
} else { // Fixed mode
numQuestionsToGenerate = settings.mcqQuestionsPerNote;
}
const prompt = this.generatePrompt(noteContent, settings, numQuestionsToGenerate);
const response = await this.makeApiRequest(prompt, settings);
const questions = this.parseResponse(response, settings, numQuestionsToGenerate);
if (questions.length === 0) {
new Notice(`Failed to generate valid questions from ${OPENAI}. Try again.`);
return null;
}
return {
notePath,
questions,
generatedAt: Date.now()
};
} catch {
new Notice(`Failed to generate questions with ${OPENAI}. Check console for details.`);
return null;
}
}
private generatePrompt(noteContent: string, settings: SpaceforgeSettings, numQuestionsToGenerate: number): string {
const questionCount = numQuestionsToGenerate; // Use calculated number
const choiceCount = settings.mcqChoicesPerQuestion;
const promptType = settings.mcqPromptType;
const difficulty = settings.mcqDifficulty;
let basePrompt = "";
if (promptType === 'basic') {
basePrompt = `Generate ${questionCount} multiple-choice questions based on the following note content. Each question should have ${choiceCount} choices, with one correct answer. Format the output as a list of questions with bullet points for each answer choice. Mark the correct answer by putting [CORRECT] at the end of the line.`;
} else {
basePrompt = `Generate ${questionCount} multiple-choice questions that test understanding of key concepts in the following note. Each question should have ${choiceCount} choices, with only one correct answer. Format the output as a numbered list of questions with lettered choices (A, B, C, etc.). Mark the correct answer by putting [CORRECT] at the end of the line.\n\nFor example:\n1. What is the capital of France?\n A) London\n B) Berlin\n C) Paris [CORRECT]\n D) Madrid\n E) Rome`;
}
if (difficulty === MCQDifficulty.Basic) {
basePrompt += `\n\nCreate straightforward questions that focus on key facts and basic concepts. Make the questions clear and direct, suitable for beginners or initial review.`;
} else {
basePrompt += `\n\nCreate challenging questions that test deeper understanding and application of concepts. Make the incorrect choices plausible to encourage critical thinking.`;
}
return `${basePrompt}\n\nNote Content:\n${noteContent}`;
}
private async makeApiRequest(prompt: string, settings: SpaceforgeSettings): Promise<string> {
const apiKey = settings.openaiApiKey;
const model = settings.openaiModel;
const difficulty = settings.mcqDifficulty;
const systemPrompt = difficulty === MCQDifficulty.Basic
? settings.mcqBasicSystemPrompt
: settings.mcqAdvancedSystemPrompt;
try {
const response = await requestUrl({
url: 'https://api.openai.com/v1/chat/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
]
})
});
if (response.status !== 200) {
const errorData: OpenAIErrorResponse = response.json ?? { message: response.text };
throw new Error(`API request failed (${response.status}): ${errorData.error?.message ?? errorData.message ?? 'Unknown error'}`);
}
const data = response.json as OpenAIResponse;
if (!data.choices?.length || !data.choices[0]?.message?.content) {
throw new Error('Invalid API response format from OpenAI - missing content');
}
return data.choices[0].message.content;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
new Notice(`OpenAI API error: ${msg}`);
throw error;
}
}
private parseResponse(response: string, _settings: SpaceforgeSettings, numQuestionsToGenerate: number): MCQQuestion[] {
const questions: MCQQuestion[] = [];
try {
const questionBlocks: string[] = response.split(/\d+\.\s+/).filter(block => block.trim().length > 0);
if (questionBlocks.length === 0) {
const lines = response.split('\n');
let currentQuestion = '';
for (const line of lines) {
if (/^\d+\./.test(line.trim())) {
if (currentQuestion) questionBlocks.push(currentQuestion);
currentQuestion = line.replace(/^\d+\.\s*/, '') + '\n';
} else if (currentQuestion) {
currentQuestion += line + '\n';
}
}
if (currentQuestion) questionBlocks.push(currentQuestion);
}
for (const block of questionBlocks) {
const lines = block.split('\n').filter(line => line.trim().length > 0);
if (lines.length < 2) continue;
let questionText = lines[0].trim();
// Remove <think> and </think> tags from the question text
questionText = questionText.replace(/<think>/g, '').replace(/<\/think>/g, '');
const choices: string[] = [];
let correctAnswerIndex = -1;
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
const isCorrect = line.includes('[CORRECT]');
const cleanedLine = line.replace(/\[CORRECT\]/g, '').replace(/^[A-Z]\)\s*|^[A-Z]\.\s*|^\w+\)\s*|^\w+\.\s*/, '').trim();
choices.push(cleanedLine);
if (isCorrect) correctAnswerIndex = choices.length - 1;
}
if (correctAnswerIndex === -1) { // Fallback if [CORRECT] not found
for (let i = 0; i < choices.length; i++) {
if (lines[i + 1] && (lines[i + 1].toLowerCase().includes('correct') || lines[i + 1].includes('✓') || lines[i + 1].includes('✔️'))) {
correctAnswerIndex = i;
break;
}
}
}
if (correctAnswerIndex === -1 && choices.length > 0) correctAnswerIndex = 0; // Default to first if still not found
if (questionText && choices.length >= 2) {
questions.push({ question: questionText, choices, correctAnswerIndex });
}
}
return questions.slice(0, numQuestionsToGenerate); // Use calculated number
} catch {
new Notice(`Error parsing response from ${OPENAI}. Try again.`);
return [];
}
}
}