File size: 30,633 Bytes
e727ed4
 
 
 
424154f
231ac39
e727ed4
 
 
 
 
 
 
 
6a14077
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
 
 
 
 
 
 
e727ed4
 
 
 
424154f
 
 
 
 
e727ed4
 
424154f
e727ed4
 
424154f
 
 
 
 
 
 
e727ed4
424154f
e727ed4
 
424154f
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
424154f
e727ed4
 
 
 
 
 
 
 
 
424154f
e727ed4
424154f
 
e727ed4
 
 
 
 
6a14077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
 
 
 
 
231ac39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424154f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a14077
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231ac39
 
 
 
 
 
 
e727ed4
 
 
0bb5dca
6a14077
 
 
 
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231ac39
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231ac39
8c4efa5
 
 
 
 
 
 
 
 
 
 
 
 
231ac39
8c4efa5
231ac39
8c4efa5
 
231ac39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a14077
e727ed4
 
 
 
 
 
 
 
6a14077
 
 
 
 
 
 
 
 
 
 
e727ed4
 
 
 
6a14077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa47ca0
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb79bda
e727ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231ac39
 
 
 
 
 
 
 
 
e727ed4
 
 
 
 
 
 
 
876125c
 
 
e727ed4
 
876125c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e727ed4
 
 
 
 
 
 
 
 
 
6a14077
 
 
e727ed4
 
 
 
 
 
 
50bb65c
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Multi Agent</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>
    <style>
:root {
    --primary-color: #304b76;
    --secondary-color: #f0f8ff;
    --text-color: #333;
    --background-color: #f5f7fa;
}
body {
    font-family: 'Poppins', sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: var(--background-color);
    color: var(--text-color);
    font-size: 16px;
}
#app {
    max-width: 900px;
    margin: 0 auto;
    padding: 10px;
}
.chat-container {
    background-color: #ffffff;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 98vh;
    transition: all 0.3s ease;
}
.messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
}
.message {
    max-width: 80%;
    margin-bottom: 20px;
    padding: 10px 20px;
    border-radius: 20px;
    font-size: 1em;
    line-height: 1.5;
    word-wrap: break-word;
    animation: fadeIn 0.5s ease;
}
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}
table, th, td {
    border: 1px solid #ddd;
}
th, td {
    padding: 10px;
    text-align: left;
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
.user-message {
    background-color: var(--primary-color);
    color: #ffffff;
    align-self: flex-end;
    border-bottom-right-radius: 5px;
}
.bot-message {
    background-color: var(--secondary-color);
    color: var(--text-color);
    align-self: flex-start;
    border-bottom-left-radius: 5px;
    position: relative;
}
.copy-button {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: transparent;
    border: none;
    cursor: pointer;
    padding: 5px;
    transition: all 0.3s ease;
}
.copy-button svg {
    width: 16px;
    height: 16px;
    stroke: var(--primary-color);
}
.copy-button:hover {
    transform: scale(1.1);
}
.input-area {
    display: flex;
    padding: 15px;
    background-color: #ffffff;
    border-top: 1px solid #e0e0e0;
}
#user-input {
    flex-grow: 1;
    padding: 12px 15px;
    border: 2px solid var(--primary-color);
    border-radius: 15px;
    font-size: 1em;
    outline: none;
    transition: all 0.3s ease;
}
#user-input:focus {
    box-shadow: 0 0 0 3px rgba(0,119,190,0.3);
}
.send-button, .reset-button {
    background-color: var(--primary-color);
    color: #ffffff;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    margin-left: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}
.send-button:hover, .reset-button:hover {
    background-color: #005fa3;
    transform: scale(1.05);
}
.send-button svg, .reset-button svg {
    width: 24px;
    height: 24px;
}
.option-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 15px;
}
.option-button {
    background-color: #ffffff;
    border: 2px solid var(--primary-color);
    border-radius: 20px;
    padding: 8px 16px;
    font-size: 0.875em;
    cursor: pointer;
    transition: all 0.3s ease;
}
.option-button:hover {
    background-color: var(--secondary-color);
    transform: translateY(-2px);
}
.option-button.selected {
    background-color: var(--primary-color);
    color: #ffffff;
}
.audio-button {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    margin-top: 10px;
    transition: all 0.3s ease;
}
.audio-button:hover {
    transform: scale(1.1);
}
.audio-button svg {
    width: 30px;
    height: 30px;
    fill: var(--primary-color);
}
.dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #5853c0;
    margin: 0 3px;
    animation: bounce 1.4s infinite ease-in-out;
}
.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
    0%, 80%, 100% { 
        transform: scale(0);
    } 40% { 
        transform: scale(1.0);
    }
}
.chat-container {
    position: relative;
}
.input-area {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    transition: transform 0.3s ease;
}
.messages {
    padding-bottom: 80px;
}
.input-hidden {
    transform: translateY(100%);
}
.tool-options {
    position: absolute;
    bottom: 100%;
    left: 0;
    background-color: #ffffff;
    border: 1px solid #ddd;  
    border-radius: 8px;      
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);  
    display: flex;
    flex-direction: column;
    width: auto;
    min-width: 120px;        
    margin-bottom: 10px;
}
.tool-options button {
    padding: 10px 15px;      
    border: none;
    background: none;
    text-align: left;
    cursor: pointer;
    white-space: nowrap;
    transition: background-color 0.3s ease;  
    font-size: 1em;          
    font-weight: 500;         
    color: #333;
    border-radius: 4px;
}
.tool-options button:hover {
    background-color: #e0e0e0;  
    color: #000;              
}
details {
    margin-top: 10px;
    border-radius: 4px;
    padding: 5px;
}
summary {
    cursor: pointer;
    font-weight: bold;
}
.ref-content {
    margin-top: 10px;
    justify-content: center;
}
.ref-item {
    margin-bottom: 0px;
}
.ref-item small {
    color: #666;
}
hr {
    margin: 10px 0;
    border: none;
    border-top: 1px solid #eee;
}
.ref-link {
    text-decoration: none;
    color: inherit;
    display: block;
    padding: 5px;
    border-radius: 4px;
    transition: background-color 0.2s;
}
.ref-link:hover {
    background-color: #e3e3ea;
    color: inherit;
}
.ref-link:visited {
    color: inherit;
}
img, video {
    max-width: 100%;
    height: auto;
}
.download-buttons {
    display: flex;
    gap: 5px;
    margin-top: 5px;
}
.download-button {
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 3px;
    padding: 2px 5px;
    font-size: 0.8em;
    cursor: pointer;
    transition: background-color 0.3s;
}

