gpt4free

Форк
0
/
chat.v1.js 
691 строка · 22.9 Кб
1
const colorThemes       = document.querySelectorAll('[name="theme"]');
2
const markdown          = window.markdownit();
3
const message_box       = document.getElementById(`messages`);
4
const message_input     = document.getElementById(`message-input`);
5
const box_conversations = document.querySelector(`.top`);
6
const spinner           = box_conversations.querySelector(".spinner");
7
const stop_generating   = document.querySelector(`.stop_generating`);
8
const regenerate        = document.querySelector(`.regenerate`);
9
const send_button       = document.querySelector(`#send-button`);
10
const imageInput        = document.querySelector('#image');
11
const fileInput         = document.querySelector('#file');
12

13
let   prompt_lock       = false;
14

15
hljs.addPlugin(new CopyButtonPlugin());
16

17
message_input.addEventListener("blur", () => {
18
    window.scrollTo(0, 0);
19
});
20

21
message_input.addEventListener("focus", () => {
22
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
23
});
24

25
const markdown_render = (content) => {
26
    return markdown.render(content
27
        .replaceAll(/<!--.+-->/gm, "")
28
        .replaceAll(/<img data-prompt="[^>]+">/gm, "")
29
    )
30
        .replaceAll("<a href=", '<a target="_blank" href=')
31
        .replaceAll('<code>', '<code class="language-plaintext">')
32
}
33

34
const delete_conversations = async () => {
35
    localStorage.clear();
36
    await new_conversation();
37
};
38

39
const handle_ask = async () => {
40
    message_input.style.height = `82px`;
41
    message_input.focus();
42
    window.scrollTo(0, 0);
43
    message = message_input.value
44
    if (message.length > 0) {
45
        message_input.value = '';
46
        await add_conversation(window.conversation_id, message);
47
        if ("text" in fileInput.dataset) {
48
            message += '\n```' + fileInput.dataset.type + '\n'; 
49
            message += fileInput.dataset.text;
50
            message += '\n```'
51
        }
52
        await add_message(window.conversation_id, "user", message);
53
        window.token = message_id();
54
        message_box.innerHTML += `
55
            <div class="message">
56
                <div class="user">
57
                    ${user_image}
58
                    <i class="fa-regular fa-phone-arrow-up-right"></i>
59
                </div>
60
                <div class="content" id="user_${token}"> 
61
                    ${markdown_render(message)}
62
                </div>
63
            </div>
64
        `;
65
        document.querySelectorAll('code:not(.hljs').forEach((el) => {
66
            hljs.highlightElement(el);
67
        });
68
        await ask_gpt();
69
    }
70
};
71

72
const remove_cancel_button = async () => {
73
    stop_generating.classList.add(`stop_generating-hiding`);
74

75
    setTimeout(() => {
76
        stop_generating.classList.remove(`stop_generating-hiding`);
77
        stop_generating.classList.add(`stop_generating-hidden`);
78
    }, 300);
79
};
80

