XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/gpt4free

refactor: streamline auth handling and CLI structure

- Added `fallback_model = "deepseek"` to `PollinationsAI` class in `PollinationsAI.py` - Modified `PollinationsAI._agenerate` to safely call `get_model` only if `model` is not None - Removed unused login loop in `OpenaiChat.synthesize` method in `OpenaiChat.py` - Replaced full CLI parser and main function implementation in `__main__.py` with import from `.main` - Added `get_auth_result` method to `AsyncAuthedProvider` in `base_provider.py` for reusable auth retrieval - Replaced repeated auth loading logic in `create_completion` and `create_streaming_completion` with call to `get_auth_result` in `base_provider.py

78c0d67d
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

4 个文件 +21 -104
Modified g4f/Provider/PollinationsAI.py +2 -1
@@ -78,6 +78,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
78 78
79 79 # Models configuration
80 80 default_model = "openai"
81 fallback_model = "deepseek"
81 82 default_image_model = "flux"
82 83 default_vision_model = default_model
83 84 default_audio_model = "openai-audio"
@@ -288,7 +289,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
288 289 break
289 290 model = cls.default_audio_model if has_audio else model
290 291 try:
291 model = cls.get_model(model)
292 model = cls.get_model(model) if model else None
292 293 except ModelNotFoundError:
293 294 pass
294 295 if model in cls.image_models:
Modified g4f/Provider/needs_auth/OpenaiChat.py +0 -2
@@ -603,8 +603,6 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
603 603
604 604 @classmethod
605 605 async def synthesize(cls, params: dict) -> AsyncIterator[bytes]:
606 async for _ in cls.login():
607 pass
608 606 async with StreamSession(
609 607 impersonate="chrome",
610 608 timeout=0
Modified g4f/cli/__main__.py +1 -83
@@ -1,88 +1,6 @@
1 1 from __future__ import annotations
2 2
3 import argparse
4 from argparse import ArgumentParser
5 from .client import get_parser, run_client_args
6
7 from g4f import Provider
8 from g4f.gui.run import gui_parser, run_gui_args
9 import g4f.cookies
10
11 def get_api_parser():
12 api_parser = ArgumentParser(description="Run the API and GUI")
13 api_parser.add_argument("--bind", default=None, help="The bind string. (Default: 0.0.0.0:1337)")
14 api_parser.add_argument("--port", "-p", default=None, help="Change the port of the server.")
15 api_parser.add_argument("--debug", "-d", action="store_true", help="Enable verbose logging.")
16 api_parser.add_argument("--gui", "-g", default=None, action="store_true", help="Start also the gui.")
17 api_parser.add_argument("--model", default=None, help="Default model for chat completion. (incompatible with --reload and --workers)")
18 api_parser.add_argument("--provider", choices=[provider.__name__ for provider in Provider.__providers__ if provider.working],
19 default=None, help="Default provider for chat completion. (incompatible with --reload and --workers)")
20 api_parser.add_argument("--media-provider", choices=[provider.__name__ for provider in Provider.__providers__ if provider.working and bool(getattr(provider, "image_models", False))],
21 default=None, help="Default provider for image generation. (incompatible with --reload and --workers)"),
22 api_parser.add_argument("--proxy", default=None, help="Default used proxy. (incompatible with --reload and --workers)")
23 api_parser.add_argument("--workers", type=int, default=None, help="Number of workers.")
24 api_parser.add_argument("--disable-colors", action="store_true", help="Don't use colors.")
25 api_parser.add_argument("--ignore-cookie-files", action="store_true", help="Don't read .har and cookie files. (incompatible with --reload and --workers)")
26 api_parser.add_argument("--g4f-api-key", type=str, default=None, help="Sets an authentication key for your API. (incompatible with --reload and --workers)")
27 api_parser.add_argument("--ignored-providers", nargs="+", choices=[provider.__name__ for provider in Provider.__providers__ if provider.working],
28 default=[], help="List of providers to ignore when processing request. (incompatible with --reload and --workers)")
29 api_parser.add_argument("--cookie-browsers", nargs="+", choices=[browser.__name__ for browser in g4f.cookies.browsers],
30 default=[], help="List of browsers to access or retrieve cookies from. (incompatible with --reload and --workers)")
31 api_parser.add_argument("--reload", action="store_true", help="Enable reloading.")
32 api_parser.add_argument("--demo", action="store_true", help="Enable demo mode.")
33 api_parser.add_argument("--timeout", type=int, default=600, help="Default timeout for requests in seconds. (incompatible with --reload and --workers)")
34 api_parser.add_argument("--ssl-keyfile", type=str, default=None, help="Path to SSL key file for HTTPS.")
35 api_parser.add_argument("--ssl-certfile", type=str, default=None, help="Path to SSL certificate file for HTTPS.")
36 api_parser.add_argument("--log-config", type=str, default=None, help="Custom log config.")
37
38 return api_parser
39
40 def main():
41 parser = argparse.ArgumentParser(description="Run gpt4free")
42 subparsers = parser.add_subparsers(dest="mode", help="Mode to run the g4f in.")
43 subparsers.add_parser("api", parents=[get_api_parser()], add_help=False)
44 subparsers.add_parser("gui", parents=[gui_parser()], add_help=False)
45 subparsers.add_parser("client", parents=[get_parser()], add_help=False)
46
47 args = parser.parse_args()
48 if args.mode == "api":
49 run_api_args(args)
50 elif args.mode == "gui":
51 run_gui_args(args)
52 elif args.mode == "client":
53 run_client_args(args)
54 else:
55 parser.print_help()
56 exit(1)
57
58 def run_api_args(args):
59 from g4f.api import AppConfig, run_api
60
61 AppConfig.set_config(
62 ignore_cookie_files=args.ignore_cookie_files,
63 ignored_providers=args.ignored_providers,
64 g4f_api_key=args.g4f_api_key,
65 provider=args.provider,
66 media_provider=args.media_provider,
67 proxy=args.proxy,
68 model=args.model,
69 gui=args.gui,
70 demo=args.demo,
71 timeout=args.timeout,
72 )
73 if args.cookie_browsers:
74 g4f.cookies.browsers = [g4f.cookies[browser] for browser in args.cookie_browsers]
75 run_api(
76 bind=args.bind,
77 port=args.port,
78 debug=args.debug,
79 workers=args.workers,
80 use_colors=not args.disable_colors,
81 reload=args.reload,
82 ssl_keyfile=args.ssl_keyfile,
83 ssl_certfile=args.ssl_certfile,
84 log_config=args.log_config,
85 )
3 from . import main
86 4
87 5 if __name__ == "__main__":
88 6 main()
Modified g4f/providers/base_provider.py +18 -18
@@ -448,6 +448,22 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
448 448 elif cache_file.exists():
449 449 cache_file.unlink()
450 450
451 @classmethod
452 def get_auth_result(cls) -> AuthResult:
453 """
454 Retrieves the authentication result from cache.
455 """
456 cache_file = cls.get_cache_file()
457 if cache_file.exists():
458 try:
459 with cache_file.open("r") as f:
460 return AuthResult(**json.load(f))
461 except json.JSONDecodeError:
462 cache_file.unlink()
463 raise MissingAuthError(f"Invalid auth file: {cache_file}")
464 else:
465 raise MissingAuthError
466
451 467 @classmethod
452 468 def create_completion(
453 469 cls,
@@ -458,15 +474,7 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
458 474 auth_result: AuthResult = None
459 475 cache_file = cls.get_cache_file()
460 476 try:
461 if cache_file.exists():
462 try:
463 with cache_file.open("r") as f:
464 auth_result = AuthResult(**json.load(f))
465 except json.JSONDecodeError:
466 cache_file.unlink()
467 raise MissingAuthError(f"Invalid auth file: {cache_file}")
468 else:
469 raise MissingAuthError
477 auth_result = cls.get_auth_result()
470 478 yield from to_sync_generator(cls.create_authed(model, messages, auth_result, **kwargs))
471 479 except (MissingAuthError, NoValidHarFileError):
472 480 response = cls.on_auth(**kwargs)
@@ -491,15 +499,7 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
491 499 auth_result: AuthResult = None
492 500 cache_file = cls.get_cache_file()
493 501 try:
494 if cache_file.exists():
495 try:
496 with cache_file.open("r") as f:
497 auth_result = AuthResult(**json.load(f))
498 except json.JSONDecodeError:
499 cache_file.unlink()
500 raise MissingAuthError(f"Invalid auth file: {cache_file}")
501 else:
502 raise MissingAuthError
502 auth_result = cls.get_auth_result()
503 503 response = to_async_iterator(cls.create_authed(model, messages, **kwargs, auth_result=auth_result))
504 504 async for chunk in response:
505 505 yield chunk