-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
1971 lines (1675 loc) · 74.2 KB
/
index.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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="manifest.json">
<link rel="icon" type="image/x-icon" href="/img/aiquokka.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Noto+Color+Emoji&family=Noto+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap"
rel="stylesheet">
<style>
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
margin: 0;
background-color: #F3F4F6;
font-family: 'Noto Sans', sans-serif;
font-size: 15px;
}
.emoji {
font-family: 'Noto Color Emoji', sans-serif;
}
h1,
h2 {
margin: 0;
}
#loading {
position: fixed;
top: 30vh;
width: 100%;
text-align: center;
margin: 0;
padding: 1em 0;
background: repeating-linear-gradient(-45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px);
color: white;
}
div.content {
flex: 1 auto;
}
div.main {
display: flex;
flex-direction: column;
height: 100%;
max-width: 100%;
padding: 0.5em;
}
#answer {
display: flex;
flex-direction: column;
flex: 1 100px;
/* for arrows */
padding: 0 8px;
overflow: auto;
}
#answer .chat-bubble {
position: relative;
max-width: 90%;
margin: 2px;
margin-bottom: 1em;
padding: 10px;
border-radius: 5px;
background-color: #b7d3e1;
box-shadow: 2px 2px 2px 2px #e5e5e5;
}
#answer .chat-bubble::after {
content: '';
position: absolute;
width: 0px;
height: 0px;
top: 4px;
border: 10px solid transparent;
}
#answer .chat-bubble.assistant {
padding-left: 6px;
align-self: flex-start;
}
#answer .chat-bubble.assistant::after {
left: -10px;
border-right-color: #b7d3e1;
border-left: 0;
}
#answer .chat-bubble.user {
padding-left: 2px;
align-self: flex-end;
background-color: #b7bde1;
}
#answer .chat-bubble.user::after {
right: -10px;
border-left-color: #b7bde1;
border-right: 0;
}
#answer .chat-bubble.system,
#answer .chat-bubble.tool {
align-self: center;
min-width: 94%;
text-align: center;
background-color: #e3e3e3;
}
#answer .chat-bubble::before {
position: relative;
bottom: 8px;
margin-right: 0.5em;
font-size: 0.8em;
}
#answer .chat-bubble.user::before {
content: '👤';
}
#answer .chat-bubble.user.image::before {
content: '👤🖼️';
}
#answer .chat-bubble.assistant::before {
content: '🤖 AI';
}
#answer .chat-bubble.assistant.toolCall::before {
content: '🛠️ AI';
}
#answer .chat-bubble.tool::before {
content: '🛠️👤';
}
#answer .chat-bubble.system::before {
content: '💻';
}
#answer img {
max-width: 100%;
}
#answer .metadata {
margin: 0;
margin-left: 8px;
font-size: 0.8em;
font-style: italic;
}
#answer .message-suffix {
float: right;
font-size: 0.8em;
font-style: italic;
}
header {
display: flex;
align-items: center;
}
header button {
background: none;
border: none;
font-size: 1.3em;
padding: 0.5em 0.7em;
cursor: pointer;
}
header button:hover {
background-color: #e4e4e4;
}
header .chat-name {
margin-right: auto;
}
header input {
font-size: 1em;
font-weight: bold;
border: none;
border-radius: 8px;
background: none;
font-family: inherit;
}
header input:hover {
background: #e4e4e4;
}
header input:focus {
outline: none;
background: #e4e4e4;
}
.sidebar {
position: fixed;
top: 0;
left: -40vw;
width: 40vw;
height: 100vh;
overflow: auto;
background-color: #e3e3e3;
border-right: 2px solid #d9d9d9;
transition: left 0.3s ease-in-out;
}
.sidebar-overlay {
display: none;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #0e0e0e6e;
cursor: pointer;
}
.sidebar.open {
left: 0;
}
.sidebar-overlay.open {
display: block;
}
.login {
border: 1px dashed #ccc;
padding: 0.5em;
}
.params {
display: flex;
flex-wrap: wrap;
}
div.sidebar>*:last-child {
/* fix for physical phones */
padding-bottom: 8em;
}
div.sidebar .version {
text-align: right;
font-size: 0.8em;
margin-top: 1em;
}
.params label {
margin-left: 0.5em;
}
.params>div {
width: 50%;
}
.params input[type="number"] {
width: 6em;
}
.inputs {
display: flex;
}
.inputs #mainInput {
flex: 1 20em;
min-height: 10em;
max-height: 10em;
}
.inputs>div {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.inputs div.actions {
display: flex;
}
.inputs button {
margin: 0 0 0 0.2em;
font-size: 3em;
padding: 0;
border-radius: 8px;
border-width: 3px;
border-color: #f3f4f6;
}
.inputs button:hover {
background-color: #e4e4e4;
}
.inputs button#messageRoleSwitcher {
font-size: 1em;
padding: 0.2em 0.5em;
}
/* Tools styles */
#toolsList>div {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
margin: 1em;
}
#toolsList>div input[type="text"] {
flex-grow: 1;
}
#toolsList>div input:nth-child(2) {
font-weight: bold;
}
#toolsList>div textarea {
width: 100%;
}
/* Chat history styles */
#chatsHistory p {
margin: 0.4em;
padding: 1em 0.6em;
cursor: pointer;
background: #b7d3e1;
border-radius: 8px;
}
#chatsHistory p:hover {
background-color: #b7bde1;
}
#chatsHistory p button {
float: right;
line-height: 2em;
padding: 0.2em 1em;
border: none;
border-radius: 8px;
cursor: pointer;
}
#chatsHistory p button:hover {
background-color: #e4e4e4;
}
#storageStats .usage-bar-background {
position: relative;
width: 80%;
height: 1em;
margin: 0 auto;
background-color: lightgrey;
border-radius: 8px;
overflow: hidden;
}
#storageStats .usage-bar {
position: absolute;
top: 0;
left: 0;
height: 100%;
}
select {
width: 10em;
}
/* Responsive styles */
@media screen and (max-width: 1024px) {
header h1 {
font-size: 1.6em;
}
.params>div {
width: 100%;
}
.params input[type="range"] {
width: 90%;
}
}
@media screen and (max-width: 800px) {
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
header div h1 {
display: none;
}
header div h1+q {
display: none;
}
header>h1 {
font-size: 1.6em;
line-height: 1.9em;
}
#answer .metadata .usage {
display: block;
}
.sidebar {
width: 70vw;
left: -70vw;
}
.inputs #mainInput {
min-height: 4em;
max-height: 8em;
}
.inputs button {
font-size: 2em;
}
}
</style>
<title>AI Quokka, Yet Another OpenAI API client</title>
</head>
<body onload="init()">
<header>
<button class="emoji" onclick="toggleSidebar()" title="Display settings">☰</button>
<h1 class="chat-name"><input id="chatNameInput" type="text" oninput="currentChat.name = this.value;" /></h1>
<div>
<h1><img src="img/aiquokka.png" style="height: 1em;" /> AI Quokka, Yet Another OpenAI API client</h1>
<q><em>...for Quokkas are known for their cheerful demeanor</em> - ChatGPT 3.5</q>
</div>
</header>
<div class="content">
<div class="main">
<div id="answer"></div>
<div class="inputs">
<textarea id="mainInput" autofocus
oninput="this.style.height=''; this.style.height=this.scrollHeight + 'px'"></textarea>
<div>
<button id="messageRoleSwitcher" onclick="toggleMessageRole()"
title="Next mesage will be under role 'User'">U</button>
<div class="actions">
<button class="emoji" id="chat" onclick="sendChat()" title="Send message to chat">💬</button>
<button class="emoji" id="image" onclick="generateImage()" title="Generate image">🌄</button>
</div>
</div>
</div>
</div>
</div>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<div class="sidebar">
<div class="login">
<label for="userSelect">Select user</label>
<select id="userSelect" name="userSelect" onchange="setCurrentUser();">
</select>
<button class="emoji" onclick="addUser();">✨ Add user</button>
<button class="emoji" onclick="deleteUser()">🚫 Delete</button>
<button class="emoji" onclick="clearUsers()">🗑️ Clear all</button>
</div>
<h1>
Parameters
<sup style="font-size: 0.5em;">
<a href="https://platform.openai.com/docs/api-reference/chat/create" target="_blank">
API reference
</a>
</sup>
</h1>
<h2>Chat</h2>
<div class="params">
<div>
<label for="chatModelSelect">Chat Model</label>
<select id="chatModelSelect" name="chatModelSelect">
</select>
</div>
<div>
<label for="temperatureInput"
title="Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.">
Temperature:
</label>
<input type="number" id="temperatureValue" value="1" />
<input type="range" id="temperatureInput" min="0" max="2" step="0.01" value="1" />
</div>
<div>
<label for="tokensLimitInput">Completion limit</label>
<input type="number" id="tokensLimitInput" name="tokensLimitInput" value="1024" />
</div>
<div>
<label for="topPInput"
title="Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered.">
Top P:
</label>
<input type="number" id="topPValue" value="1" />
<input type="range" id="topPInput" min="0" max="1" step="0.01" value="1" />
</div>
<div>
<label for="frequencyPenaltyInput"
title="How much to penalize new tokens based on their existing frequency in the text so far. Decreases the model's likelihood to repeat the same line verbatim.">
Frequency penalty:
</label>
<input type="number" id="frequencyPenaltyValue" value="0" />
<input type="range" id="frequencyPenaltyInput" min="0" max="2" step="0.01" value="0" />
</div>
<div>
<label for="presencePenaltyInput"
title="How much to penalize new tokens based on whether they appear in the text so far. Increases the model's likelihood to talk about new topics.">
Presence penalty:
</label>
<input type="number" id="presencePenaltyValue" value="0" />
<input type="range" id="presencePenaltyInput" min="0" max="2" step="0.01" value="0" />
</div>
<div>
<label for="seedInput">Seed (beta):</label>
<input type="number" id="seedInput" value="" />
</div>
</div>
<h2>Image</h2>
<div class="params">
<div>
<label for="imageModelSelect">Image Model</label>
<select id="imageModelSelect" name="imageModelSelect">
</select>
</div>
<div>
<label for="imageSizeSelect">Image Size</label>
<select id="imageSizeSelect" name="imageSizeSelect">
<option value="1024x1024">1024x1024</option>
<option value="1024x1792">1024x1792 (Dall-e 3)</option>
<option value="1792x1024">1792x1024 (Dall-e 3)</option>
<option value="512x512">512x512 (Dall-e 2)</option>
<option value="256x256">256x256 (Dall-e 2)</option>
</select>
</div>
<div>
<label for="imageDisableRevisedPromptCb">Disable revised prompt (Dall-e 3)</label>
<input type="checkbox" id="imageDisableRevisedPromptCb" name="imageDisableRevisedPromptCb" />
</div>
<div
title="If checked, creates images with finer details and greater consistency across the image; but for double/higher price https://openai.com/pricing">
<label for="imageQualityHdCb">HD quality (Dall-e 3)</label>
<input type="checkbox" id="imageQualityHdCb" name="imageQualityHdCb" />
</div>
<div>
<label for="imageStyleSelect">Style</label>
<select id="imageStyleSelect" name="imageStyleSelect">
<option value="vivid">Vivid (default) (Dall-e 3)</option>
<option value="">None (Dall-e 2)</option>
<option value="natural">Natural (Dall-e 3)</option>
</select>
</div>
</div>
<h2 title="Tools available in all chats">Global tools</h2>
<div>
<button onclick="addTool()">🛠️ Add global tool</button>
<div id="toolsList"></div>
</div>
<h1>Your conversations</h1>
<div id="chatsHistory"></div>
<div id="storageStats"></div>
<h1>Import/Export</h1>
<div class="params">
<input type="file" id="importFile" accept=".json" />
<button onclick="importData()">Import</button>
<button onclick="exportData()">Export</button>
<span>
<label for="overwriteChatsCb" title="Overwrite existing chats by Id (checked) or append (unchecked)">
Overwrite chats
</label>
<input type="checkbox" id="overwriteChatsCb" name="overwriteChatsCb" />
</span>
</div>
<div class="version">v0.1.6</div>
</div>
<h2 id="loading" style="visibility: hidden;">Loading...</h2>
<script>
'use strict';
const localStorageUsersKey = 'localStorageUsersKey';
let users = null;
let currentUser = null;
let db = null;
let currentChat = null;
let chatRenderer = null;
let tools = null;
let builtInTools = null;
let nextMessageRole = null;
let userSelect = null;
let loadingElement = null;
let mainInput = null;
let chatsHistoryContainer = null;
let storageStatsDiv = null;
let chatNameInput = null;
let tokensLimitInput = null;
let chatModelSelect = null;
let imageModelSelect = null;
let temperatureInput = null;
let topPInput = null;
let frequencyPenaltyInput = null;
let presencePenaltyInput = null;
let seedInput = null;
let versionElement = null;
let toolsListContainer = null;
const QuokkaMessageTypes = {
chat: 'chat',
image: 'image',
toolCall: 'toolCall'
};
const OpenAiMessageRoles = {
user: 'user',
assistant: 'assistant',
system: 'system',
tool: 'tool'
};
class QuokkaMessage {
constructor(role, content, type, model, tokenUsage, finishReason, imageOptions, timeStamp, toolCallOptions) {
this.role = role;
this.content = content;
this.type = type;
this.model = model;
this.finishReason = finishReason;
this.timeStamp = timeStamp || null;
this.tokenUsage = tokenUsage ? {
prompt_tokens: tokenUsage.prompt_tokens,
completion_tokens: tokenUsage.completion_tokens,
total_tokens: tokenUsage.total_tokens
} : null;
this.imageOptions = imageOptions ? {
size: imageOptions.size,
quality: imageOptions.quality
} : null;
this.toolCallOptions = toolCallOptions ? {
toolCallId: toolCallOptions.toolCallId,
type: toolCallOptions.type,
name: toolCallOptions.name,
arguments: toolCallOptions.arguments
} : null;
}
toOpenAIModel() {
const result = {
role: this.role,
content: this.content
};
if (this.type === QuokkaMessageTypes.toolCall && this.role === OpenAiMessageRoles.assistant && this.toolCallOptions) {
result.tool_calls = [{
id: this.toolCallOptions.toolCallId,
type: this.toolCallOptions.type,
function: {
name: this.toolCallOptions.name,
arguments: this.toolCallOptions.arguments
}
}];
}
if (this.type === QuokkaMessageTypes.toolCall && this.role === OpenAiMessageRoles.tool && this.toolCallOptions) {
result.tool_call_id = this.toolCallOptions.toolCallId;
}
return result;
}
}
class QuokkaChat {
#observers = []; // private to avoid storing in IndexedDB
constructor(id, name, conversationHistory) {
if (id) {
this.id = id;
}
this._name = name || '*New chat*';
this.conversationHistory = conversationHistory || [];
}
get name() {
return this._name;
}
set name(name) {
this._name = name;
saveCurrentChat(); // TODO move
this.#observers.forEach(o => o.nameChanged?.(name));
}
addMessage(role, content, type, model, tokenUsage, finishReason, imageOptions, toolCallOptions) {
if (!this.id || this.id <= 0) {
//new chat, get name
const name = prompt('Provide name for this chat please, you can change it later');
this._name = name;
this.#observers.forEach(o => o.nameChanged?.(name));
}
const timeStamp = new Date().toISOString(); // consider using server response field "created" instead
const newMessage = new QuokkaMessage(role, content, type, model, tokenUsage, finishReason, imageOptions, timeStamp, toolCallOptions);
this.conversationHistory.push(newMessage);
saveCurrentChat(); // TODO move
this.#observers.forEach(o => o.messageAdded?.(newMessage));
}
subscribe(observer) {
this.#observers.push(observer);
}
}
class QuokkaCostEstimator {
// prices below are USD per million tokens
static #priceListCompletions = [
{ model: /^gpt-4o-mini-[0-9-]*$/, priceIn: 0.15, priceOut: 0.60 },
{ model: /^gpt-4o-[0-9-]*$/, priceIn: 5, priceOut: 15 },
{ model: /^gpt-4-*[0-9]*-preview$/, priceIn: 10, priceOut: 30 },
{ model: /^gpt-4-*[0-9]*$/, priceIn: 30, priceOut: 60 },
{ model: /^gpt-3.5-turbo-*[0-9]*$/, priceIn: 0.5, priceOut: 1.5 },
{ model: /^gpt-4-vision-preview$/, priceIn: 10, priceOut: 30 },
{ model: /^gpt-4-32k$/, priceIn: 30, priceOut: 60 },
// for o1 output tokens include internal reasoning tokens generated by the model that are not visible in API responses
{ model: /^o1-preview$/, priceIn: 15, priceOut: 60 },
{ model: /^o1-mini$/, priceIn: 3, priceOut: 12 }
];
// prices below are USD per image
static #priceListImages = [
{ model: 'dall-e-3', quality: 'standard', size: '1024x1024', price: 0.040 },
{ model: 'dall-e-3', quality: 'standard', size: '1024x1792', price: 0.080 },
{ model: 'dall-e-3', quality: 'standard', size: '1792x1024', price: 0.080 },
{ model: 'dall-e-3', quality: 'hd', size: '1024x1024', price: 0.080 },
{ model: 'dall-e-3', quality: 'hd', size: '1024x1792', price: 0.120 },
{ model: 'dall-e-3', quality: 'hd', size: '1792x1024', price: 0.120 },
{ model: 'dall-e-2', quality: 'standard', size: '1024x1024', price: 0.020 },
{ model: 'dall-e-2', quality: 'standard', size: '512x512', price: 0.018 },
{ model: 'dall-e-2', quality: 'standard', size: '256x256', price: 0.016 }
];
static estimateCost(message) {
try {
if (message.type === QuokkaMessageTypes.chat || message.type === QuokkaMessageTypes.toolCall) {
return QuokkaCostEstimator.estimateChatCost(message);
} else if (message.type === QuokkaMessageTypes.image) {
return QuokkaCostEstimator.estimateImageCost(message);
}
} catch (error) {
console.error('Failed to estimate cost for message', message, error);
}
return null;
}
static estimateChatCost(message) {
if (!message.model || !message.tokenUsage) {
return null;
}
const model = message.model;
const inTokens = message.tokenUsage?.prompt_tokens;
const outTokens = message.tokenUsage?.completion_tokens;
const priceModel = QuokkaCostEstimator.#priceListCompletions.find(p => model.match(p.model));
if (!priceModel) {
console.warn('No price found for model', model);
return null;
}
const costIn = priceModel.priceIn * inTokens / 1_000_000;
const costOut = priceModel.priceOut * outTokens / 1_000_000;
return {
costIn,
costOut,
costTotal: costIn + costOut
};
}
static estimateImageCost(message) {
if (!message.model || !message.imageOptions || !message.imageOptions.size) {
return null;
}
const model = message.model;
const size = message.imageOptions.size;
const quality = message.imageOptions.quality ?? 'standard';
const priceModel = QuokkaCostEstimator.#priceListImages.find(p => p.model === model && p.size === size && p.quality === quality);
if (!priceModel) {
console.warn('No price found for model', model, 'size', size, 'quality', quality);
return null;
}
return {
costIn: null,
costOut: priceModel.price,
costTotal: priceModel.price
};
}
}
class QuokkaChatRenderer {
#chat = null;
#answerDiv = null;
#totalCostParagraph = null;
constructor(answerDiv) {
this.#answerDiv = answerDiv;
}
// Observer methods
nameChanged(name) {
this.renderChatName();
}
messageAdded(message) {
this.renderMessage(message);
this.scrollToBottom();
}
// Renderer methods
selectChat(chat) {
this.#chat = chat;
this.#chat.subscribe(this);
this.renderChatName();
this.renderChat();
}
renderChatName() {
chatNameInput.value = this.#chat.name;
}
renderChat() {
this.#answerDiv.innerHTML = '';
this.#chat.conversationHistory?.forEach(ch => {
this.renderMessage(ch);
});
this.scrollToBottom();
}
renderMessage(message) {
const { role, content = '', type } = message || {};
if (!role) {
console.warn('Invalid message, missing role', message);
return;
}
this.renderMetadata(message);
const answerParagraph = document.createElement('p');
answerParagraph.classList.add('chat-bubble', role, type);
if (type === QuokkaMessageTypes.image && role === 'assistant' && content instanceof Blob) {
const img = document.createElement('img');
img.src = URL.createObjectURL(content);
answerParagraph.append(img);
} else if (type === QuokkaMessageTypes.toolCall && role === 'assistant') {
answerParagraph.innerHTML += `Tool call: '${message?.toolCallOptions?.name}' will be called with arguments: ${message?.toolCallOptions?.arguments}`;
} else if (type === QuokkaMessageTypes.toolCall && role === 'tool') {
answerParagraph.innerHTML += `Tool call result: ${content}`;
} else {
answerParagraph.innerHTML += content?.replace(/\n/g, '<br />');
}
if (message?.finishReason) {
answerParagraph.innerHTML += `<br /><span class="message-suffix">Finish reason: ${message.finishReason}</span>`;
}
if (message?.toolCallOptions?.toolCallId) {
answerParagraph.innerHTML += `<br /><span class="message-suffix">Tool call ID: ${message.toolCallOptions.toolCallId}</span>`;
}
this.#answerDiv.append(answerParagraph);
this.renderTotalCost();
}
renderMetadata(message) {
if (!message || (!message.tokenUsage && !message.model)) {
return;
}
const metadataParagraph = document.createElement('p');
metadataParagraph.classList.add('metadata');
if (message.model) {
metadataParagraph.innerHTML += `<span class="model">Model: ${message.model}. </span>`;
}
if (message.tokenUsage) {
const completionText = `✔️completion: ${message.tokenUsage.completion_tokens}`;
const promptText = `❔prompt: ${message.tokenUsage.prompt_tokens}`;
const totalText = `🟰total: ${message.tokenUsage.total_tokens}`;
metadataParagraph.innerHTML += `<span class="usage">Tokens usage: ${completionText} ${promptText} ${totalText}. </span>`;
}
if (message.timeStamp) {
const timeStamp = message.timeStamp ? new Date(message.timeStamp).toLocaleString() : 'unknown';
metadataParagraph.innerHTML += `<span class="time-stamp">🕒${timeStamp}. </span>`;
}
const cost = QuokkaCostEstimator.estimateCost(message);
if (cost) {
metadataParagraph.innerHTML += `<span class="price">💰Cost: $${cost.costTotal.toFixed(3)} ($${cost.costIn?.toFixed(6) ?? 'n/a'} in, $${cost.costOut?.toFixed(6) ?? 'n/a'} out)</span>`;
}
this.#answerDiv.append(metadataParagraph);
}
renderTotalCost() {
const estimatedMessages = this.#chat.conversationHistory
.map(m => QuokkaCostEstimator.estimateCost(m))
.filter(c => c);
if (estimatedMessages.length === 0) {
return;
}
const totalCost = estimatedMessages.reduce((acc, c) => {
acc.costIn += c.costIn;
acc.costOut += c.costOut;
acc.costTotal += c.costTotal;
return acc;
}, { costIn: 0, costOut: 0, costTotal: 0 });
if (this.#totalCostParagraph) {
this.#totalCostParagraph.remove();
}
this.#totalCostParagraph = document.createElement('p');
this.#totalCostParagraph.classList.add('metadata');
this.#totalCostParagraph.innerHTML = `Estimated total conversation cost: $${totalCost.costTotal.toFixed(3)} ($${totalCost.costIn.toFixed(6)} in, $${totalCost.costOut.toFixed(6)} out)`;
this.#answerDiv.append(this.#totalCostParagraph);
}
scrollToBottom() {
setTimeout(() => {
this.#answerDiv.scrollTop = this.#answerDiv.scrollHeight;
});
}
}
class QuokkaTool {
constructor(name, description, url, parametersSchema, active) {
this.name = name;
this.description = description;
this.url = url;
this.parametersSchema = parametersSchema;
this.active = active;
}
toOpenAIModel(toolCompatMode) {
const result = {
type: 'function',
function: {
name: this.name,
description: this.description
}
};
if (this.parametersSchema) {
result.function.parameters = this.parametersSchema;
// TODO: remove this compatibility for LocalAI
if (toolCompatMode) {
// scan only one level of properties for now
Object.entries(result.function.parameters.properties).forEach(([key, value]) => {
if (value.type === 'object' && !value.properties) {
value.type = 'string';
}
});
}
} else if (toolCompatMode) { // compatibility mode for LocalAI
result.function.parameters = {
"type": "object",
"properties": {
"i": {
"type": "number",
"description": "i"
}
},
"required": []