81
const ask_gpt = async () => {
82
    regenerate.classList.add(`regenerate-hidden`);
83
    messages = await get_messages(window.conversation_id);
84

85
    // Remove generated images from history
86
    for (i in messages) {
87
        messages[i]["content"] = messages[i]["content"].replaceAll(
88
            /<!-- generated images start -->[\s\S]+<!-- generated images end -->/gm,
89
            ""
90
        )
91
        delete messages[i]["provider"];
92
    }
93

94
    window.scrollTo(0, 0);
95
    window.controller = new AbortController();
96

97
    jailbreak    = document.getElementById("jailbreak");
98
    provider     = document.getElementById("provider");
99
    model        = document.getElementById("model");
100
    prompt_lock  = true;
101
    window.text  = '';
102

103
    stop_generating.classList.remove(`stop_generating-hidden`);
104

105
    message_box.scrollTop = message_box.scrollHeight;
106
    window.scrollTo(0, 0);
107
    await new Promise((r) => setTimeout(r, 500));
108
    window.scrollTo(0, 0);
109

110
    message_box.innerHTML += `
111
        <div class="message">
112
            <div class="assistant">
113
                ${gpt_image} <i class="fa-regular fa-phone-arrow-down-left"></i>
114
            </div>
115
            <div class="content" id="gpt_${window.token}">
116
                <div class="provider"></div>
117
                <div class="content_inner"><span id="cursor"></span></div>
118
            </div>
119
        </div>
120
    `;
121
    content = document.getElementById(`gpt_${window.token}`);
122
    content_inner = content.querySelector('.content_inner');
123

124
    message_box.scrollTop = message_box.scrollHeight;
125
    window.scrollTo(0, 0);
126
    try {
127
        let body = JSON.stringify({
128
            id: window.token,
129
            conversation_id: window.conversation_id,
130
            model: model.options[model.selectedIndex].value,
131
            jailbreak: jailbreak.options[jailbreak.selectedIndex].value,
132
            web_search: document.getElementById(`switch`).checked,
133
            provider: provider.options[provider.selectedIndex].value,
134
            patch_provider: document.getElementById('patch').checked,
135
            messages: messages
136
        });
137
        const headers = {
138
            accept: 'text/event-stream'
139
        }
140
        if (imageInput && imageInput.files.length > 0) {
141
            const formData = new FormData();
142
            formData.append('image', imageInput.files[0]);
143
            formData.append('json', body);
144
            body = formData;
145
        } else {
146
            headers['content-type'] = 'application/json';
147
        }
148
        const response = await fetch(`/backend-api/v2/conversation`, {
149
            method: 'POST',
150
            signal: window.controller.signal,
151
            headers: headers,
152
            body: body
153
        });
154

155
        await new Promise((r) => setTimeout(r, 1000));
156
        window.scrollTo(0, 0);
157

158
        const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
159

160
        error = provider = null;
161
        while (true) {
162
            const { value, done } = await reader.read();
163
            if (done) break;
164
            for (const line of value.split("\n")) {
165
                if (!line) continue;
166
                const message = JSON.parse(line);
167
                if (message["type"] == "content") {
168
                    text += message["content"];
169
                } else if (message["type"] == "provider") {
170
                    provider = message["provider"];
171
                    content.querySelector('.provider').innerHTML =
172
                        '<a href="' + provider.url + '" target="_blank">' + provider.name + "</a>"
173
                } else if (message["type"] == "error") {
174
                    error = message["error"];
175
                } else if (message["type"] == "message") {
176
                    console.error(message["message"])
177
                }
178
            }
179
            if (error) {
180
                console.error(error);
181
                content_inner.innerHTML += "<p>An error occured, please try again, if the problem persists, please use a other model or provider.</p>";
182
            } else {
183
                html = markdown_render(text);
184
                let lastElement, lastIndex = null;
185
                for (element of ['</p>', '</code></pre>', '</li>\n</ol>']) {
186
                    const index = html.lastIndexOf(element)
187
                    if (index > lastIndex) {
188
                        lastElement = element;
189
                        lastIndex = index;
190
                    }
191
                }
192
                if (lastIndex) {
193
                    html = html.substring(0, lastIndex) + '<span id="cursor"></span>' + lastElement;
194
                }
195
                content_inner.innerHTML = html;
196
                document.querySelectorAll('code:not(.hljs').forEach((el) => {
197
                    hljs.highlightElement(el);
198
                });
199
            }
200

201
            window.scrollTo(0, 0);
202
            if (message_box.scrollTop >= message_box.scrollHeight - message_box.clientHeight - 100) {
203
                message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
204
            }
205
        }
206
        if (!error && imageInput) imageInput.value = "";
207
        if (!error && fileInput) fileInput.value = "";
208
    } catch (e) {
209
        console.error(e);
210

211
        if (e.name != `AbortError`) {
212
            text = `oops ! something went wrong, please try again / reload. [stacktrace in console]`;
213
            content_inner.innerHTML = text;
214
        } else {
215
            content_inner.innerHTML += ` [aborted]`;
216
            text += ` [aborted]`
217
        }
218
    }
219
    let cursorDiv = document.getElementById(`cursor`);
220
    if (cursorDiv) cursorDiv.parentNode.removeChild(cursorDiv);
221
    add_message(window.conversation_id, "assistant", text, provider);
222
    message_box.scrollTop = message_box.scrollHeight;
223
    await remove_cancel_button();
224
    prompt_lock = false;
225
    window.scrollTo(0, 0);
226
    await load_conversations(20, 0);
227
    regenerate.classList.remove(`regenerate-hidden`);
228
};
229

