File size: 8,451 Bytes
a918c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# AI Prompts and Parameters Documentation

This document outlines the different types of AI requests, prompts, and parameters used in the Cloze Reader application.

## Overview

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).

## Request Types

### 1. Contextual Hint Generation

**Purpose:** Generate hints for word puzzles without revealing the answer word.

**API Endpoint:** `https://openrouter.ai/api/v1/chat/completions`

**Parameters:**
```json
{
  "model": "google/gemma-3-27b-it:free",
  "messages": [
    {
      "role": "user", 
      "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.\""
    }
  ],
  "max_tokens": 50,
  "temperature": 0.6
}
```

**Example Request Body:**
```json
{
  "model": "google/gemma-3-27b-it:free",
  "messages": [
    {
      "role": "user",
      "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.\""
    }
  ],
  "max_tokens": 50,
  "temperature": 0.6
}
```

### 2. Word Selection for Cloze Exercises

**Purpose:** Select appropriate words to be blanked out in reading passages.

**Parameters:**
```json
{
  "model": "google/gemma-3-27b-it:free",
  "messages": [
    {
      "role": "user",
      "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]\""
    }
  ],
  "max_tokens": 100,
  "temperature": 0.5
}
```

**Response Format:** JSON array of strings
```json
["word1", "word2", "word3"]
```

### 3. Batch Passage Processing

**Purpose:** Process two passages simultaneously to reduce API calls and improve performance.

**Parameters:**
```json
{
  "model": "google/gemma-3-27b-it:free",
  "messages": [
    {
      "role": "system",
      "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."
    },
    {
      "role": "user",
      "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\": {...}}"
    }
  ],
  "max_tokens": 500,
  "temperature": 0.5
}
```

**Response Format:**
```json
{
  "passage1": {
    "words": ["word1", "word2"],
    "context": "A one-sentence description of the book and author"
  },
  "passage2": {
    "words": ["word3", "word4"],
    "context": "A one-sentence description of the book and author"
  }
}
```

### 4. Literary Contextualization

**Purpose:** Generate factual introductions about books and authors for educational context.

**Parameters:**
```json
{
  "model": "google/gemma-3-27b-it:free",
  "messages": [
    {
      "role": "user",
      "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."
    }
  ],
  "max_tokens": 80,
  "temperature": 0.5
}
```

**Response Format:** Plain text sentence
```

"The Flockmaster of Poison Creek is a Western novel by George W. Ogden published in the early 20th century."
```

## Common Request Configuration

### Headers
All requests include these headers:

```javascript
{
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${this.apiKey}`,
  'HTTP-Referer': window.location.origin,
  'X-Title': 'Cloze Reader'
}
```

### Parameter Patterns

| Feature | Max Tokens | Temperature | Retry Logic |
|---------|------------|-------------|-------------|
| Hints | 50 | 0.6 | 3 attempts |
| Word Selection | 100 | 0.3 | 3 attempts |
| Batch Processing | 500 | 0.3 | 3 attempts |
| Contextualization | 80 | 0.2 | 3 attempts |

### Temperature Guidelines
- **0.2**: Factual content (contextualization)
- **0.3**: Structured tasks (word selection, batch processing)
- **0.6**: Creative tasks (hint generation)

## Response Processing

### JSON Parsing Strategy
1. **Direct parsing**: Attempt to parse response as JSON
2. **Markdown extraction**: Extract JSON from code blocks (```json ... ```)
3. **Cleanup**: Remove markdown artifacts and fix truncated JSON
4. **Fallback extraction**: Use regex to extract partial data

### Artifact Removal
All responses are cleaned to remove AI formatting artifacts:
```javascript
content = content
  .replace(/^\s*["']|["']\s*$/g, '')  // Remove leading/trailing quotes
  .replace(/^\s*[:;]+\s*/, '')        // Remove leading colons and semicolons
  .replace(/\*+/g, '')                // Remove asterisks (markdown bold/italic)
  .replace(/_+/g, '')                 // Remove underscores (markdown)
  .replace(/#+\s*/g, '')              // Remove hash symbols (markdown headers)
  .replace(/\s+/g, ' ')               // Normalize whitespace
  .trim();
```

### Error Handling
- **API errors**: Check for `data.error` in OpenRouter responses
- **Malformed responses**: Validate response structure before processing
- **Graceful degradation**: Fall back to manual/simple methods when AI fails
- **Retry mechanism**: Exponential backoff with 3 attempts

## Implementation Notes

### Model Choice
- **Model**: `google/gemma-3-27b-it:free`
- **Rationale**: Free tier model suitable for educational use
- **Limitations**: Rate limiting requires batch processing and careful request management

### Rate Limiting Strategy
1. **Batch processing**: Combine multiple operations into single requests
2. **Two-passage system**: Process pairs of passages to reduce total API calls
3. **Fallback mechanisms**: Manual word selection when API unavailable
4. **Retry logic**: Handle temporary failures gracefully

### Security Considerations
- API keys loaded from environment variables via meta tags
- Keys excluded from version control via `.gitignore`
- HTTP-Referer header for request origin validation