Spaces:
Running
Running
fix api key loading and enhance ai prompts
Browse files- Add python-dotenv for proper .env file loading in FastAPI
- Update aiService retry delay from 1s to 0.5s for faster responses
- Enhance word selection with cloze deletion test principles
- Add capitalized words to word selection avoid list
- Improve contextualization prompt with Project Gutenberg expertise
- Increase batch processing max_tokens from 500 to 800
- Add JSON repair logic for unterminated strings
- Update batch processing temperature to 0.5 for better variance
- Add comprehensive AI prompts documentation
- app.py +4 -0
- docs/ai-prompts-and-parameters.md +204 -0
- requirements.txt +2 -1
- src/aiService.js +18 -6
app.py
CHANGED
@@ -2,6 +2,10 @@ from fastapi import FastAPI
|
|
2 |
from fastapi.responses import HTMLResponse, RedirectResponse
|
3 |
from fastapi.staticfiles import StaticFiles
|
4 |
import os
|
|
|
|
|
|
|
|
|
5 |
|
6 |
app = FastAPI()
|
7 |
|
|
|
2 |
from fastapi.responses import HTMLResponse, RedirectResponse
|
3 |
from fastapi.staticfiles import StaticFiles
|
4 |
import os
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
|
7 |
+
# Load environment variables from .env file
|
8 |
+
load_dotenv()
|
9 |
|
10 |
app = FastAPI()
|
11 |
|
docs/ai-prompts-and-parameters.md
ADDED
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# AI Prompts and Parameters Documentation
|
2 |
+
|
3 |
+
This document outlines the different types of AI requests, prompts, and parameters used in the Cloze Reader application.
|
4 |
+
|
5 |
+
## Overview
|
6 |
+
|
7 |
+
The Cloze Reader uses OpenRouter's API with the `google/gemma-3-27b-it:free` model to power various AI-driven features. All requests use a consistent retry mechanism with exponential backoff (3 attempts, 0.5s initial delay).
|
8 |
+
|
9 |
+
## Request Types
|
10 |
+
|
11 |
+
### 1. Contextual Hint Generation
|
12 |
+
|
13 |
+
**Purpose:** Generate hints for word puzzles without revealing the answer word.
|
14 |
+
|
15 |
+
**API Endpoint:** `https://openrouter.ai/api/v1/chat/completions`
|
16 |
+
|
17 |
+
**Parameters:**
|
18 |
+
```json
|
19 |
+
{
|
20 |
+
"model": "google/gemma-3-27b-it:free",
|
21 |
+
"messages": [
|
22 |
+
{
|
23 |
+
"role": "user",
|
24 |
+
"content": "You provide clues for word puzzles. You will be told the target word that players need to guess, but you must NEVER mention, spell, or reveal that word in your response. Follow the EXACT format requested. Be concise and direct about the target word without revealing it. Use plain text only - no bold, italics, asterisks, or markdown formatting. Stick to word limits.\n\n[CONTEXT AND PASSAGE]\n\nImportant: The hidden word is \"[TARGET_WORD]\". Never say this word directly - use \"it,\" \"this word,\" or \"the word\" instead.\n\nSuggest a word that could replace it in this sentence. Pick something simple and explain why it works. Under 15 words.\nExample: \"You could use 'bright' here - it captures the same feeling of intensity.\""
|
25 |
+
}
|
26 |
+
],
|
27 |
+
"max_tokens": 50,
|
28 |
+
"temperature": 0.6
|
29 |
+
}
|
30 |
+
```
|
31 |
+
|
32 |
+
**Example Request Body:**
|
33 |
+
```json
|
34 |
+
{
|
35 |
+
"model": "google/gemma-3-27b-it:free",
|
36 |
+
"messages": [
|
37 |
+
{
|
38 |
+
"role": "user",
|
39 |
+
"content": "You are a cluemaster for a fill-in-the-blank game rendering clues for word puzzles. You will be told the target word that players need to guess, but you must NEVER mention, spell, or reveal that word in your response. Follow the EXACT format requested. Be concise and direct about the target word without revealing it. Use plain text only - no bold, italics, asterisks, or markdown formatting. Stick to word limits.\n\nfrom \"William the Conqueror\" by Edward Augustus Freeman: \"Of bloodshed, of wanton interference\nwith law and usage, there is wonderfully little. Englishmen and Normans\nwere held to have ____ down in peace under the equal protection of\nKing William.\"\n\nImportant: The hidden word is \"settled\". Never say this word directly - use \"it,\" \"this word,\" or \"the word\" instead.\n\nSuggest a word that could replace it in this sentence. Pick something simple and explain why it works. Under 15 words.\nExample: \"You could use 'bright' here - it captures the same feeling of intensity.\""
|
40 |
+
}
|
41 |
+
],
|
42 |
+
"max_tokens": 50,
|
43 |
+
"temperature": 0.6
|
44 |
+
}
|
45 |
+
```
|
46 |
+
|
47 |
+
### 2. Word Selection for Cloze Exercises
|
48 |
+
|
49 |
+
**Purpose:** Select appropriate words to be blanked out in reading passages.
|
50 |
+
|
51 |
+
**Parameters:**
|
52 |
+
```json
|
53 |
+
{
|
54 |
+
"model": "google/gemma-3-27b-it:free",
|
55 |
+
"messages": [
|
56 |
+
{
|
57 |
+
"role": "user",
|
58 |
+
"content": "You are a cluemaster vocabulary selector for educational cloze exercises. Select exactly [COUNT] words from this passage for a cloze exercise.\n\nREQUIREMENTS:\n- Choose clear, properly-spelled words (no OCR errors like \"andsatires\")\n- Select meaningful nouns, verbs, or adjectives (4-12 letters)\n- Words must appear EXACTLY as written in the passage\n- Avoid: capitalized words, function words, archaic terms, proper nouns, technical jargon\n- Skip any words that look malformed or concatenated\n\nReturn ONLY a JSON array of the selected words.\n\nPassage: \"[PASSAGE_TEXT]\""
|
59 |
+
}
|
60 |
+
],
|
61 |
+
"max_tokens": 100,
|
62 |
+
"temperature": 0.5
|
63 |
+
}
|
64 |
+
```
|
65 |
+
|
66 |
+
**Response Format:** JSON array of strings
|
67 |
+
```json
|
68 |
+
["word1", "word2", "word3"]
|
69 |
+
```
|
70 |
+
|
71 |
+
### 3. Batch Passage Processing
|
72 |
+
|
73 |
+
**Purpose:** Process two passages simultaneously to reduce API calls and improve performance.
|
74 |
+
|
75 |
+
**Parameters:**
|
76 |
+
```json
|
77 |
+
{
|
78 |
+
"model": "google/gemma-3-27b-it:free",
|
79 |
+
"messages": [
|
80 |
+
{
|
81 |
+
"role": "system",
|
82 |
+
"content": "Process two passages for a cloze reading exercise. For each passage: 1) Select words for blanks, 2) Generate a contextual introduction. Return a JSON object with both passages' data."
|
83 |
+
},
|
84 |
+
{
|
85 |
+
"role": "user",
|
86 |
+
"content": "Process these two passages for cloze exercises:\n\nPASSAGE 1:\nTitle: \"[BOOK1_TITLE]\" by [BOOK1_AUTHOR]\nText: \"[PASSAGE1_TEXT]\"\nSelect [COUNT] words for blanks.\n\nPASSAGE 2:\nTitle: \"[BOOK2_TITLE]\" by [BOOK2_AUTHOR]\nText: \"[PASSAGE2_TEXT]\"\nSelect [COUNT] words for blanks.\n\nFor each passage return:\n- \"words\": array of selected words (exactly as they appear)\n- \"context\": one-sentence intro about the book/author\n\nReturn as JSON: {\"passage1\": {...}, \"passage2\": {...}}"
|
87 |
+
}
|
88 |
+
],
|
89 |
+
"max_tokens": 500,
|
90 |
+
"temperature": 0.5
|
91 |
+
}
|
92 |
+
```
|
93 |
+
|
94 |
+
**Response Format:**
|
95 |
+
```json
|
96 |
+
{
|
97 |
+
"passage1": {
|
98 |
+
"words": ["word1", "word2"],
|
99 |
+
"context": "A one-sentence description of the book and author"
|
100 |
+
},
|
101 |
+
"passage2": {
|
102 |
+
"words": ["word3", "word4"],
|
103 |
+
"context": "A one-sentence description of the book and author"
|
104 |
+
}
|
105 |
+
}
|
106 |
+
```
|
107 |
+
|
108 |
+
### 4. Literary Contextualization
|
109 |
+
|
110 |
+
**Purpose:** Generate factual introductions about books and authors for educational context.
|
111 |
+
|
112 |
+
**Parameters:**
|
113 |
+
```json
|
114 |
+
{
|
115 |
+
"model": "google/gemma-3-27b-it:free",
|
116 |
+
"messages": [
|
117 |
+
{
|
118 |
+
"role": "user",
|
119 |
+
"content": "You are a historical and literary expert of public domain entries in Project Gutenberg. Write one factual sentence about \"[BOOK_TITLE]\" by [AUTHOR]. Focus on what type of work it is, when it was written, or its historical significance. Be accurate and concise."
|
120 |
+
}
|
121 |
+
],
|
122 |
+
"max_tokens": 80,
|
123 |
+
"temperature": 0.5
|
124 |
+
}
|
125 |
+
```
|
126 |
+
|
127 |
+
**Response Format:** Plain text sentence
|
128 |
+
```
|
129 |
+
|
130 |
+
"The Flockmaster of Poison Creek is a Western novel by George W. Ogden published in the early 20th century."
|
131 |
+
```
|
132 |
+
|
133 |
+
## Common Request Configuration
|
134 |
+
|
135 |
+
### Headers
|
136 |
+
All requests include these headers:
|
137 |
+
|
138 |
+
```javascript
|
139 |
+
{
|
140 |
+
'Content-Type': 'application/json',
|
141 |
+
'Authorization': `Bearer ${this.apiKey}`,
|
142 |
+
'HTTP-Referer': window.location.origin,
|
143 |
+
'X-Title': 'Cloze Reader'
|
144 |
+
}
|
145 |
+
```
|
146 |
+
|
147 |
+
### Parameter Patterns
|
148 |
+
|
149 |
+
| Feature | Max Tokens | Temperature | Retry Logic |
|
150 |
+
|---------|------------|-------------|-------------|
|
151 |
+
| Hints | 50 | 0.6 | 3 attempts |
|
152 |
+
| Word Selection | 100 | 0.3 | 3 attempts |
|
153 |
+
| Batch Processing | 500 | 0.3 | 3 attempts |
|
154 |
+
| Contextualization | 80 | 0.2 | 3 attempts |
|
155 |
+
|
156 |
+
### Temperature Guidelines
|
157 |
+
- **0.2**: Factual content (contextualization)
|
158 |
+
- **0.3**: Structured tasks (word selection, batch processing)
|
159 |
+
- **0.6**: Creative tasks (hint generation)
|
160 |
+
|
161 |
+
## Response Processing
|
162 |
+
|
163 |
+
### JSON Parsing Strategy
|
164 |
+
1. **Direct parsing**: Attempt to parse response as JSON
|
165 |
+
2. **Markdown extraction**: Extract JSON from code blocks (```json ... ```)
|
166 |
+
3. **Cleanup**: Remove markdown artifacts and fix truncated JSON
|
167 |
+
4. **Fallback extraction**: Use regex to extract partial data
|
168 |
+
|
169 |
+
### Artifact Removal
|
170 |
+
All responses are cleaned to remove AI formatting artifacts:
|
171 |
+
```javascript
|
172 |
+
content = content
|
173 |
+
.replace(/^\s*["']|["']\s*$/g, '') // Remove leading/trailing quotes
|
174 |
+
.replace(/^\s*[:;]+\s*/, '') // Remove leading colons and semicolons
|
175 |
+
.replace(/\*+/g, '') // Remove asterisks (markdown bold/italic)
|
176 |
+
.replace(/_+/g, '') // Remove underscores (markdown)
|
177 |
+
.replace(/#+\s*/g, '') // Remove hash symbols (markdown headers)
|
178 |
+
.replace(/\s+/g, ' ') // Normalize whitespace
|
179 |
+
.trim();
|
180 |
+
```
|
181 |
+
|
182 |
+
### Error Handling
|
183 |
+
- **API errors**: Check for `data.error` in OpenRouter responses
|
184 |
+
- **Malformed responses**: Validate response structure before processing
|
185 |
+
- **Graceful degradation**: Fall back to manual/simple methods when AI fails
|
186 |
+
- **Retry mechanism**: Exponential backoff with 3 attempts
|
187 |
+
|
188 |
+
## Implementation Notes
|
189 |
+
|
190 |
+
### Model Choice
|
191 |
+
- **Model**: `google/gemma-3-27b-it:free`
|
192 |
+
- **Rationale**: Free tier model suitable for educational use
|
193 |
+
- **Limitations**: Rate limiting requires batch processing and careful request management
|
194 |
+
|
195 |
+
### Rate Limiting Strategy
|
196 |
+
1. **Batch processing**: Combine multiple operations into single requests
|
197 |
+
2. **Two-passage system**: Process pairs of passages to reduce total API calls
|
198 |
+
3. **Fallback mechanisms**: Manual word selection when API unavailable
|
199 |
+
4. **Retry logic**: Handle temporary failures gracefully
|
200 |
+
|
201 |
+
### Security Considerations
|
202 |
+
- API keys loaded from environment variables via meta tags
|
203 |
+
- Keys excluded from version control via `.gitignore`
|
204 |
+
- HTTP-Referer header for request origin validation
|
requirements.txt
CHANGED
@@ -1,2 +1,3 @@
|
|
1 |
fastapi==0.104.1
|
2 |
-
uvicorn[standard]==0.24.0
|
|
|
|
1 |
fastapi==0.104.1
|
2 |
+
uvicorn[standard]==0.24.0
|
3 |
+
python-dotenv==1.0.0
|
src/aiService.js
CHANGED
@@ -20,7 +20,7 @@ class OpenRouterService {
|
|
20 |
this.apiKey = key;
|
21 |
}
|
22 |
|
23 |
-
async retryRequest(requestFn, maxRetries = 3, delayMs =
|
24 |
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
25 |
try {
|
26 |
return await requestFn();
|
@@ -140,13 +140,18 @@ ${prompt}`
|
|
140 |
model: this.model,
|
141 |
messages: [{
|
142 |
role: 'user',
|
143 |
-
content: `You are a vocabulary selector for educational cloze exercises. Select exactly ${count} words from this passage for a cloze exercise.
|
|
|
|
|
|
|
|
|
|
|
144 |
|
145 |
REQUIREMENTS:
|
146 |
- Choose clear, properly-spelled words (no OCR errors like "andsatires")
|
147 |
- Select meaningful nouns, verbs, or adjectives (4-12 letters)
|
148 |
- Words must appear EXACTLY as written in the passage
|
149 |
-
- Avoid: function words, archaic terms, proper nouns, technical jargon
|
150 |
- Skip any words that look malformed or concatenated
|
151 |
|
152 |
Return ONLY a JSON array of the selected words.
|
@@ -244,8 +249,8 @@ For each passage return:
|
|
244 |
|
245 |
Return as JSON: {"passage1": {...}, "passage2": {...}}`
|
246 |
}],
|
247 |
-
max_tokens:
|
248 |
-
temperature: 0.
|
249 |
})
|
250 |
});
|
251 |
|
@@ -282,6 +287,13 @@ Return as JSON: {"passage1": {...}, "passage2": {...}}`
|
|
282 |
.trim();
|
283 |
|
284 |
// Try to fix common JSON issues
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
285 |
// Check if JSON is truncated (missing closing braces)
|
286 |
const openBraces = (jsonString.match(/{/g) || []).length;
|
287 |
const closeBraces = (jsonString.match(/}/g) || []).length;
|
@@ -388,7 +400,7 @@ Return as JSON: {"passage1": {...}, "passage2": {...}}`
|
|
388 |
model: this.model,
|
389 |
messages: [{
|
390 |
role: 'user',
|
391 |
-
content: `You are a literary expert. Write one factual sentence about "${title}" by ${author}. Focus on what type of work it is, when it was written, or its historical significance. Be accurate and concise
|
392 |
}],
|
393 |
max_tokens: 80,
|
394 |
temperature: 0.2
|
|
|
20 |
this.apiKey = key;
|
21 |
}
|
22 |
|
23 |
+
async retryRequest(requestFn, maxRetries = 3, delayMs = 500) {
|
24 |
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
25 |
try {
|
26 |
return await requestFn();
|
|
|
140 |
model: this.model,
|
141 |
messages: [{
|
142 |
role: 'user',
|
143 |
+
content: `You are a cluemaster vocabulary selector for educational cloze exercises. Select exactly ${count} words from this passage for a cloze exercise.
|
144 |
+
|
145 |
+
CLOZE DELETION PRINCIPLES:
|
146 |
+
- Select words that require understanding context and vocabulary to identify
|
147 |
+
- Choose words essential for comprehension that test language ability
|
148 |
+
- Target words where deletion creates meaningful cognitive gaps
|
149 |
|
150 |
REQUIREMENTS:
|
151 |
- Choose clear, properly-spelled words (no OCR errors like "andsatires")
|
152 |
- Select meaningful nouns, verbs, or adjectives (4-12 letters)
|
153 |
- Words must appear EXACTLY as written in the passage
|
154 |
+
- Avoid: capitalized words, function words, archaic terms, proper nouns, technical jargon
|
155 |
- Skip any words that look malformed or concatenated
|
156 |
|
157 |
Return ONLY a JSON array of the selected words.
|
|
|
249 |
|
250 |
Return as JSON: {"passage1": {...}, "passage2": {...}}`
|
251 |
}],
|
252 |
+
max_tokens: 800,
|
253 |
+
temperature: 0.5
|
254 |
})
|
255 |
});
|
256 |
|
|
|
287 |
.trim();
|
288 |
|
289 |
// Try to fix common JSON issues
|
290 |
+
// Check for truncated strings (unterminated quotes)
|
291 |
+
const quoteCount = (jsonString.match(/"/g) || []).length;
|
292 |
+
if (quoteCount % 2 !== 0) {
|
293 |
+
// Add missing closing quote
|
294 |
+
jsonString += '"';
|
295 |
+
}
|
296 |
+
|
297 |
// Check if JSON is truncated (missing closing braces)
|
298 |
const openBraces = (jsonString.match(/{/g) || []).length;
|
299 |
const closeBraces = (jsonString.match(/}/g) || []).length;
|
|
|
400 |
model: this.model,
|
401 |
messages: [{
|
402 |
role: 'user',
|
403 |
+
content: `You are a historical and literary expert of public domain entries in Project Gutenberg. Write one factual sentence about "${title}" by ${author}. Focus on what type of work it is, when it was written, or its historical significance. Be accurate and concise.`
|
404 |
}],
|
405 |
max_tokens: 80,
|
406 |
temperature: 0.2
|