230
const clear_conversations = async () => {
231
    const elements = box_conversations.childNodes;
232
    let index = elements.length;
233

234
    if (index > 0) {
235
        while (index--) {
236
            const element = elements[index];
237
            if (
238
                element.nodeType === Node.ELEMENT_NODE &&
239
                element.tagName.toLowerCase() !== `button`
240
            ) {
241
                box_conversations.removeChild(element);
242
            }
243
        }
244
    }
245
};
246

247
const clear_conversation = async () => {
248
    let messages = message_box.getElementsByTagName(`div`);
249

250
    while (messages.length > 0) {
251
        message_box.removeChild(messages[0]);
252
    }
253
};
254

255
const show_option = async (conversation_id) => {
256
    const conv = document.getElementById(`conv-${conversation_id}`);
257
    const yes = document.getElementById(`yes-${conversation_id}`);
258
    const not = document.getElementById(`not-${conversation_id}`);
259

260
    conv.style.display = `none`;
261
    yes.style.display  = `block`;
262
    not.style.display  = `block`;
263
};
264

265
const hide_option = async (conversation_id) => {
266
    const conv = document.getElementById(`conv-${conversation_id}`);
267
    const yes  = document.getElementById(`yes-${conversation_id}`);
268
    const not  = document.getElementById(`not-${conversation_id}`);
269

270
    conv.style.display = `block`;
271
    yes.style.display  = `none`;
272
    not.style.display  = `none`;
273
};
274

275
const delete_conversation = async (conversation_id) => {
276
    localStorage.removeItem(`conversation:${conversation_id}`);
277

278
    const conversation = document.getElementById(`convo-${conversation_id}`);
279
    conversation.remove();
280

281
    if (window.conversation_id == conversation_id) {
282
        await new_conversation();
283
    }
284

285
    await load_conversations(20, 0, true);
286
};
287

288
const set_conversation = async (conversation_id) => {
289
    history.pushState({}, null, `/chat/${conversation_id}`);
290
    window.conversation_id = conversation_id;
291

292
    await clear_conversation();
293
    await load_conversation(conversation_id);
294
    await load_conversations(20, 0, true);
295
};
296

297
const new_conversation = async () => {
298
    history.pushState({}, null, `/chat/`);
299
    window.conversation_id = uuid();
300

301
    await clear_conversation();
302
    await load_conversations(20, 0, true);
303

304
    await say_hello()
305
};
306

307
const load_conversation = async (conversation_id) => {
308
    let messages = await get_messages(conversation_id);
309

310
    for (item of messages) {
311
        message_box.innerHTML += `
312
            <div class="message">
313
                <div class=${item.role == "assistant" ? "assistant" : "user"}>
314
                    ${item.role == "assistant" ? gpt_image : user_image}
315
                    ${item.role == "assistant"
316
                        ? `<i class="fa-regular fa-phone-arrow-down-left"></i>`
317
                        : `<i class="fa-regular fa-phone-arrow-up-right"></i>`
318
                    }
319
                </div>
320
                <div class="content">
321
                    ${item.provider
322
                        ? '<div class="provider"><a href="' + item.provider.url + '" target="_blank">' + item.provider.name + '</a></div>'
323
                        : ''
324
                    }
325
                    <div class="content_inner">${markdown_render(item.content)}</div>
326
                </div>
327
            </div>
328
        `;
329
    }
330

331
    document.querySelectorAll('code:not(.hljs').forEach((el) => {
332
        hljs.highlightElement(el);
333
    });
334

335
    message_box.scrollTo({ top: message_box.scrollHeight, behavior: "smooth" });
336

337
    setTimeout(() => {
338
        message_box.scrollTop = message_box.scrollHeight;
339
    }, 500);
340
};
341

