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

XFEstudio/gpt4free

Refactor Api class model handling and improve provider registration in ClientFactory

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

代码差异

5 个文件 +156 -130
Modified g4f/api/__init__.py +2 -2
@@ -624,7 +624,7 @@ class Api:
624 624 except ValueError as e:
625 625 return ErrorResponse.from_message(str(e), 404)
626 626 if not hasattr(provider, "get_models"):
627 models = []
627 models = getattr(provider, "models", [])
628 628 elif credentials is not None and credentials.credentials != "secret":
629 629 models = provider.get_models(api_key=credentials.credentials)
630 630 else:
@@ -641,7 +641,7 @@ class Api:
641 641 "audio": (model.get("id") if isinstance(model, dict) else model) in getattr(provider, "audio_models", []),
642 642 "video": (model.get("id") if isinstance(model, dict) else model) in getattr(provider, "video_models", []),
643 643 "type": "image" if (model.get("id") if isinstance(model, dict) else model) in getattr(provider, "image_models", []) else "chat",
644 "count": provider.models_count.get(model.get("id") if isinstance(model, dict) else model, 0),
644 "count": provider.models_count.get(model.get("id"), 0) if isinstance(model, dict) else 0,
645 645 **(model if isinstance(model, dict) else {})
646 646 } for model in (models.values() if isinstance(models, dict) else models)]
647 647 }
Modified g4f/client/__init__.py +6 -120
@@ -1,6 +1,5 @@
1 1 from __future__ import annotations
2 2
3 import json
4 3 import os
5 4 import time
6 5 import random
@@ -8,25 +7,21 @@ import string
8 7 import asyncio
9 8 import aiohttp
10 9 import base64
11 import requests
12 from pathlib import Path
13 from datetime import datetime
14 from typing import Union, AsyncIterator, Iterator, Awaitable, Optional, List, Dict, Any, Type
10 from typing import Union, AsyncIterator, Iterator, Awaitable, Optional, Type
15 11
16 12 from ..image.copy_images import copy_media, get_media_dir
17 13 from ..typing import Messages, ImageType
18 14 from ..providers.types import ProviderType, BaseProvider
19 15 from ..providers.response import *
20 from ..errors import NoMediaResponseError, ProviderNotFoundError
16 from ..errors import NoMediaResponseError
21 17 from ..providers.retry_provider import IterListProvider
22 18 from ..providers.asyncio import to_sync_generator
23 from ..Provider import PollinationsImage, ProviderUtils
24 from ..Provider.template import OpenaiTemplate
19 from ..Provider import PollinationsImage
25 20 from ..tools.run_tools import async_iter_run_tools, iter_run_tools
26 from ..cookies import get_cookies_dir
27 21 from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse, UsageModel, ToolCallModel, ClientResponse
28 22 from .models import ClientModels
29 23 from .types import IterResponse, Client as BaseClient
24 from .factory import AbstractClientFactory, create_custom_provider
30 25 from .service import convert_to_provider
31 26 from .helper import find_stop, filter_json, filter_none, safe_aclose
32 27 from .. import debug
@@ -726,55 +721,7 @@ class AsyncImages(Images):
726 721 )
727 722
728 723
729 def create_custom_provider(
730 base_url: str,
731 api_key: str = None,
732 name: str = None,
733 working: bool = True,
734 default_model: str = "",
735 models: List[str] = None,
736 **kwargs
737 ) -> Type[OpenaiTemplate]:
738 """
739 Create a custom provider class based on OpenaiTemplate.
740
741 Args:
742 base_url: The base URL for the API (e.g., "https://api.example.com/v1")
743 api_key: Optional API key for authentication
744 name: Optional name for the provider (defaults to derived from base_url)
745 working: Whether the provider is working (default: True)
746 default_model: Default model to use
747 models: List of available models
748 **kwargs: Additional attributes to set on the provider class
749
750 Returns:
751 A custom provider class that extends OpenaiTemplate
752 """
753 if name is None:
754 # Derive name from base_url
755 from urllib.parse import urlparse
756 parsed = urlparse(base_url)
757 name = parsed.netloc.replace(".", "_").replace("-", "_").title().replace("_", "")
758 if not name:
759 name = "CustomProvider"
760
761 # Create a new class that extends OpenaiTemplate
762 class_attrs = {
763 "url": base_url,
764 "base_url": base_url.rstrip("/"),
765 "api_key": api_key,
766 "working": working,
767 "default_model": default_model,
768 "models": models or [],
769 **kwargs
770 }
771
772 CustomProvider = type(name, (OpenaiTemplate,), class_attrs)
773 print(f"Created custom provider class '{name}' with base URL '{base_url}'")
774 return CustomProvider
775
776
777 class ClientFactory:
724 class ClientFactory(AbstractClientFactory):
778 725 """
779 726 Factory class for creating Client and AsyncClient instances with various provider configurations.
780 727
@@ -785,7 +732,7 @@ class ClientFactory:
785 732
786 733 Example usage:
787 734 # Create client with a named provider
788 client = ClientFactory.create_client("PollinationsAI")
735 client = AbstractClientFactory.create_client("PollinationsAI")
789 736
790 737 # Create client with custom provider
791 738 client = ClientFactory.create_client(
@@ -797,67 +744,6 @@ class ClientFactory:
797 744 async_client = ClientFactory.create_async_client("PollinationsAI")
798 745 """
799 746
800 # Registry of live/custom providers
801 _live_providers_url = "https://g4f.dev/dist/js/providers.json"
802 _live_providers: Dict[str, Dict] = {}
803
804 @classmethod
805 def create_provider(
806 cls,
807 name: str,
808 provider: Union[Type[BaseProvider], str],
809 base_url: str = None,
810 api_key: str = None,
811 **kwargs
812 ) -> Type[BaseProvider]:
813 """
814 Register a live/custom provider that can be used by name.
815
816 Args:
817 name: Name to register the provider under
818 provider: Either a provider class or "custom" to create a custom provider
819 base_url: Base URL for custom providers
820 api_key: API key for custom providers
821 **kwargs: Additional arguments for custom provider creation
822
823 Returns:
824 The registered provider class
825 """
826 if not isinstance(provider, str):
827 return provider
828 elif provider.startswith("custom:"):
829 if provider.startswith("custom:"):
830 serverId = provider[7:]
831 base_url = f"https://g4f.space/custom/{serverId}"
832 if not base_url:
833 raise ValueError("base_url is required for custom providers")
834 provider = create_custom_provider(base_url, api_key, name=name, **kwargs)
835 elif provider in ProviderUtils.convert:
836 provider = ProviderUtils.convert[provider]
837 else:
838 if not cls._live_providers:
839 path = Path(get_cookies_dir()) / "models" / datetime.today().strftime('%Y-%m-%d') / f"providers.json"
840 path.parent.mkdir(parents=True, exist_ok=True)
841 if path.exists():
842 with open(path, "r", encoding="utf-8") as f:
843 cls._live_providers = json.load(f)
844 cls._live_providers = requests.get(cls._live_providers_url).json()
845 with open(path, "w", encoding="utf-8") as f:
846 json.dump(cls._live_providers, f, indent=4)
847 if provider in cls._live_providers.get("providers", {}):
848 config = cls._live_providers["providers"][provider]
849 if "provider" in config and config.get("provider") in ProviderUtils.convert:
850 return ProviderUtils.convert[config.get("provider")]
851 return create_custom_provider(
852 base_url=config.get("baseUrl") if api_key else config.get("backupUrl", config.get("baseUrl")),
853 api_key=api_key,
854 name=provider,
855 default_model=cls._live_providers["defaultModels"].get(provider, ""),
856 )
857 else:
858 raise ProviderNotFoundError(f"Provider '{name}' not found")
859 return provider
860
861 747 @classmethod
862 748 def create_client(
863 749 cls,
Added g4f/client/factory.py +136 -0
@@ -0,0 +1,136 @@
1 from __future__ import annotations
2
3 import json
4 import requests
5 from pathlib import Path
6 from datetime import datetime
7 from typing import Union, List, Dict, Type
8
9 from ..providers.types import ProviderType, BaseProvider
10 from ..errors import ProviderNotFoundError
11 from ..Provider import ProviderUtils
12 from ..Provider.template import OpenaiTemplate
13 from ..cookies import get_cookies_dir
14 from ..config import AppConfig
15
16 def create_custom_provider(
17 base_url: str,
18 api_key: str = None,
19 name: str = None,
20 working: bool = True,
21 default_model: str = "",
22 models: List[str] = None,
23 **kwargs
24 ) -> ProviderType:
25 """
26 Create a custom provider class based on OpenaiTemplate.
27
28 Args:
29 base_url: The base URL for the API (e.g., "https://api.example.com/v1")
30 api_key: Optional API key for authentication
31 name: Optional name for the provider (defaults to derived from base_url)
32 working: Whether the provider is working (default: True)
33 default_model: Default model to use
34 models: List of available models
35 **kwargs: Additional attributes to set on the provider class
36
37 Returns:
38 A custom provider class that extends OpenaiTemplate
39 """
40 if name is None:
41 # Derive name from base_url
42 from urllib.parse import urlparse
43 parsed = urlparse(base_url)
44 name = parsed.netloc.replace(".", "_").replace("-", "_").title().replace("_", "")
45 if not name:
46 name = "CustomProvider"
47
48 # Create a new class that extends OpenaiTemplate
49 class_attrs = {
50 "url": base_url,
51 "base_url": base_url.rstrip("/"),
52 "api_key": api_key,
53 "working": working,
54 "default_model": default_model,
55 "models": models or [],
56 **kwargs
57 }
58
59 CustomProvider = type(name, (OpenaiTemplate,), class_attrs)
60 return CustomProvider
61
62
63 class AbstractClientFactory:
64 # Registry of live/custom providers
65 _live_providers_url = "https://g4f.dev/dist/js/providers.json"
66 _live_providers: Dict[str, Dict] = {}
67
68 @classmethod
69 def create_provider(
70 cls,
71 name: str,
72 provider: Union[Type[BaseProvider], str],
73 base_url: str = None,
74 api_key: str = None,
75 **kwargs
76 ) -> Type[BaseProvider]:
77 """
78 Register a live/custom provider that can be used by name.
79
80 Args:
81 name: Name to register the provider under
82 provider: Either a provider class or "custom" to create a custom provider
83 base_url: Base URL for custom providers
84 api_key: API key for custom providers
85 **kwargs: Additional arguments for custom provider creation
86
87 Returns:
88 The registered provider class
89 """
90 if not isinstance(provider, str):
91 return provider
92 elif provider.startswith("custom:"):
93 base_url = f"https://g4f.space/custom/{provider[7:]}"
94 if not api_key and not cls.is_provider_api_key(AppConfig.g4f_api_key):
95 api_key = AppConfig.g4f_api_key
96 provider = create_custom_provider(base_url, api_key, name=name, **kwargs)
97 elif provider in ProviderUtils.convert:
98 provider = ProviderUtils.convert[provider]
99 else:
100 if not cls._live_providers:
101 path = Path(get_cookies_dir()) / "models" / datetime.today().strftime('%Y-%m-%d') / f"providers.json"
102 path.parent.mkdir(parents=True, exist_ok=True)
103 if path.exists():
104 with open(path, "r", encoding="utf-8") as f:
105 cls._live_providers = json.load(f)
106 cls._live_providers = requests.get(cls._live_providers_url).json()
107 with open(path, "w", encoding="utf-8") as f:
108 json.dump(cls._live_providers, f, indent=4)
109 if provider in cls._live_providers.get("providers", {}):
110 config = cls._live_providers["providers"][provider]
111 if "provider" in config and config.get("provider") in ProviderUtils.convert:
112 return ProviderUtils.convert[config.get("provider")]
113 if not api_key and not cls.is_provider_api_key(AppConfig.g4f_api_key) and config.get("backupUrl"):
114 api_key = AppConfig.g4f_api_key
115 return create_custom_provider(
116 base_url=config.get("baseUrl") if cls.is_provider_api_key(api_key) or config.get("backupUrl") is None else config.get("backupUrl", config.get("baseUrl")),
117 api_key=api_key,
118 name=provider,
119 default_model=cls._live_providers["defaultModels"].get(provider, ""),
120 )
121 else:
122 try:
123 provider = ProviderUtils.get_by_label(provider)
124 except ValueError as e:
125 from g4f.mcp.pa_provider import get_pa_registry
126 registry = get_pa_registry()
127 if provider:
128 provider_cls = registry.get_provider_class(provider)
129 if provider_cls:
130 return provider_cls
131 raise ProviderNotFoundError(str(e)) from e
132 return provider
133
134 @classmethod
135 def is_provider_api_key(cls, api_key: str) -> bool:
136 return api_key and not api_key.startswith("g4f_") and not api_key.startswith("gfs_")
Modified g4f/cookies.py +5 -5
@@ -67,6 +67,10 @@ class BrowserConfig:
67 67 cls.host = os.environ.get("G4F_BROWSER_HOST", cls.host)
68 68 cls.executable_path = os.environ.get("G4F_BROWSER_EXECUTABLE_PATH", cls.executable_path)
69 69 cls.connection_timeout = float(os.environ.get("G4F_BROWSER_CONNECTION_TIMEOUT", cls.connection_timeout))
70 if cls.port:
71 cls.port = int(cls.port)
72 debug.log(f"Using browser: {cls.host}:{cls.port}")
73 cls.impersonate = os.environ.get("G4F_BROWSER_IMPERSONATE", cls.impersonate)
70 74
71 75 COOKIE_DOMAINS = (
72 76 ".bing.com",
@@ -231,12 +235,8 @@ def read_cookie_files(dir_path: Optional[str] = None, domains_filter: Optional[L
231 235 debug.error("Warning: 'python-dotenv' is not installed. Env vars not loaded.")
232 236
233 237 AppConfig.load_from_env()
234
235 238 BrowserConfig.load_from_env()
236 if BrowserConfig.port:
237 BrowserConfig.port = int(BrowserConfig.port)
238 debug.log(f"Using browser: {BrowserConfig.host}:{BrowserConfig.port}")
239 BrowserConfig.impersonate = os.environ.get("G4F_BROWSER_IMPERSONATE", BrowserConfig.impersonate)
239
240 240 if os.path.exists(os.path.join(dir_path, ".browser_is_open")):
241 241 os.remove(os.path.join(dir_path, ".browser_is_open"))
242 242
Modified g4f/mcp/pa_provider.py +7 -3
@@ -529,8 +529,8 @@ def list_pa_providers(directory: "Optional[str | Path]" = None) -> List[Path]:
529 529 directory = get_workspace_dir()
530 530 directory = Path(directory)
531 531 if not directory.exists():
532 return []
533 return sorted(directory.rglob("*.pa.py"))
532 return directory, []
533 return directory, sorted(directory.rglob("*.pa.py"))
534 534
535 535
536 536 # ---------------------------------------------------------------------------
@@ -582,7 +582,8 @@ class PaProviderRegistry:
582 582 def refresh(self) -> None:
583 583 """Re-scan the workspace and reload all ``.pa.py`` providers."""
584 584 entries: List[tuple] = []
585 for pa_path in list_pa_providers():
585 directory, pa_paths = list_pa_providers()
586 for pa_path in pa_paths:
586 587 try:
587 588 cls = load_pa_provider(pa_path)
588 589 if cls is None:
@@ -604,6 +605,7 @@ class PaProviderRegistry:
604 605 bool(getattr(cls, "working", True)),
605 606 getattr(cls, "url", None),
606 607 cls,
608 str(pa_path)[len(str(directory)):]
607 609 ))
608 610 except Exception:
609 611 pass
@@ -621,6 +623,7 @@ class PaProviderRegistry:
621 623 "models": e[2],
622 624 "working": e[3],
623 625 "url": e[4],
626 "path": e[6]
624 627 }
625 628 for e in self._entries
626 629 ]
@@ -645,6 +648,7 @@ class PaProviderRegistry:
645 648 "models": e[2],
646 649 "working": e[3],
647 650 "url": e[4],
651 "path": e[6]
648 652 }
649 653 return None
650 654