返回提交历史
Modified
g4f/Provider/GeminiPro.py
+1
-1
Modified
g4f/Provider/bing/conversation.py
+1
-1
Modified
g4f/gui/client/css/style.css
+16
-6
Modified
g4f/gui/client/html/index.html
+0
-5
Modified
g4f/gui/client/js/chat.v1.js
+104
-106
XFEstudio/gpt4free
Add word count from iG8R Improve Bing provider Some gui improvments Improve error handling in gui
74a33f10
代码差异
5 个文件
+122
-119
@@ -32,7 +32,7 @@ class GeminiPro(AsyncGeneratorProvider, ProviderModelMixin):
32
32
connector: BaseConnector = None,
33
33
**kwargs
34
34
) -> AsyncResult:
35
model = "gemini-pro-vision" if model is None and image is not None else model
35
model = "gemini-pro-vision" if not model and image is not None else model
36
36
model = cls.get_model(model)
37
37
38
38
if not api_key:
@@ -46,7 +46,7 @@ async def create_conversation(session: ClientSession, proxy: str = None) -> Conv
46
46
}
47
47
for k, v in headers.items():
48
48
session.headers[k] = v
49
url = 'https://www.bing.com/turing/conversation/create?bundleVersion=1.1579.2'
49
url = 'https://www.bing.com/turing/conversation/create?bundleVersion=1.1626.1'
50
50
async with session.get(url, headers=headers, proxy=proxy) as response:
51
51
try:
52
52
data = await response.json()
@@ -205,6 +205,12 @@ body {
205
205
gap: 10px;
206
206
}
207
207
208
.conversations .convo .choise {
209
position: absolute;
210
right: 8px;
211
background-color: var(--blur-bg);
212
}
213
208
214
.conversations i {
209
215
color: var(--conversations);
210
216
cursor: pointer;
@@ -227,6 +233,10 @@ body {
227
233
padding-bottom: 0;
228
234
}
229
235
236
.message.regenerate {
237
opacity: 0.75;
238
}
239
230
240
.message:last-child {
231
241
animation: 0.6s show_message;
232
242
}
@@ -397,7 +407,7 @@ body {
397
407
padding: 6px var(--inner-gap);
398
408
}
399
409
400
.stop_generating, .regenerate {
410
.stop_generating, .toolbar .regenerate {
401
411
position: absolute;
402
412
z-index: 1000000;
403
413
top: 0;
@@ -405,14 +415,14 @@ body {
405
415
}
406
416
407
417
@media only screen and (min-width: 40em) {
408
.stop_generating, .regenerate {
418
.stop_generating, .toolbar .regenerate {
409
419
left: 50%;
410
420
transform: translateX(-50%);
411
421
right: auto;
412
422
}
413
423
}
414
424
415
.stop_generating button, .regenerate button{
425
.stop_generating button, .toolbar .regenerate button{
416
426
backdrop-filter: blur(20px);
417
427
-webkit-backdrop-filter: blur(20px);
418
428
background-color: var(--blur-bg);
@@ -602,7 +612,6 @@ select {
602
612
.input-box {
603
613
display: flex;
604
614
align-items: center;
605
padding-right: var(--inner-gap);
606
615
cursor: pointer;
607
616
}
608
617
@@ -991,8 +1000,9 @@ a:-webkit-any-link {
991
1000
padding-right: 5px;
992
1001
padding-top: 2px;
993
1002
padding-bottom: 2px;
994
top: 20px;
995
left: 8px;
1003
position: absolute;
1004
bottom: 8px;
1005
right: 8px;
996
1006
}
997
1007
998
1008
#send-button:hover {
@@ -37,10 +37,6 @@
37
37
import llamaTokenizer from "llama-tokenizer-js"
38
38
</script>
39
39
<script src="https://unpkg.com/gpt-tokenizer/dist/cl100k_base.js" async></script>
40
<script type="module" async>
41
import { countWords } from 'https://esm.run/alfaaz';
42
window.countWords = countWords;
43
</script>
44
40
<script>
45
41
const user_image = '<img src="/assets/img/user.png" alt="your avatar">';
46
42
const gpt_image = '<img src="/assets/img/gpt.png" alt="your avatar">';
@@ -55,7 +51,6 @@
55
51
}
56
52
57
53
#message-input {
58
margin-right: 30px;
59
54
height: 82px;
60
55
margin-left: 20px;
61
56
}
@@ -1,13 +1,13 @@
1
1
const colorThemes = document.querySelectorAll('[name="theme"]');
2
2
const markdown = window.markdownit();
3
3
const message_box = document.getElementById(`messages`);
4
const message_input = document.getElementById(`message-input`);
4
const messageInput = document.getElementById(`message-input`);
5
5
const box_conversations = document.querySelector(`.top`);
6
6
const stop_generating = document.querySelector(`.stop_generating`);
7
7
const regenerate = document.querySelector(`.regenerate`);
8
8
const sidebar = document.querySelector(".conversations");
9
9
const sidebar_button = document.querySelector(".mobile-sidebar");
10
const send_button = document.getElementById("send-button");
10
const sendButton = document.getElementById("send-button");
11
11
const imageInput = document.getElementById("image");
12
12
const cameraInput = document.getElementById("camera");
13
13
const fileInput = document.getElementById("file");
@@ -19,11 +19,11 @@ let prompt_lock = false;
19
19
20
20
hljs.addPlugin(new CopyButtonPlugin());
21
21
22
message_input.addEventListener("blur", () => {
22
messageInput.addEventListener("blur", () => {
23
23
window.scrollTo(0, 0);
24
24
});
25
25
26
message_input.addEventListener("focus", () => {
26
messageInput.addEventListener("focus", () => {
27
27
document.documentElement.scrollTop = document.documentElement.scrollHeight;
28
28
});
29
29
@@ -60,7 +60,7 @@ const register_remove_message = async () => {
60
60
}
61
61
const message_el = el.parentElement.parentElement;
62
62
await remove_message(window.conversation_id, message_el.dataset.index);
63
await load_conversation(window.conversation_id);
63
await load_conversation(window.conversation_id, false);
64
64
})
65
65
}
66
66
});
@@ -78,13 +78,13 @@ const delete_conversations = async () => {
78
78
};
79
79
80
80
const handle_ask = async () => {
81
message_input.style.height = `82px`;
82
message_input.focus();
81
messageInput.style.height = "82px";
82
messageInput.focus();
83
83
window.scrollTo(0, 0);
84
84
85
message = message_input.value
85
message = messageInput.value
86
86
if (message.length > 0) {
87
message_input.value = '';
87
messageInput.value = "";
88
88
prompt_lock = true;
89
89
count_input()
90
90
await add_conversation(window.conversation_id, message);
@@ -158,17 +158,19 @@ const prepare_messages = (messages, filter_last_message = true) => {
158
158
}
159
159
160
160
let new_messages = [];
161
for (i in messages) {
162
new_message = messages[i];
163
// Remove generated images from history
164
new_message.content = new_message.content.replaceAll(
165
/<!-- generated images start -->[\s\S]+<!-- generated images end -->/gm,
166
""
167
)
168
delete new_message["provider"];
169
// Remove regenerated messages
170
if (!new_message.regenerate) {
171
new_messages.push(new_message)
161
if (messages) {
162
for (i in messages) {
163
new_message = messages[i];
164
// Remove generated images from history
165
new_message.content = new_message.content.replaceAll(
166
/<!-- generated images start -->[\s\S]+<!-- generated images end -->/gm,
167
""
168
)
169
delete new_message["provider"];
170
// Remove regenerated messages
171
if (!new_message.regenerate) {
172
new_messages.push(new_message)
173
}
172
174
}
173
175
}
174
176
@@ -263,11 +265,13 @@ const ask_gpt = async () => {
263
265
const { value, done } = await reader.read();
264
266
if (done) break;
265
267
for (const line of value.split("\n")) {
266
if (!line) continue;
268
if (!line) {
269
continue;
270
}
267
271
const message = JSON.parse(line);
268
272
if (message.type == "content") {
269
273
text += message.content;
270
} else if (message["type"] == "provider") {
274
} else if (message.type == "provider") {
271
275
provider_result = message.provider
272
276
content.querySelector('.provider').innerHTML = `
273
277
<a href="${provider_result.url}" target="_blank">
@@ -275,21 +279,21 @@ const ask_gpt = async () => {
275
279
</a>
276
280
${provider_result.model ? ' with ' + provider_result.model : ''}
277
281
`
278
} else if (message["type"] == "error") {
279
error = message["error"];
280
} else if (message["type"] == "message") {
281
console.error(message["message"])
282
} else if (message.type == "error") {
283
error = message.error;
284
} else if (messag.type == "message") {
285
console.error(messag.message)
282
286
}
283
287
}
284
288
if (error) {
285
289
console.error(error);
286
content_inner.innerHTML += "<p>An error occured, please try again, if the problem persists, please use a other model or provider.</p>";
290
content_inner.innerHTML += `<p><strong>An error occured:</strong> ${error}</p>`;
287
291
} else {
288
292
html = markdown_render(text);
289
293
let lastElement, lastIndex = null;
290
for (element of ['</p>', '</code></pre>', '</li>\n</ol>', '</li>\n</ul>']) {
294
for (element of ['</p>', '</code></pre>', '</p>\n</li>\n</ol>', '</li>\n</ol>', '</li>\n</ul>']) {
291
295
const index = html.lastIndexOf(element)
292
if (index > lastIndex) {
296
if (index - element.length > lastIndex) {
293
297
lastElement = element;
294
298
lastIndex = index;
295
299
}
@@ -308,7 +312,6 @@ const ask_gpt = async () => {
308
312
}
309
313
}
310
314
if (!error) {
311
// Remove cursor
312
315
html = markdown_render(text);
313
316
content_inner.innerHTML = html;
314
317
highlight(content_inner);
@@ -319,17 +322,16 @@ const ask_gpt = async () => {
319
322
}
320
323
} catch (e) {
321
324
console.error(e);
322
323
325
if (e.name != "AbortError") {
324
326
error = true;
325
327
text = "oops ! something went wrong, please try again / reload. [stacktrace in console]";
326
328
content_inner.innerHTML = text;
327
329
} else {
328
content_inner.innerHTML += ` [aborted]`;
329
text += ` [aborted]`
330
content_inner.innerHTML += " [aborted]";
331
if (text) text += " [aborted]";
330
332
}
331
333
}
332
if (!error) {
334
if (!error && text) {
333
335
await add_message(window.conversation_id, "assistant", text, provider_result);
334
336
await load_conversation(window.conversation_id);
335
337
} else {
@@ -368,30 +370,22 @@ const clear_conversation = async () => {
368
370
while (messages.length > 0) {
369
371
message_box.removeChild(messages[0]);
370
372
}
371
372
if (systemPrompt) {
373
systemPrompt.value = "";
374
}
375
373
};
376
374
377
375
const show_option = async (conversation_id) => {
378
376
const conv = document.getElementById(`conv-${conversation_id}`);
379
const yes = document.getElementById(`yes-${conversation_id}`);
380
const not = document.getElementById(`not-${conversation_id}`);
377
const choi = document.getElementById(`cho-${conversation_id}`);
381
378
382
conv.style.display = `none`;
383
yes.style.display = `block`;
384
not.style.display = `block`;
379
conv.style.display = "none";
380
choi.style.display = "block";
385
381
};
386
382
387
383
const hide_option = async (conversation_id) => {
388
384
const conv = document.getElementById(`conv-${conversation_id}`);
389
const yes = document.getElementById(`yes-${conversation_id}`);
390
const not = document.getElementById(`not-${conversation_id}`);
385
const choi = document.getElementById(`cho-${conversation_id}`);
391
386
392
conv.style.display = `block`;
393
yes.style.display = `none`;
394
not.style.display = `none`;
387
conv.style.display = "block";
388
choi.style.display = "none";
395
389
};
396
390
397
391
const delete_conversation = async (conversation_id) => {
@@ -422,12 +416,15 @@ const new_conversation = async () => {
422
416
window.conversation_id = uuid();
423
417
424
418
await clear_conversation();
419
if (systemPrompt) {
420
systemPrompt.value = "";
421
}
425
422
load_conversations();
426
423
hide_sidebar();
427
424
say_hello();
428
425
};
429
426
430
const load_conversation = async (conversation_id) => {
427
const load_conversation = async (conversation_id, scroll = true) => {
431
428
let conversation = await get_conversation(conversation_id);
432
429
let messages = conversation?.items || [];
433
430
@@ -451,7 +448,7 @@ const load_conversation = async (conversation_id) => {
451
448
</div>
452
449
` : "";
453
450
elements += `
454
<div class="message" data-index="${i}">
451
<div class="message${item.regenerate ? " regenerate": ""}" data-index="${i}">
455
452
<div class="${item.role}">
456
453
${item.role == "assistant" ? gpt_image : user_image}
457
454
<i class="fa-solid fa-xmark"></i>
@@ -483,30 +480,14 @@ const load_conversation = async (conversation_id) => {
483
480
register_remove_message();
484
481
highlight(message_box);
485
482
486
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "smooth" });
487
488
setTimeout(() => {
489
message_box.scrollTop = message_box.scrollHeight;
490
}, 500);
491
};
483
if (scroll) {
484
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "smooth" });
492
485
493
function count_tokens(model, text) {
494
if (model.startsWith("gpt-3") || model.startsWith("gpt-4")) {
495
return GPTTokenizer_cl100k_base?.encode(text).length;
486
setTimeout(() => {
487
message_box.scrollTop = message_box.scrollHeight;
488
}, 500);
496
489
}
497
if (model.startsWith("llama2") || model.startsWith("codellama")) {
498
return llamaTokenizer?.encode(text).length;
499
}
500
if (model.startsWith("mistral") || model.startsWith("mixtral")) {
501
return mistralTokenizer?.encode(text).length;
502
}
503
}
504
505
function count_words_and_tokens(text, model) {
506
const tokens_count = model ? count_tokens(model, text) : null;
507
const tokens_append = tokens_count ? `, ${tokens_count} tokens` : "";
508
return countWords ? `(${countWords(text)} words${tokens_append})` : "";
509
}
490
};
510
491
511
492
async function get_conversation(conversation_id) {
512
493
let conversation = await JSON.parse(
@@ -556,10 +537,12 @@ async function save_system_message() {
556
537
const hide_last_message = async (conversation_id) => {
557
538
const conversation = await get_conversation(conversation_id)
558
539
const last_message = conversation.items.pop();
559
if (last_message["role"] == "assistant") {
560
last_message["regenerate"] = true;
540
if (last_message !== null) {
541
if (last_message["role"] == "assistant") {
542
last_message["regenerate"] = true;
543
}
544
conversation.items.push(last_message);
561
545
}
562
conversation.items.push(last_message);
563
546
await save_conversation(conversation_id, conversation);
564
547
};
565
548
@@ -568,7 +551,9 @@ const remove_message = async (conversation_id, index) => {
568
551
let new_items = [];
569
552
for (i in conversation.items) {
570
553
if (i == index - 1) {
571
delete conversation.items[i]["regenerate"];
554
if (!conversation.items[index]?.regenerate) {
555
delete conversation.items[i]["regenerate"];
556
}
572
557
}
573
558
if (i != index) {
574
559
new_items.push(conversation.items[i])
@@ -609,8 +594,10 @@ const load_conversations = async () => {
609
594
<span class="convo-title">${conversation.title}</span>
610
595
</div>
611
596
<i onclick="show_option('${conversation.id}')" class="fa-regular fa-trash" id="conv-${conversation.id}"></i>
612
<i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-check" id="yes-${conversation.id}" style="display:none;"></i>
613
<i onclick="hide_option('${conversation.id}')" class="fa-regular fa-x" id="not-${conversation.id}" style="display:none;"></i>
597
<div id="cho-${conversation.id}" class="choise" style="display:none;">
598
<i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-check"></i>
599
<i onclick="hide_option('${conversation.id}')" class="fa-regular fa-x"></i>
600
</div>
614
601
</div>
615
602
`;
616
603
}
@@ -748,15 +735,45 @@ colorThemes.forEach((themeOption) => {
748
735
});
749
736
});
750
737
738
function count_tokens(model, text) {
739
if (model) {
740
if (model.startsWith("llama2") || model.startsWith("codellama")) {
741
return llamaTokenizer?.encode(text).length;
742
}
743
if (model.startsWith("mistral") || model.startsWith("mixtral")) {
744
return mistralTokenizer?.encode(text).length;
745
}
746
}
747
return GPTTokenizer_cl100k_base?.encode(text).length;
748
}
749
750
function count_words(text) {
751
return text.trim().match(/[\w\u4E00-\u9FA5]+/gu)?.length || 0;
752
}
753
754
function count_words_and_tokens(text, model) {
755
return `(${count_words(text)} words, ${count_tokens(model, text)} tokens)`;
756
}
757
758
let countFocus = messageInput;
751
759
const count_input = async () => {
752
if (message_input.value) {
760
if (countFocus.value) {
753
761
model = modelSelect.options[modelSelect.selectedIndex].value;
754
inputCount.innerText = count_words_and_tokens(message_input.value, model);
762
inputCount.innerText = count_words_and_tokens(countFocus.value, model);
755
763
} else {
756
764
inputCount.innerHTML = " "
757
765
}
758
766
};
759
message_input.addEventListener("keyup", count_input);
767
messageInput.addEventListener("keyup", count_input);
768
systemPrompt.addEventListener("keyup", count_input);
769
systemPrompt.addEventListener("focus", function() {
770
countFocus = systemPrompt;
771
count_input();
772
});
773
systemPrompt.addEventListener("blur", function() {
774
countFocus = messageInput;
775
count_input();
776
});
760
777
761
778
window.onload = async () => {
762
779
setTheme();
@@ -771,7 +788,7 @@ window.onload = async () => {
771
788
772
789
load_conversations();
773
790
774
message_input.addEventListener("keydown", async (evt) => {
791
messageInput.addEventListener("keydown", async (evt) => {
775
792
if (prompt_lock) return;
776
793
777
794
if (evt.keyCode === 13 && !evt.shiftKey) {
@@ -779,41 +796,22 @@ window.onload = async () => {
779
796
console.log("pressed enter");
780
797
await handle_ask();
781
798
} else {
782
message_input.style.removeProperty("height");
783
message_input.style.height = message_input.scrollHeight + "px";
799
messageInput.style.removeProperty("height");
800
messageInput.style.height = messageInput.scrollHeight + "px";
784
801
}
785
802
});
786
803
787
send_button.addEventListener(`click`, async () => {
804
sendButton.addEventListener(`click`, async () => {
788
805
console.log("clicked send");
789
806
if (prompt_lock) return;
790
807
await handle_ask();
791
808
});
792
809
810
messageInput.focus();
811
793
812
register_settings_localstorage();
794
813
};
795
814
796
const observer = new MutationObserver((mutationsList) => {
797
for (const mutation of mutationsList) {
798
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
799
const height = message_input.offsetHeight;
800
801
let heightValues = {
802
81: "20px",
803
82: "20px",
804
100: "30px",
805
119: "39px",
806
138: "49px",
807
150: "55px"
808
}
809
810
send_button.style.top = heightValues[height] || '';
811
}
812
}
813
});
814
815
observer.observe(message_input, { attributes: true });
816
817
815
(async () => {
818
816
response = await fetch('/backend-api/v2/models')
819
817
models = await response.json()