342
const get_conversation = async (conversation_id) => {
343
    let conversation = await JSON.parse(
344
        localStorage.getItem(`conversation:${conversation_id}`)
345
    );
346
    return conversation;
347
};
348

349
const get_messages = async (conversation_id) => {
350
    let conversation = await get_conversation(conversation_id);
351
    return conversation?.items || [];
352
};
353

354
const add_conversation = async (conversation_id, content) => {
355
    if (content.length > 17) {
356
        title = content.substring(0, 17) + '...'
357
    } else {
358
        title = content + '&nbsp;'.repeat(19 - content.length)
359
    }
360

361
    if (localStorage.getItem(`conversation:${conversation_id}`) == null) {
362
        localStorage.setItem(
363
            `conversation:${conversation_id}`,
364
            JSON.stringify({
365
                id: conversation_id,
366
                title: title,
367
                items: [],
368
            })
369
        );
370
    }
371

372
    history.pushState({}, null, `/chat/${conversation_id}`);
373
};
374

375
const remove_last_message = async (conversation_id) => {
376
    const conversation = await get_conversation(conversation_id)
377

378
    conversation.items.pop();
379

380
    localStorage.setItem(
381
        `conversation:${conversation_id}`,
382
        JSON.stringify(conversation)
383
    );
384
};
385

386
const add_message = async (conversation_id, role, content, provider) => {
387
    const conversation = await get_conversation(conversation_id);
388

389
    conversation.items.push({
390
        role: role,
391
        content: content,
392
        provider: provider
393
    });
394

395
    localStorage.setItem(
396
        `conversation:${conversation_id}`,
397
        JSON.stringify(conversation)
398
    );
399
};
400

401
const load_conversations = async (limit, offset, loader) => {
402
    let conversations = [];
403
    for (let i = 0; i < localStorage.length; i++) {
404
        if (localStorage.key(i).startsWith("conversation:")) {
405
            let conversation = localStorage.getItem(localStorage.key(i));
406
            conversations.push(JSON.parse(conversation));
407
        }
408
    }
409

410
    await clear_conversations();
411

412
    for (conversation of conversations) {
413
        box_conversations.innerHTML += `
414
            <div class="convo" id="convo-${conversation.id}">
415
                <div class="left" onclick="set_conversation('${conversation.id}')">
416
                    <i class="fa-regular fa-comments"></i>
417
                    <span class="convo-title">${conversation.title}</span>
418
                </div>
419
                <i onclick="show_option('${conversation.id}')" class="fa-regular fa-trash" id="conv-${conversation.id}"></i>
420
                <i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-check" id="yes-${conversation.id}" style="display:none;"></i>
421
                <i onclick="hide_option('${conversation.id}')" class="fa-regular fa-x" id="not-${conversation.id}" style="display:none;"></i>
422
            </div>
423
        `;
424
    }
425

426
    document.querySelectorAll('code:not(.hljs').forEach((el) => {
427
        hljs.highlightElement(el);
428
    });
429
};
430

431
document.getElementById(`cancelButton`).addEventListener(`click`, async () => {
432
    window.controller.abort();
433
    console.log(`aborted ${window.conversation_id}`);
434
});
435

436
document.getElementById(`regenerateButton`).addEventListener(`click`, async () => {
437
    await remove_last_message(window.conversation_id);
438
    window.token = message_id();
439
    await ask_gpt();
440
});
441

