Spaces:
Sleeping
Sleeping
File size: 13,162 Bytes
63a5bc1 25876df 63a5bc1 7d032f3 63a5bc1 47a380e 7d032f3 47a380e a261c04 47a380e a261c04 47a380e a261c04 25876df a261c04 47a380e a261c04 47a380e 63a5bc1 47a380e 7d032f3 47a380e 7d032f3 47a380e 09d70c8 243e743 09d70c8 243e743 09d70c8 78a1f73 09d70c8 63a5bc1 7d032f3 63a5bc1 7d032f3 63a5bc1 7d032f3 63a5bc1 7d032f3 63a5bc1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
class OpenRouterService {
constructor() {
this.apiUrl = 'https://openrouter.ai/api/v1/chat/completions';
this.apiKey = this.getApiKey();
this.model = 'google/gemma-3-27b-it:free';
// Focused tool definitions for specific, non-overlapping question types
this.questionTools = {
part_of_speech: {
name: 'identify_part_of_speech',
description: 'Identify the grammatical category directly and clearly',
parameters: {
type: 'object',
properties: {
hint: { type: 'string', description: 'Direct answer: "This is a [noun/verb/adjective/adverb]" then add a simple, concrete clue about what type (e.g., "a thing", "an action", "describes something")' }
},
required: ['hint']
}
},
sentence_role: {
name: 'explain_sentence_role',
description: 'Explain the structural function using context clues',
parameters: {
type: 'object',
properties: {
hint: { type: 'string', description: 'Point to specific words around the blank. Example: "Look at \'the whole ___ consisting of\' - what could contain something?" Focus on the immediate context.' }
},
required: ['hint']
}
},
word_category: {
name: 'categorize_word',
description: 'State clearly if abstract or concrete',
parameters: {
type: 'object',
properties: {
hint: { type: 'string', description: 'Start simple: "This is abstract/concrete." Then give a relatable example or size clue: "Think about something very big/small" or "Like feelings/objects"' }
},
required: ['hint']
}
},
synonym: {
name: 'provide_synonym',
description: 'Give clear synonym or similar word',
parameters: {
type: 'object',
properties: {
hint: { type: 'string', description: 'Direct synonyms or word families: "Try a word similar to [related word]" or "Think of another word for [meaning]"' }
},
required: ['hint']
}
}
};
}
getApiKey() {
if (typeof process !== 'undefined' && process.env && process.env.OPENROUTER_API_KEY) {
return process.env.OPENROUTER_API_KEY;
}
if (typeof window !== 'undefined' && window.OPENROUTER_API_KEY) {
return window.OPENROUTER_API_KEY;
}
console.warn('No API key found in getApiKey()');
return '';
}
setApiKey(key) {
this.apiKey = key;
}
async generateContextualHint(questionType, word, sentence, bookTitle, wordContext) {
// Check for API key at runtime
const currentKey = this.getApiKey();
if (currentKey && !this.apiKey) {
this.apiKey = currentKey;
}
if (!this.apiKey) {
return this.getEnhancedFallback(questionType, word, sentence, bookTitle);
}
try {
const prompts = {
part_of_speech: `What part of speech is the word in this blank in: "${sentence}"? Provide a clear, direct answer.`,
sentence_role: `What grammatical role does the word in this blank play in: "${sentence}"? Focus on its function.`,
word_category: `Is the word in this blank an abstract or concrete noun? Explain briefly with an example.`,
synonym: `What's a good synonym for the word that would fit in this blank: "${sentence}"?`
};
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': window.location.origin,
'X-Title': 'Cloze Reader'
},
body: JSON.stringify({
model: this.model,
messages: [{
role: 'system',
content: 'You are a helpful reading tutor. Provide clear, educational answers that help students learn without giving away the answer directly.'
}, {
role: 'user',
content: prompts[questionType] || `Help me understand the word that fits in this context: "${sentence}"`
}],
max_tokens: 150,
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content.trim();
} catch (error) {
console.error('Error generating contextual hint:', error);
return this.getEnhancedFallback(questionType, word, sentence, bookTitle);
}
}
getEnhancedFallback(questionType, word, sentence, bookTitle) {
const fallbacks = {
part_of_speech: `Consider what "${word}" is doing in the sentence. Is it a person, place, thing (noun), an action (verb), or describing something (adjective)?`,
sentence_role: `Look at how "${word}" connects to other words around it. What is its job in making the sentence complete?`,
word_category: `Think about whether "${word}" is something you can touch or see (concrete) or an idea/feeling (abstract).`,
synonym: `What other word could replace "${word}" and keep the same meaning in this sentence?`
};
return fallbacks[questionType] || `Think about what "${word}" means in this classic literature context.`;
}
async getContextualHint(passage, wordToReplace, context) {
if (!this.apiKey) {
return 'API key required for contextual hints';
}
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': window.location.origin,
'X-Title': 'Cloze Reader'
},
body: JSON.stringify({
model: this.model,
messages: [{
role: 'user',
content: `In this passage: "${passage}"
The word "${wordToReplace}" has been replaced with a blank. Give me a helpful hint about what word fits here, considering the context: "${context}".
Provide a brief, educational hint that helps understand the word without giving it away directly.`
}],
max_tokens: 150,
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content.trim();
} catch (error) {
console.error('Error getting contextual hint:', error);
return 'Unable to generate hint at this time';
}
}
async selectSignificantWords(passage, count) {
console.log('selectSignificantWords called with count:', count);
// Check for API key at runtime in case it was loaded after initialization
const currentKey = this.getApiKey();
if (currentKey && !this.apiKey) {
this.apiKey = currentKey;
}
console.log('API key available:', !!this.apiKey);
if (!this.apiKey) {
console.error('No API key for word selection');
throw new Error('API key required for word selection');
}
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': window.location.origin,
'X-Title': 'Cloze Reader'
},
body: JSON.stringify({
model: this.model,
messages: [{
role: 'system',
content: 'You are an educational assistant that selects meaningful words from passages for cloze reading exercises. Select words that are important for comprehension and appropriate for the difficulty level.'
}, {
role: 'user',
content: `From this passage, select exactly ${count} meaningful words to create blanks for a cloze reading exercise. The words should be distributed throughout the passage and be important for understanding the text. Return ONLY the words as a JSON array, nothing else.
Passage: "${passage}"`
}],
max_tokens: 100,
temperature: 0.3
})
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
const content = data.choices[0].message.content.trim();
// Try to parse as JSON array
try {
const words = JSON.parse(content);
if (Array.isArray(words)) {
return words.slice(0, count);
}
} catch (e) {
// If not valid JSON, try to extract words from the response
const matches = content.match(/"([^"]+)"/g);
if (matches) {
return matches.map(m => m.replace(/"/g, '')).slice(0, count);
}
}
throw new Error('Failed to parse AI response');
} catch (error) {
console.error('Error selecting words with AI:', error);
throw error;
}
}
async generateContextualization(title, author) {
console.log('generateContextualization called for:', title, 'by', author);
// Check for API key at runtime
const currentKey = this.getApiKey();
if (currentKey && !this.apiKey) {
this.apiKey = currentKey;
}
console.log('API key available for contextualization:', !!this.apiKey);
if (!this.apiKey) {
console.log('No API key, returning fallback contextualization');
return `π Practice with classic literature from ${author}'s "${title}"`;
}
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': window.location.origin,
'X-Title': 'Cloze Reader'
},
body: JSON.stringify({
model: this.model,
messages: [{
role: 'system',
content: 'You are a literary expert. Provide exactly 1 short, factual sentence about this classic work. Be accurate and concise. Do not add fictional details or characters.'
}, {
role: 'user',
content: `Write one factual sentence about "${title}" by ${author}. Focus on what type of work it is, when it was written, or its historical significance.`
}],
max_tokens: 80,
temperature: 0.2
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('Contextualization API error:', response.status, errorText);
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
const content = data.choices[0].message.content.trim();
console.log('Contextualization received:', content);
return content;
} catch (error) {
console.error('Error getting contextualization:', error);
return `π Practice with classic literature from ${author}'s "${title}"`;
}
}
async getContextualization(title, author, passage) {
console.log('getContextualization called for:', title, 'by', author);
// Check for API key at runtime
const currentKey = this.getApiKey();
if (currentKey && !this.apiKey) {
this.apiKey = currentKey;
}
console.log('API key available for contextualization:', !!this.apiKey);
if (!this.apiKey) {
console.log('No API key, returning fallback contextualization');
return `π Practice with classic literature from ${author}'s "${title}"`;
}
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': window.location.origin,
'X-Title': 'Cloze Reader'
},
body: JSON.stringify({
model: this.model,
messages: [{
role: 'system',
content: 'You are a literary expert providing brief educational context about classic literature. Always respond with exactly 2 sentences, no more. Avoid exaggerative adverbs. Be factual and restrained.'
}, {
role: 'user',
content: `Provide educational context for this passage from "${title}" by ${author}: "${passage}"`
}],
max_tokens: 100,
temperature: 0.3
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('Contextualization API error:', response.status, errorText);
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
const content = data.choices[0].message.content.trim();
console.log('Contextualization received:', content);
return content;
} catch (error) {
console.error('Error getting contextualization:', error);
return `π Practice with classic literature from ${author}'s "${title}"`;
}
}
}
export { OpenRouterService as AIService }; |