Hma47 commited on
Commit
a0cb69d
·
verified ·
1 Parent(s): b8bb3b2

Upload 4 files

Browse files
Files changed (4) hide show
  1. Apache License.txt +17 -0
  2. README.md +95 -0
  3. index.html +651 -0
  4. 📘 Enhanced Collaborative guide.txt +181 -0
Apache License.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2025 Shift Mind AI Labs
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: "✍️ Enhanced Collaborative Writing with AI"
3
+ emoji: "🤝"
4
+ colorFrom: "red"
5
+ colorTo: "yellow"
6
+ sdk: "static"
7
+ sdk_version: "0.1.0"
8
+ app_file: "index.html"
9
+ pinned: false
10
+ ---
11
+
12
+ # ✍️ Enhanced Collaborative Writing with AI
13
+ **Developed by Shift Mind AI Labs**
14
+
15
+ Enhanced Collaborative Writing with AI is an open-source, privacy-first tool designed to empower students, teachers, and creative professionals to co-author texts with real-time AI support. With a wide range of roles, writing styles, and intelligent feedback powered by GPT-4o-mini, the tool supports academic, creative, technical, and storytelling tasks for all learners.
16
+
17
+ ---
18
+
19
+ ## 🚀 Features
20
+
21
+ - **Multiple Writing Roles:** Choose from Literature Author, Academic Researcher, Journalist, Consultant, Storyteller, Creative Writer, Technical Writer, and more.
22
+ - **AI Collaboration:** The AI generates contextually relevant text, continues ideas, expands, adds contrast, or moves toward conclusions.
23
+ - **Personal & AI Contributions Highlighted:** Easily distinguish your own writing from AI-generated content.
24
+ - **Rephrase & Revise:** Instantly rephrase AI contributions for better clarity, tone, or content.
25
+ - **Writing Analytics:** Real-time stats on word count, character count, and number of AI contributions.
26
+ - **Progress Tracking:** Visual panel for context and writing journey.
27
+ - **Client-side Privacy:** All logic and data storage are local; your OpenAI API key and writing never leave your browser.
28
+
29
+ ---
30
+
31
+ ## 🛠 How to Use
32
+
33
+ 1. **Open the tool** in your browser (no installation or login required).
34
+ 2. **Enter your OpenAI API key** (your key is stored only in your browser for this session).
35
+ 3. **Choose your subject/topic and writing role/style.**
36
+ 4. **Start writing:**
37
+ - Write and edit your own text.
38
+ - Use the AI to continue, expand, or rephrase as needed.
39
+ - Switch roles or styles for different genres.
40
+ 5. **Review statistics and progress** in real time.
41
+ 6. **Finish and export:**
42
+ - Copy, download, or share your final document and process stats.
43
+
44
+ ---
45
+
46
+ ## 👩‍🏫 For Teachers: Classroom Applications
47
+
48
+ - Collaborative essays, reports, and stories
49
+ - Genre-based writing workshops
50
+ - Feedback and revision practice
51
+ - Differentiation for struggling and advanced writers
52
+ - Evidence for formative assessment and writing portfolios
53
+
54
+ ---
55
+
56
+ ## 👨‍🎓 For Students: Benefits
57
+
58
+ - Experiment with genres and voices
59
+ - Build confidence and fluency
60
+ - Learn from real-time AI modeling
61
+ - Receive targeted, actionable feedback
62
+ - Own your creative process with privacy and control
63
+
64
+ ---
65
+
66
+ ## 🔐 Data Privacy
67
+
68
+ - Your OpenAI API key and all writing are only stored in your browser.
69
+ - No data is transmitted to Shift Mind AI Labs, Hugging Face, or third parties.
70
+
71
+ ---
72
+
73
+ ## 📄 License
74
+
75
+ Licensed under the [Apache License 2.0](./LICENSE).
76
+
77
+ ---
78
+
79
+ ## 🧠 About Shift Mind AI Labs
80
+
81
+ Shift Mind AI Labs creates open-source, ethical AI tools to support creativity, education, and global learning.
82
+
83
+ 🌐 https://www.shiftmind.io
84
+ ✉️ info@shiftmind.io
85
+
86
+ ---
87
+
88
+ ## 🙌 Contributing
89
+
90
+ Pull requests, feedback, and collaborations are welcome!
91
+ For pilots, partnerships, or school integration: **info@shiftmind.io**
92
+
93
+ ---
94
+
95
+ *Empowering every writer to collaborate, reflect, and grow—together with AI.*
index.html ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Enhanced Collaborative Writing with AI (GPT-4o-mini)</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <style>
8
+ body { background: #f5f7fa; font-family: 'Segoe UI', Arial, sans-serif; color: #333; margin: 0; }
9
+ .container { max-width: 760px; margin: 40px auto; background: #fff; border-radius: 14px; box-shadow: 0 2px 18px rgba(44,62,80,0.10); padding: 36px 26px 22px 26px; }
10
+ h1 { text-align: center; color: #154360; }
11
+ label { font-weight: 500; margin-bottom: 7px; display: block; }
12
+ [contenteditable="true"] {
13
+ width: 100%; min-height: 180px; font-size: 1.07rem; border: 1px solid #bbb; border-radius: 7px;
14
+ padding: 13px; background: #f6fafd; margin-bottom: 12px; box-sizing: border-box; outline: none;
15
+ white-space: pre-wrap; line-height: 1.6;
16
+ }
17
+ .ai-text {
18
+ background: #fffac2;
19
+ color: #664d03;
20
+ border-radius: 4px;
21
+ padding: 0 2px;
22
+ margin-right:2px;
23
+ transition: background 0.3s;
24
+ }
25
+ .user-text {
26
+ background: #e4ffd5;
27
+ color: #217c33;
28
+ border-radius: 4px;
29
+ padding: 0 2px;
30
+ margin-right:2px;
31
+ transition: background 0.3s;
32
+ }
33
+ select, input[type="text"], input[type="password"] {
34
+ width: 98%; padding: 7px 1%; border-radius: 7px; border: 1px solid #bbb; font-size: 1rem; margin-bottom: 8px;
35
+ }
36
+ select { width: 99%; }
37
+ .role-desc {
38
+ background: #f8f8fa;
39
+ border-left: 5px solid #2471a3;
40
+ padding: 12px 16px;
41
+ border-radius: 6px;
42
+ margin-bottom: 13px;
43
+ font-size: 0.98rem;
44
+ color: #555;
45
+ min-height: 72px;
46
+ }
47
+ .button-bar { display: flex; gap: 14px; margin-top: 6px; margin-bottom: 10px; }
48
+ button { background: #2e86de; color: #fff; border: none; border-radius: 7px; padding: 9px 24px; font-size: 1rem; cursor: pointer; transition: background 0.3s; }
49
+ button:hover:not(:disabled) { background: #0b7dda; }
50
+ button:disabled { background: #b2bec3; cursor: not-allowed; }
51
+ #ai-status { font-size: 1rem; color: #2e86de; text-align: left; margin-bottom: 9px; min-height: 20px;}
52
+ .final-output { background: #f1f8f5; border-radius: 8px; padding: 18px; margin-top: 22px; font-size: 1.07rem;}
53
+ .api-key-label { color: #a93226; margin-top: 6px;}
54
+ .writing-stats {
55
+ background: #f8f9fa;
56
+ border-radius: 6px;
57
+ padding: 8px 12px;
58
+ margin-bottom: 10px;
59
+ font-size: 0.9rem;
60
+ color: #666;
61
+ display: flex;
62
+ justify-content: space-between;
63
+ }
64
+ .context-panel {
65
+ background: #f0f4f8;
66
+ border-radius: 6px;
67
+ padding: 10px;
68
+ margin-bottom: 10px;
69
+ font-size: 0.85rem;
70
+ color: #555;
71
+ border-left: 3px solid #3498db;
72
+ }
73
+ .continuation-mode {
74
+ display: flex;
75
+ gap: 10px;
76
+ margin-bottom: 10px;
77
+ align-items: center;
78
+ }
79
+ .continuation-mode label {
80
+ margin: 0;
81
+ font-size: 0.9rem;
82
+ }
83
+ .continuation-mode select {
84
+ width: auto;
85
+ margin: 0;
86
+ }
87
+ @media (max-width:800px){ .container{padding:12px 3vw;} }
88
+ </style>
89
+ </head>
90
+ <body>
91
+ <div class="container">
92
+ <h1>Enhanced Collaborative Writing with AI (<span style="color:#2471a3;">GPT-4o-mini</span>)</h1>
93
+ <label for="api-key-input" class="api-key-label">OpenAI API Key <span style="font-weight:400;color:#666;">(never shared, stored only in this session)</span>:</label>
94
+ <input id="api-key-input" type="password" placeholder="sk-...">
95
+
96
+ <label for="subject-input">Subject or Topic:</label>
97
+ <input id="subject-input" type="text" placeholder="e.g., The importance of teamwork">
98
+
99
+ <label for="role-select">Select the Agent's Writing Role/Style:</label>
100
+ <select id="role-select">
101
+ <option value="literature">Literature Author</option>
102
+ <option value="researcher">Academic Researcher</option>
103
+ <option value="journalist">Journalist</option>
104
+ <option value="consultant">Consultant / Advisor</option>
105
+ <option value="storyteller">Storyteller (Children's)</option>
106
+ <option value="creative">Creative Writer</option>
107
+ <option value="technical">Technical Writer</option>
108
+ </select>
109
+ <div id="role-desc" class="role-desc"></div>
110
+
111
+ <button id="start-btn">Start Writing</button>
112
+
113
+ <div id="editor-section" style="display:none;">
114
+ <div class="writing-stats">
115
+ <span id="word-count">Words: 0</span>
116
+ <span id="char-count">Characters: 0</span>
117
+ <span id="contribution-count">AI Contributions: 0</span>
118
+ </div>
119
+
120
+ <div class="continuation-mode">
121
+ <label for="continuation-style">AI Continuation Style:</label>
122
+ <select id="continuation-style">
123
+ <option value="smooth">Smooth Flow</option>
124
+ <option value="expand">Expand Ideas</option>
125
+ <option value="contrast">Add Contrast</option>
126
+ <option value="conclude">Move Toward Conclusion</option>
127
+ </select>
128
+ </div>
129
+
130
+ <div class="continuation-mode">
131
+ <label for="sentence-count">AI Sentences to Add:</label>
132
+ <select id="sentence-count">
133
+ <option value="1">1 sentence</option>
134
+ <option value="2" selected>2 sentences</option>
135
+ <option value="3">3 sentences</option>
136
+ <option value="4">4 sentences</option>
137
+ <option value="5">5 sentences</option>
138
+ </select>
139
+ </div>
140
+
141
+ <div id="context-panel" class="context-panel" style="display:none;">
142
+ <strong>Current Context:</strong> <span id="context-summary"></span>
143
+ </div>
144
+
145
+ <label for="writing-area">Your Collaborative Writing</label>
146
+ <div id="writing-area" contenteditable="true" spellcheck="true"></div>
147
+ <div id="ai-status"></div>
148
+ <div class="button-bar">
149
+ <button id="ai-continue-btn">AI Continue</button>
150
+ <button id="ai-rephrase-btn" style="background:#8e44ad;">Rephrase Last</button>
151
+ <button id="finish-btn" style="background:#27ae60;">Finish</button>
152
+ </div>
153
+ </div>
154
+
155
+ <div id="final-output" class="final-output" style="display:none;"></div>
156
+ </div>
157
+
158
+ <script>
159
+ // Enhanced agent roles with better context awareness
160
+ const agentRoles = {
161
+ literature: {
162
+ name: "Literature Author",
163
+ description: `• Rich imagery, metaphors, and emotional depth<br>
164
+ • Character development and atmospheric setting<br>
165
+ • Poetic language with symbolic meaning<br>
166
+ • Builds narrative tension and mood progressively`,
167
+ system: `You are a masterful literary author. Write with rich, evocative language that creates vivid imagery and emotional resonance. Use metaphors, symbolism, and sensory details. Develop characters and atmosphere. Each contribution should deepen the narrative and maintain literary quality while flowing naturally from the existing text.`
168
+ },
169
+ researcher: {
170
+ name: "Academic Researcher",
171
+ description: `• Evidence-based and analytically rigorous<br>
172
+ • Structured arguments with logical progression<br>
173
+ • Technical precision and scholarly tone<br>
174
+ • Builds comprehensive understanding systematically`,
175
+ system: `You are a distinguished academic researcher. Write with precision, analytical depth, and scholarly rigor. Support points with evidence, maintain logical structure, and use appropriate technical language. Each contribution should advance the argument or analysis while building on previous points systematically.`
176
+ },
177
+ journalist: {
178
+ name: "Journalist",
179
+ description: `• Clear, factual, and compelling narrative<br>
180
+ • Investigative depth with human interest<br>
181
+ • Balanced perspective with key details<br>
182
+ • Engages readers while informing thoroughly`,
183
+ system: `You are an experienced journalist. Write with clarity, accuracy, and engaging narrative flow. Focus on key facts, human interest, and balanced reporting. Each contribution should advance the story, reveal new information, or provide deeper context while maintaining journalistic integrity.`
184
+ },
185
+ consultant: {
186
+ name: "Consultant / Advisor",
187
+ description: `• Strategic insights with actionable recommendations<br>
188
+ • Problem-solving framework and solutions<br>
189
+ • Professional tone with clear next steps<br>
190
+ • Builds comprehensive strategic understanding`,
191
+ system: `You are a senior strategic consultant. Write with authority, providing actionable insights and recommendations. Use frameworks, strategic thinking, and solution-oriented language. Each contribution should build the case, provide analysis, or offer concrete next steps that advance the overall strategic narrative.`
192
+ },
193
+ storyteller: {
194
+ name: "Storyteller (Children's)",
195
+ description: `• Engaging, age-appropriate language with wonder<br>
196
+ • Clear moral lessons through entertaining narrative<br>
197
+ • Rhythmic, memorable phrases and repetition<br>
198
+ • Builds excitement and learning progressively`,
199
+ system: `You are a beloved children's storyteller. Write with warmth, wonder, and age-appropriate language. Use gentle repetition, clear moral lessons, and engaging narrative elements. Each contribution should advance the story, develop characters, or reinforce the central message while maintaining child-friendly appeal.`
200
+ },
201
+ creative: {
202
+ name: "Creative Writer",
203
+ description: `• Innovative narrative techniques and perspectives<br>
204
+ • Experimental language and unique voice<br>
205
+ • Unexpected connections and creative insights<br>
206
+ • Pushes boundaries while maintaining coherence`,
207
+ system: `You are an innovative creative writer. Experiment with language, perspective, and narrative techniques. Bring fresh insights and unexpected connections. Each contribution should surprise while maintaining coherence, advancing the creative vision, and building on established themes in novel ways.`
208
+ },
209
+ technical: {
210
+ name: "Technical Writer",
211
+ description: `• Clear, precise explanations of complex concepts<br>
212
+ • Step-by-step logical progression<br>
213
+ • Practical examples and applications<br>
214
+ • Builds comprehensive technical understanding`,
215
+ system: `You are an expert technical writer. Explain complex concepts with clarity and precision. Use logical progression, practical examples, and clear structure. Each contribution should build technical understanding, provide concrete details, or advance the explanation while remaining accessible and well-organized.`
216
+ }
217
+ };
218
+
219
+ // Enhanced continuation styles
220
+ const continuationStyles = {
221
+ smooth: "Continue the narrative flow naturally, maintaining the same tone and building on the immediate context.",
222
+ expand: "Elaborate on the ideas presented, adding depth, examples, or additional perspectives to enrich the content.",
223
+ contrast: "Introduce a contrasting viewpoint, alternative perspective, or counterpoint to create intellectual tension.",
224
+ conclude: "Guide the writing toward a natural conclusion, summarizing key points or bringing the narrative to closure."
225
+ };
226
+
227
+ // Global variables
228
+ let writingContext = {
229
+ subject: "",
230
+ overallTheme: "",
231
+ keyPoints: [],
232
+ lastUserContribution: "",
233
+ narrativeDirection: "",
234
+ toneConsistency: "",
235
+ aiContributions: 0,
236
+ totalWords: 0
237
+ };
238
+
239
+ // Elements
240
+ const apiKeyInput = document.getElementById('api-key-input');
241
+ const subjectInput = document.getElementById('subject-input');
242
+ const roleSelect = document.getElementById('role-select');
243
+ const roleDesc = document.getElementById('role-desc');
244
+ const startBtn = document.getElementById('start-btn');
245
+ const editorSection = document.getElementById('editor-section');
246
+ const writingArea = document.getElementById('writing-area');
247
+ const aiContinueBtn = document.getElementById('ai-continue-btn');
248
+ const aiRephraseBtn = document.getElementById('ai-rephrase-btn');
249
+ const aiStatus = document.getElementById('ai-status');
250
+ const finishBtn = document.getElementById('finish-btn');
251
+ const finalOutput = document.getElementById('final-output');
252
+ const continuationStyle = document.getElementById('continuation-style');
253
+ const sentenceCount = document.getElementById('sentence-count');
254
+ const contextPanel = document.getElementById('context-panel');
255
+ const contextSummary = document.getElementById('context-summary');
256
+ const wordCount = document.getElementById('word-count');
257
+ const charCount = document.getElementById('char-count');
258
+ const contributionCount = document.getElementById('contribution-count');
259
+
260
+ // Display role description
261
+ function updateRoleDesc() {
262
+ const role = roleSelect.value;
263
+ roleDesc.innerHTML = `<b>${agentRoles[role].name}:</b><br>${agentRoles[role].description}`;
264
+ }
265
+ updateRoleDesc();
266
+ roleSelect.onchange = updateRoleDesc;
267
+
268
+ // Update writing statistics
269
+ function updateStats() {
270
+ const text = writingArea.textContent || "";
271
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
272
+ const chars = text.length;
273
+
274
+ wordCount.textContent = `Words: ${words}`;
275
+ charCount.textContent = `Characters: ${chars}`;
276
+ contributionCount.textContent = `AI Contributions: ${writingContext.aiContributions}`;
277
+ writingContext.totalWords = words;
278
+ }
279
+
280
+ // Analyze and update context
281
+ function analyzeContext() {
282
+ const fullText = writingArea.textContent || "";
283
+ const sentences = fullText.split(/[.!?]+/).filter(s => s.trim().length > 0);
284
+
285
+ if (sentences.length > 0) {
286
+ const lastSentences = sentences.slice(-3).join('. ');
287
+ contextSummary.textContent = lastSentences.substring(0, 100) + (lastSentences.length > 100 ? '...' : '');
288
+ contextPanel.style.display = 'block';
289
+ }
290
+ }
291
+
292
+ // Enhanced AI call with better context management
293
+ async function callOpenAI(apiKey, agentSystemPrompt, context, isRephrase = false) {
294
+ const fullText = writingArea.textContent || "";
295
+ const {allText, lastUserText, textSegments} = getEnhancedContext(writingArea);
296
+
297
+ // Build comprehensive context
298
+ const contextPrompt = `
299
+ WRITING CONTEXT:
300
+ - Subject: "${writingContext.subject}"
301
+ - Current word count: ${writingContext.totalWords}
302
+ - AI contributions so far: ${writingContext.aiContributions}
303
+ - Continuation style requested: ${continuationStyles[continuationStyle.value]}
304
+ - Last user contribution: "${lastUserText}"
305
+
306
+ FULL TEXT SO FAR:
307
+ """${allText}"""
308
+
309
+ INSTRUCTIONS:
310
+ ${isRephrase ?
311
+ 'Rephrase the last AI contribution to be more engaging and better integrated with the user\'s writing. Keep the same general meaning but improve flow and style.' :
312
+ `Write exactly ${sentenceCount.value} sentence${sentenceCount.value > 1 ? 's' : ''} that continue this collaborative piece naturally. ${continuationStyles[continuationStyle.value]}
313
+
314
+ CRITICAL REQUIREMENTS:
315
+ - Write EXACTLY ${sentenceCount.value} sentence${sentenceCount.value > 1 ? 's' : ''} - no more, no less
316
+ - Do NOT repeat or echo the user's last contribution
317
+ - Maintain consistent tone and style throughout
318
+ - Build on existing themes and narrative direction
319
+ - Each sentence should advance the content meaningfully
320
+ - Ensure smooth transitions from previous text
321
+ - Respond ONLY with the continuation text, no explanations`
322
+ }`;
323
+
324
+ const messages = [
325
+ { role: "system", content: agentSystemPrompt },
326
+ { role: "user", content: contextPrompt }
327
+ ];
328
+
329
+ const body = {
330
+ model: "gpt-4o-mini",
331
+ messages,
332
+ max_tokens: isRephrase ? 100 : Math.min(200, parseInt(sentenceCount.value) * 40),
333
+ temperature: 0.7,
334
+ presence_penalty: 0.6,
335
+ frequency_penalty: 0.3
336
+ };
337
+
338
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
339
+ method: "POST",
340
+ headers: {
341
+ "Content-Type": "application/json",
342
+ "Authorization": "Bearer " + apiKey
343
+ },
344
+ body: JSON.stringify(body)
345
+ });
346
+
347
+ if (!response.ok) {
348
+ let msg = "Unknown error";
349
+ try { msg = (await response.json()).error?.message || msg; } catch { }
350
+ throw new Error(msg);
351
+ }
352
+
353
+ const data = await response.json();
354
+ const aiText = data.choices[0].message.content.trim();
355
+
356
+ // Update context tracking
357
+ if (!isRephrase) {
358
+ writingContext.aiContributions++;
359
+ writingContext.lastUserContribution = lastUserText;
360
+ }
361
+
362
+ return aiText;
363
+ }
364
+
365
+ // Enhanced context extraction
366
+ function getEnhancedContext(container) {
367
+ let allText = '';
368
+ let lastUserText = '';
369
+ let textSegments = [];
370
+ let currentSegment = { type: 'user', text: '' };
371
+
372
+ const processNode = (node) => {
373
+ if (node.nodeType === 3) { // Text node
374
+ const text = node.textContent;
375
+ if (text.trim()) {
376
+ allText += text;
377
+ currentSegment.text += text;
378
+ if (currentSegment.type === 'user') {
379
+ lastUserText = text.trim();
380
+ }
381
+ }
382
+ } else if (node.nodeType === 1) { // Element node
383
+ if (node.classList.contains('ai-text')) {
384
+ if (currentSegment.text.trim()) {
385
+ textSegments.push({...currentSegment});
386
+ }
387
+ currentSegment = { type: 'ai', text: node.textContent };
388
+ allText += node.textContent;
389
+ textSegments.push({...currentSegment});
390
+ currentSegment = { type: 'user', text: '' };
391
+ } else if (node.classList.contains('user-text')) {
392
+ allText += node.textContent;
393
+ currentSegment.text += node.textContent;
394
+ lastUserText = node.textContent.trim();
395
+ } else if (node.tagName === 'BR') {
396
+ allText += '\n';
397
+ currentSegment.text += '\n';
398
+ } else {
399
+ for (let child of node.childNodes) {
400
+ processNode(child);
401
+ }
402
+ }
403
+ }
404
+ };
405
+
406
+ for (let node of container.childNodes) {
407
+ processNode(node);
408
+ }
409
+
410
+ if (currentSegment.text.trim()) {
411
+ textSegments.push(currentSegment);
412
+ }
413
+
414
+ return { allText: allText.trim(), lastUserText: lastUserText.trim(), textSegments };
415
+ }
416
+
417
+ // Start writing functionality
418
+ startBtn.onclick = async () => {
419
+ const apiKey = apiKeyInput.value.trim();
420
+ if (!apiKey.startsWith('sk-') || apiKey.length < 30) {
421
+ apiKeyInput.value = "";
422
+ apiKeyInput.focus();
423
+ apiKeyInput.placeholder = "Please enter a valid OpenAI API key!";
424
+ return;
425
+ }
426
+
427
+ const subject = subjectInput.value.trim();
428
+ if (!subject) {
429
+ subjectInput.focus();
430
+ subjectInput.placeholder = "Please enter a subject!";
431
+ return;
432
+ }
433
+
434
+ // Initialize context
435
+ writingContext.subject = subject;
436
+ writingContext.aiContributions = 0;
437
+ writingContext.totalWords = 0;
438
+
439
+ // Disable inputs
440
+ apiKeyInput.disabled = true;
441
+ subjectInput.disabled = true;
442
+ roleSelect.disabled = true;
443
+ startBtn.disabled = true;
444
+
445
+ // Show editor
446
+ editorSection.style.display = '';
447
+ aiStatus.textContent = "AI is crafting the opening...";
448
+ aiContinueBtn.disabled = true;
449
+ aiRephraseBtn.disabled = true;
450
+ writingArea.innerHTML = "";
451
+
452
+ try {
453
+ const agentSystemPrompt = agentRoles[roleSelect.value].system;
454
+ const aiText = await callOpenAI(apiKey, agentSystemPrompt, { subject, isOpening: true });
455
+
456
+ writingArea.innerHTML = `<span class="ai-text">${escapeHTML(aiText)}</span>`;
457
+ placeCaretAtEnd(writingArea);
458
+
459
+ aiStatus.textContent = "Great start! Add your thoughts and click 'AI Continue' when ready.";
460
+ aiContinueBtn.disabled = false;
461
+ writingArea.focus();
462
+
463
+ updateStats();
464
+ analyzeContext();
465
+
466
+ } catch (e) {
467
+ aiStatus.textContent = "Error: " + e.message;
468
+ apiKeyInput.disabled = false;
469
+ startBtn.disabled = false;
470
+ roleSelect.disabled = false;
471
+ }
472
+ };
473
+
474
+ // AI Continue functionality
475
+ aiContinueBtn.onclick = async () => {
476
+ aiStatus.textContent = "AI is continuing the narrative...";
477
+ aiContinueBtn.disabled = true;
478
+ aiRephraseBtn.disabled = true;
479
+ writingArea.contentEditable = "false";
480
+
481
+ // Highlight user contributions
482
+ writingArea.innerHTML = buildHTMLWithUserHighlight(writingArea);
483
+
484
+ try {
485
+ const apiKey = apiKeyInput.value.trim();
486
+ const agentSystemPrompt = agentRoles[roleSelect.value].system;
487
+ const aiText = await callOpenAI(apiKey, agentSystemPrompt, writingContext);
488
+
489
+ insertAIText(aiText);
490
+
491
+ aiStatus.textContent = "Your turn! Edit, add more, or click 'AI Continue' for the next contribution.";
492
+ writingArea.contentEditable = "true";
493
+ aiContinueBtn.disabled = false;
494
+ aiRephraseBtn.disabled = false;
495
+
496
+ placeCaretAtEnd(writingArea);
497
+ writingArea.focus();
498
+
499
+ updateStats();
500
+ analyzeContext();
501
+
502
+ } catch (e) {
503
+ aiStatus.textContent = "Error: " + e.message;
504
+ writingArea.contentEditable = "true";
505
+ aiContinueBtn.disabled = false;
506
+ aiRephraseBtn.disabled = false;
507
+ }
508
+ };
509
+
510
+ // AI Rephrase functionality
511
+ aiRephraseBtn.onclick = async () => {
512
+ const aiSpans = writingArea.querySelectorAll('.ai-text');
513
+ if (aiSpans.length === 0) {
514
+ aiStatus.textContent = "No AI contributions to rephrase yet.";
515
+ return;
516
+ }
517
+
518
+ aiStatus.textContent = "AI is rephrasing the last contribution...";
519
+ aiContinueBtn.disabled = true;
520
+ aiRephraseBtn.disabled = true;
521
+
522
+ try {
523
+ const apiKey = apiKeyInput.value.trim();
524
+ const agentSystemPrompt = agentRoles[roleSelect.value].system;
525
+ const newText = await callOpenAI(apiKey, agentSystemPrompt, writingContext, true);
526
+
527
+ // Replace last AI contribution
528
+ const lastAISpan = aiSpans[aiSpans.length - 1];
529
+ lastAISpan.textContent = newText;
530
+
531
+ aiStatus.textContent = "Rephrased! Continue editing or add more content.";
532
+ aiContinueBtn.disabled = false;
533
+ aiRephraseBtn.disabled = false;
534
+
535
+ updateStats();
536
+ analyzeContext();
537
+
538
+ } catch (e) {
539
+ aiStatus.textContent = "Error: " + e.message;
540
+ aiContinueBtn.disabled = false;
541
+ aiRephraseBtn.disabled = false;
542
+ }
543
+ };
544
+
545
+ // Finish writing
546
+ finishBtn.onclick = () => {
547
+ editorSection.style.display = "none";
548
+ finalOutput.style.display = "";
549
+ finalOutput.innerHTML = `
550
+ <h2>Final Collaborative Writing</h2>
551
+ <div style="margin-bottom: 15px; font-size: 0.9rem; color: #666;">
552
+ <strong>Statistics:</strong> ${writingContext.totalWords} words, ${writingContext.aiContributions} AI contributions
553
+ </div>
554
+ <hr>
555
+ <div style="white-space: pre-line; line-height: 1.6;">${writingArea.innerHTML}</div>
556
+ <hr><br>
557
+ <a href="javascript:window.location.reload()" style="color:#2980b9; text-decoration: none;">Start New Writing Session</a>
558
+ `;
559
+ };
560
+
561
+ // Enhanced helper functions
562
+ function escapeHTML(str) {
563
+ return str.replace(/[&<>"']/g, function (m) {
564
+ return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[m];
565
+ });
566
+ }
567
+
568
+ function buildHTMLWithUserHighlight(container) {
569
+ let html = '';
570
+ for (let node of container.childNodes) {
571
+ if (node.nodeType === 1 && node.classList.contains('ai-text')) {
572
+ html += node.outerHTML;
573
+ } else if (node.nodeType === 3) {
574
+ let txt = node.textContent;
575
+ if (txt.trim()) {
576
+ html += `<span class="user-text">${escapeHTML(txt)}</span>`;
577
+ } else {
578
+ html += escapeHTML(txt);
579
+ }
580
+ } else if (node.nodeType === 1 && node.tagName === "BR") {
581
+ html += '<br>';
582
+ } else if (node.nodeType === 1 && !node.classList.contains('ai-text') && !node.classList.contains('user-text')) {
583
+ // Handle other elements
584
+ let innerText = node.textContent;
585
+ if (innerText.trim()) {
586
+ html += `<span class="user-text">${escapeHTML(innerText)}</span>`;
587
+ }
588
+ } else if (node.nodeType === 1) {
589
+ html += node.outerHTML;
590
+ }
591
+ }
592
+ return html;
593
+ }
594
+
595
+ function insertAIText(aiText) {
596
+ let html = writingArea.innerHTML.replace(/\s*$/, "");
597
+ let toInsert = `<span class="ai-text">${escapeHTML(aiText)}</span>`;
598
+
599
+ // Smart spacing logic
600
+ const currentText = writingArea.textContent || "";
601
+ if (currentText && !currentText.match(/[.!?]\s*$/)) {
602
+ if (aiText.match(/^[A-Z]/)) {
603
+ toInsert = ". " + toInsert;
604
+ } else {
605
+ toInsert = " " + toInsert;
606
+ }
607
+ } else if (currentText) {
608
+ toInsert = " " + toInsert;
609
+ }
610
+
611
+ writingArea.innerHTML = html + toInsert;
612
+ }
613
+
614
+ function placeCaretAtEnd(el) {
615
+ el.focus();
616
+ if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
617
+ let range = document.createRange();
618
+ range.selectNodeContents(el);
619
+ range.collapse(false);
620
+ let sel = window.getSelection();
621
+ sel.removeAllRanges();
622
+ sel.addRange(range);
623
+ }
624
+ }
625
+
626
+ // Enhanced input handling
627
+ writingArea.addEventListener('input', function() {
628
+ writingArea.innerHTML = buildHTMLWithUserHighlight(writingArea);
629
+ placeCaretAtEnd(writingArea);
630
+ updateStats();
631
+ analyzeContext();
632
+ });
633
+
634
+ // Auto-save functionality (in memory)
635
+ let autoSaveData = {};
636
+ setInterval(() => {
637
+ if (writingArea.innerHTML) {
638
+ autoSaveData = {
639
+ content: writingArea.innerHTML,
640
+ subject: writingContext.subject,
641
+ role: roleSelect.value,
642
+ stats: {
643
+ words: writingContext.totalWords,
644
+ contributions: writingContext.aiContributions
645
+ }
646
+ };
647
+ }
648
+ }, 30000); // Auto-save every 30 seconds
649
+ </script>
650
+ </body>
651
+ </html>
📘 Enhanced Collaborative guide.txt ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 📘 Enhanced Collaborative Writing with AI: Teacher & Student Guide
2
+ 1. Introduction
3
+ Enhanced Collaborative Writing with AI is a next-generation writing tool that empowers students, teachers, and creative professionals to co-author texts with real-time AI assistance. Leveraging GPT-4o-mini, the tool supports a range of writing purposes (literary, academic, journalistic, technical, storytelling, and more) and offers tailored support to nurture writing fluency, critical thinking, and collaborative skills—all in a privacy-first, browser-based environment.
4
+
5
+ 2. Getting Started
6
+ A. System & Privacy Requirements
7
+ No installation, signup, or login required.
8
+
9
+ Works in any modern browser (Chrome, Edge, Safari, Firefox, etc.).
10
+
11
+ All content, including your OpenAI API key, stays local to your device and is never sent to a third party except OpenAI (for AI completions).
12
+
13
+ B. Initial Setup
14
+ Open the Application:
15
+ Navigate to the provided web page or run the HTML file locally.
16
+
17
+ Enter OpenAI API Key:
18
+
19
+ Required for AI-powered writing and feedback.
20
+
21
+ Your key is never shared or stored outside your session.
22
+
23
+ Enter Your Subject or Topic:
24
+
25
+ Define the writing focus (e.g., “The Importance of Teamwork,” “Climate Change in Urban Areas,” or “Creative Short Story”).
26
+
27
+ Select the Writing Role/Style:
28
+
29
+ Choose from Literature Author, Academic Researcher, Journalist, Consultant, Storyteller (Children’s), Creative Writer, or Technical Writer.
30
+
31
+ The tool displays a description of the selected style for guidance.
32
+
33
+ 3. Collaborative Writing Workflow
34
+ A. Starting a Session
35
+ Click Start Writing to begin.
36
+
37
+ The AI generates an opening passage in your chosen style and subject.
38
+
39
+ B. Interactive Writing Area
40
+ The editor will now be active, showing:
41
+
42
+ Writing statistics: word count, character count, and number of AI contributions.
43
+
44
+ Continuation controls:
45
+
46
+ AI Continuation Style: Choose how the AI will add to your text (Smooth Flow, Expand Ideas, Add Contrast, Move Toward Conclusion).
47
+
48
+ AI Sentences to Add: Choose 1–5 sentences per AI contribution.
49
+
50
+ C. Writing, Collaboration, and Revision
51
+ Write and Edit:
52
+
53
+ Add your own text anywhere in the document.
54
+
55
+ All user-written text is visually highlighted for clarity.
56
+
57
+ Request AI Collaboration:
58
+
59
+ Click AI Continue to have the AI add sentences according to your chosen style and amount.
60
+
61
+ AI contributions appear in a different highlight color for transparency.
62
+
63
+ Rephrase AI Content:
64
+
65
+ If the AI’s last addition isn’t ideal, click Rephrase Last to ask for a fresh alternative.
66
+
67
+ Monitor Context Panel:
68
+
69
+ The tool summarizes the current context to ensure narrative coherence, especially in longer works.
70
+
71
+ Track Progress:
72
+
73
+ Writing statistics update in real time to help with goal-setting and self-regulation.
74
+
75
+ D. Completion & Output
76
+ When finished, click Finish:
77
+
78
+ A summary window appears, showing the final text, word count, and AI contributions.
79
+
80
+ Option to copy, save, or start a new session.
81
+
82
+ 4. Classroom Integration & Teacher Use
83
+ A. Pedagogical Applications
84
+ Collaborative Essays & Reports:
85
+
86
+ Pairs/groups can co-write with AI to generate drafts, arguments, and revisions.
87
+
88
+ Writing Workshops:
89
+
90
+ Use different roles/styles to illustrate genre differences and voice.
91
+
92
+ Feedback & Revision:
93
+
94
+ Students analyze, critique, and rephrase both AI and peer-generated content.
95
+
96
+ Personalized Support:
97
+
98
+ The tool provides scaffolding for struggling writers and challenges for advanced students.
99
+
100
+ Creative Writing & Storytelling:
101
+
102
+ Experiment with narrative, style, and collaborative storytelling.
103
+
104
+ B. Assessment & Differentiation
105
+ Formative Assessment:
106
+
107
+ Track progress via statistics, drafts, and contributions.
108
+
109
+ Portfolio Evidence:
110
+
111
+ Finished pieces and process logs can be used for portfolios and progress tracking.
112
+
113
+ Differentiated Instruction:
114
+
115
+ Assign roles or styles based on student needs/interests.
116
+
117
+ C. Practical Classroom Tips
118
+ Group Dynamics:
119
+
120
+ Assign collaborative groups different sections or styles to merge later.
121
+
122
+ Reflection Activities:
123
+
124
+ Have students reflect on the AI’s choices, their own revisions, and the collaborative process.
125
+
126
+ Skill Building:
127
+
128
+ Focus on genre, voice, tone, structure, and argument development in context.
129
+
130
+ 5. Student Guidance: Making the Most of the Tool
131
+ A. Personal Writing Growth
132
+ Experiment with Roles:
133
+
134
+ Try different writing styles/roles to build flexibility and creativity.
135
+
136
+ Learn from AI:
137
+
138
+ Study the AI’s contributions—what makes them effective? Where can you improve or diverge?
139
+
140
+ Iterate & Revise:
141
+
142
+ Use the rephrase feature and edit freely; writing is a process.
143
+
144
+ Set Goals:
145
+
146
+ Use the statistics to challenge yourself (e.g., word count targets, number of revisions).
147
+
148
+ B. Ethical & Critical Use
149
+ AI as a Co-Writer, Not a Replacement:
150
+
151
+ Balance AI help with your own voice and ideas.
152
+
153
+ Critical Thinking:
154
+
155
+ Evaluate AI-generated text—does it make sense? Is it relevant, factual, and original?
156
+
157
+ Academic Integrity:
158
+
159
+ Always cite sources for factual or research-based work.
160
+
161
+ 6. Best Practices & Advanced Tips
162
+ Draft Multiple Versions:
163
+
164
+ Use the tool to create different drafts and compare outcomes.
165
+
166
+ Peer Review:
167
+
168
+ Share your output with classmates or teachers for further feedback.
169
+
170
+ Advanced Styles:
171
+
172
+ Adjust the AI continuation style (Expand Ideas, Add Contrast, etc.) for richer, more complex writing.
173
+
174
+ Collaborative Projects:
175
+
176
+ Use in group assignments where students and AI alternate contributions for a true “collaborative authorship” experience.
177
+
178
+ 7. Support, Troubleshooting, and Contact
179
+ API Key Security:
180
+
181
+ Never share your OpenAI key. It is stored only for your session and is required for AI-powered writing.