442
const uuid = () => {
443
    return `xxxxxxxx-xxxx-4xxx-yxxx-${Date.now().toString(16)}`.replace(
444
        /[xy]/g,
445
        function (c) {
446
            var r = (Math.random() * 16) | 0,
447
                v = c == "x" ? r : (r & 0x3) | 0x8;
448
            return v.toString(16);
449
        }
450
    );
451
};
452

453
const message_id = () => {
454
    random_bytes = (Math.floor(Math.random() * 1338377565) + 2956589730).toString(
455
        2
456
    );
457
    unix = Math.floor(Date.now() / 1000).toString(2);
458

459
    return BigInt(`0b${unix}${random_bytes}`).toString();
460
};
461

462
document.querySelector(".mobile-sidebar").addEventListener("click", (event) => {
463
    const sidebar = document.querySelector(".conversations");
464

465
    if (sidebar.classList.contains("shown")) {
466
        sidebar.classList.remove("shown");
467
        event.target.classList.remove("rotated");
468
    } else {
469
        sidebar.classList.add("shown");
470
        event.target.classList.add("rotated");
471
    }
472

473
    window.scrollTo(0, 0);
474
});
475

476
const register_settings_localstorage = async () => {
477
    for (id of ["switch", "model", "jailbreak", "patch", "provider"]) {
478
        element = document.getElementById(id);
479
        element.addEventListener('change', async (event) => {
480
            switch (event.target.type) {
481
                case "checkbox":
482
                    localStorage.setItem(id, event.target.checked);
483
                    break;
484
                case "select-one":
485
                    localStorage.setItem(id, event.target.selectedIndex);
486
                    break;
487
                default:
488
                    console.warn("Unresolved element type");
489
            }
490
        });
491
    }
492
}
493

494
const load_settings_localstorage = async () => {
495
    for (id of ["switch", "model", "jailbreak", "patch", "provider"]) {
496
        element = document.getElementById(id);
497
        value = localStorage.getItem(element.id);
498
        if (value) {
499
            switch (element.type) {
500
                case "checkbox":
501
                    element.checked = value === "true";
502
                    break;
503
                case "select-one":
504
                    element.selectedIndex = parseInt(value);
505
                    break;
506
                default:
507
                    console.warn("Unresolved element type");
508
            }
509
        }
510
    }
511
}
512

513
const say_hello = async () => {
514
    tokens = [`Hello`, `!`, ` How`,` can`, ` I`,` assist`,` you`,` today`,`?`]
515

516
    message_box.innerHTML += `
517
        <div class="message">
518
            <div class="assistant">
519
                ${gpt_image}
520
                <i class="fa-regular fa-phone-arrow-down-left"></i>
521
            </div>
522
            <div class="content">
523
                <p class=" welcome-message"></p>
524
            </div>
525
        </div>
526
    `;
527

528
    to_modify = document.querySelector(`.welcome-message`);
529
    for (token of tokens) {
530
        await new Promise(resolve => setTimeout(resolve, (Math.random() * (100 - 200) + 100)))
531
        to_modify.textContent += token;
532
    }
533
}
534

535
// Theme storage for recurring viewers
536
const storeTheme = function (theme) {
537
    localStorage.setItem("theme", theme);
538
};
539

540
// set theme when visitor returns
541
const setTheme = function () {
542
    const activeTheme = localStorage.getItem("theme");
543
    colorThemes.forEach((themeOption) => {
544
        if (themeOption.id === activeTheme) {
545
            themeOption.checked = true;
546
        }
547
    });
548
    // fallback for no :has() support
549
    document.documentElement.className = activeTheme;
550
};
551

552
colorThemes.forEach((themeOption) => {
553
    themeOption.addEventListener("click", () => {
554
        storeTheme(themeOption.id);
555
        // fallback for no :has() support
556
        document.documentElement.className = themeOption.id;
557
    });
558
});
559

560

