-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSheetAI.js
More file actions
1914 lines (1604 loc) · 63.5 KB
/
SheetAI.js
File metadata and controls
1914 lines (1604 loc) · 63.5 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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************
* Google Apps Script for OpenAI API Integration
* Made for you by https://www.zyxware.com
* Updates: https://github.com/zyxware/SheetAI
* Documentation: https://github.com/zyxware/SheetAI/blob/main/README.md
* Features:
* - Executes OpenAI prompts on Google Sheets data
* - Batch Processing Capability (supports up to 50,000 requests per batch)
* - Saves results back to the Data sheet
*********************************/
/**
* Configuration keys used in the Config sheet
*/
const CONFIG_KEYS = {
API_KEY: 'API_KEY',
DEFAULT_MODEL: 'DEFAULT_MODEL',
DEBUG: 'DEBUG',
BATCH_SIZE: 'BATCH_SIZE',
TEMPERATURE: 'TEMPERATURE',
MAX_TOKENS: 'MAX_TOKENS',
SEED: 'SEED'
};
/**
* Default values for configuration
*/
const CONFIG_DEFAULTS = {
DEFAULT_MODEL: 'gpt-4o-mini',
DEBUG: false,
BATCH_SIZE: 2000,
TEMPERATURE: 0,
MAX_TOKENS: 256,
SEED: 101
};
/**
* Gets a configuration value from the Config sheet
* @param {string} key - The configuration key
* @returns {any} The configuration value or undefined if not found
*/
function getConfigValue(key) {
var configSheet = getSheet('Config');
// If Config sheet doesn't exist, return undefined
if (!configSheet) {
return undefined;
}
var configData = configSheet.getDataRange().getValues();
// Look for the key in the Config sheet
for (var i = 0; i < configData.length; i++) {
if (configData[i][0] === key) {
return configData[i][1];
}
}
// Key not found
return undefined;
}
/**
* Gets the API key from the Config sheet
* @returns {string} The API key
*/
function getApiKey() {
return getConfigValue(CONFIG_KEYS.API_KEY);
}
/**
* Gets the default model from the Config sheet or uses the default
* @returns {string} The default model
*/
function getDefaultModel() {
var model = getConfigValue(CONFIG_KEYS.DEFAULT_MODEL);
return model !== undefined ? model : CONFIG_DEFAULTS.DEFAULT_MODEL;
}
/**
* Checks if debug mode is enabled
* @returns {boolean} True if debug mode is enabled
*/
function isDebugModeEnabled() {
var debug = getConfigValue(CONFIG_KEYS.DEBUG);
if (debug === undefined) {
return CONFIG_DEFAULTS.DEBUG;
}
return debug === true || debug === 'TRUE' || debug === 'Yes' || debug === 'true' || debug === 1 || debug === '1';
}
/**
* Validates that required configuration is set
* @returns {boolean} True if configuration is valid
*/
function validateConfig() {
var apiKey = getApiKey();
if (!apiKey) {
SpreadsheetApp.getUi().alert(
'Configuration Error',
'API_KEY is not set. Please create a sheet named "Config" with columns "Key" and "Value", ' +
'and add a row with Key="API_KEY" and Value=your_openai_api_key.',
SpreadsheetApp.getUi().ButtonSet.OK
);
return false;
}
return true;
}
// OpenAI Pricing Configuration
const PRICING_CONFIG = {
"gpt-4.5-preview": { "input_per_1m": 75.00, "cached_input_per_1m": 37.50, "output_per_1m": 150.00 },
"gpt-4o": { "input_per_1m": 2.50, "cached_input_per_1m": 1.25, "output_per_1m": 10.00 },
"gpt-4o-mini": { "input_per_1m": 0.15, "cached_input_per_1m": 0.075, "output_per_1m": 0.60 },
"gpt-4o-mini-audio-preview": { "input_per_1m": 0.15, "cached_input_per_1m": 0.075, "output_per_1m": 0.60 },
"gpt-4o-audio-preview": { "input_per_1m": 2.50, "cached_input_per_1m": 1.25, "output_per_1m": 10.00 },
"gpt-4o-mini-realtime-preview": { "input_per_1m": 0.60, "cached_input_per_1m": 0.30, "output_per_1m": 2.40 },
"gpt-4o-realtime-preview": { "input_per_1m": 5.00, "cached_input_per_1m": 2.50, "output_per_1m": 20.00 },
"o3-mini": { "input_per_1m": 1.10, "cached_input_per_1m": 0.55, "output_per_1m": 4.40 },
"o1-mini": { "input_per_1m": 1.10, "cached_input_per_1m": 0.55, "output_per_1m": 4.40 },
"o1": { "input_per_1m": 15.00, "cached_input_per_1m": 7.50, "output_per_1m": 60.00 }
};
// OpenAI Batch API Pricing Configuration
const PRICING_CONFIG_BATCH = {
"gpt-4o-mini": { "input_per_1m": 0.075, "output_per_1m": 0.30 },
"o3-mini": { "input_per_1m": 0.55, "output_per_1m": 2.20 },
"o1-mini": { "input_per_1m": 0.55, "output_per_1m": 2.20 },
"o1": { "input_per_1m": 7.50, "output_per_1m": 30.00 },
"gpt-4o": { "input_per_1m": 1.25, "output_per_1m": 5.00 },
"gpt-4.5-preview": { "input_per_1m": 37.50, "output_per_1m": 75.00 }
};
/* ======== UI Functions ======== */
function onOpen() {
// Create the menu
SpreadsheetApp.getUi()
.createMenu('OpenAI Tools')
.addItem('Run for First 10 Rows', 'runPromptsForFirst10Rows')
.addItem('Run for All Rows', 'runPromptsForAllRows')
.addSeparator()
.addItem('Create Batch', 'createBatchWithConfigLimit')
.addItem('Check and Process Batch', 'checkAndProcessNextCompletedBatch')
.addItem('Check Batch Status', 'checkBatchStatus')
.addToUi();
}
function runPromptsForFirst10Rows() {
if (!validateConfig()) return;
checkForUpdates();
runPrompts(10);
}
function runPromptsForAllRows() {
if (!validateConfig()) return;
checkForUpdates();
runPrompts(Infinity);
}
/**
* Gets the batch size from the Config sheet or uses the default
* @returns {number} The batch size
*/
function getBatchSize() {
var size = getConfigValue(CONFIG_KEYS.BATCH_SIZE);
return size !== undefined ? size : CONFIG_DEFAULTS.BATCH_SIZE;
}
function createBatchWithConfigLimit() {
if (!validateConfig()) return;
checkForUpdates();
// Check if a batch is already being created
var lock = LockService.getScriptLock();
if (!lock.tryLock(1000)) {
showAlert('Batch Creation in Progress',
'A batch is already being created. Please wait until it completes.',
SpreadsheetApp.getUi().ButtonSet.OK);
return;
}
try {
// Get the batch size from config
var batchSize = getBatchSize();
createBatch(Infinity, batchSize);
} finally {
lock.releaseLock();
}
}
function checkBatchStatus() {
if (!validateConfig()) return;
checkForUpdates();
var ui = SpreadsheetApp.getUi();
try {
// First check our local Batch Status sheet
var batchStatusSheet = getSheet('Batch Status');
if (batchStatusSheet.getLastRow() <= 1) {
showAlert('No Batches', 'No batch jobs were found in the Batch Status sheet.', ui.ButtonSet.OK);
return;
}
var batchData = batchStatusSheet.getDataRange().getValues();
var headers = batchData[0];
// Define column indices based on expected structure
var batchIdColIndex = headers.indexOf("Batch ID");
var openAIBatchIdColIndex = headers.indexOf("OpenAI Batch ID");
var statusColIndex = headers.indexOf("Status");
var createdAtColIndex = headers.indexOf("Created At");
var lastCheckedColIndex = headers.indexOf("Last Checked At");
var inputFileIdColIndex = headers.indexOf("Input File ID");
var outputFileIdColIndex = headers.indexOf("Output File ID");
var errorFileIdColIndex = headers.indexOf("Error File ID");
var totalRequestsColIndex = headers.indexOf("Total Requests");
var completedColIndex = headers.indexOf("Completed");
var failedColIndex = headers.indexOf("Failed");
var processedColIndex = headers.indexOf("Processed");
// Add Processed column if it doesn't exist
if (processedColIndex < 0) {
processedColIndex = headers.length;
batchStatusSheet.getRange(1, processedColIndex + 1).setValue("Processed");
headers.push("Processed");
// Initialize all existing rows with "No" for Processed
for (var i = 1; i < batchData.length; i++) {
batchStatusSheet.getRange(i + 1, processedColIndex + 1).setValue("No");
}
}
if (openAIBatchIdColIndex < 0 || statusColIndex < 0) {
showAlert('Error', 'Batch Status sheet is missing required columns.', ui.ButtonSet.OK);
return;
}
// Get all batches from OpenAI
var openAIBatches = fetchAllBatches();
var openAIBatchesMap = {};
// Create a map for quick lookup
for (var i = 0; i < openAIBatches.length; i++) {
openAIBatchesMap[openAIBatches[i].id] = openAIBatches[i];
}
var updatedCount = 0;
// Update status for each batch in our sheet
for (var i = 1; i < batchData.length; i++) {
var openAIBatchId = batchData[i][openAIBatchIdColIndex];
var currentStatus = batchData[i][statusColIndex];
var currentProcessed = batchData[i][processedColIndex] || "No";
// Skip batches that are already processed
if (currentProcessed === "Yes") continue;
// Check if this batch exists in OpenAI
if (openAIBatchId && openAIBatchesMap[openAIBatchId]) {
var openAIBatch = openAIBatchesMap[openAIBatchId];
// If the status has changed or we need to update counts
if (openAIBatch.status !== currentStatus ||
(completedColIndex >= 0 && openAIBatch.request_counts.completed !== batchData[i][completedColIndex])) {
// Get the full batch details
var fullBatchDetails = retrieveBatch(openAIBatchId);
// Update status
batchStatusSheet.getRange(i + 1, statusColIndex + 1).setValue(fullBatchDetails.status);
batchStatusSheet.getRange(i + 1, lastCheckedColIndex + 1).setValue(new Date().toISOString());
// Update request counts
if (totalRequestsColIndex >= 0) {
batchStatusSheet.getRange(i + 1, totalRequestsColIndex + 1).setValue(fullBatchDetails.request_counts.total);
}
if (completedColIndex >= 0) {
batchStatusSheet.getRange(i + 1, completedColIndex + 1).setValue(fullBatchDetails.request_counts.completed);
}
if (failedColIndex >= 0) {
batchStatusSheet.getRange(i + 1, failedColIndex + 1).setValue(fullBatchDetails.request_counts.failed);
}
// Update the output file ID if available
if (fullBatchDetails.output_file_id && outputFileIdColIndex >= 0) {
batchStatusSheet.getRange(i + 1, outputFileIdColIndex + 1).setValue(fullBatchDetails.output_file_id);
}
updatedCount++;
debugLog(`Updated batch ${openAIBatchId} status from ${currentStatus} to ${fullBatchDetails.status}`);
}
}
}
if (updatedCount > 0) {
showAlert('Batch Status Updated', `Updated status for ${updatedCount} batches.`, ui.ButtonSet.OK);
} else {
showAlert('No Updates', 'No batch status updates were needed.', ui.ButtonSet.OK);
}
// Activate the Batch Status sheet
SpreadsheetApp.getActiveSpreadsheet().setActiveSheet(batchStatusSheet);
} catch (e) {
debugLog('Error checking batch status: ' + e.toString());
showAlert('Error', 'Failed to check batch status: ' + e.toString(), ui.ButtonSet.OK, true);
}
}
function checkAndProcessNextCompletedBatch() {
if (!validateConfig()) return;
// Check if a batch is already being processed
var lock = LockService.getScriptLock();
if (!lock.tryLock(1000)) {
showAlert('Batch Processing in Progress',
'A batch is already being checked or processed. Please wait until it completes.',
SpreadsheetApp.getUi().ButtonSet.OK);
return;
}
try {
var ui = SpreadsheetApp.getUi();
// Force debug logging for this function
Logger.log("Starting checkAndProcessNextCompletedBatch");
// First check our local Batch Status sheet to find batches that need processing
var batchStatusSheet = getSheet('Batch Status');
if (batchStatusSheet.getLastRow() <= 1) {
Logger.log("No batches found in Batch Status sheet");
showAlert('No Batches', 'No batch jobs were found in the Batch Status sheet.', ui.ButtonSet.OK);
return;
}
var batchData = batchStatusSheet.getDataRange().getValues();
var headers = batchData[0];
Logger.log("Found " + (batchData.length - 1) + " batches in Batch Status sheet");
// Define column indices based on expected structure
var batchIdColIndex = headers.indexOf("Batch ID");
var openAIBatchIdColIndex = headers.indexOf("OpenAI Batch ID");
var statusColIndex = headers.indexOf("Status");
var outputFileIdColIndex = headers.indexOf("Output File ID");
var processedColIndex = headers.indexOf("Processed");
var lastCheckedColIndex = headers.indexOf("Last Checked At");
Logger.log("Column indices - Batch ID: " + batchIdColIndex +
", OpenAI Batch ID: " + openAIBatchIdColIndex +
", Status: " + statusColIndex +
", Output File ID: " + outputFileIdColIndex +
", Processed: " + processedColIndex);
// Add Processed column if it doesn't exist
if (processedColIndex < 0) {
processedColIndex = headers.length;
batchStatusSheet.getRange(1, processedColIndex + 1).setValue("Processed");
headers.push("Processed");
// Initialize all existing rows with "No" for Processed
for (var i = 1; i < batchData.length; i++) {
batchStatusSheet.getRange(i + 1, processedColIndex + 1).setValue("No");
}
Logger.log("Added Processed column");
}
if (openAIBatchIdColIndex < 0 || statusColIndex < 0) {
Logger.log("Missing required columns in Batch Status sheet");
showAlert('Error', 'Batch Status sheet is missing required columns.', ui.ButtonSet.OK);
return;
}
// Get all batches from OpenAI to update status
Logger.log("Fetching batches from OpenAI");
var openAIBatches = fetchAllBatches();
var openAIBatchesMap = {};
// Create a map for quick lookup
for (var i = 0; i < openAIBatches.length; i++) {
openAIBatchesMap[openAIBatches[i].id] = openAIBatches[i];
}
Logger.log("Found " + openAIBatches.length + " batches in OpenAI");
// First, update the status of all batches
var updatedCount = 0;
for (var i = 1; i < batchData.length; i++) {
var batchId = batchData[i][batchIdColIndex];
var openAIBatchId = batchData[i][openAIBatchIdColIndex];
var currentStatus = batchData[i][statusColIndex];
var currentProcessed = batchData[i][processedColIndex] || "No";
Logger.log("Checking batch " + batchId + " (OpenAI ID: " + openAIBatchId + ") - Status: " + currentStatus + ", Processed: " + currentProcessed);
// Skip batches that are already processed
if (currentProcessed === "Yes") {
Logger.log("Skipping already processed batch: " + batchId);
continue;
}
// Check if this batch exists in OpenAI
if (openAIBatchId && openAIBatchesMap[openAIBatchId]) {
var openAIBatch = openAIBatchesMap[openAIBatchId];
// If the status has changed or we need to update
if (openAIBatch.status !== currentStatus || !batchData[i][outputFileIdColIndex]) {
Logger.log("Status changed for batch " + batchId + " from " + currentStatus + " to " + openAIBatch.status);
// Get the full batch details
var fullBatchDetails = retrieveBatch(openAIBatchId);
// Update status
batchStatusSheet.getRange(i + 1, statusColIndex + 1).setValue(fullBatchDetails.status);
batchStatusSheet.getRange(i + 1, lastCheckedColIndex + 1).setValue(new Date().toISOString());
// Update the output file ID if available
if (fullBatchDetails.output_file_id && outputFileIdColIndex >= 0) {
batchStatusSheet.getRange(i + 1, outputFileIdColIndex + 1).setValue(fullBatchDetails.output_file_id);
Logger.log("Updated output file ID for batch " + batchId + ": " + fullBatchDetails.output_file_id);
}
updatedCount++;
}
}
}
Logger.log("Updated " + updatedCount + " batches");
// Now find a completed batch to process
var batchToProcess = null;
var batchRowIndex = -1;
// Refresh the data after updates
batchData = batchStatusSheet.getDataRange().getValues();
for (var i = 1; i < batchData.length; i++) {
var batchId = batchData[i][batchIdColIndex];
var openAIBatchId = batchData[i][openAIBatchIdColIndex];
var currentStatus = batchData[i][statusColIndex];
var currentProcessed = batchData[i][processedColIndex] || "No";
var outputFileId = batchData[i][outputFileIdColIndex];
// Only process completed batches that have an output file and aren't already processed
if (currentStatus === "completed" && outputFileId && currentProcessed === "No") {
batchToProcess = {
id: openAIBatchId,
output_file_id: outputFileId
};
batchRowIndex = i;
Logger.log("Found completed batch to process: " + batchId);
break;
}
}
// If we found a batch to process
if (batchToProcess) {
var batchId = batchData[batchRowIndex][batchIdColIndex];
var openAIBatchId = batchToProcess.id;
Logger.log("Processing batch " + batchId + " (OpenAI ID: " + openAIBatchId + ")");
// Process the batch
var processed = processBatchById(batchId, openAIBatchId);
if (processed) {
showAlert('Batch Processed',
`Successfully processed batch ${batchId}.\n\nOpenAI Batch ID: ${openAIBatchId}`,
ui.ButtonSet.OK);
} else {
showAlert('Processing Failed',
`Failed to process batch ${batchId}.\n\nOpenAI Batch ID: ${openAIBatchId}\n\nCheck the Error Log for details.`,
ui.ButtonSet.OK, true);
}
} else {
Logger.log("No completed batches found to process");
showAlert('No Batches to Process',
'No completed batches were found that need processing. Batches may still be in progress at OpenAI.',
ui.ButtonSet.OK);
}
} catch (e) {
Logger.log("Error in checkAndProcessNextCompletedBatch: " + e.toString());
showAlert('Error', 'Failed to check or process batches: ' + e.toString(), SpreadsheetApp.getUi().ButtonSet.OK, true);
} finally {
lock.releaseLock();
}
}
/* ======== Utility Functions ======== */
/**
* Gets only the active prompts from the Prompts sheet
* @return {Array} Array of active prompts with name, text, model, temperature, max_tokens, and seed properties
*/
function getActivePrompts() {
var promptsSheet = getSheet('Prompts');
var promptsData = promptsSheet.getDataRange().getValues();
// Check if we have headers
if (promptsData.length <= 1) {
return [];
}
var headers = promptsData[0];
var promptNameIndex = headers.indexOf("Prompt Name");
var promptTextIndex = headers.indexOf("Prompt Text");
var modelIndex = headers.indexOf("Model");
var activeColIndex = headers.indexOf("Active");
var temperatureIndex = headers.indexOf("Temperature");
var maxTokensIndex = headers.indexOf("Max Tokens");
// Get default values from config
var defaultTemperature = getTemperature();
var defaultMaxTokens = getMaxTokens();
var defaultModel = getDefaultModel();
// If required columns don't exist, return empty array
if (promptNameIndex < 0 || promptTextIndex < 0) {
debugLog("Prompts sheet is missing required columns");
return [];
}
// If Active column doesn't exist, add it
if (activeColIndex < 0) {
activeColIndex = headers.length;
promptsSheet.getRange(1, activeColIndex + 1).setValue("Active");
// Set all existing prompts as active by default
if (promptsData.length > 1) {
var activeRange = promptsSheet.getRange(2, activeColIndex + 1, promptsData.length - 1, 1);
activeRange.setValue(1);
}
// Refresh the data after adding the column
promptsData = promptsSheet.getDataRange().getValues();
headers = promptsData[0];
}
// Filter to only include active prompts (where Active = 1)
var activePrompts = [];
for (var i = 1; i < promptsData.length; i++) {
if (promptsData[i][activeColIndex] === 1) {
activePrompts.push({
name: promptsData[i][promptNameIndex],
text: promptsData[i][promptTextIndex],
model: modelIndex >= 0 && promptsData[i][modelIndex] ? promptsData[i][modelIndex] : defaultModel,
temperature: temperatureIndex >= 0 && promptsData[i][temperatureIndex] !== "" && promptsData[i][temperatureIndex] !== null && promptsData[i][temperatureIndex] !== undefined ? promptsData[i][temperatureIndex] : defaultTemperature,
max_tokens: maxTokensIndex >= 0 && promptsData[i][maxTokensIndex] ? promptsData[i][maxTokensIndex] : defaultMaxTokens
});
}
}
return activePrompts;
}
function getPricing(model) {
return PRICING_CONFIG[model.toLowerCase()] || PRICING_CONFIG["gpt-4o-mini"];
}
function getSheet(sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
return sheet || ss.insertSheet(sheetName);
}
/* ======== Alert and Logging Functions ======== */
/**
* Shows an alert popup to the user
* @param {string} title - The alert title
* @param {string} message - The alert message
* @param {ButtonSet} buttons - The buttons to display (e.g., ui.ButtonSet.OK)
*/
function showAlert(title, message, buttons) {
SpreadsheetApp.getUi().alert(title, message, buttons);
// Also log the message for reference
Logger.log(`ALERT - ${title}: ${message}`);
}
/**
* Adds an entry to the Error Log sheet
* @param {Date} timestamp - When the error occurred
* @param {number} row - The row number in the Data sheet
* @param {string} errorType - Type of error
* @param {string} errorMessage - The error message
* @param {string} batchId - The batch ID (if applicable)
*/
function logError(timestamp, row, errorType, errorMessage, batchId = '') {
var errorSheet = getSheet('Error Log');
// Add headers if the sheet is empty
if (errorSheet.getLastRow() === 0) {
errorSheet.appendRow([
"Timestamp",
"Row",
"Error Type",
"Error Message",
"Batch ID"
]);
// Format the header row
errorSheet.getRange(1, 1, 1, 5).setFontWeight('bold');
errorSheet.setFrozenRows(1);
}
// Add the error entry
errorSheet.appendRow([
timestamp,
row,
errorType,
errorMessage,
batchId
]);
// Also log to the console for debugging
Logger.log(`ERROR - Row ${row}, Type: ${errorType}, Message: ${errorMessage}, Batch: ${batchId}`);
}
/**
* Adds an entry to the Execution Log sheet if debug mode is enabled
* @param {Date} timestamp - When the execution occurred
* @param {number} row - The row number in the Data sheet
* @param {string} model - The model used
* @param {string} promptName - The name of the prompt
* @param {string} responseContent - The response content received
* @param {number} inputTokens - Number of input tokens
* @param {number} outputTokens - Number of output tokens
* @param {number} totalTokens - Total tokens used
* @param {number} cost - The cost in USD
*/
function logExecution(timestamp, row, model, promptName, responseContent, inputTokens, outputTokens, totalTokens, cost) {
// Only log execution if debug mode is enabled
if (!isDebugModeEnabled()) {
return;
}
var logSheet = getSheet('Execution Log');
// Add headers if the sheet is empty
if (logSheet.getLastRow() === 0) {
logSheet.appendRow([
"Timestamp",
"Row",
"Model",
"Prompt Sent",
"Response Received",
"Input Tokens",
"Output Tokens",
"Total Tokens",
"Cost (USD)"
]);
// Format the header row
logSheet.getRange(1, 1, 1, 9).setFontWeight('bold');
logSheet.setFrozenRows(1);
}
// Add the log entry
logSheet.appendRow([
timestamp,
row,
model,
promptName,
responseContent,
inputTokens,
outputTokens,
totalTokens,
cost
]);
// Also log a summary to the console
Logger.log(`EXECUTION - Row ${row}, Model: ${model}, Prompt: ${promptName}, Tokens: ${totalTokens}, Cost: $${cost.toFixed(6)}`);
}
/**
* Logs a debug message only if debug mode is enabled
* @param {string} message - The message to log
*/
function debugLog(message) {
if (isDebugModeEnabled()) {
Logger.log(`DEBUG - ${message}`);
}
}
/* ======== Main Function to Run Prompts ======== */
function runPrompts(maxRows) {
var ui = SpreadsheetApp.getUi();
var apiKey = getApiKey();
var seed = getSeed();
if (!apiKey) {
showAlert('Error', 'API key is missing. Please add it to the Config sheet.', ui.ButtonSet.OK);
return;
}
try {
// Record start time for this execution
var startTime = new Date();
var debugMode = isDebugModeEnabled();
// Get active prompts using the getActivePrompts function
var activePrompts = getActivePrompts();
if (activePrompts.length === 0) {
showAlert('No Active Prompts', 'No active prompts found in the Prompts sheet.', ui.ButtonSet.OK);
return;
}
// Get data from the Data sheet
var dataSheet = getSheet('Data');
if (!dataSheet) {
showAlert('Error', 'Data sheet not found.', ui.ButtonSet.OK);
return;
}
var dataRange = dataSheet.getDataRange().getValues();
var headers = dataRange[0];
// Find Status column or add it if it doesn't exist
var statusColIndex = -1;
for (var i = 0; i < headers.length; i++) {
var header = headers[i];
if (header === null || header === undefined) continue;
var headerStr = String(header); // Safely convert to string
if (headerStr === 'Status') {
statusColIndex = i;
break;
}
}
if (statusColIndex < 0) {
statusColIndex = headers.length;
dataSheet.getRange(1, statusColIndex + 1).setValue('Status');
headers.push('Status');
}
// Find rows that need processing (status is 0 or empty)
var rowsToProcess = [];
for (var i = 1; i < dataRange.length && rowsToProcess.length < maxRows; i++) {
var status = dataRange[i][statusColIndex];
if (status === 0 || status === '' || status === null || status === undefined) {
rowsToProcess.push(i);
}
}
if (rowsToProcess.length === 0) {
showAlert('No Data', 'No rows found that need processing.', ui.ButtonSet.OK);
return;
}
// Track metrics
var promptMetrics = {};
var totalProcessed = 0;
var totalErrors = 0;
// Process each row
for (var i = 0; i < rowsToProcess.length; i++) {
var rowIndex = rowsToProcess[i];
var rowNumber = rowIndex + 1; // +1 for the actual row number in the sheet
try {
// Mark the row as in progress (status = 1)
dataSheet.getRange(rowNumber, statusColIndex + 1).setValue(1);
// Process each active prompt for this row
for (var j = 0; j < activePrompts.length; j++) {
var prompt = activePrompts[j];
var promptName = prompt.name;
var promptTemplate = prompt.text;
var model = prompt.model;
var temperature = prompt.temperature;
var max_tokens = prompt.max_tokens;
try {
// Replace placeholders in the prompt template
var promptText = promptTemplate;
// Find all placeholders in the format {{Column Name}}
var placeholders = promptTemplate.match(/\{\{([^}]+)\}\}/g) || [];
for (var k = 0; k < placeholders.length; k++) {
var placeholder = placeholders[k];
var columnName = placeholder.substring(2, placeholder.length - 2).trim();
// Find the column index
var columnIndex = -1;
for (var l = 0; l < headers.length; l++) {
var header = headers[l];
if (header === null || header === undefined) continue;
var headerStr = String(header); // Safely convert to string
if (headerStr === columnName) {
columnIndex = l;
break;
}
}
if (columnIndex >= 0) {
var cellValue = dataRange[rowIndex][columnIndex] || '';
promptText = promptText.replace(placeholder, cellValue);
}
}
// Call the OpenAI API
var apiCallStartTime = new Date();
var response = callOpenAI(apiKey, model, promptText, temperature, max_tokens, seed);
var apiCallEndTime = new Date();
var apiCallDuration = (apiCallEndTime - apiCallStartTime) / 1000; // Duration in seconds
var responseText = response.text;
var parsedResponse = response.parsedJson;
var inputTokens = response.inputTokens;
var outputTokens = response.outputTokens;
var totalTokens = response.totalTokens;
var cost = calculateCost(model, inputTokens, outputTokens, false, response.cachedTokens);
// Update metrics
if (!promptMetrics[promptName]) {
promptMetrics[promptName] = {
count: 0,
inputTokens: 0,
outputTokens: 0,
totalTokens: 0,
cost: 0,
model: model,
duration: 0,
cachedTokens: 0
};
}
promptMetrics[promptName].count++;
promptMetrics[promptName].inputTokens += inputTokens;
promptMetrics[promptName].outputTokens += outputTokens;
promptMetrics[promptName].totalTokens += totalTokens;
promptMetrics[promptName].cost += cost;
promptMetrics[promptName].duration += apiCallDuration;
promptMetrics[promptName].cachedTokens += response.cachedTokens || 0;
// Save response to the Data sheet
saveResponseToDataSheet(dataSheet, headers, rowIndex, parsedResponse, promptName);
// Log execution
logExecution(
new Date(),
rowNumber,
model,
promptName,
responseText,
inputTokens,
outputTokens,
totalTokens,
cost
);
totalProcessed++;
} catch (e) {
logError(new Date(), rowNumber, 'Error processing', `Error processing ${promptName}: ${e.toString()}`, '');
totalErrors++;
}
}
// Mark the row as completed (status = 1 for non batch mode)
dataSheet.getRange(rowNumber, statusColIndex + 1).setValue(1);
} catch (e) {
logError(new Date(), rowNumber, 'Error processing', `Error processing row ${rowNumber}: ${e.toString()}`, '');
totalErrors++;
}
}
// Record end time and calculate duration
var endTime = new Date();
var executionDuration = (endTime - startTime) / 1000; // Duration in seconds
// Add summary entries for each prompt
if (Object.keys(promptMetrics).length > 0) {
for (var promptName in promptMetrics) {
var metrics = promptMetrics[promptName];
addPromptSummary(
startTime,
endTime,
metrics.duration,
promptName,
metrics.count,
metrics.inputTokens,
metrics.outputTokens,
metrics.cost,
metrics.cachedTokens || 0
);
}
}
showAlert('Processing Complete',
`Processed ${totalProcessed} prompts with ${totalErrors} errors.`,
ui.ButtonSet.OK);
} catch (e) {
debugLog('Error running prompts: ' + e.toString());
showAlert('Error', 'Failed to run prompts: ' + e.toString(), ui.ButtonSet.OK);
}
}
/* ======== Cost Summary Functions ======== */
function addPromptSummary(startTime, endTime, durationSeconds, promptName, rowsExecuted, inputTokens, outputTokens, cost, cachedTokens = 0) {
var costSummarySheet = getSheet('Cost Summary');
// Initialize headers if sheet is empty
if (costSummarySheet.getLastRow() === 0) {
costSummarySheet.appendRow([
"Date",
"Start Time",
"End Time",
"Duration (sec)",
"Prompt Title",
"No. of Rows Executed",
"Total Input Tokens",
"Cached Tokens",
"Total Output Tokens",
"Total Tokens",
"Total Cost (USD)"
]);
}
// Format date and times
var dateStr = Utilities.formatDate(startTime, Session.getScriptTimeZone(), "yyyy-MM-dd");
var startTimeStr = Utilities.formatDate(startTime, Session.getScriptTimeZone(), "HH:mm:ss");
var endTimeStr = Utilities.formatDate(endTime, Session.getScriptTimeZone(), "HH:mm:ss");
// Add new row for this prompt execution
costSummarySheet.appendRow([
dateStr,
startTimeStr,
endTimeStr,
durationSeconds.toFixed(1),
promptName,
rowsExecuted,
inputTokens,
cachedTokens,
outputTokens,
inputTokens + outputTokens,
cost.toFixed(6)
]);
// Format the cost column as currency
var lastRow = costSummarySheet.getLastRow();
costSummarySheet.getRange(lastRow, 11).setNumberFormat("$0.000000");
// Format the duration as number with 1 decimal place
costSummarySheet.getRange(lastRow, 4).setNumberFormat("0.0");
}
/* ======== Save Cleaned Response to Data Sheet ======== */
function saveResponseToDataSheet(sheet, headers, rowIndex, response, promptName) {
try {
// No need to parse the response again as it's already a JSON object
var parsedResponse = response;
for (var key in parsedResponse) {
if (Object.prototype.hasOwnProperty.call(parsedResponse, key)) {
var colName = promptName + ' - ' + key; // Format: Prompt Name - Key
var colIndex = headers.indexOf(colName);
// If the column does not exist, create it
if (colIndex < 0) {
colIndex = headers.length;
sheet.getRange(1, colIndex + 1).setValue(colName);
headers.push(colName);
}
// Write response data to the correct cell in the row
sheet.getRange(rowIndex + 1, colIndex + 1).setValue(parsedResponse[key]);
}
}
} catch (e) {
debugLog("Error processing response: " + e);
logError(new Date(), rowIndex, 'Error processing response', `Error processing response: ${e.toString()}`, '');
}
}
/* ======== OpenAI API Function ======== */
function callOpenAI(apiKey, model, prompt, temperature, max_tokens, seed) {
var url = 'https://api.openai.com/v1/chat/completions';
var payload = {
model: model,
messages: [
{ role: 'system', content: 'You are a helpful assistant. Return valid JSON only.' },
{ role: 'user', content: prompt }
],
temperature: temperature,
max_tokens: max_tokens,
seed: seed,
response_format: { type: "json_object" }
};
var options = {
method: 'post',
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + apiKey },
payload: JSON.stringify(payload),
muteHttpExceptions: true