返回提交历史
Modified
g4f/Provider/github/GithubCopilot.py
+2
-2
Modified
g4f/Provider/needs_auth/LMArena.py
+4
-34
Modified
g4f/gui/server/api.py
+2
-2
Modified
g4f/gui/server/backend_api.py
+4
-17
XFEstudio/gpt4free
refactor: update function signatures and remove unused parameters for improved clarity and security
282b350d
代码差异
4 个文件
+12
-55
@@ -273,7 +273,7 @@ class GithubCopilot(OpenaiTemplate):
273
273
usage = await resp.json()
274
274
return usage
275
275
276
async def main(args: Optional[List[str]] = None):
276
async def main(args: Optional[list[str]] = None):
277
277
"""CLI entry point for GitHub Copilot OAuth authentication."""
278
278
import argparse
279
279
@@ -373,7 +373,7 @@ Examples:
373
373
parser.print_help()
374
374
375
375
376
def cli_main(args: Optional[List[str]] = None):
376
def cli_main(args: Optional[list[str]] = None):
377
377
"""Synchronous CLI entry point for setup.py console_scripts."""
378
378
asyncio.run(main(args))
379
379
@@ -161,41 +161,11 @@ class LMArena(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
161
161
return cls.models
162
162
163
163
@classmethod
164
async def get_args_from_nodriver(cls, proxy, force=True):
164
async def get_args_from_nodriver(cls, proxy):
165
165
cache_file = cls.get_cache_file()
166
166
grecaptcha = []
167
167
168
169
async def is_auth(page:nodriver.Tab):
170
cookies = {c.name: c.value for c in await page.send(nodriver.cdp.network.get_cookies([cls.url]))}
171
return any("arena-auth-prod" in cookie for cookie in cookies)
172
173
async def clear_cookies_for_url(browser: nodriver.Browser, url: str):
174
debug.log(f"Clearing cookies for {url}")
175
host = urlparse(url).hostname
176
if not host:
177
raise ValueError(f"Bad url: {url}")
178
179
tab = browser.main_tab # any open tab is fine
180
cookies = await browser.cookies.get_all() # returns CDP cookies :contentReference[oaicite:2]{index=2}
181
for c in cookies:
182
dom = (c.domain or "").lstrip(".")
183
if dom and (host == dom or host.endswith("." + dom)):
184
if c.name == "cf_clearance":
185
continue
186
await tab.send(
187
cdp.network.delete_cookies(
188
name=c.name,
189
domain=dom, # exact domain :contentReference[oaicite:3]{index=3}
190
path=c.path, # exact path :contentReference[oaicite:4]{index=4}
191
# partition_key=c.partition_key, # if you use partitioned cookies
192
)
193
)
194
195
168
async def callback(page: nodriver.Tab):
196
if force:
197
await clear_cookies_for_url(page.browser, cls.url)
198
await page.reload()
199
169
button = await page.find("Accept Cookies")
200
170
if button:
201
171
await button.click()
@@ -277,8 +247,8 @@ class LMArena(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
277
247
await cls.__load_actions(html)
278
248
279
249
args = await get_args_from_nodriver(
280
cls.url, proxy=proxy, callback=callback, cookies=args.get("cookies", {}), user_data_dir="grecaptcha",
281
browser_args=["--guest", "--disable-gpu", "--no-sandbox"])
250
cls.url, proxy=proxy, callback=callback
251
)
282
252
283
253
with cache_file.open("w") as f:
284
254
json.dump(args, f)
@@ -614,7 +584,7 @@ class LMArena(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
614
584
force = True
615
585
debug.error(error)
616
586
continue
617
except Exception:
587
except:
618
588
raise
619
589
if args and os.getenv("G4F_SHARE_AUTH") and not kwargs.get("action"):
620
590
yield "\n" * 10
@@ -48,7 +48,7 @@ class Api:
48
48
for model, providers in models.__models__.values()]
49
49
50
50
@staticmethod
51
def get_provider_models(provider: str, api_key: str = None, base_url: str = None, ignored: list = None):
51
def get_provider_models(provider: str, api_key: str = None, ignored: list = None):
52
52
def get_model_data(provider: ProviderModelMixin, model: str, default: bool = False) -> dict:
53
53
model_id = model.get("id") if isinstance(model, dict) else model
54
54
return {
@@ -69,7 +69,7 @@ class Api:
69
69
has_grouped_models = hasattr(provider, "get_grouped_models")
70
70
method = provider.get_grouped_models if has_grouped_models else provider.get_models
71
71
if "api_key" in signature(provider.get_models).parameters:
72
models = method(api_key=api_key, base_url=base_url)
72
models = method(api_key=api_key)
73
73
elif "ignored" in signature(provider.get_models).parameters:
74
74
models = method(ignored=ignored)
75
75
else:
@@ -178,21 +178,6 @@ class Backend_Api(Api):
178
178
response = self.get_providers(**kwargs)
179
179
return jsonify(response)
180
180
181
def get_demo_models():
182
return [{
183
"name": model.name,
184
"image": isinstance(model, models.ImageModel),
185
"vision": isinstance(model, models.VisionModel),
186
"audio": isinstance(model, models.AudioModel),
187
"video": isinstance(model, models.VideoModel),
188
"providers": [
189
provider.get_parent()
190
for provider in providers
191
],
192
"demo": True
193
}
194
for model, providers in models.demo_models.values()]
195
196
181
def handle_conversation():
197
182
"""
198
183
Handles conversation requests and streams responses back.
@@ -209,6 +194,9 @@ class Backend_Api(Api):
209
194
except json.JSONDecodeError as e:
210
195
logger.exception(e)
211
196
return jsonify({"error": {"message": "Invalid JSON data"}}), 400
197
for key in ["base_url", "proxy", "media"]:
198
if key in json_data:
199
del json_data[key] # Remove unsupported fields for security
212
200
if app.demo and has_crypto:
213
201
secret = request.headers.get("x-secret", request.headers.get("x_secret"))
214
202
if not secret or not validate_secret(secret):
@@ -653,9 +641,8 @@ class Backend_Api(Api):
653
641
654
642
def get_provider_models(self, provider: str):
655
643
api_key = request.headers.get("x-api-key")
656
base_url = request.headers.get("x-api-base")
657
644
ignored = request.headers.get("x-ignored", "").split()
658
return super().get_provider_models(provider, api_key, base_url, ignored)
645
return super().get_provider_models(provider, api_key, ignored)
659
646
660
647
def _format_json(self, response_type: str, content = None, **kwargs) -> str:
661
648
"""