Introduction

This javascript code, created with GPT/Claude and It adds a quality-of-life proxy switcher to SillyTavern. It provides a panel of buttons for quickly applying predefined proxies, settings, models, etc. Although SillyTavern now includes the Kingbased proxy preset manager, this script offers greater flexibility with more setup. Requires a browser script extension of your choice to run. (Tempermonkey, Greasemonkey, Userscripts etc..)

Note: This script is primarily for PC and may not be fully mobile-friendly. It relies on mouse hover to select endpoints. But the latest update does have a context menu in the lower left to create simple buttons that are touch friendly.

image


Image2

Defining Proxies

To add proxies, modify the array under const proxies. The script includes examples like Miniproxy, MM, Charybdis, and a Dummy template:

{
    name: 'Dummy',
    proxy: 'https://dummy.onrender.com/',
    model: 'Opus',
    settings: {
        max_context: [25000, 50000, 18000, 32000],
        max_response: [4096, 2048],
        temperature: [2.0, 1.0],
        freq_pen: [0.25],
        pres_pen: [0.05],
        top_p: [0.1],
    },
    urls: ['oai', 'ant', 'azr', 'aws', 'gem', 'mix'],
    token: 'TOKEN'
}
  • settings parameters are applied per endpoint in the order: max_context: [GPT, Claude, Gemini, Mistral].
  • model sets a default value for the proxy.
  • urls specifies supported endpoints. Custom URLs can be defined like this:
1
2
3
4
urls: {
    oai: 'ok/openai',
    ant: 'ok/anthropic',
}

Defining Model Buttons

Edit const modelSwap to define which models get quick-switch buttons. Example:

1
2
3
4
5
6
7
const modelSwap = {
    'claude-3-opus-20240229': { displayName: "Opus", max_context: 64000, max_response: 2048, temperature: 1.0, top_p: 1, top_k: 74},
    'claude-2.0': { displayName: "Claude 2.0"},
    'claude-2.1': { displayName: "Claude 2.1"},
    'gpt-4-turbo-2024-04-09': { displayName: "GPT-4-Turbo", max_context: 80000},
    'gpt-3.5-turbo-16k-0613': { displayName: "Turbo 16k", max_context: 16383},
};

Supported parameters include:

  • displayName (mandatory)
  • max_context
  • max_response
  • temperature
  • top_p
  • top_k
  • freq_pen
  • pres_pen

To change the default model, modify const defaultModels:

1
2
3
4
5
6
7
8
const defaultModels = {
    oai: 'gpt-4-1106-preview',
    azr: 'gpt-4-1106-preview',
    ant: 'claude-3-sonnet-20240229',
    aws: 'claude-3-sonnet-20240229',
    gem: 'gemini-1.5-pro-latest',
    mix: 'mistral-medium-latest'
};

SillyTavern Proxy Switcher (STPS) Script

Latest update: 22/07/24 v8 - https://files.catbox.moe/tuh0t6.js
Previous: v7

  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
// ==UserScript==
// @name         SillyTavern Proxy Switcher
// @version      8.0
// @description  SillyTavern Proxy Switcher - Now with a mobile friendly-ish context menu.
// @author       Walter
// @match        http://127.0.0.1:8000/
// @grant        GM_addStyle
// ==/UserScript==

// Check https://rentry.org/STPS for updates and how to modify.