.download-button:hover {
    background-color: #e0e0e0;
}
@media (max-width: 600px) {
    body {
        font-size: 14px;
    }
    #app {
        padding: 5px;
    }
    .chat-container {
        height: 100vh;
        border-radius: 0;
    }
    .messages {
        padding: 10px;
    }
    .message {
        max-width: 90%;
    }
    #user-input {
        font-size: 16px;
        padding: 12px;
    }
    .send-button, .reset-button {
        width: 44px;
        height: 44px;
    }
    .tool-options {
        width: 100%;
        left: 0;
        right: 0;
    }
    .tool-options button {
        padding: 12px 15px;
    }
}
@media (max-width: 900px) and (orientation: landscape) {
    .chat-container {
        height: 100vh;
    }
    .messages {
        max-height: calc(100vh - 60px);
    }
}
@media (hover: none) {
    .option-button:active {
        background-color: var(--primary-color);
        color: #ffffff;
    }
}
    </style>
</head>
<body>
    <div id="app">
        <div class="chat-container">
            <div class="messages" ref="messageContainer" @scroll="handleScroll">
                <div v-for="(message, index) in messages" :key="index" 
                     :class="['message', message.type === 'user' ? 'user-message' : 'bot-message']">
                    <div v-if="message.type === 'bot' && message.content === ''" id="typing-animation"></div>
                    <div v-else v-html="message.content"></div>
                    <button v-if="message.type === 'bot' && message.audio" @click="toggleAudio(index)" class="audio-button">
                        <svg v-if="!message.isPlaying" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path d="M8 5v14l11-7z"/>
                        </svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
                        </svg>
                    </button>
                    <button v-if="message.type === 'bot' && message.rawResponse" @click="copyMarkdownToClipboard(message.rawResponse)" class="copy-button">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
                            <rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect>
                        </svg>
                    </button>
                    <div v-if="message.type === 'bot' && message.rawResponse" class="option-buttons">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span>Would you like to download this chat as</span>
                            <button @click="downloadResponse(message.rawResponse, 'pdf')" class="option-button">PDF</button>
                            <button @click="downloadResponse(message.rawResponse, 'docx')" class="option-button">DOCX</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="input-area" :class="{ 'input-hidden': isScrollingUp }">
                <input type="text" id="user-input" v-model="userInput" @keyup.enter="sendMessage" @input="handleInput($event)" placeholder="Type your message... (type / to see available tools)">
                <div v-if="showToolOptions" class="tool-options">
                    <button @click="selectTool('web')">/web</button>
                    <button @click="selectTool('news')">/news</button>
                </div>
                <button class="send-button" @click="sendMessage">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="22" y1="2" x2="11" y2="13"></line>
                        <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                    </svg>
                </button>
                <button class="reset-button" @click="resetConversation">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path>
                        <path d="M3 3v5h5"></path>
                    </svg>
                </button>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script>
        marked.setOptions({
            highlight: function (code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                } else {
                    return hljs.highlightAuto(code).value;
                }
            },
            sanitize: false
        });
        
        function createTypingAnimation() {
          const container = document.getElementById('typing-animation');
          for (let i = 0; i < 3; i++) {
            const dot = document.createElement('div');
            dot.className = 'dot';
            container.appendChild(dot);
          }
        }

        function extractCustomFileName(html) {
              // Try to find the first h1-h4 tag content
              const headingMatch = html.match(/<h[1-4][^>]*>(.*?)<\/h[1-4]>/i);
              if (headingMatch) {
                  return headingMatch[1].trim();
              }
          
              // If no heading found, use the first 7 words
              const textContent = html.replace(/<[^>]+>/g, ' ').trim();
              const words = textContent.split(/\s+/);
              return words.slice(0, 7).join(' ');
          } 
      
        async function convertHtmlToFile(html, fileType, customFileName = '') {
          
          const url = 'https://pvanand-web-scraping.hf.space/html_to_' + fileType;
          customFileName = extractCustomFileName(html);
          
          function sanitizeFileName(name) {
            return (name.replace(/[^a-z0-9\s]/gi, '')
                       .toLowerCase()
                       .replace(/\s+/g, '_')
                       .substring(0, 50)) || 'generated_report';
          }
          const fileName = `${sanitizeFileName(customFileName || 'generated_report')}.${fileType}`;
          try {
            const response = await fetch(url, {
              method: 'POST',
              headers: { 
                'accept': 'application/json',
                'Content-Type': 'application/json' 
              },
              body: JSON.stringify({ html_content: html })
            });
            if (!response.ok) throw new Error('Conversion failed');
            const blob = await response.blob();
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(a.href);
          } catch (error) {
            throw new Error(`Failed to download ${fileName}. Please try again.`);
          }
        }

        const app = new Vue({
            el: '#app',
            data: {
                messages: [],
                userInput: '',
                selectedOptions: {},
                conversationId: '',
                currentAudio: null,
                isScrollingUp: false,
                lastScrollTop: 0,
                tool_call: 'auto',
                showToolOptions: false,
            },
            methods: {
                async sendMessage() {
                    if (!this.userInput.trim()) return;
                    
                    this.messages.push({ type: 'user', content: marked.parse(this.userInput) });
                    const message = this.userInput;
                    this.userInput = '';
                    this.selectedOptions = {};
                    let streamingIndex = this.messages.push({ type: 'bot', content: '' }) - 1;
                    
                    this.$nextTick(() => {
                        createTypingAnimation();
                    });
                    try {
                        const response = await fetch('https://pvanand-general-chat.hf.space/v2/followup-tools-agent', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-API-Key': '44d5c2ac18ced6fc25c1e57dcd06fc0b31fb4ad97bf56e67540671a647465df4'
                            },
                            body: JSON.stringify({
                                query: message,
                                model_id: 'openai/gpt-4o-mini',
                                conversation_id: this.conversationId,
                                user_id: 'string',
                                tool_call: this.tool_call,
                            })
                        });
                        const reader = response.body.getReader();
                        let rawResponse = '';
                        let jsonData = null;
                        let refData = null; // New variable to hold reference data
                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) break;
                            const chunk = new TextDecoder().decode(value);
                            if (chunk.includes('<json>')) {
                                const [textPart, jsonPart] = chunk.split('<json>');
                                rawResponse += textPart;
                                const jsonString = jsonPart.split('</json>')[0];
                                // Check for <ref> tag first
                                const refMatch = jsonString.match(/<ref>(.*?)<\/ref>/);
                                if (refMatch) {
                                    refData = JSON.parse(refMatch[1]); // Parse the reference data
                                } else {
                                    try {
                                        jsonData = JSON.parse(jsonString); // Parse JSON only if <ref> is not present
                                    } catch (error) {
                                        console.error("JSON parsing error:", error);
                                        console.log("Raw JSON string:", jsonString);
                                    }
                                }
                            } else {
                                rawResponse += chunk;
                            }
                                                    // After processing, display the refData if it exists
                            if (refData) {
                            const refMessage = `
                                <details>
                                    <summary>Reference Information</summary>
                                    <div class="ref-content">
                                        ${refData.map(item => `
                                            <div class="ref-item">
                                                <a href="${item.url}" target="_blank" class="ref-link">
                                                    <strong>${item.title}</strong>: ${item.snippet}
                                                </a>
                                                <br>
                                                <small>Last updated: ${item.last_updated}</small>
                                            </div>
                                        `).join('<hr>')}
                                    </div>
                                </details>
                            `;
                            this.messages.push({ type: 'bot', content: refMessage });
                        } 
                            
                            rawResponse = rawResponse.replace(/<\/?response>/g, '');
                            rawResponse = rawResponse.replace(/<tools>[\s\S]*?<\/tools>/g, ''); 
                            rawResponse = rawResponse.replace(/<interact>[\s\S]*?<\/interact>/g, '');
                            rawResponse = rawResponse.replace(/<tool>[\s\S]*?<\/tool>/g, '');
                            this.$set(this.messages[streamingIndex], 'content', marked.parse(rawResponse));
                            this.$set(this.messages[streamingIndex], 'rawResponse', rawResponse);
                        }
                        if (jsonData) {
                            if (jsonData.tools && jsonData.tools.length > 0) {
                                let toolsMessage = "\n\n**Tools Used:**\n";
                                jsonData.tools.forEach(tool => {
                                    toolsMessage += `- ${tool.name.charAt(0).toUpperCase() + tool.name.slice(1)}: ${tool.input}\n`;
                                });
                                
                                this.$set(this.messages[streamingIndex], 'content', this.messages[streamingIndex].content + marked.parse(toolsMessage));
                            }
                            if (jsonData.clarification && jsonData.clarification.length > 0) {
                                streamingIndex = this.messages.push({ type: 'bot', content: '' }) - 1;
                                this.renderClarificationQuestions(jsonData.clarification, streamingIndex);
                            }
                        }
                        rawResponse = rawResponse.replace(/[#!*_\[\]\(\)`]/g, '');
                        const audioUrl = await this.convertToSpeech(rawResponse);
                        if (audioUrl) {
                            this.$set(this.messages[streamingIndex], 'audio', audioUrl);
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        this.messages.push({ type: 'bot', content: 'An error occurred while processing your request.' });
                    }
                    this.$nextTick(() => this.scrollToBottom());
                },
                handleScroll(event) {
                    const st = event.target.scrollTop;
                    this.isScrollingUp = st < this.lastScrollTop;
                    this.lastScrollTop = st <= 0 ? 0 : st;
                },
                renderClarificationQuestions(clarification, messageIndex) {
                    if (!clarification || clarification.length === 0) return;
    
                    let clarificationHtml = '';
                    clarification.forEach((item, questionIndex) => {
                        clarificationHtml += `<strong>${item.question}</strong><br>`;
                        clarificationHtml += '<div class="option-buttons">';
                        item.options.forEach((option, optionIndex) => {
                            const escapedOption = option.replace(/'/g, "\\'");
                            clarificationHtml += `<button class="option-button" onclick="app.toggleOption('${escapedOption}', ${questionIndex}, ${optionIndex})">${option}</button>`;
                        });
                        clarificationHtml += '</div><br>';
                    });
    
                    this.$set(this.messages[messageIndex], 'content', this.messages[messageIndex].content + marked.parse(clarificationHtml));
                    this.$nextTick(() => {
                        this.scrollToBottom();
                        this.updateButtonStates();
                    });
                },
                toggleOption(option, questionIndex, optionIndex) {
                    if (!this.selectedOptions[questionIndex]) {
                        this.$set(this.selectedOptions, questionIndex, []);
                    }
        
                    const index = this.selectedOptions[questionIndex].indexOf(option);
                    if (index > -1) {
                        this.selectedOptions[questionIndex].splice(index, 1);
                    } else {
                        this.selectedOptions[questionIndex].push(option);
                    }
        
                    this.updateInputFromSelectedOptions();
                    this.updateButtonStates();
                },
                updateInputFromSelectedOptions() {
                    this.userInput = Object.entries(this.selectedOptions)
                        .map(([questionIndex, options]) => 
                            `Q${parseInt(questionIndex) + 1}: ${options.join(', ')}`)
                        .join(' | ');
                    this.$nextTick(() => document.getElementById('user-input').focus());
                },
                updateButtonStates() {
                    Object.entries(this.selectedOptions).forEach(([questionIndex, options]) => {
                        const buttons = document.querySelectorAll(`.option-buttons:nth-of-type(${parseInt(questionIndex) + 1}) .option-button`);
                        buttons.forEach((button) => {
                            if (options.includes(button.textContent)) {
                                button.classList.add('selected');
                            } else {
                                button.classList.remove('selected');
                            }
                        });
                    });
                },
                resetConversation() {
                    this.conversationId = uuid.v4();
                    this.messages = [];
                    this.selectedOptions = {};
                    this.userInput = '';
                    this.isScrollingUp = false;
                    this.lastScrollTop = 0;
                    this.tool_call = 'auto';
                    this.showToolOptions = false;
                    this.$nextTick(() => {
                        if (this.$refs.messageContainer) {
                            this.$refs.messageContainer.scrollTop = 0;
                        }
                    });
                    const inputArea = document.querySelector('.input-area');
                    if (inputArea) inputArea.classList.remove('input-hidden');
                },
                scrollToBottom() {
                    const container = this.$refs.messageContainer;
                    container.scrollTop = container.scrollHeight;
                },
                async convertToSpeech(text) {
                    const voice = 'en-US-JennyNeural';
                    const encodedText = encodeURIComponent(text);
                    try {
                        const response = await fetch(`https://pvanand-audio-chat-indic.hf.space/auto-tts?text=${encodedText}`, {
                            method: 'GET',
                            headers: {
                                'accept': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        const blob = await response.blob();
                        return URL.createObjectURL(blob);
                    } catch (error) {
                        console.error('Error:', error);
                        return null;
                    }
                },
                toggleAudio(index) {
                    const message = this.messages[index];
                    if (this.currentAudio && this.currentAudio !== message.audioElement) {
                        this.currentAudio.pause();
                        this.messages.forEach(m => {
                            if (m.audioElement === this.currentAudio) {
                                m.isPlaying = false;
                            }
                        });
                    }
                    if (!message.audioElement) {
                        message.audioElement = new Audio(message.audio);
                        message.audioElement.addEventListener('ended', () => {
                            message.isPlaying = false;
                            this.$forceUpdate();
                        });
                    }
                    if (message.isPlaying) {
                        message.audioElement.pause();
                    } else {
                        message.audioElement.play();
                        this.currentAudio = message.audioElement;
                    }
                    message.isPlaying = !message.isPlaying;
                    this.$forceUpdate();
                },
                copyMarkdownToClipboard(rawResponse) {
                    navigator.clipboard.writeText(rawResponse).then(() => {
                        // remove alert
                    }).catch(err => {
                        console.error('Failed to copy: ', err);
                    });
                },
                async downloadResponse(rawResponse, fileType) {
                    try {
                        const html = marked.parse(rawResponse);
                        await convertHtmlToFile(html, fileType);
                    } catch (error) {
                        console.error('Error downloading file:', error);
                        // You might want to show an error message to the user here
                    }
                },
                handleInput(event) {
                console.log("Input event triggered", event.target.value); // For debugging
                if (event.target.value === '/') {
                    console.log("Slash detected, showing tool options"); // For debugging
                    this.showToolOptions = true;
                } else {
                    this.showToolOptions = false;
                }
                // Reset tool_call to 'auto' if input doesn't contain /web or /news
                if (!event.target.value.includes('/web') && !event.target.value.includes('/news')) {
                    this.tool_call = 'auto';
                }
            },
            selectTool(tool) {
            if (tool === 'web') {
                this.tool_call = 'web';
                this.userInput = '/web ';
            } else if (tool === 'news') {
                this.tool_call = 'news';
                this.userInput = '/news ';
            } else {
                this.tool_call = 'auto';
            }
            this.showToolOptions = false;
            this.$nextTick(() => {
                const inputElement = document.getElementById('user-input');
                inputElement.focus();
                inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length);
            });
        },
                watch: {
                userInput(newVal, oldVal) {
                    console.log("userInput changed", newVal); // For debugging
                    if (newVal === '/') {
                        this.showToolOptions = true;
                    } else {
                        this.showToolOptions = false;
                    }
                }
            },
            toggleSnippet(index) {
        this.$set(this.expandedSnippets, index, !this.expandedSnippets[index]);
            },
            },
            mounted() {
                this.resetConversation();
            }
        });
    </script>
</body>
</html>