-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatgpt_token_cost_analysis.html
612 lines (554 loc) · 29.6 KB
/
chatgpt_token_cost_analysis.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Token Cost Analysis</title>
<script src="https://unpkg.com/gpt-tokenizer"></script>
<style>
body {
font-family: 'Arial, sans-serif', sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.checkbox-container {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.checkbox-container input[type="checkbox"] {
margin-right: 10px;
width: auto;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.checkbox-container label {
margin-bottom: 0;
display: flex;
align-items: center;
font-size: 16px;
line-height: 1;
}
#results:empty, #debug:empty {
display: none;
}
#results, #debug {
margin-top: 30px;
padding: 20px;
background-color: #ecf0f1;
border-radius: 4px;
}
h1, h2, h3 {
color: #2c3e50;
}
h1 {
text-align: center;
margin-bottom: 30px;
}
select, input[type="file"], input[type="checkbox"] {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
#loadingMessage {
display: none;
color: #3498db;
margin-bottom: 20px;
text-align: center;
}
#results, #debug {
margin-top: 30px;
padding: 20px;
background-color: #ecf0f1;
border-radius: 4px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #3498db;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
#loadingIcon {
border: 4px solid #f3f3f3;
border-radius: 50%;
border-top: 4px solid #3498db;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 0 auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#downloadContainer {
margin-top: 30px;
text-align: center;
}
#downloadLink {
display: inline-block;
padding: 10px 20px;
background-color: #3498db;
color: white;
text-decoration: none;
border-radius: 4px;
transition: background-color 0.3s;
}
#downloadLink:hover {
background-color: #2980b9;
}
#footer {
margin-top: 30px;
font-size: 0.9em;
color: #7f8c8d;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>ChatGPT Token Cost Analysis</h1>
<div id="status_loading_gpttokenizer"></div>
<label for="modelSelect">Select the model*:</label>
<select id="modelSelect">
<optgroup label="OpenAI GPT-4o Models">
<option value="gpt-4o">gpt-4o (5.00 USD / 1M input tokens, 15.00 USD / 1M output tokens)</option>
<option value="gpt-4o-2024-05-13">gpt-4o-2024-05-13 (5.00 USD / 1M input tokens, 15.00 USD / 1M output tokens)</option>
<option value="gpt-4o-2024-08-06">gpt-4o-2024-08-06 (2.50 USD / 1M input tokens, 10.00 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI GPT-4o mini Models">
<option value="gpt-4o-mini">gpt-4o-mini (0.15 USD / 1M input tokens, 0.60 USD / 1M output tokens)</option>
<option value="gpt-4o-mini-2024-07-18">gpt-4o-mini-2024-07-18 (0.15 USD / 1M input tokens, 0.60 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI o1-preview Models">
<option value="o1-preview">o1-preview (15.00 USD / 1M input tokens, 60.00 USD / 1M output tokens)</option>
<option value="o1-preview-2024-09-12">o1-preview-2024-09-12 (15.00 USD / 1M input tokens, 60.00 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI o1-mini Models">
<option value="o1-mini">o1-mini (3.00 USD / 1M input tokens, 12.00 USD / 1M output tokens)</option>
<option value="o1-mini-2024-09-12">o1-mini-2024-09-12 (3.00 USD / 1M input tokens, 12.00 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI GPT-3.5 Turbo Models">
<option value="gpt-3.5-turbo-0125">gpt-3.5-turbo-0125 (0.50 USD / 1M input tokens, 1.50 USD / 1M output tokens)</option>
<option value="gpt-3.5-turbo-instruct">gpt-3.5-turbo-instruct (1.50 USD / 1M input tokens, 2.00 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI Embedding Models">
<option value="text-embedding-3-small">text-embedding-3-small (0.02 USD / 1M tokens)</option>
<option value="text-embedding-3-large">text-embedding-3-large (0.13 USD / 1M tokens)</option>
<option value="ada-v2">ada-v2 (0.10 USD / 1M tokens)</option>
</optgroup>
<optgroup label="OpenAI Fine-tuning Models">
<option value="gpt-3.5-turbo">gpt-3.5-turbo (3.00 USD / 1M input tokens, 6.00 USD / 1M output tokens)</option>
<option value="davinci-002">davinci-002 (12.00 USD / 1M input tokens, 12.00 USD / 1M output tokens)</option>
<option value="babbage-002">babbage-002 (1.60 USD / 1M input tokens, 1.60 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="OpenAI Older Models">
<option value="gpt-4-turbo">gpt-4-turbo (10.00 USD / 1M input tokens, 30.00 USD / 1M output tokens)</option>
<option value="gpt-4-turbo-2024-04-09">gpt-4-turbo-2024-04-09 (10.00 USD / 1M input tokens, 30.00 USD / 1M output tokens)</option>
<option value="gpt-4">gpt-4 (30.00 USD / 1M input tokens, 60.00 USD / 1M output tokens)</option>
<option value="gpt-4-32k">gpt-4-32k (60.00 USD / 1M input tokens, 120.00 USD / 1M output tokens)</option>
<option value="gpt-4-0125-preview">gpt-4-0125-preview (10.00 USD / 1M input tokens, 30.00 USD / 1M output tokens)</option>
<option value="gpt-4-1106-preview">gpt-4-1106-preview (10.00 USD / 1M input tokens, 30.00 USD / 1M output tokens)</option>
<option value="gpt-4-vision-preview">gpt-4-vision-preview (10.00 USD / 1M input tokens, 30.00 USD / 1M output tokens)</option>
<option value="gpt-3.5-turbo-1106">gpt-3.5-turbo-1106 (1.00 USD / 1M input tokens, 2.00 USD / 1M output tokens)</option>
<option value="gpt-3.5-turbo-0613">gpt-3.5-turbo-0613 (1.50 USD / 1M input tokens, 2.00 USD / 1M output tokens)</option>
<option value="gpt-3.5-turbo-16k-0613">gpt-3.5-turbo-16k-0613 (3.00 USD / 1M input tokens, 4.00 USD / 1M output tokens)</option>
<option value="gpt-3.5-turbo-0301">gpt-3.5-turbo-0301 (1.50 USD / 1M input tokens, 2.00 USD / 1M output tokens)</option>
<option value="davinci-002">davinci-002 (2.00 USD / 1M input tokens, 2.00 USD / 1M output tokens)</option>
<option value="babbage-002">babbage-002 (0.40 USD / 1M input tokens, 0.40 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="Claude Models (Experimental)">
<option value="claude-3-haiku">Claude 3 Haiku (0.25 USD / 1M input tokens, 1.25 USD / 1M output tokens)</option>
<option value="claude-3-sonnet">Claude 3 Sonnet (3.00 USD / 1M input tokens, 15.00 USD / 1M output tokens)</option>
<option value="claude-3-opus">Claude 3 Opus (15.00 USD / 1M input tokens, 75.00 USD / 1M output tokens)</option>
<option value="claude-2-1">Claude 2.1 (8.00 USD / 1M input tokens, 24.00 USD / 1M output tokens)</option>
<option value="claude-2-0">Claude 2.0 (8.00 USD / 1M input tokens, 24.00 USD / 1M output tokens)</option>
<option value="claude-instant">Claude Instant (0.80 USD / 1M input tokens, 2.40 USD / 1M output tokens)</option>
</optgroup>
<optgroup label="Gemini Models (Experimental)">
<option value="gemini-1-5-flash">Gemini 1.5 Flash (0.35 USD / 1M input tokens, 1.05 USD / 1M output tokens)</option>
<option value="gemini-1-5-pro">Gemini 1.5 Pro (3.50 USD / 1M input tokens, 10.50 USD / 1M output tokens)</option>
<option value="gemini-1-0-pro">Gemini 1.0 Pro (0.50 USD / 1M input tokens, 1.50 USD / 1M output tokens)</option>
</optgroup>
</select>
<div class="checkbox-container">
<label for="apiBatch">
<input type="checkbox" id="apiBatch">
API Batch*
</label>
</div>
<label for="fileInput">Select the exported ChatGPT Conversation JSON file:</label>
<input type="file" id="fileInput" accept=".json">
<div id="loadingMessage">
Loading the JSON file, please wait...
<div id="loadingIcon"></div>
</div>
<div id="debug"></div>
<div id="results"></div>
<div id="downloadContainer">
<a href="#" id="downloadLink">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAhGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAEgAAAABAAAASAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAABB553+AAAACXBIWXMAAAsTAAALEwEAmpwYAAACMmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+NTEyPC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjUxMjwvZXhpZjpQaXhlbFhEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOkNvbG9yU3BhY2U+MTwvZXhpZjpDb2xvclNwYWNlPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KanJCRQAAAbBJREFUOBGVkztKA2EUhfMwgliIEIUgiAiCYKf2glhbWbkCN+EK7FyAW7AQCwuX4AbstLQQFIOvJON3/rlnMkyUMRduzn2ce/7XpNGosSzLmmVKNS/3amMPgz18F1/TkOu1AlUCgzMhcEYsu468XeU6bzmowVH0jX/S/yv4p0C1USfoo5nnB0pXURVTbuJEj/tqYp/ReA/8EpbqUR7DryuFmB7hIKibgSvU9onn8BuEB+ZGPwcV5S4Sp6OCx7htSCCXnYsL+krSp0SeaygoklAl9ydzSizr55DdlhYub2JCI/EYSiQhnu4YvMJlT/iSiGCxOy9QIM0L/AE/CbJ3Z8H56B9GvxPoq9mjf49f+lF2IKzi6yJiaZdc+ghSC9Rxt8A3EGh+57ScR9zFN/AFC/aD4M+kzeCQmoQJs06Iia886A3tcICLK3u1YDoahdRg+CO1xz/pL0ddw2WzULERC/q1uqy+yMQy7mOVBaqx5p9xXVcyv+gd2TZuES+Qs+p/dQd6qEfv0FtXQzVfUrpDcpsXKvfV8/zAgjqmbDaHqX/9Bl0f+QiJHq4/v5vTqPpkLz8GHxq29/nHtAAAAABJRU5ErkJggg==" alt="" /> Download this page
</a>
<p>This page ensures the privacy of your sensitive data because it works entirely locally. Your JSON file containing private chats is never uploaded to a remote server. However, for added security, you can download the page, review the source code, and use it offline without sharing your sensitive information online. If you prefer, you can also download the latest release from the GitHub repository <a href="https://github.com/levysoft/chatgpt-token-cost-analysis/releases/latest">here</a>, so you can also download the JavaScript file locally.</p>
</div>
<footer id="footer">
<p>*Models and prices are sourced from the official OpenAI page: <a href="https://openai.com/api/pricing/" target="_blank">OpenAI API Pricing</a> (in the case of API Batch, which returns completions within 24 hours, consider a 50% discount).</p>
<p>*API Batch returns completions within 24 hours with a 50% discount.</p>
<p>Updated Prices on: August 06, 2024</p>
</footer>
</div>
<script>
const pricing = {
"gpt-4o": { input: 5.0, output: 15.0 },
"gpt-4o-2024-05-13": { input: 5.0, output: 15.0 },
"gpt-4o-2024-08-06": { input: 2.5, output: 10.0 },
"gpt-4o-mini": { input: 0.15, output: 0.60 },
"gpt-4o-mini-2024-07-18": { input: 0.15, output: 0.60 },
"o1-preview": { input: 15.00, output: 60.00 },
"o1-preview-2024-09-12": { input: 15.00, output: 60.00 },
"o1-mini": { input: 3.00, output: 12.00 },
"o1-mini-2024-09-12": { input: 3.00, output: 12.00 },
"gpt-3.5-turbo-0125": { input: 0.5, output: 1.5 },
"gpt-3.5-turbo-instruct": { input: 1.5, output: 2.0 },
"text-embedding-3-small": { input: 0.02, output: 0.02 },
"text-embedding-3-large": { input: 0.13, output: 0.13 },
"ada-v2": { input: 0.1, output: 0.1 },
"gpt-3.5-turbo": { input: 3.0, output: 6.0 },
"davinci-002": { input: 12.0, output: 12.0 },
"babbage-002": { input: 1.6, output: 1.6 },
"gpt-4-turbo": { input: 10.0, output: 30.0 },
"gpt-4-turbo-2024-04-09": { input: 10.0, output: 30.0 },
"gpt-4": { input: 30.0, output: 60.0 },
"gpt-4-32k": { input: 60.0, output: 120.0 },
"gpt-4-0125-preview": { input: 10.0, output: 30.0 },
"gpt-4-1106-preview": { input: 10.0, output: 30.0 },
"gpt-4-vision-preview": { input: 10.0, output: 30.0 },
"gpt-3.5-turbo-1106": { input: 1.0, output: 2.0 },
"gpt-3.5-turbo-0613": { input: 1.5, output: 2.0 },
"gpt-3.5-turbo-16k-0613": { input: 3.0, output: 4.0 },
"gpt-3.5-turbo-0301": { input: 1.5, output: 2.0 },
"davinci-002": { input: 2.0, output: 2.0 },
"babbage-002": { input: 0.4, output: 0.4 },
"claude-3-haiku": { input: 0.25, output: 1.25 },
"claude-3-sonnet": { input: 3.0, output: 15.0 },
"claude-3-opus": { input: 15.0, output: 75.0 },
"claude-2-1": { input: 8.0, output: 24.0 },
"claude-2-0": { input: 8.0, output: 24.0 },
"claude-instant": { input: 0.8, output: 2.4 },
"gemini-1-5-flash": { input: 0.35, output: 1.05 },
"gemini-1-5-pro": { input: 3.5, output: 10.5 },
"gemini-1-0-pro": { input: 0.5, output: 1.5 }
};
const debugEl = document.getElementById('debug');
// Function to load script dynamically
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = () => callback(null);
script.onerror = () => callback(new Error(`Failed to load script: ${url}`));
document.head.appendChild(script);
}
// Function to check if GPTTokenizer_cl100k_base is loaded correctly
function checkGPTTokenizer() {
const statusDiv = document.getElementById('status_loading_gpttokenizer');
if (typeof GPTTokenizer_cl100k_base !== 'undefined') {
const successMessage = document.createElement('p');
successMessage.textContent = 'Remote Encoder GPTTokenizer_cl100k_base loaded successfully.';
statusDiv.appendChild(successMessage);
} else {
const errorMessage = document.createElement('p');
errorMessage.textContent = 'Remote Encoder GPTTokenizer_cl100k_base not loaded. Attempting to load the local version...';
statusDiv.appendChild(errorMessage);
loadScript('cl100k_base.js', function(err) {
if (err) {
const finalErrorMessage = document.createElement('p');
finalErrorMessage.textContent = 'Failed to load local GPTTokenizer_cl100k_base.';
statusDiv.appendChild(finalErrorMessage);
// Add second row with fallback error message
const additionalMessage = document.createElement('p');
additionalMessage.textContent = 'Switch to Fallback: rough approximation based on the number of words.';
statusDiv.appendChild(additionalMessage);
} else {
if (typeof GPTTokenizer_cl100k_base !== 'undefined') {
const successLocalMessage = document.createElement('p');
successLocalMessage.textContent = 'Local GPTTokenizer_cl100k_base loaded successfully.';
statusDiv.appendChild(successLocalMessage);
} else {
const errorLocalMessage = document.createElement('p');
errorLocalMessage.textContent = 'Local GPTTokenizer_cl100k_base is still not available after loading.';
statusDiv.appendChild(errorLocalMessage);
}
}
});
}
}
/**
* Appends a debug message to the debug element.
* Creates a new paragraph element with the provided message.
* @param {string} message - The debug message to display.
*/
function debug(message) {
const messageEl = document.createElement('p');
messageEl.textContent = message;
debugEl.appendChild(messageEl);
}
document.getElementById('modelSelect').addEventListener('change', resetResults);
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
/**
* Handles the file selection event.
* Reads the selected JSON file and processes it if valid.
* Displays a loading message during the file reading process.
* @param {Event} event - The file input change event.
*/
function handleFileSelect(event) {
const file = event.target.files[0];
debug(`Selected file: ${file.name}`);
const reader = new FileReader();
// Show the loading message
document.getElementById('loadingMessage').style.display = 'block';
reader.onload = function(e) {
debug('File loaded successfully');
const content = e.target.result;
//processJSON(content);
if (isValidJSON(content)) {
debug('JSON validation is OK');
processJSON(content);
} else {
debug('Invalid JSON format');
alert('Please select a correctly formatted conversations.json file.');
event.target.value = ''; // Reset the input
}
// Hide the loading message
document.getElementById('loadingMessage').style.display = 'none';
};
reader.onerror = function(e) {
debug(`Error reading file: ${e.target.error}`);
// Hide the loading message even in case of error
document.getElementById('loadingMessage').style.display = 'none';
};
reader.readAsText(file);
}
/**
* Validates the JSON content structure.
* Checks for required properties in each conversation object.
* @param {string} content - The JSON content as a string.
* @returns {boolean} - Returns true if the JSON is valid, otherwise false.
*/
function isValidJSON(content) {
try {
const data = JSON.parse(content);
function isValidConversation(convo) {
if (!convo.hasOwnProperty('title') ||
!convo.hasOwnProperty('create_time') ||
!convo.hasOwnProperty('update_time') ||
!convo.hasOwnProperty('mapping')) {
return false;
}
const mapping = convo.mapping;
if (typeof mapping !== 'object') {
return false;
}
return true;
}
if (Array.isArray(data) && data.every(isValidConversation)) {
return true;
} else {
throw new Error('Invalid JSON format');
}
} catch (err) {
return false;
}
}
/**
* Processes the JSON content.
* Parses the JSON, extracts messages, analyzes them, and displays the results.
* @param {string} content - The JSON content as a string.
*/
function processJSON(content) {
try {
const data = JSON.parse(content);
debug(`JSON parsed successfully. Number of items: ${data.length}`);
const messages = extractMessages(data);
debug(`Messages extracted: ${messages.length}`);
const results = analyzeMessages(messages);
displayResults(results);
} catch (error) {
debug(`Error processing JSON: ${error.message}`);
}
}
/**
* Extracts messages from the JSON data.
* Iterates through each conversation and its mapping to collect messages.
* @param {Array} data - The parsed JSON data array.
* @returns {Array} - An array of extracted messages.
*/
function extractMessages(data) {
let messages = [];
data.forEach(conversation => {
if (conversation.mapping) {
Object.values(conversation.mapping).forEach(item => {
if (item.message && item.message.content && item.message.content.parts) {
const timestamp = item.message.create_time;
if (timestamp && timestamp > 0) { // Check for valid timestamps: some have null create_time
messages.push({
role: item.message.author.role,
content: item.message.content.parts.join(' '),
create_time: timestamp
});
}
}
});
}
});
return messages;
}
/**
* Counts the number of tokens in the given text.
* Uses the GPTTokenizer_cl100k_base if available, otherwise falls back to word count approximation.
* @param {string} text - The text to tokenize.
* @returns {number} - The number of tokens in the text.
*/
function countTokens(text) {
if (typeof GPTTokenizer_cl100k_base !== 'undefined') {
return GPTTokenizer_cl100k_base.encode(text).length;
} else {
debug('GPTTokenizer_cl100k_base is not available');
// Fallback: rough approximation based on the number of words
return text.split(/\s+/).length;
}
}
/**
* Analyzes the extracted messages.
* Calculates the number of input and output tokens and their respective costs.
* Aggregates the costs by month.
* @param {Array} messages - The array of extracted messages.
* @returns {Object} - An object containing total input tokens, total output tokens, total cost, and monthly costs.
*/
function analyzeMessages(messages) {
const model = document.getElementById('modelSelect').value;
const isApiBatch = document.getElementById('apiBatch').checked;
let inputPrice = pricing[model].input / 1000000;
let outputPrice = pricing[model].output / 1000000;
if (isApiBatch) {
inputPrice /= 2;
outputPrice /= 2;
}
let totalInputTokens = 0;
let totalOutputTokens = 0;
const monthlyCosts = {};
messages.forEach(message => {
const tokenCount = countTokens(message.content);
const date = new Date(message.create_time * 1000);
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
if (!monthlyCosts[monthKey]) {
monthlyCosts[monthKey] = { input: 0, output: 0, inputTokens: 0, outputTokens: 0 };
}
if (message.role === 'user' || message.role === 'system') {
totalInputTokens += tokenCount;
monthlyCosts[monthKey].input += tokenCount * inputPrice;
monthlyCosts[monthKey].inputTokens += tokenCount;
} else if (message.role === 'assistant') {
totalOutputTokens += tokenCount;
monthlyCosts[monthKey].output += tokenCount * outputPrice;
monthlyCosts[monthKey].outputTokens += tokenCount;
}
});
const totalCost = (totalInputTokens * inputPrice) + (totalOutputTokens * outputPrice);
debug(`Analysis completed. Input Tokens: ${totalInputTokens}, Output Tokens: ${totalOutputTokens}`);
return {
totalInputTokens,
totalOutputTokens,
totalCost,
monthlyCosts
};
}
/**
* Displays the analysis results.
* Shows the total input tokens, output tokens, total cost, and monthly costs in a table format.
* @param {Object} results - The results object containing total input tokens, total output tokens, total cost, and monthly costs.
*/
function displayResults(results) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = `
<h2>Analysis Results</h2>
<p>Total Input Tokens: ${results.totalInputTokens.toLocaleString()}</p>
<p>Total Output Tokens: ${results.totalOutputTokens.toLocaleString()}</p>
<p>Total Cost: $${results.totalCost.toFixed(2)}</p>
<h3>Monthly Costs</h3>
<table>
<tr>
<th>Month</th>
<th>Input Tokens</th>
<th>Output Tokens</th>
<th>Input Cost</th>
<th>Output Cost</th>
<th>Total Cost</th>
</tr>
${Object.entries(results.monthlyCosts).map(([month, costs]) => `
<tr>
<td>${month}</td>
<td>${costs.inputTokens.toLocaleString()}</td>
<td>${costs.outputTokens.toLocaleString()}</td>
<td>$${costs.input.toFixed(2)}</td>
<td>$${costs.output.toFixed(2)}</td>
<td>$${(costs.input + costs.output).toFixed(2)}</td>
</tr>
`).join('')}
</table>
`;
debug('Results displayed');
}
// Add code to download the HTML page
document.getElementById('downloadLink').addEventListener('click', function() {
// Extract the HTML of the current page
const pageHTML = document.documentElement.outerHTML;
// Create a blob with the HTML content
const blob = new Blob([pageHTML], { type: 'text/html' });
// Create a URL for the blob
const url = URL.createObjectURL(blob);
// Set the href attribute of the download link
this.href = url;
// Set the file name for the download
this.download = 'chatgpt_token_cost_analysis.html';
});
// Function to reset the results
function resetResults() {
document.getElementById('results').innerHTML = '';
document.getElementById('debug').innerHTML = '';
document.getElementById('fileInput').value = '';
}
// Perform the check when the document is ready
document.addEventListener('DOMContentLoaded', checkGPTTokenizer);
</script>
</body>
</html>