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

XFEstudio/gpt4free

Refactor model handling and improve timeout functionality

- Removed empty string mapping from model_map in AnyModelProviderMixin. - Updated clean_name function to exclude 'chat' from version patterns. - Added stream_timeout parameter to AsyncGeneratorProvider for more flexible timeout handling. - Enhanced chunk yielding in AsyncAuthedProvider to support stream_timeout, allowing for better control over asynchronous responses.

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

代码差异

11 个文件 +674 -578
Modified example.env +2 -0
@@ -3,6 +3,8 @@
3 3
4 4 G4F_API_KEY=
5 5 G4F_PROXY=
6 G4F_TIMEOUT=
7 G4F_STREAM_TIMEOUT
6 8
7 9 HUGGINGFACE_API_KEY=
8 10 POLLINATIONS_API_KEY=
Modified g4f/Provider/GLM.py +1 -1
@@ -23,7 +23,7 @@ class GLM(AsyncGeneratorProvider, ProviderModelMixin):
23 23 cls.api_key = response.json().get("token")
24 24 response = requests.get(f"{cls.url}/api/models", headers={"Authorization": f"Bearer {cls.api_key}"})
25 25 data = response.json().get("data", [])
26 cls.model_aliases = {data.get("name"): data.get("id") for data in data}
26 cls.model_aliases = {data.get("name", "").replace("\u4efb\u52a1\u4e13\u7528", "ChatGLM"): data.get("id") for data in data}
27 27 cls.models = list(cls.model_aliases.keys())
28 28 return cls.models
29 29
Modified g4f/Provider/deprecated/DuckDuckGo.py +1 -1
@@ -17,7 +17,7 @@ class DuckDuckGo(AbstractProvider, ProviderModelMixin):
17 17 url = "https://duckduckgo.com/aichat"
18 18 api_base = "https://duckduckgo.com/duckchat/v1/"
19 19
20 working = has_requirements
20 working = False
21 21 supports_stream = True
22 22 supports_system_message = True
23 23 supports_message_history = True
Modified g4f/api/__init__.py +9 -3
@@ -92,6 +92,7 @@ logger = logging.getLogger(__name__)
92 92
93 93 DEFAULT_PORT = 1337
94 94 DEFAULT_TIMEOUT = 600
95 DEFAULT_STREAM_TIMEOUT = 15
95 96
96 97 @asynccontextmanager
97 98 async def lifespan(app: FastAPI):
@@ -99,6 +100,8 @@ async def lifespan(app: FastAPI):
99 100 if not AppConfig.ignore_cookie_files:
100 101 read_cookie_files()
101 102 AppConfig.g4f_api_key = os.environ.get("G4F_API_KEY", AppConfig.g4f_api_key)
103 AppConfig.timeout = os.environ.get("G4F_TIMEOUT", AppConfig.timeout)
104 AppConfig.stream_timeout = os.environ.get("G4F_STREAM_TIMEOUT", AppConfig.stream_timeout)
102 105 yield
103 106 if has_nodriver:
104 107 for browser in util.get_registered_instances():
@@ -133,7 +136,7 @@ def create_app():
133 136 if AppConfig.gui:
134 137 if not has_a2wsgi:
135 138 raise MissingRequirementsError("a2wsgi is required for GUI. Install it with: pip install a2wsgi")
136 gui_app = WSGIMiddleware(get_gui_app(AppConfig.demo, AppConfig.timeout))
139 gui_app = WSGIMiddleware(get_gui_app(AppConfig.demo, AppConfig.timeout, AppConfig.stream_timeout))
137 140 app.mount("/", gui_app)
138 141
139 142 if AppConfig.ignored_providers:
@@ -185,6 +188,7 @@ class AppConfig:
185 188 gui: bool = False
186 189 demo: bool = False
187 190 timeout: int = DEFAULT_TIMEOUT
191 stream_timeout: int = DEFAULT_STREAM_TIMEOUT
188 192
189 193 @classmethod
190 194 def set_config(cls, **data):
@@ -418,6 +422,8 @@ class Api:
418 422 config.conversation_id = conversation_id
419 423 if config.timeout is None:
420 424 config.timeout = AppConfig.timeout
425 if config.stream_timeout is None:
426 config.stream_timeout = AppConfig.stream_timeout
421 427 if credentials is not None and credentials.credentials != "secret":
422 428 config.api_key = credentials.credentials
423 429
@@ -451,7 +457,7 @@ class Api:
451 457 "model": AppConfig.model,
452 458 "provider": AppConfig.provider,
453 459 "proxy": AppConfig.proxy,
454 **config.dict(exclude_none=True),
460 **(config.model_dump(exclude_none=True) if hasattr(config, "model_dump") else config.dict(exclude_none=True)),
455 461 **{
456 462 "conversation_id": None,
457 463 "conversation": conversation,
@@ -474,7 +480,7 @@ class Api:
474 480 self.conversations[config.conversation_id] = {}
475 481 self.conversations[config.conversation_id][config.provider] = chunk
476 482 else:
477 yield f"data: {chunk.json()}\n\n"
483 yield f"data: {chunk.model_dump_json() if hasattr(chunk, 'model_dump_json') else chunk.json()}\n\n"
478 484 except GeneratorExit:
479 485 pass
480 486 except Exception as e:
Modified g4f/api/stubs.py +1 -0
@@ -22,6 +22,7 @@ class RequestConfig(BaseModel):
22 22 proxy: Optional[str] = None
23 23 conversation: Optional[dict] = None
24 24 timeout: Optional[int] = None
25 stream_timeout: Optional[int] = None
25 26 tool_calls: list = Field(default=[], examples=[[
26 27 {
27 28 "function": {
Modified g4f/gui/__init__.py +2 -1
@@ -8,12 +8,13 @@ try:
8 8 except ImportError as e:
9 9 import_error = e
10 10
11 def get_gui_app(demo: bool = False, timeout: int = None):
11 def get_gui_app(demo: bool = False, timeout: int = None, stream_timeout: int = None):
12 12 if import_error is not None:
13 13 raise MissingRequirementsError(f'Install "gui" requirements | pip install -U g4f[gui]\n{import_error}')
14 14 app = create_app()
15 15 app.demo = demo
16 16 app.timeout = timeout
17 app.stream_timeout = stream_timeout
17 18
18 19 site = Website(app)
19 20 for route in site.routes:
Modified g4f/gui/server/backend_api.py +2 -0
@@ -196,6 +196,8 @@ class Backend_Api(Api):
196 196 json_data['media'] = media
197 197 if app.timeout:
198 198 json_data['timeout'] = app.timeout
199 if app.stream_timeout:
200 json_data['stream_timeout'] = app.stream_timeout
199 201 if app.demo and not json_data.get("provider"):
200 202 model = json_data.get("model")
201 203 if model != "default" and model in models.demo_models:
Modified g4f/models.py +5 -1
@@ -14,6 +14,7 @@ from .Provider import (
14 14 HuggingSpace,
15 15 Grok,
16 16 DeepseekAI_JanusPro7b,
17 GLM,
17 18 Kimi,
18 19 LambdaChat,
19 20 Mintlify,
@@ -25,6 +26,7 @@ from .Provider import (
25 26 PerplexityLabs,
26 27 PollinationsAI,
27 28 PollinationsImage,
29 Qwen,
28 30 TeachAnything,
29 31 Together,
30 32 WeWordle,
@@ -159,8 +161,10 @@ default = Model(
159 161 DeepInfra,
160 162 OperaAria,
161 163 Startnest,
162 LambdaChat,
164 GLM,
165 Kimi,
163 166 PollinationsAI,
167 Qwen,
164 168 Together,
165 169 Chatai,
166 170 WeWordle,
Modified g4f/providers/any_provider.py +2 -1
@@ -220,6 +220,7 @@ class AnyModelProviderMixin(ProviderModelMixin):
220 220
221 221 cls.video_models.append("video")
222 222 cls.model_map["video"] = {"Video": "video"}
223 del cls.model_map[""]
223 224 cls.audio_models = [*cls.audio_models]
224 225
225 226 # Create a mapping of parent providers to their children
@@ -415,7 +416,7 @@ def clean_name(name: str) -> str:
415 416 name = re.sub(r'-\d{2}-\d{2}', '', name)
416 417 name = re.sub(r'-[0-9a-f]{8}$', '', name)
417 418 # Version patterns
418 name = re.sub(r'-(instruct|chat|preview|experimental|v\d+|fp8|bf16|hf|free|tput)$', '', name)
419 name = re.sub(r'-(instruct|preview|experimental|v\d+|fp8|bf16|hf|free|tput)$', '', name)
419 420 # Other replacements
420 421 name = name.replace("_", ".")
421 422 name = name.replace("c4ai-", "")
Modified g4f/providers/base_provider.py +12 -4
@@ -291,6 +291,7 @@ class AsyncGeneratorProvider(AbstractProvider):
291 291 model: str,
292 292 messages: Messages,
293 293 timeout: int = None,
294 stream_timeout: int = None,
294 295 **kwargs
295 296 ) -> CreateResult:
296 297 """
@@ -308,7 +309,7 @@ class AsyncGeneratorProvider(AbstractProvider):
308 309 """
309 310 return to_sync_generator(
310 311 cls.create_async_generator(model, messages, **kwargs),
311 timeout=timeout
312 timeout=timeout if stream_timeout is None else stream_timeout,
312 313 )
313 314
314 315 @staticmethod
@@ -482,7 +483,7 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
482 483 auth_result = chunk
483 484 else:
484 485 yield chunk
485 for chunk in to_sync_generator(cls.create_authed(model, messages, auth_result, **kwargs)):
486 for chunk in to_sync_generator(cls.create_authed(model, messages, auth_result, **kwargs), kwargs.get("stream_timeout", kwargs.get("timeout"))):
486 487 if cache_file is not None:
487 488 cls.write_cache_file(cache_file, auth_result)
488 489 cache_file = None
@@ -500,8 +501,15 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
500 501 try:
501 502 auth_result = cls.get_auth_result()
502 503 response = to_async_iterator(cls.create_authed(model, messages, **kwargs, auth_result=auth_result))
503 async for chunk in response:
504 yield chunk
504 if "stream_timeout" in kwargs:
505 while True:
506 try:
507 yield await asyncio.wait_for(response.__anext__(), timeout=kwargs["stream_timeout"])
508 except StopAsyncIteration:
509 break
510 else:
511 async for chunk in response:
512 yield chunk
505 513 except (MissingAuthError, NoValidHarFileError, CloudflareError):
506 514 # if cache_file.exists():
507 515 # cache_file.unlink()