561
window.onload = async () => {
562
    setTheme();
563

564
    let conversations = 0;
565
    for (let i = 0; i < localStorage.length; i++) {
566
        if (localStorage.key(i).startsWith("conversation:")) {
567
            conversations += 1;
568
        }
569
    }
570

571
    if (conversations == 0) localStorage.clear();
572

573
    await setTimeout(() => {
574
        load_conversations(20, 0);
575
    }, 1);
576

577
    if (/\/chat\/.+/.test(window.location.href)) {
578
        await load_conversation(window.conversation_id);
579
    } else {
580
        await say_hello()
581
    }
582
        
583
    message_input.addEventListener(`keydown`, async (evt) => {
584
        if (prompt_lock) return;
585
        if (evt.keyCode === 13 && !evt.shiftKey) {
586
            evt.preventDefault();
587
            console.log("pressed enter");
588
            await handle_ask();
589
        } else {
590
            message_input.style.removeProperty("height");
591
            message_input.style.height = message_input.scrollHeight  + "px";
592
        }
593
    });
594
    
595
    send_button.addEventListener(`click`, async () => {
596
        console.log("clicked send");
597
        if (prompt_lock) return;
598
        await handle_ask();
599
    });
600

601
    register_settings_localstorage();
602
};
603

604
const observer = new MutationObserver((mutationsList) => {
605
    for (const mutation of mutationsList) {
606
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
607
            const height = message_input.offsetHeight;
608
            
609
            let heightValues = {
610
                81: "20px",
611
                82: "20px",
612
                100: "30px",
613
                119: "39px",
614
                138: "49px",
615
                150: "55px"
616
            }
617
            
618
            send_button.style.top = heightValues[height] || '';
619
        }
620
    }
621
});
622

623
observer.observe(message_input, { attributes: true });
624

625
(async () => {
626
    response = await fetch('/backend-api/v2/models')
627
    models = await response.json()
628
    let select = document.getElementById('model');
629

630
    for (model of models) {
631
        let option = document.createElement('option');
632
        option.value = option.text = model;
633
        select.appendChild(option);
634
    }
635

636
    response = await fetch('/backend-api/v2/providers')
637
    providers = await response.json()
638
    select = document.getElementById('provider');
639

640
    for (provider of providers) {
641
        let option = document.createElement('option');
642
        option.value = option.text = provider;
643
        select.appendChild(option);
644
    }
645

646
    await load_settings_localstorage()
647
})();
648

649
(async () => {
650
    response = await fetch('/backend-api/v2/version')
651
    versions = await response.json()
652
    
653
    document.title = 'g4f - gui - ' + versions["version"];
654
    text = "version ~ "
655
    if (versions["version"] != versions["latest_version"]) {
656
        release_url = 'https://github.com/xtekky/gpt4free/releases/tag/' + versions["latest_version"];
657
        text += '<a href="' + release_url +'" target="_blank" title="New version: ' + versions["latest_version"] +'">' + versions["version"] + ' 🆕</a>';
658
    } else {
659
        text += versions["version"];
660
    }
661
    document.getElementById("version_text").innerHTML = text
662
})()
663
imageInput.addEventListener('click', async (event) => {
664
    imageInput.value = '';
665
});
666
fileInput.addEventListener('click', async (event) => {
667
    fileInput.value = '';
668
    delete fileInput.dataset.text;
669
});
670
fileInput.addEventListener('change', async (event) => {
671
    if (fileInput.files.length) {
672
        type = fileInput.files[0].type;
673
        if (type && type.indexOf('/')) {
674
            type = type.split('/').pop().replace('x-', '')
675
            type = type.replace('plain', 'plaintext')
676
                       .replace('shellscript', 'sh')
677
                       .replace('svg+xml', 'svg')
678
                       .replace('vnd.trolltech.linguist', 'ts')
679
        } else {
680
            type = fileInput.files[0].name.split('.').pop()
681
        }
682
        fileInput.dataset.type = type
683
        const reader = new FileReader();
684
        reader.addEventListener('load', (event) => {
685
            fileInput.dataset.text = event.target.result;
686
        });
687
        reader.readAsText(fileInput.files[0]);
688
    } else {
689
        delete fileInput.dataset.text;
690
    }
691
});

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.