(function() {
    'use strict';

    // Configuration
    const config = {
        defaultModels: {
            oai: 'gpt-4o-2024-05-13',
            azr: 'gpt-4o-2024-05-13',
            ant: 'claude-3-5-sonnet-20240620',
            aws: 'claude-3-sonnet-20240229',
            gem: 'gemini-1.5-pro-latest',
            mix: 'mistral-medium-latest'
        },
        defaultUrls: {
            ant: 'proxy/anthropic',
            oai: 'proxy/openai',
            aws: 'proxy/aws/claude',
            azr: 'proxy/azure',
            gem: 'proxy/google-ai',
            mix: 'proxy/mistral-ai'
        },
        zoneNames: {
            ant: 'Claude',
            aws: 'AWS',
            oai: 'GPT',
            azr: 'Azure',
            gem: 'Gemini',
            mix: 'Mistral'
        },
        defaultSettings: {
            max_context: [62000, 62000, 32000, 32000],
            max_response: [4096, 4096, 1024, 1024],
            temperature: [2.0, 0.9, 1.0, 1.0],
            top_p: [0.80, 0.95, 1, 1],
            top_k: [0, 2, 0, 0],
            freq_pen: [0.50, 0.00, 0.00, 0.00],
            pres_pen: [0.05, 0.00, 0.00, 0.00],
        },
        settingsMap: {
            max_context: 'openai_max_context',
            max_response: 'openai_max_tokens',
            temperature: 'temp_openai',
            top_p: 'top_p_openai',
            top_k: 'top_k_openai',
            freq_pen: 'freq_pen_counter_openai',
            pres_pen: 'pres_pen_counter_openai'
        }
    };

    const proxies = [{
        name: 'Dummy',
        proxy: 'https://dummy.onrender.com/',
        model: 'Opus',
        settings: {
            max_context: [64000, 32000, 32000, 12000],
            max_response: [4096, 2048, 768, 512],
            temperature: [1.0, 1.0, 1.0, 1.0],
            top_p: [0.8, 1, 1, 1],
            top_k: [0, 74, 0, 0],
            freq_pen: [0.25],
            pres_pen: [0.05],
        },
        urls: ['oai', 'ant', 'azr', 'aws', 'gem', 'mix'],
        token: 'TOKEN'
    }, {
        name: 'MM',
        proxy: 'https://examined-back-breakdown-diabetes.trycloudflare.com/',
        model: 'Opus',
        settings: {
            max_context: [64000, 32000],
            max_response: [4096, 2048],
            temperature: [2.0, 1.0],
            top_p: [1, 1],
            top_k: [0, 74],
        },
        urls: {
            ant: 'proxy/anthropic',
            aws: 'proxy/aws/claude',
        },
        token: 'YOUR_MM_TOKEN'
    }, {
        name: 'Charybdis',
        proxy: 'https://charybdis.dragonetwork.pl/',
        settings: {
            max_context: [64000, 32000],
            max_response: [1024, 1024],
            temperature: [1.0, 0.9],
            top_p: [1, 1],
            top_k: [0, 74],
        },
        urls: ['ant', 'oai'],
        token: 'YOUR_CHAR_TOKEN'
    }, {
        name: 'MiniProxy',
        proxy: 'https://assistant.aitism.net/assistant/miniproxy',
        model: 'Opus',
        settings: {
            max_context: [64000],
            max_response: [2048],
            temperature: [1.0],
            top_p: [0.8, 1],
            top_k: [0, 74],
        },
        urls: ['ant', 'oai', 'aws', 'azr'],
        token: 'YOUR_FIZ_TOKEN'
    }];

    const modelSwap = {
        'claude-3-opus-20240229': { displayName: "Opus"},
        'claude-3-5-sonnet-20240620': { displayName: "Sonnet 3.5"},
        'claude-3-sonnet-20240229': { displayName: "Sonnet"},
        'claude-3-haiku-20240307': { displayName: "Haiku"},
        'claude-2.1': { displayName: "Claude 2.1"},
        'gpt-4-turbo-2024-04-09': { displayName: "GPT-4-Turbo", max_context: 80000},
        'gpt-3.5-turbo-16k-0613': { displayName: "Turbo 16k", max_context: 16383},
        'gpt-4-1106-preview': { displayName: "4-Turbo-Preview", max_context: 80000},
        'gpt-4-0613': { displayName: "GPT-4", max_context: 8191},
        'gpt-4o-2024-05-13': { displayName: "Omni", max_context: 80000},
        'gpt-4o-mini': { displayName: "Mini", max_context: 80000},
        'open-mistral-nemo': { displayName: "Nemo"},
        'open-mixtral-8x22b': { displayName: "Mixtral 22b"},
        'open-mixtral-8x7b': { displayName: "Mixtral 7b"},
        'mistral-small-latest': { displayName: "Small"},
        'mistral-medium-latest': { displayName: "Medium"},
        'mistral-large-2402': { displayName: "Large"},
        'open-mixtral-8x7b': { displayName: "Mixtral"},
        'gemini-1.5-pro-latest': { displayName: "Gemini Pro"},
        'gemini-1.0-pro-vision-latest': { displayName: "Gemini Vision"},
        'gemini-ultra': { displayName: "Gemini Ultra"},
    };

    // CSS Styles
    GM_addStyle(`
        .proxy-switcher-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            padding: 10px;
            background-color: var(--SmartThemeBlurTintColor);
            border-radius: 5px;
            border: 1px solid var(--SmartThemeBorderColor);
        }
        .proxy-button {
            position: relative;
            width: 100px;
            height: 40px;
            margin: 5px;
            background-color: #333;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            z-index: 50;
        }
        .proxy-button-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 55;
        }
        .proxy-button-zone {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            z-index: 60;
            opacity: 0;
            transition: opacity 0.15s;
        }
        .proxy-button-zone:hover {
            opacity: 0.8;
        }
        .proxy-button-zone-text {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 70;
            color: white;
            font-weight: bold;
            pointer-events: none;
        }
        .model-button-container {
            display: flex;
            justify-content: flex-start;
            margin-top: 5px;
        }
        .model-button {
            background-color: #222;
            color: #fff;
            border: none;
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
            border-radius: 5px;
            font-size: 14px;
        }
        .model-button:hover, .model-button-hover {
            background-color: #444;
        }
        .model-category-title {
            color: var(--SmartThemeBodyColor);
            font-size: 18px;
            font-weight: bold;
            margin-top: 15px;
            margin-bottom: 10px;
            text-align: center;
        }
        .custom-panel {
            position: relative;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 5000;
        }
        .panel-content {
            background-color: var(--SmartThemeBlurTintColor);
            border: 1px solid var(--SmartThemeBorderColor);
            border-radius: 10px;
            padding: 20px;
            max-width: 80%;
            max-height: 80%;
            position: relative;
        }
        .close-button {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            cursor: pointer;
            background: none;
            border: none;
            color: var(--SmartThemeBodyColor);
        }
        .panel-item {
            margin-bottom: 20px;
        }
        .button-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
        }
        .custom-button {
            background-color: var(--SmartThemeChatTintColor);
            color: var(--SmartThemeBodyColor);
            border: 1px solid var(--SmartThemeBorderColor);
            border-radius: 5px;
            padding: 10px 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            min-width: 120px;
            text-align: center;
        }
        .custom-button:hover {
            background-color: var(--SmartThemeSelectedBG);
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .custom-button:focus {
            outline: 2px solid var(--SmartThemeBorderColor);
            outline-offset: 2px;
        }
        .panel-title {
            color: var(--SmartThemeBodyColor);
            margin-bottom: 20px;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
        }
        .proxy-name {
            color: var(--SmartThemeBodyColor);
            margin-bottom: 10px;
            font-size: 18px;
            text-align: center;
            font-weight: bold;
        }
        @media (max-width: 768px) {
            .custom-panel {
                align-items: flex-start;
                padding-top: 20px;
            }
            .panel-content {
                width: 95%;
                max-height: none;
                margin-bottom: 20px;
            }
            .custom-button {
                min-width: 100px;
                padding: 8px 12px;
                font-size: 12px;
            }
            .panel-title {
                font-size: 20px;
            }
            .proxy-name {
                font-size: 16px;
            }
        }
        .panel-separator {
            border: 0;
            height: 1px;
            background-image: linear-gradient(to right, rgba(0, 0, 0, 0), var(--SmartThemeBorderColor), rgba(0, 0, 0, 0));
            margin: 15px 0;
        }
`);

    // Helper functions
    const createElement = (tag, attributes = {}, children = []) => {
        const element = document.createElement(tag);
        Object.entries(attributes).forEach(([key, value]) => {
            element[key] = value;
        });
        children.forEach(child => element.appendChild(child));
        return element;
    };

    const createButton = (text, onClick, className = 'custom-button') =>
    createElement('button', { className, textContent: text, onclick: onClick });

    const createPanel = (id, title) => {
        const panel = createElement('div', { id, className: 'custom-panel' });
        const content = createElement('div', { className: 'panel-content' });
        const closeButton = createButton('×', () => panel.remove(), 'close-button');
        const titleElement = createElement('div', { className: 'panel-title', textContent: title });

        content.append(closeButton, titleElement);
        panel.appendChild(content);
        panel.content = content;

        panel.onclick = (e) => { if (e.target === panel) panel.remove(); };
        return panel;
    };

    // Main functions
    const switchProxy = (proxy, url) => {
        console.log(`Switching to ${proxy.name} - ${url}`);

        const mainApiSelector = document.getElementById('main_api');
        mainApiSelector.value = 'openai';
        mainApiSelector.dispatchEvent(new Event('change'));

        const chatCompletionSource = ['oai', 'azr'].includes(url) ? 'openai'
        : ['ant', 'aws'].includes(url) ? 'claude'
        : url === 'gem' ? 'makersuite'
        : 'mistralai';
        const chatCompletionSourceSelector = document.getElementById('chat_completion_source');
        chatCompletionSourceSelector.value = chatCompletionSource;
        chatCompletionSourceSelector.dispatchEvent(new Event('change'));

        const modelSelector = document.getElementById(`model_${chatCompletionSource === 'openai' ? 'openai' : chatCompletionSource}_select`);
        const modelName = proxy.model ? Object.keys(modelSwap).find(key => modelSwap[key].displayName === proxy.model) : config.defaultModels[url];
        modelSelector.value = modelName;
        modelSelector.dispatchEvent(new Event('change'));

        const reverseProxyInput = document.getElementById('openai_reverse_proxy');
        let proxyUrl;
        if (typeof proxy.urls === 'object' && url in proxy.urls) {
            proxyUrl = `${proxy.proxy}${proxy.urls[url]}`;
        } else if (Array.isArray(proxy.urls) && proxy.urls.includes(url)) {
            proxyUrl = `${proxy.proxy}${config.defaultUrls[url]}`;
        } else {
            proxyUrl = `${proxy.proxy}${config.defaultUrls[url]}`;
        }
        reverseProxyInput.value = proxyUrl;
        reverseProxyInput.dispatchEvent(new Event('input'));

        document.getElementById('openai_proxy_password').value = proxy.token || '';
        document.getElementById('openai_proxy_password').dispatchEvent(new Event('input'));

        const urlSettingsIndex = ['oai', 'azr'].includes(url) ? 0
        : ['ant', 'aws'].includes(url) ? 1
        : url === 'gem' ? 2
        : 3;

        Object.entries(config.settingsMap).forEach(([setting, inputId]) => {
            if (inputId) {
                const input = document.getElementById(inputId);
                const values = proxy.settings && proxy.settings[setting] ? proxy.settings[setting] : [];
                const defaultValues = config.defaultSettings[setting];

                let value = values.length > 0 ? (values.length === 1 ? values[0] : values[urlSettingsIndex]) : defaultValues[0];

                input.value = value;
                input.dispatchEvent(new Event('input'));
            }
        });

        // Close the panel
        const panel = document.getElementById('proxies-panel');
        if (panel) {
            panel.remove();
        }
        closeAllPanels();
    };

    const switchModel = (modelName) => {
        console.log(`Switching to model: ${modelName}`);

        const currentProxy = getCurrentProxy();
        if (!currentProxy) {
            console.error('No proxy currently selected');
            return;
        }

        const chatCompletionSource = modelName.startsWith('gpt') ? 'openai'
        : modelName.startsWith('claude') ? 'claude'
        : modelName.startsWith('gemini') ? 'makersuite'
        : 'mistralai';

        const chatCompletionSourceSelector = document.getElementById('chat_completion_source');
        chatCompletionSourceSelector.value = chatCompletionSource;
        chatCompletionSourceSelector.dispatchEvent(new Event('change'));

        const modelSelector = document.getElementById(`model_${chatCompletionSource}_select`);
        modelSelector.value = modelName;
        modelSelector.dispatchEvent(new Event('change'));

        const selectedUrl = chatCompletionSource === 'openai' ? (currentProxy.urls.includes('oai') ? 'oai' : 'azr')
        : chatCompletionSource === 'claude' ? (currentProxy.urls.includes('ant') ? 'ant' : 'aws')
        : chatCompletionSource === 'makersuite' ? 'gem'
        : 'mix';

        const reverseProxyInput = document.getElementById('openai_reverse_proxy');
        let proxyUrl;
        if (typeof currentProxy.urls === 'object' && selectedUrl in currentProxy.urls) {
            proxyUrl = `${currentProxy.proxy}${currentProxy.urls[selectedUrl]}`;
        } else if (Array.isArray(currentProxy.urls) && currentProxy.urls.includes(selectedUrl)) {
            proxyUrl = `${currentProxy.proxy}${config.defaultUrls[selectedUrl]}`;
        } else {
            proxyUrl = `${currentProxy.proxy}${config.defaultUrls[selectedUrl]}`;
        }

        reverseProxyInput.value = proxyUrl;
        reverseProxyInput.dispatchEvent(new Event('input'));

        if (modelName in modelSwap) {
            const modelData = modelSwap[modelName];
            Object.entries(config.settingsMap).forEach(([setting, inputId]) => {
                if (modelData[setting]) {
                    const input = document.getElementById(inputId);
                    input.value = modelData[setting];
                    input.dispatchEvent(new Event('input'));
                }
            });
        }

        // Close the panel
        const panel = document.getElementById('models-panel');
        if (panel) {
            panel.remove();
        }
        closeAllPanels();
    };

    const createProxyButton = (proxy) => {
        const button = createElement('button', { className: 'proxy-button' });
        const buttonText = createElement('span', { className: 'proxy-button-text', textContent: proxy.name });
        button.appendChild(buttonText);

        const proxyUrls = Array.isArray(proxy.urls) ? proxy.urls : Object.keys(proxy.urls || {});
        proxyUrls.forEach((url, index) => {
            const zone = createElement('div', {
                className: `proxy-button-zone proxy-button-zone-${url}`,
                style: `width: ${100 / proxyUrls.length}%; left: ${(100 / proxyUrls.length) * index}%;`
            });
            zone.addEventListener('click', () => switchProxy(proxy, url));

            const zoneText = createElement('span', {
                className: 'proxy-button-zone-text',
                textContent: config.zoneNames[url] || url.toUpperCase()
            });

            zone.addEventListener('mouseenter', () => {
                buttonText.style.display = 'none';
                zoneText.style.display = 'block';
            });

            zone.addEventListener('mouseleave', () => {
                buttonText.style.display = 'block';
                zoneText.style.display = 'none';
            });

            button.append(zone, zoneText);
        });

        return button;
    };

    const createModelButton = (modelName, modelData, modelSelector) => {
        const modelButton = createButton(modelData.displayName, () => {
            console.log(`Switching to model: ${modelName}`);
            modelSelector.value = modelName;
            modelSelector.dispatchEvent(new Event('change'));

            Object.entries(config.settingsMap).forEach(([setting, inputId]) => {
                if (modelData[setting]) {
                    const input = document.getElementById(inputId);
                    input.value = modelData[setting];
                    input.dispatchEvent(new Event('input'));
                }
            });
        }, 'model-button');

        modelButton.addEventListener('mouseenter', () => modelButton.classList.add('model-button-hover'));
        modelButton.addEventListener('mouseleave', () => modelButton.classList.remove('model-button-hover'));

        return modelButton;
    };

    const updateModelButtons = () => {
        const chatCompletionSource = document.getElementById('chat_completion_source').value;
        const modelButtonContainer = document.querySelector('.model-button-container');
        modelButtonContainer.innerHTML = '';

        const modelSelector = document.getElementById(`model_${['openai', 'custom'].includes(chatCompletionSource) ? 'openai' : chatCompletionSource}_select`);

        Array.from(modelSelector.options)
            .map(option => option.value)
            .filter(modelName => modelName in modelSwap)
            .forEach(modelName => {
            const modelButton = createModelButton(modelName, modelSwap[modelName], modelSelector);
            modelButtonContainer.appendChild(modelButton);
        });
    };

    const closeAllPanels = () => {
        const panels = document.querySelectorAll('.custom-panel');
        panels.forEach(panel => panel.remove());
    };

    const toggleProxiesPanel = () => {
        const existingPanel = document.getElementById('proxies-panel');
        if (existingPanel) {
            closeAllPanels();
            return;
        }

        closeAllPanels();

        const panel = createPanel('proxies-panel', 'Available Proxies');
        const separator = createElement('hr', { className: 'panel-separator' });
        panel.content.appendChild(separator);

        proxies.forEach(proxy => {
            const proxyDiv = createElement('div', { className: 'panel-item' });
            const proxyName = createElement('div', { className: 'proxy-name', textContent: proxy.name });
            const urlList = createElement('div', { className: 'button-list' });

            const proxyUrls = Array.isArray(proxy.urls) ? proxy.urls : Object.keys(proxy.urls || {});
            proxyUrls.forEach(url => {
                const urlButton = createButton(config.zoneNames[url] || url.toUpperCase(), () => {
                    switchProxy(proxy, url);
                    closeAllPanels();
                });
                urlList.appendChild(urlButton);
            });

            proxyDiv.append(proxyName, urlList);
            panel.content.appendChild(proxyDiv);
        });

        document.body.appendChild(panel);
    };

    const toggleModelsPanel = () => {
        const existingPanel = document.getElementById('models-panel');
        if (existingPanel) {
            closeAllPanels();
            return;
        }

        closeAllPanels();

        const currentProxy = getCurrentProxy();
        if (!currentProxy) {
            console.error('No proxy currently selected');
            return;
        }

        const panel = createPanel('models-panel', `Available Models for ${currentProxy.name}`);

        // Add the separator after the title
        const separator = createElement('hr', { className: 'panel-separator' });
        panel.content.appendChild(separator);

        const availableModels = getAvailableModels(currentProxy);

        const modelCategories = {
            'GPT': ['gpt'],
            'Claude': ['claude'],
            'Mistral': ['mistral'],
            'Gemini': ['gemini']
        };

        Object.entries(modelCategories).forEach(([category, prefixes]) => {
            const categoryModels = availableModels.filter(model =>
                                                          prefixes.some(prefix => model.toLowerCase().startsWith(prefix))
                                                         );

            if (categoryModels.length > 0) {
                const categoryTitle = createElement('div', { className: 'model-category-title', textContent: category });
                panel.content.appendChild(categoryTitle);

                const modelList = createElement('div', { className: 'button-list' });

                categoryModels.forEach(modelName => {
                    const modelButton = createButton(modelSwap[modelName]?.displayName || modelName, () => {
                        switchModel(modelName);
                        closeAllPanels();
                    });
                    modelList.appendChild(modelButton);
                });

                panel.content.appendChild(modelList);

                // Add a separator after each category (except the last one)
                if (category !== Object.keys(modelCategories).pop()) {
                    const categorySeparator = createElement('hr', { className: 'panel-separator' });
                    panel.content.appendChild(categorySeparator);
                }
            }
        });

        document.body.appendChild(panel);
    };

    const getCurrentProxy = () => {
        const reverseProxyInput = document.getElementById('openai_reverse_proxy');
        const currentProxyUrl = reverseProxyInput.value;

        return proxies.find(proxy => {
            const proxyUrls = Array.isArray(proxy.urls) ? proxy.urls : Object.keys(proxy.urls || {});
            return proxyUrls.some(url => currentProxyUrl.includes(proxy.proxy + (proxy.urls[url] || config.defaultUrls[url])));
        });
    };

    const getAvailableModels = (proxy) => {
        const proxyUrls = Array.isArray(proxy.urls) ? proxy.urls : Object.keys(proxy.urls || {});

        const prefixMap = {
            oai: 'gpt',
            azr: 'gpt',
            ant: 'claude',
            aws: 'claude',
            gem: 'gemini',
            mix: 'mistral'
        };

        return proxyUrls.flatMap(url => {
            const prefix = prefixMap[url] || '';
            return Object.keys(modelSwap).filter(model => model.startsWith(prefix));
        });
    };

    const initProxySwitcher = () => {
        console.log("Initializing Proxy Switcher");
        const proxyWarningElement = document.getElementById('ReverseProxyWarningMessage');
        proxyWarningElement.innerHTML = '';
        proxyWarningElement.classList.add('proxy-switcher-container');

        Object.values(proxies).forEach(proxy => {
            const button = createProxyButton(proxy);
            proxyWarningElement.appendChild(button);
        });

        const modelButtonContainer = createElement('div', { className: 'model-button-container' });
        proxyWarningElement.appendChild(modelButtonContainer);

        updateModelButtons();

        document.getElementById('chat_completion_source').addEventListener('change', updateModelButtons);

        console.log("Proxy Switcher initialized");
        setTimeout(removeDuplicateButtons, 100);
    };

    const removeDuplicateButtons = () => {
        const proxyWarningElement = document.getElementById('ReverseProxyWarningMessage');
        const buttons = proxyWarningElement.querySelectorAll('button');
        const buttonTexts = new Set();

        buttons.forEach(button => {
            const buttonText = button.textContent;
            if (buttonTexts.has(buttonText)) {
                button.remove();
            } else {
                buttonTexts.add(buttonText);
            }
        });
    };

    const restructureHamburgerMenu = () => {
        const optionsContent = document.querySelector('.options-content');
        if (!optionsContent) return;

        const newOrder = [
            'option_toggle_AN',
            'option_toggle_CFG',
            'option_toggle_logprobs',
            'option_new_bookmark',
            'option_convert_to_group',
            'hr',
            'option_close_chat',
            'option_select_chat',
            'option_start_new_chat',
            'option_delete_mes',
            'hr',
            'option_regenerate',
            'hr',
            'option_impersonate',
            'option_continue',
            'option_proxies',
            'option_models'
        ];

        const fragment = document.createDocumentFragment();

        newOrder.forEach(id => {
            if (id === 'hr') {
                fragment.appendChild(createElement('hr', { style: 'border-top: 2px solid #444; margin: 10px 0;' }));
            } else if (id === 'option_proxies' || id === 'option_models') {
                const a = createElement('a', {
                    id,
                    className: 'interactable',
                    tabIndex: '0'
                });
                const icon = createElement('i', {
                    className: id === 'option_proxies' ? 'fa-lg fa-solid fa-network-wired' : 'fa-lg fa-solid fa-microchip'
                });
                const span = createElement('span', { textContent: id === 'option_proxies' ? 'Proxies' : 'Models' });
                a.append(icon, span);
                fragment.appendChild(a);
            } else {
                const element = optionsContent.querySelector(`#${id}`);
                if (element) {
                    if (id === 'option_regenerate') {
                        const span = element.querySelector('span');
                        if (span) span.style.fontWeight = 'bold';
                    }
                    fragment.appendChild(element);
                }
            }
        });

        optionsContent.innerHTML = '';
        optionsContent.appendChild(fragment);

        document.getElementById('option_proxies').addEventListener('click', toggleProxiesPanel);
        document.getElementById('option_models').addEventListener('click', toggleModelsPanel);
    };

    const observeMainApi = () => {
        const mainApiSelector = document.getElementById('main_api');
        if (mainApiSelector.value === 'openai') {
            initProxySwitcher();
        }

        new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
                    if (mainApiSelector.value === 'openai') {
                        initProxySwitcher();
                    } else {
                        const proxyWarningElement = document.getElementById('ReverseProxyWarningMessage');
                        proxyWarningElement.innerHTML = '';
                        proxyWarningElement.classList.remove('proxy-switcher-container');
                    }
                }
            });
        }).observe(mainApiSelector, { attributes: true });
    };

    // Dynamic CSS for zone colors
    Object.entries(config.zoneNames).forEach(([key, value], index) => {
        GM_addStyle(`
        .proxy-button-zone-${key}:hover {
            background-color: hsla(${60 * index}, 50%, 50%, 0.8);
        }
    `);
    });

    // Initialize
    window.addEventListener('load', () => {
        initProxySwitcher();
        restructureHamburgerMenu();
    });

})();

Changelog

22/07/24: Sonnet 3.5 adds two new buttons in the context menu in the text field (where you have regenerate, Delete messages, author's note etc..). Models and Proxies. Makes a pop-up window to make this more mobile friendly, it still retains it previous buttons. Also this script re-arranges the buttons a little, to avoid accidentally clicking regenerate when going to delete messages.

3/4/24: Fixed script breaking on staging, reorganized code, added more options, placed within the reverse proxy menu, model quick-switch buttons can alter values, predefined values for each endpoint, set default model per proxy, added defaults.

30/1/24: Proxy buttons now in the left navigation panel, works on release and staging branches.

1/29/24: Public Release.

Edit Report
Pub: 21 Jan 2024 13:43 UTC
Edit: 22 Jul 2024 01:41 UTC
Views: 1158