返回提交历史
Modified
g4f/Provider/needs_auth/Gemini.py
+13
-2
Modified
g4f/api/__init__.py
+10
-2
Modified
g4f/client/__init__.py
+44
-15
Modified
g4f/gui/client/demo.html
+32
-17
Modified
g4f/gui/client/static/js/chat.v1.js
+54
-22
Modified
g4f/gui/server/backend_api.py
+6
-31
Modified
g4f/gui/server/website.py
+0
-2
Modified
g4f/providers/retry_provider.py
+1
-1
XFEstudio/gpt4free
Fix model and provider in chat completion response Add login button to HuggingFace demo Custom conversation ids in chat ui Remove rate limiter in demo mode Improve YouTube support in Gemini
5cbbe2fd
代码差异
8 个文件
+160
-92
@@ -203,7 +203,14 @@ class Gemini(AsyncGeneratorProvider, ProviderModelMixin):
203
203
skip -= 1
204
204
continue
205
205
yield item
206
reasoning = "".join(find_str(response_part[4][0], 3))
206
reasoning = "\n\n".join(find_str(response_part[4][0], 3))
207
reasoning = re.sub(r"<b>|</b>", "**", reasoning)
208
def replace_image(match):
209
return f"})"
210
reasoning = re.sub(r"//yt3.(?:ggpht.com|googleusercontent.com/ytc)/[\w=-]+", replace_image, reasoning)
211
reasoning = re.sub(r"\nyoutube\n", "\n\n\n", reasoning)
212
reasoning = re.sub(r"\nYouTube\n", "\nYouTube ", reasoning)
213
reasoning = reasoning.replace('https://www.gstatic.com/images/branding/productlogos/youtube/v9/192px.svg', '<i class="fa-brands fa-youtube"></i>')
207
214
content = response_part[4][0][1][0]
208
215
if reasoning:
209
216
yield Reasoning(status="🤔")
@@ -215,8 +222,12 @@ class Gemini(AsyncGeneratorProvider, ProviderModelMixin):
215
222
if match:
216
223
image_prompt = match.group(1)
217
224
content = content.replace(match.group(0), '')
218
pattern = r"http://googleusercontent.com/image_generation_content/\d+"
225
pattern = r"http://googleusercontent.com/(?:image_generation|youtube)_content/\d+"
219
226
content = re.sub(pattern, "", content)
227
content = content.replace("<!-- end list -->", "")
228
content = content.replace("https://www.google.com/search?q=http://", "https://")
229
content = content.replace("https://www.google.com/search?q=https://", "https://")
230
content = content.replace("https://www.google.com/url?sa=E&source=gmail&q=http://", "http://")
220
231
if last_content and content.startswith(last_content):
221
232
yield content[len(last_content):]
222
233
else:
@@ -170,7 +170,9 @@ class Api:
170
170
try:
171
171
user_g4f_api_key = await self.get_g4f_api_key(request)
172
172
except HTTPException:
173
user_g4f_api_key = None
173
user_g4f_api_key = await self.security(request)
174
if hasattr(user_g4f_api_key, "credentials"):
175
user_g4f_api_key = user_g4f_api_key.credentials
174
176
path = request.url.path
175
177
if path.startswith("/v1") or path.startswith("/api/") or (AppConfig.demo and path == '/backend-api/v2/upload_cookies'):
176
178
if user_g4f_api_key is None:
@@ -581,11 +583,17 @@ class Api:
581
583
pass
582
584
if not os.path.isfile(target):
583
585
source_url = get_source_url(str(request.query_params))
586
ssl = None
587
if source_url is None:
588
backend_url = os.environ.get("G4F_BACKEND_URL")
589
if backend_url:
590
source_url = f"{backend_url}/images/{filename}"
591
ssl = False
584
592
if source_url is not None:
585
593
try:
586
594
await copy_images(
587
595
[source_url],
588
target=target)
596
target=target, ssl=ssl)
589
597
debug.log(f"Image copied from {source_url}")
590
598
except Exception as e:
591
599
debug.error(f"Download failed: {source_url}\n{type(e).__name__}: {e}")
@@ -12,7 +12,7 @@ from typing import Union, AsyncIterator, Iterator, Awaitable, Optional
12
12
from ..image.copy_images import copy_images
13
13
from ..typing import Messages, ImageType
14
14
from ..providers.types import ProviderType, BaseRetryProvider
15
from ..providers.response import ResponseType, ImageResponse, FinishReason, BaseConversation, SynthesizeData, ToolCalls, Usage
15
from ..providers.response import *
16
16
from ..errors import NoImageResponseError
17
17
from ..providers.retry_provider import IterListProvider
18
18
from ..providers.asyncio import to_sync_generator
@@ -49,6 +49,7 @@ def iter_response(
49
49
finish_reason = None
50
50
tool_calls = None
51
51
usage = None
52
provider: ProviderInfo = None
52
53
completion_id = ''.join(random.choices(string.ascii_letters + string.digits, k=28))
53
54
idx = 0
54
55
@@ -65,10 +66,13 @@ def iter_response(
65
66
elif isinstance(chunk, Usage):
66
67
usage = chunk
67
68
continue
69
elif isinstance(chunk, ProviderInfo):
70
provider = chunk
71
continue
68
72
elif isinstance(chunk, BaseConversation):
69
73
yield chunk
70
74
continue
71
elif isinstance(chunk, SynthesizeData) or not chunk:
75
elif isinstance(chunk, HiddenResponse):
72
76
continue
73
77
elif isinstance(chunk, Exception):
74
78
continue
@@ -76,7 +80,6 @@ def iter_response(
76
80
if isinstance(chunk, list):
77
81
chunk = "".join(map(str, chunk))
78
82
else:
79
80
83
temp = chunk.__str__()
81
84
if not isinstance(temp, str):
82
85
if isinstance(temp, list):
@@ -84,6 +87,8 @@ def iter_response(
84
87
else:
85
88
temp = repr(chunk)
86
89
chunk = temp
90
if not chunk:
91
continue
87
92
88
93
content += chunk
89
94
@@ -96,7 +101,11 @@ def iter_response(
96
101
finish_reason = "stop"
97
102
98
103
if stream:
99
yield ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
104
chunk = ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
105
if provider is not None:
106
chunk.provider = provider.name
107
chunk.model = provider.model
108
yield chunk
100
109
101
110
if finish_reason is not None:
102
111
break
@@ -108,7 +117,7 @@ def iter_response(
108
117
finish_reason = "stop" if finish_reason is None else finish_reason
109
118
110
119
if stream:
111
yield ChatCompletionChunk.model_construct(
120
chat_completion = ChatCompletionChunk.model_construct(
112
121
None, finish_reason, completion_id, int(time.time()),
113
122
usage=usage
114
123
)
@@ -116,19 +125,24 @@ def iter_response(
116
125
if response_format is not None and "type" in response_format:
117
126
if response_format["type"] == "json_object":
118
127
content = filter_json(content)
119
yield ChatCompletion.model_construct(
128
chat_completion = ChatCompletion.model_construct(
120
129
content, finish_reason, completion_id, int(time.time()),
121
130
usage=UsageModel.model_construct(**usage.get_dict()),
122
131
**filter_none(tool_calls=[ToolCallModel.model_construct(**tool_call) for tool_call in tool_calls]) if tool_calls is not None else {}
123
132
)
133
if provider is not None:
134
chat_completion.provider = provider.name
135
chat_completion.model = provider.model
136
yield chat_completion
124
137
125
138
# Synchronous iter_append_model_and_provider function
126
139
def iter_append_model_and_provider(response: ChatCompletionResponseType, last_model: str, last_provider: ProviderType) -> ChatCompletionResponseType:
127
140
if isinstance(last_provider, BaseRetryProvider):
128
last_provider = last_provider.last_provider
141
yield from response
142
return
129
143
for chunk in response:
130
144
if isinstance(chunk, (ChatCompletion, ChatCompletionChunk)):
131
if last_provider is not None:
145
if chunk.provider is None and last_provider is not None:
132
146
chunk.model = getattr(last_provider, "last_model", last_model)
133
147
chunk.provider = last_provider.__name__
134
148
yield chunk
@@ -146,6 +160,7 @@ async def async_iter_response(
146
160
idx = 0
147
161
tool_calls = None
148
162
usage = None
163
provider: ProviderInfo = None
149
164
150
165
try:
151
166
async for chunk in response:
@@ -161,12 +176,17 @@ async def async_iter_response(
161
176
elif isinstance(chunk, Usage):
162
177
usage = chunk
163
178
continue
164
elif isinstance(chunk, SynthesizeData) or not chunk:
179
elif isinstance(chunk, ProviderInfo):
180
provider = chunk
181
continue
182
elif isinstance(chunk, HiddenResponse):
165
183
continue
166
184
elif isinstance(chunk, Exception):
167
185
continue
168
186
169
187
chunk = str(chunk)
188
if not chunk:
189
continue
170
190
content += chunk
171
191
idx += 1
172
192
@@ -179,7 +199,11 @@ async def async_iter_response(
179
199
finish_reason = "stop"
180
200
181
201
if stream:
182
yield ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
202
chunk = ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
203
if provider is not None:
204
chunk.provider = provider.name
205
chunk.model = provider.model
206
yield chunk
183
207
184
208
if finish_reason is not None:
185
209
break
@@ -190,7 +214,7 @@ async def async_iter_response(
190
214
usage = Usage(completion_tokens=idx, total_tokens=idx)
191
215
192
216
if stream:
193
yield ChatCompletionChunk.model_construct(
217
chat_completion = ChatCompletionChunk.model_construct(
194
218
None, finish_reason, completion_id, int(time.time()),
195
219
usage=usage.get_dict()
196
220
)
@@ -198,11 +222,15 @@ async def async_iter_response(
198
222
if response_format is not None and "type" in response_format:
199
223
if response_format["type"] == "json_object":
200
224
content = filter_json(content)
201
yield ChatCompletion.model_construct(
225
chat_completion = ChatCompletion.model_construct(
202
226
content, finish_reason, completion_id, int(time.time()),
203
227
usage=UsageModel.model_construct(**usage.get_dict()),
204
228
**filter_none(tool_calls=[ToolCallModel.model_construct(**tool_call) for tool_call in tool_calls]) if tool_calls is not None else {}
205
229
)
230
if provider is not None:
231
chat_completion.provider = provider.name
232
chat_completion.model = provider.model
233
yield chat_completion
206
234
finally:
207
235
await safe_aclose(response)
208
236
@@ -214,11 +242,12 @@ async def async_iter_append_model_and_provider(
214
242
last_provider = None
215
243
try:
216
244
if isinstance(last_provider, BaseRetryProvider):
217
if last_provider is not None:
218
last_provider = last_provider.last_provider
245
async for chunk in response:
246
yield chunk
247
return
219
248
async for chunk in response:
220
249
if isinstance(chunk, (ChatCompletion, ChatCompletionChunk)):
221
if last_provider is not None:
250
if chunk.provider is None and last_provider is not None:
222
251
chunk.model = getattr(last_provider, "last_model", last_model)
223
252
chunk.provider = last_provider.__name__
224
253
yield chunk
@@ -183,25 +183,10 @@
183
183
const isIframe = window.self !== window.top;
184
184
const backendUrl = "{{backend_url}}";
185
185
let url = new URL(window.location.href)
186
let params = new URLSearchParams(url.search);
187
186
if (isIframe && backendUrl) {
188
if (params.get("get_gpu_token")) {
189
window.addEventListener('DOMContentLoaded', async function() {
190
const link = document.getElementById("new_window");
191
link.href = `${backendUrl}${url.search}`;
192
link.click();
193
});
194
} else {
195
window.location.replace(`${backendUrl}${url.search}`);
196
}
187
window.location.replace(`${backendUrl}${url.search}`);
197
188
return;
198
189
}
199
if (params.get("__sign")) {
200
localStorage.setItem("HuggingSpace-api_key", params.get("__sign"));
201
if (!isIframe) {
202
window.location.replace("/");
203
}
204
}
205
190
})();
206
191
</script>
207
192
<script src="https://unpkg.com/es-module-shims@1.7.0/dist/es-module-shims.js"></script>
@@ -240,10 +225,13 @@
240
225
<p>
241
226
<a href="https://huggingface.co/settings/tokens" target="_blank">Get Access Token</a>
242
227
</p>
228
<img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/sign-in-with-huggingface-xl-dark.svg" alt="Sign in with Hugging Face" style="cursor: pointer; display: none;" id="signin">
229
<button id="signout" style="display: none">Sign out</button>
243
230
</form>
244
231
<script type="module">
245
232
import * as hub from "@huggingface/hub";
246
233
import { init } from "@huggingface/space-header";
234
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";
247
235
248
236
const isIframe = window.self !== window.top;
249
237
const button = document.querySelector('form a.button');
@@ -269,7 +257,6 @@
269
257
return;
270
258
}
271
259
localStorage.setItem("HuggingFace-api_key", accessToken);
272
localStorage.setItem("HuggingFace-user", JSON.stringify(user));
273
260
localStorage.setItem("user", user.name);
274
261
localStorage.setItem("report_error", "true")
275
262
location.href = "/chat/";
@@ -280,6 +267,34 @@
280
267
event.preventDefault();
281
268
check_access_token();
282
269
});
270
271
let oauthResult = localStorage.getItem("oauth");
272
if (oauthResult) {
273
try {
274
oauthResult = JSON.parse(oauthResult);
275
} catch {
276
oauthResult = null;
277
}
278
}
279
oauthResult ||= await oauthHandleRedirectIfPresent();
280
if (oauthResult) {
281
localStorage.setItem("oauth", JSON.stringify(oauthResult));
282
localStorage.setItem("HuggingFace-api_key", oauthResult.accessToken);
283
localStorage.setItem("user", oauthResult.userInfo.fullname);
284
document.getElementById("signout").style.removeProperty("display");
285
document.getElementById("signout").onclick = async function() {
286
localStorage.removeItem("oauth");
287
localStorage.removeItem("HuggingFace-api_key");
288
window.location.href = window.location.href.replace(/\?.*$/, '');
289
window.location.reload();
290
}
291
} else {
292
document.getElementById("signin").style.removeProperty("display");
293
document.getElementById("signin").onclick = async function() {
294
// prompt=consent to re-trigger the consent screen instead of silently redirecting
295
window.location.href = (await oauthLoginUrl({clientId: 'ed074164-4f8d-4fb2-8bec-44952707965e', scopes: ['inference-api']})) + "&prompt=consent";
296
}
297
}
283
298
</script>
284
299
285
300
<!-- Footer -->
@@ -39,6 +39,7 @@ let finish_storage = {};
39
39
let usage_storage = {};
40
40
let reasoning_storage = {};
41
41
let generate_storage = {};
42
let title_ids_storage = {};
42
43
let is_demo = false;
43
44
let wakeLock = null;
44
45
let countTokensEnabled = true;
@@ -74,6 +75,8 @@ if (window.markdownit) {
74
75
)
75
76
.replaceAll("<a href=", '<a target="_blank" href=')
76
77
.replaceAll('<code>', '<code class="language-plaintext">')
78
.replaceAll('<i class="', '<i class="')
79
.replaceAll('"></i>', '"></i>')
77
80
}
78
81
}
79
82
@@ -301,7 +304,9 @@ const register_message_buttons = async () => {
301
304
const conversation = await get_conversation(window.conversation_id);
302
305
let buffer = "";
303
306
conversation.items.forEach(message => {
304
buffer += render_reasoning_text(message.reasoning);
307
if (message.reasoning) {
308
buffer += render_reasoning_text(message.reasoning);
309
}
305
310
buffer += `${message.role == 'user' ? 'User' : 'Assistant'}: ${message.content.trim()}\n\n\n`;
306
311
});
307
312
var download = document.getElementById("download");
@@ -435,25 +440,27 @@ const handle_ask = async (do_ask_gpt = true) => {
435
440
imageInput.dataset.objects = images.join(" ");
436
441
}
437
442
}
438
message_box.innerHTML += `
439
<div class="message" data-index="${message_index}">
440
<div class="user">
441
${user_image}
442
<i class="fa-solid fa-xmark"></i>
443
<i class="fa-regular fa-phone-arrow-up-right"></i>
443
const message_el = document.createElement("div");
444
message_el.classList.add("message");
445
message_el.dataset.index = message_index;
446
message_el.innerHTML = `
447
<div class="user">
448
${user_image}
449
<i class="fa-solid fa-xmark"></i>
450
<i class="fa-regular fa-phone-arrow-up-right"></i>
451
</div>
452
<div class="content" id="user_${message_id}">
453
<div class="content_inner">
454
${markdown_render(message)}
455
${images.map((object)=>`<img src="${object}" alt="Image upload">`).join("")}
444
456
</div>
445
<div class="content" id="user_${message_id}">
446
<div class="content_inner">
447
${markdown_render(message)}
448
${images.map((object)=>'<img src="' + object + '" alt="Image upload">').join("")}
449
</div>
450
<div class="count">
451
${countTokensEnabled ? count_words_and_tokens(message, get_selected_model()?.value) : ""}
452
</div>
457
<div class="count">
458
${countTokensEnabled ? count_words_and_tokens(message, get_selected_model()?.value) : ""}
453
459
</div>
454
460
</div>
455
461
`;
456
highlight(message_box);
462
message_box.appendChild(message_el);
463
highlight(message_el);
457
464
if (do_ask_gpt) {
458
465
const all_pinned = document.querySelectorAll(".buttons button.pinned")
459
466
if (all_pinned.length > 0) {
@@ -1012,7 +1019,7 @@ const ask_gpt = async (message_id, message_index = -1, regenerate = false, provi
1012
1019
}
1013
1020
try {
1014
1021
let api_key;
1015
if (is_demo && provider == "Feature") {
1022
if (is_demo && ["OpenaiChat", "DeepSeekAPI", "PollinationsAI"].includes(provider)) {
1016
1023
api_key = localStorage.getItem("user");
1017
1024
} else if (["HuggingSpace", "G4F"].includes(provider)) {
1018
1025
api_key = localStorage.getItem("HuggingSpace-api_key");
@@ -1096,9 +1103,30 @@ const clear_conversation = async () => {
1096
1103
}
1097
1104
};
1098
1105
1106
var illegalRe = /[\/\?<>\\:\*\|":]/g;
1107
var controlRe = /[\x00-\x1f\x80-\x9f]/g;
1108
var reservedRe = /^\.+$/;
1109
var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
1110
1111
function sanitize(input, replacement) {
1112
var sanitized = input
1113
.replace(illegalRe, replacement)
1114
.replace(controlRe, replacement)
1115
.replace(reservedRe, replacement)
1116
.replace(windowsReservedRe, replacement);
1117
return sanitized.replaceAll(/\/|#|\s{2,}/g, replacement).trim();
1118
}
1119
1099
1120
async function set_conversation_title(conversation_id, title) {
1100
1121
conversation = await get_conversation(conversation_id)
1101
1122
conversation.new_title = title;
1123
const new_id = sanitize(title, " ");
1124
if (new_id && !appStorage.getItem(`conversation:${new_id}`)) {
1125
appStorage.removeItem(`conversation:${conversation.id}`);
1126
title_ids_storage[conversation_id] = new_id;
1127
conversation.id = new_id;
1128
add_url_to_history(`/chat/${conversation_id}`);
1129
}
1102
1130
appStorage.setItem(
1103
1131
`conversation:${conversation.id}`,
1104
1132
JSON.stringify(conversation)
@@ -1123,6 +1151,7 @@ const show_option = async (conversation_id) => {
1123
1151
input_el.onclick = (e) => e.stopPropagation()
1124
1152
input_el.onfocus = () => trash_el.style.display = "none";
1125
1153
input_el.onchange = () => set_conversation_title(conversation_id, input_el.value);
1154
input_el.onblur = () => set_conversation_title(conversation_id, input_el.value);
1126
1155
left_el.removeChild(title_el);
1127
1156
left_el.appendChild(input_el);
1128
1157
}
@@ -1162,6 +1191,9 @@ const delete_conversation = async (conversation_id) => {
1162
1191
};
1163
1192
1164
1193
const set_conversation = async (conversation_id) => {
1194
if (title_ids_storage[conversation_id]) {
1195
conversation_id = title_ids_storage[conversation_id];
1196
}
1165
1197
try {
1166
1198
add_url_to_history(`/chat/${conversation_id}`);
1167
1199
} catch (e) {
@@ -1912,11 +1944,11 @@ async function on_load() {
1912
1944
messageInput.focus();
1913
1945
//await handle_ask();
1914
1946
}
1915
} else if (/\/chat\/[^?]+/.test(window.location.href)) {
1916
load_conversation(window.conversation_id);
1917
} else {
1947
} else if (/\/chat\/[?$]/.test(window.location.href)) {
1918
1948
chatPrompt.value = document.getElementById("systemPrompt")?.value || "";
1919
1949
say_hello();
1950
} else {
1951
load_conversation(window.conversation_id);
1920
1952
}
1921
1953
load_conversations();
1922
1954
}
@@ -2007,7 +2039,8 @@ async function on_api() {
2007
2039
}
2008
2040
providerSelect.innerHTML = `
2009
2041
<option value="" selected="selected">Demo Mode</option>
2010
<option value="Feature">Feature Provider</option>
2042
<option value="DeepSeekAPI">DeepSeek Provider</option>
2043
<option value="OpenaiChat">OpenAI Provider</option>
2011
2044
<option value="PollinationsAI">Pollinations AI</option>
2012
2045
<option value="G4F">G4F framework</option>
2013
2046
<option value="HuggingFace">HuggingFace</option>
@@ -2340,7 +2373,6 @@ fileInput.addEventListener('change', async (event) => {
2340
2373
Object.keys(data).forEach(key => {
2341
2374
if (key == "options") {
2342
2375
Object.keys(data[key]).forEach(keyOption => {
2343
console.log(keyOption, data[key][keyOption]);
2344
2376
appStorage.setItem(keyOption, data[key][keyOption]);
2345
2377
count += 1;
2346
2378
});
@@ -14,12 +14,6 @@ from pathlib import Path
14
14
from urllib.parse import quote_plus
15
15
from hashlib import sha256
16
16
from werkzeug.utils import secure_filename
17
try:
18
from flask_limiter import Limiter
19
from flask_limiter.util import get_remote_address
20
has_flask_limiter = True
21
except ImportError:
22
has_flask_limiter = False
23
17
24
18
from ...image import is_allowed_extension, to_image
25
19
from ...client.service import convert_to_provider
@@ -62,19 +56,8 @@ class Backend_Api(Api):
62
56
"""
63
57
self.app: Flask = app
64
58
65
if has_flask_limiter and app.demo:
66
limiter = Limiter(
67
get_remote_address,
68
app=app,
69
default_limits=["200 per day", "50 per hour"],
70
storage_uri="memory://",
71
auto_check=False,
72
strategy="moving-window",
73
)
74
75
if has_flask_limiter and app.demo:
59
if app.demo:
76
60
@app.route('/', methods=['GET'])
77
@limiter.exempt
78
61
def home():
79
62
return render_template('demo.html', backend_url=os.environ.get("G4F_BACKEND_URL", ""))
80
63
else:
@@ -116,7 +99,7 @@ class Backend_Api(Api):
116
99
}
117
100
for model, providers in models.demo_models.values()]
118
101
119
def handle_conversation(limiter_check: callable = None):
102
def handle_conversation():
120
103
"""
121
104
Handles conversation requests and streams responses back.
122
105
@@ -135,7 +118,7 @@ class Backend_Api(Api):
135
118
else:
136
119
json_data = request.json
137
120
138
if app.demo and json_data.get("provider") not in ["Custom", "Feature", "HuggingFace", "HuggingSpace", "HuggingChat", "G4F", "PollinationsAI"]:
121
if app.demo and json_data.get("provider") not in ["DeepSeekAPI", "OpenaiChat", "HuggingFace", "HuggingSpace", "HuggingChat", "G4F", "PollinationsAI"]:
139
122
model = json_data.get("model")
140
123
if model != "default" and model in models.demo_models:
141
124
json_data["provider"] = random.choice(models.demo_models[model][1])
@@ -143,8 +126,6 @@ class Backend_Api(Api):
143
126
if not model or model == "default":
144
127
json_data["model"] = models.demo_models["default"][0].name
145
128
json_data["provider"] = random.choice(models.demo_models["default"][1])
146
if limiter_check is not None and json_data.get("provider") in ["Feature"]:
147
limiter_check()
148
129
if "images" in json_data:
149
130
kwargs["images"] = json_data["images"]
150
131
kwargs = self._prepare_conversation_kwargs(json_data, kwargs)
@@ -158,15 +139,9 @@ class Backend_Api(Api):
158
139
mimetype='text/event-stream'
159
140
)
160
141
161
if has_flask_limiter and app.demo:
162
@app.route('/backend-api/v2/conversation', methods=['POST'])
163
@limiter.limit("2 per minute")
164
def _handle_conversation():
165
return handle_conversation(limiter.check)
166
else:
167
@app.route('/backend-api/v2/conversation', methods=['POST'])
168
def _handle_conversation():
169
return handle_conversation()
142
@app.route('/backend-api/v2/conversation', methods=['POST'])
143
def _handle_conversation():
144
return handle_conversation()
170
145
171
146
@app.route('/backend-api/v2/usage', methods=['POST'])
172
147
def add_usage():
@@ -33,8 +33,6 @@ class Website:
33
33
def _chat(self, conversation_id):
34
34
if conversation_id == "share":
35
35
return render_template('index.html', chat_id=str(uuid.uuid4()))
36
if '-' not in conversation_id:
37
return redirect_home()
38
36
return render_template('index.html', chat_id=conversation_id)
39
37
40
38
def _index(self):
@@ -87,7 +87,7 @@ class IterListProvider(BaseRetryProvider):
87
87
for provider in self.get_providers(stream and not ignore_stream, ignored):
88
88
self.last_provider = provider
89
89
debug.log(f"Using {provider.__name__} provider")
90
yield ProviderInfo(**provider.get_dict())
90
yield ProviderInfo(**provider.get_dict(), model=model if model else getattr(provider, "default_model"))
91
91
try:
92
92
response = provider.get_async_create_function()(model, messages, stream=stream, **kwargs)
93
93
if hasattr(response, "__aiter__"):