Repository navigation
Expand file tree
/
Copy pathopenaiModule.js
More file actions
814 lines (682 loc) · 27.2 KB
/
Copy pathopenaiModule.js
File metadata and controls
814 lines (682 loc) · 27.2 KB
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
import OpenAI from 'openai';
import dotenv from 'dotenv';
import config from './config.js';
import { writeQuestionPrompt, writeOutputPrompt } from './prompts/writePrompts.js';
import { editQuestionPrompt, editOutputPrompt } from './prompts/editPrompts.js';
import { textTypeClassificationPrompt } from './prompts/textTypeClassificationPrompt.js';
import { replyQuestionPrompt, replyOutputPrompt, initialReplyQuestionPrompt } from './prompts/replyPrompts.js';
import { factCheckPrompt, factCorrectionPrompt } from './prompts/factCheckingPrompt.js';
import { logger } from './config.js';
import { toneClassificationPrompt } from './prompts/toneClassificationPrompt.js';
import memoryManager from './memory/memoryManager.js';
import { dependencyAnalysisPrompt } from './prompts/dependencyAnalysisPrompt.js';
dotenv.config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
timeout: config.openai.timeout,
});
function updateFollowupStatus(conversationPlanning, followupNeeded) {
return {
...conversationPlanning,
followup_needed: followupNeeded
};
}
async function generateWriteQuestion(conversationPlanning) {
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}; A: ${q.response}`)
.join('\n');
const prompt = writeQuestionPrompt(qaFormat);
logger.section('OPENAI REQUEST (Question Generation)', {
prompt,
model: config.openai.write.question.model,
maxTokens: config.openai.write.question.maxTokens,
temperature: config.openai.write.question.temperature
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.write.question.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.write.question.maxTokens,
temperature: config.openai.write.question.temperature,
});
const responseText = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Question Generation)', {
rawResponse: responseText
});
// clean
const cleanedResponse = responseText.replace(/```json\n?|\n?```/g, '').trim();
logger.section('CLEANED RESPONSE', {
original: responseText,
cleaned: cleanedResponse
});
let parsedResponse;
try {
parsedResponse = JSON.parse(cleanedResponse);
logger.section('PARSED RESPONSE', parsedResponse);
} catch (parseError) {
logger.warn('Failed to parse cleaned response:', parseError);
logger.info('Attempting to fix response format...');
// Fallback parsing logic
const questionMatch = cleanedResponse.match(/"question"\s*:\s*"([^"]+)"/);
const followupMatch = cleanedResponse.match(/"followup_needed"\s*:\s*(true|false)/);
if (questionMatch && followupMatch) {
parsedResponse = {
question: questionMatch[1],
followup_needed: followupMatch[1] === 'true'
};
logger.section('FALLBACK PARSED RESPONSE', parsedResponse);
} else {
throw new Error('Could not parse response into required format');
}
}
const { question, followup_needed } = parsedResponse;
// find the maxisting ID to avoid conflicts when questions are removed
const maxId = conversationPlanning.questions.reduce((max, q) => Math.max(max, q.id), 0);
let updatedConversationPlanning = {
...conversationPlanning,
questions: [
...conversationPlanning.questions,
{
id: maxId + 1,
question,
response: ''
}
]
};
updatedConversationPlanning = updateFollowupStatus(updatedConversationPlanning, followup_needed);
logger.section('FINAL RESULT', {
question,
followup_needed,
updatedQuestionCount: updatedConversationPlanning.questions.length
});
return { question, conversationPlanning: updatedConversationPlanning };
} catch (error) {
logger.error('Failed to generate question:', error);
throw error;
}
}
async function generateWriteOutput(conversationPlanning, toneClassification) {
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}; A: ${q.response}`)
.join('\n');
const prompt = writeOutputPrompt(qaFormat, toneClassification);
logger.section('OPENAI REQUEST (Output Generation)', {
prompt,
model: config.openai.write.output.model,
maxTokens: config.openai.write.output.maxTokens,
temperature: config.openai.write.output.temperature
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.write.output.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.write.output.maxTokens,
temperature: config.openai.write.output.temperature,
});
const output = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Output Generation)', {
output,
length: output.length
});
return output;
} catch (error) {
logger.error('Failed to generate output:', error);
throw error;
}
}
async function generateEditQuestion(originalText, conversationPlanning) {
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}; A: ${q.response}`)
.join('\n');
const prompt = editQuestionPrompt(originalText, qaFormat);
logger.info('\n=== SENDING TO OPENAI (Edit Question Generation) ===');
logger.info('Prompt:', prompt);
logger.info('================================================\n');
try {
const completion = await openai.chat.completions.create({
model: config.openai.edit.question.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.edit.question.maxTokens,
temperature: config.openai.edit.question.temperature,
});
const responseText = completion.choices[0].message.content.trim();
logger.info('Raw OpenAI response:', responseText);
const cleanedResponse = responseText.replace(/```json\n?|\n?```/g, '').trim();
let parsedResponse;
try {
parsedResponse = JSON.parse(cleanedResponse);
} catch (parseError) {
logger.warn('Failed to parse cleaned response:', parseError);
const questionMatch = cleanedResponse.match(/"question"\s*:\s*"([^"]+)"/);
const followupMatch = cleanedResponse.match(/"followup_needed"\s*:\s*(true|false)/);
if (questionMatch && followupMatch) {
parsedResponse = {
question: questionMatch[1],
followup_needed: followupMatch[1] === 'true'
};
} else {
throw new Error('Could not parse response into required format');
}
}
const { question, followup_needed } = parsedResponse;
//fnd the max existing ID to avoid conflicts when questions are removed
const maxId = conversationPlanning.questions.reduce((max, q) => Math.max(max, q.id), 0);
let updatedConversationPlanning = {
...conversationPlanning,
questions: [
...conversationPlanning.questions,
{
id: maxId + 1,
question,
response: ''
}
]
};
updatedConversationPlanning = updateFollowupStatus(updatedConversationPlanning, followup_needed);
logger.section('FINAL RESULT', {
question,
followup_needed,
updatedQuestionCount: updatedConversationPlanning.questions.length
});
return { question, conversationPlanning: updatedConversationPlanning };
} catch (error) {
logger.error('Failed to generate edit question:', error);
throw error;
}
}
async function generateEditOutput(originalText, conversationPlanning) {
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}; A: ${q.response}`)
.join('\n');
const prompt = editOutputPrompt(originalText, qaFormat);
logger.info('\n=== SENDING TO OPENAI (Edit Output Generation) ===');
logger.info('Prompt:', prompt);
logger.info('=============================================\n');
try {
const completion = await openai.chat.completions.create({
model: config.openai.edit.output.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.edit.output.maxTokens,
temperature: config.openai.edit.output.temperature,
});
const output = completion.choices[0].message.content.trim();
logger.info('Generated edit output:', output);
return output;
} catch (error) {
logger.error('Failed to generate edit output:', error);
throw error;
}
}
async function classifyTextType(text) {
const prompt = textTypeClassificationPrompt(text);
logger.section('TEXT TYPE CLASSIFICATION REQUEST', {
text: text.substring(0, 100) + (text.length > 100 ? '...' : ''),
model: config.openai.textTypeClassification.model,
temperature: config.openai.textTypeClassification.temperature,
maxTokens: config.openai.textTypeClassification.maxTokens
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.textTypeClassification.model,
messages: [{ role: 'system', content: prompt }],
temperature: config.openai.textTypeClassification.temperature,
max_tokens: config.openai.textTypeClassification.maxTokens,
});
const type = completion.choices[0].message.content.trim().toLowerCase();
logger.section('TEXT TYPE CLASSIFICATION RESULT', {
rawResponse: type,
validCategories: config.openai.textTypeClassification.validCategories,
defaultCategory: config.openai.textTypeClassification.defaultCategory,
finalType: config.openai.textTypeClassification.validCategories.includes(type)
? type
: config.openai.textTypeClassification.defaultCategory
});
return config.openai.textTypeClassification.validCategories.includes(type)
? type
: config.openai.textTypeClassification.defaultCategory;
} catch (error) {
logger.error('Error in text type classification:', {
error: error.message,
stack: error.stack,
defaultingTo: config.openai.textTypeClassification.defaultCategory
});
return config.openai.textTypeClassification.defaultCategory;
}
}
// Simple utility function to process email templates
function processEmailTemplate(originalText) {
let processedText = originalText;
// Get user name from memory if available
const userName = memoryManager.isEnabled() ? memoryManager.getUserName() || "Student" : "Student";
// Replace the {Name} placeholder with the user's name from memory
processedText = originalText.replace(/\{Name\}/g, userName);
return { processedText, extractedName: userName };
}
async function generateReplyQuestion(originalText, conversationPlanning) {
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}; A: ${q.response}`)
.join('\n');
// Process template variables in the original text
const { processedText, extractedName } = processEmailTemplate(originalText);
const prompt = replyQuestionPrompt(processedText, qaFormat);
logger.section('OPENAI REQUEST (Reply Question Generation)', {
prompt,
model: config.openai.reply.question.model,
maxTokens: config.openai.reply.question.maxTokens,
temperature: config.openai.reply.question.temperature,
extractedRecipientName: extractedName
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.reply.question.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.reply.question.maxTokens,
temperature: config.openai.reply.question.temperature,
});
const responseText = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Reply Question Generation)', {
rawResponse: responseText
});
const cleanedResponse = responseText.replace(/```json\n?|\n?```/g, '').trim();
let parsedResponse;
try {
parsedResponse = JSON.parse(cleanedResponse);
} catch (parseError) {
logger.warn('Failed to parse cleaned response:', parseError);
const questionMatch = cleanedResponse.match(/"question"\s*:\s*"([^"]+)"/);
const followupMatch = cleanedResponse.match(/"followup_needed"\s*:\s*(true|false)/);
if (questionMatch && followupMatch) {
parsedResponse = {
question: questionMatch[1],
followup_needed: followupMatch[1] === 'true'
};
} else {
throw new Error('Could not parse response into required format');
}
}
const { question, followup_needed } = parsedResponse;
// Find the maximum existing ID to avoid conflicts when questions are removed
const maxId = conversationPlanning.questions.reduce((max, q) => Math.max(max, q.id), 0);
let updatedConversationPlanning = {
...conversationPlanning,
questions: [
...conversationPlanning.questions,
{
id: maxId + 1,
question,
response: ''
}
]
};
updatedConversationPlanning = updateFollowupStatus(updatedConversationPlanning, followup_needed);
logger.section('FINAL RESULT', {
question,
followup_needed,
updatedQuestionCount: updatedConversationPlanning.questions.length
});
return { question, conversationPlanning: updatedConversationPlanning };
} catch (error) {
logger.error('Failed to generate reply question:', error);
throw error;
}
}
async function generateReplyOutput(originalText, conversationPlanning, toneClassification) {
// Format Q&A with proper newlines and spacing
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}\nA: ${q.response}`)
.join('\n\n');
// Process template variables in the original text
const { processedText, extractedName } = processEmailTemplate(originalText);
const prompt = replyOutputPrompt(processedText, qaFormat, toneClassification);
logger.section('OPENAI REQUEST (Reply Output Generation)', {
prompt,
model: config.openai.reply.output.model,
maxTokens: config.openai.reply.output.maxTokens,
temperature: config.openai.reply.output.temperature,
originalTextLength: processedText.length,
qaFormatLength: qaFormat.length,
questionsCount: conversationPlanning.questions.length,
hasTone: !!toneClassification,
extractedRecipientName: extractedName
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.reply.output.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.reply.output.maxTokens,
temperature: config.openai.reply.output.temperature,
});
const output = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Reply Output Generation)', {
output,
length: output.length,
words: output.split(/\s+/).length
});
return output;
} catch (error) {
logger.error('Failed to generate reply output:', error);
throw error;
}
}
async function performFactCheck(qaFormat, output) {
const prompt = factCheckPrompt(qaFormat, output);
logger.section('FACT CHECK REQUEST', {
qaFormat,
output,
prompt
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.factChecking.check.model,
messages: [{ role: 'system', content: prompt }],
temperature: config.openai.factChecking.check.temperature,
max_tokens: config.openai.factChecking.check.maxTokens,
});
const responseText = completion.choices[0].message.content.trim();
//cleaning json response
const cleanedResponse = responseText
.replace(/^```json\s*/, '') // Remove opening JSON code block
.replace(/\s*```$/, '') // Remove closing code block
.trim(); // Remove any extra whitespace
try {
const parsedResponse = JSON.parse(cleanedResponse);
logger.section('FACT CHECK RESULTS', {
rawResponse: responseText,
cleaned: cleanedResponse,
parsed: parsedResponse,
passed: parsedResponse.passed,
issueCount: parsedResponse.issues.length,
issues: parsedResponse.issues
});
return parsedResponse;
} catch (parseError) {
logger.error('Failed to parse fact check response:', {
error: parseError,
responseText,
cleanedResponse
});
// Return a default response to prevent complete failure
return {
passed: false,
issues: [{
type: "error",
detail: "Failed to parse fact check response",
qa_reference: "System error"
}]
};
}
} catch (error) {
logger.error('Failed to perform fact check:', error);
throw error;
}
}
async function generateCorrection(qaFormat, output, issues) {
const prompt = factCorrectionPrompt(qaFormat, output, issues);
try {
const completion = await openai.chat.completions.create({
model: config.openai.factChecking.correction.model,
messages: [{ role: 'system', content: prompt }],
temperature: config.openai.factChecking.correction.temperature,
max_tokens: config.openai.factChecking.correction.maxTokens,
});
return completion.choices[0].message.content.trim();
} catch (error) {
logger.error('Failed to generate correction:', error);
throw error;
}
}
async function generateBackgroundDraft(conversationPlanning, toneClassification, context = null) {
logger.section('BACKGROUND DRAFT GENERATION', {
questionsCount: conversationPlanning.questions.length,
answeredQuestions: conversationPlanning.questions.filter(q => q.response && q.response.trim()).length,
factCheckingEnabled: config.openai.continuousDrafts.factCheckContinuousDrafts
});
// here we generate the background draft without fact-checking for speed (configurable)
if (!config.openai.continuousDrafts.factCheckContinuousDrafts) {
const draft = context
? await generateReplyOutput(context, conversationPlanning, toneClassification)
: await generateWriteOutput(conversationPlanning, toneClassification);
logger.section('BACKGROUND DRAFT COMPLETE', {
draft: draft.substring(0, 200) + '...',
length: draft.length
});
return draft;
}
//if fact-checking is enabled for continuous drafts, use the full process
return await generateOutputWithFactCheck(conversationPlanning, toneClassification, context);
}
async function generateOutputWithFactCheck(conversationPlanning, toneClassification, context = null) {
logger.section('FACT CHECKING STATUS', {
enabled: config.openai.factChecking.enabled,
maxAttempts: config.openai.factChecking.maxAttempts
});
if (!config.openai.factChecking.enabled) {
logger.info('Fact checking disabled, generating output without verification');
return context
? await generateReplyOutput(context, conversationPlanning, toneClassification)
: await generateWriteOutput(conversationPlanning, toneClassification);
}
const qaFormat = conversationPlanning.questions
.map(q => `Q: ${q.question}\nA: ${q.response}`)
.join('\n\n');
let attempts = 0;
logger.section('INITIAL OUTPUT GENERATION', {
questionsCount: conversationPlanning.questions.length,
qaFormat
});
// Process context if it exists (for email templates)
let processedContext = context;
let extractedName = null;
if (context) {
const templateResult = processEmailTemplate(context);
processedContext = templateResult.processedText;
extractedName = templateResult.extractedName;
logger.section('CONTEXT PROCESSING', {
originalContextLength: context.length,
processedContextLength: processedContext.length,
extractedRecipientName: extractedName
});
}
// Generate initial output using appropriate function
let output = context
? await generateReplyOutput(processedContext, conversationPlanning, toneClassification)
: await generateWriteOutput(conversationPlanning, toneClassification);
while (attempts < config.openai.factChecking.maxAttempts) {
attempts++;
logger.section(`FACT CHECK ATTEMPT ${attempts}/${config.openai.factChecking.maxAttempts}`, {
currentOutput: output
});
const checkResult = await performFactCheck(qaFormat, output);
if (checkResult.passed) {
logger.section('FACT CHECK PASSED', {
finalOutput: output
});
return output;
}
logger.section('FACT CHECK FAILED', {
issuesFound: checkResult.issues.length,
issues: checkResult.issues
});
if (attempts === config.openai.factChecking.maxAttempts) {
logger.warn('Maximum fact check attempts reached');
}
// Generate correction based on issues
const correctionPrompt = factCorrectionPrompt(qaFormat, output, checkResult.issues, toneClassification);
logger.section('GENERATING CORRECTION', {
attempt: attempts,
prompt: correctionPrompt
});
const completion = await openai.chat.completions.create({
model: config.openai.factChecking.correction.model,
messages: [{ role: 'system', content: correctionPrompt }],
temperature: config.openai.factChecking.correction.temperature,
max_tokens: config.openai.factChecking.correction.maxTokens,
});
output = completion.choices[0].message.content.trim();
logger.section('CORRECTION RESULT', {
correctedOutput: output
});
}
logger.section('FACT CHECK FINAL STATUS', {
status: 'Maximum attempts reached without passing fact check',
attemptsUsed: attempts,
finalOutput: output
});
return output;
}
async function classifyTone(qaFormat, originalText = '') {
// Process template variables in the original text if provided
let processedText = originalText;
let extractedName = null;
if (originalText) {
const templateResult = processEmailTemplate(originalText);
processedText = templateResult.processedText;
extractedName = templateResult.extractedName;
}
const prompt = toneClassificationPrompt(qaFormat, processedText);
logger.section('TONE CLASSIFICATION REQUEST', {
prompt,
model: config.openai.toneClassification.model,
temperature: config.openai.toneClassification.temperature,
hasOriginalText: !!originalText,
qaFormatLength: qaFormat.length,
extractedRecipientName: extractedName
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.toneClassification.model,
messages: [{ role: 'system', content: prompt }],
temperature: config.openai.toneClassification.temperature,
max_tokens: config.openai.toneClassification.maxTokens,
});
const responseText = completion.choices[0].message.content.trim();
const cleanedResponse = responseText.replace(/```json\n?|\n?```/g, '').trim();
try {
const parsedResponse = JSON.parse(cleanedResponse);
logger.section('TONE CLASSIFICATION RESULT', {
tone: parsedResponse.tone,
confidence: parsedResponse.confidence,
reasoning: parsedResponse.reasoning,
rawResponse: responseText
});
return parsedResponse;
} catch (parseError) {
logger.error('Error parsing tone classification response:', {
error: parseError,
responseText,
cleanedResponse
});
return {
tone: 'FORMAL_PROFESSIONAL',
confidence: 1.0,
reasoning: 'Default tone due to parsing error'
};
}
} catch (error) {
logger.error('Error in tone classification:', {
error: error.message,
stack: error.stack
});
throw error;
}
}
async function generateInitialReplyQuestion(originalText) {
// Process template variables in the original text
const { processedText, extractedName } = processEmailTemplate(originalText);
const prompt = initialReplyQuestionPrompt(processedText);
logger.section('OPENAI REQUEST (Initial Reply Question Generation)', {
model: config.openai.initialReplyQuestion.model,
temperature: config.openai.initialReplyQuestion.temperature,
maxTokens: config.openai.initialReplyQuestion.maxTokens,
extractedRecipientName: extractedName
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.initialReplyQuestion.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.initialReplyQuestion.maxTokens,
temperature: config.openai.initialReplyQuestion.temperature,
});
const question = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Initial Reply Question Generation)', {
question
});
return question;
} catch (error) {
logger.error('Failed to generate initial reply question:', error);
return "How would you like to respond to this message?";
}
}
async function analyzeDependencies(originalAnswer, newAnswer, changedQuestionId, allQuestions) {
const prompt = dependencyAnalysisPrompt(originalAnswer, newAnswer, changedQuestionId, allQuestions);
logger.section('OPENAI REQUEST (Dependency Analysis)', {
prompt,
model: config.openai.dependencyAnalysis.model,
maxTokens: config.openai.dependencyAnalysis.maxTokens,
temperature: config.openai.dependencyAnalysis.temperature,
changedQuestionId,
totalQuestions: allQuestions.length
});
try {
const completion = await openai.chat.completions.create({
model: config.openai.dependencyAnalysis.model,
messages: [{ role: 'system', content: prompt }],
max_tokens: config.openai.dependencyAnalysis.maxTokens,
temperature: config.openai.dependencyAnalysis.temperature,
});
const responseText = completion.choices[0].message.content.trim();
logger.section('OPENAI RESPONSE (Dependency Analysis)', {
rawResponse: responseText
});
// cleaning json response
const cleanedResponse = responseText.replace(/```json\n?|\n?```/g, '').trim();
let parsedResponse;
try {
parsedResponse = JSON.parse(cleanedResponse);
logger.section('PARSED DEPENDENCY ANALYSIS', parsedResponse);
} catch (parseError) {
logger.warn('Failed to parse dependency analysis response:', parseError);
logger.info('Falling back to conservative approach (invalidate all)');
// fallback: mark all subsequent questions as affected
const subsequentQuestions = allQuestions.filter(q => q.id > changedQuestionId);
parsedResponse = {
affectedQuestions: subsequentQuestions.map(q => ({
questionId: q.id,
question: q.question,
status: 'AFFECTED',
reasoning: 'Fallback due to parsing error - invalidating for safety'
})),
summary: 'Parsing failed, using conservative approach'
};
}
return parsedResponse;
} catch (error) {
logger.error('Failed to analyze dependencies:', error);
//fallback: mark all subsequent questions as affected
const subsequentQuestions = allQuestions.filter(q => q.id > changedQuestionId);
return {
affectedQuestions: subsequentQuestions.map(q => ({
questionId: q.id,
question: q.question,
status: 'AFFECTED',
reasoning: 'Error in analysis - invalidating for safety'
})),
summary: 'Analysis failed, using conservative approach'
};
}
}
export {
generateWriteQuestion,
generateWriteOutput,
generateEditQuestion,
generateEditOutput,
generateReplyQuestion,
generateReplyOutput,
classifyTextType,
generateOutputWithFactCheck,
generateBackgroundDraft,
classifyTone,
generateInitialReplyQuestion,
performFactCheck,
analyzeDependencies
};