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

XFEstudio/gpt4free

fix: improve session handling, message formatting, and content saving

- Added `timeout` parameter support to `LMArenaBeta._create_async_generator` and passed it to `StreamSession` - Ensured fallback to `default_model` in `LMArenaBeta` if `model` is not provided - Modified `OpenaiChat._create_completion` to rebuild messages excluding assistant roles if conversation ID exists - Corrected OpenaiChat `nodriver_auth` to await `browser.get` and replaced page access with reload - Improved `save_content` in `client.py` with robust content extraction, null checks, and logging for missing content - Removed premature `input_text.strip()` in `stream_response` and relocated it to `run_client_args` - Simplified and centralized markdown filtering call in `save_content` - Replaced raw `print` logging in `__init__.py` with `debug.log` for `nodriver` URL opening message

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

代码差异

4 个文件 +25 -12
Modified g4f/Provider/needs_auth/LMArenaBeta.py +4 -1
@@ -92,6 +92,7 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
92 92 messages: Messages,
93 93 conversation: JsonConversation = None,
94 94 proxy: str = None,
95 timeout: int = None,
95 96 **kwargs
96 97 ) -> AsyncResult:
97 98 cache_file = cls.get_cache_file()
@@ -114,6 +115,8 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
114 115
115 116 # Build the JSON payload
116 117 is_image_model = model in image_models
118 if not model:
119 model = cls.default_model
117 120 if model in image_models:
118 121 model = image_models[model]
119 122 elif model in text_models:
@@ -158,7 +161,7 @@ class LMArenaBeta(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
158 161 ],
159 162 "modality": "image" if is_image_model else "chat"
160 163 }
161 async with StreamSession(**args) as session:
164 async with StreamSession(**args, timeout=timeout) as session:
162 165 async with session.post(
163 166 cls.api_endpoint,
164 167 json=data,
Modified g4f/Provider/needs_auth/OpenaiChat.py +10 -4
@@ -431,8 +431,14 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
431 431 if action != "continue":
432 432 data["parent_message_id"] = getattr(conversation, "parent_message_id", conversation.message_id)
433 433 conversation.parent_message_id = None
434 messages = messages if conversation.conversation_id is None else [{"role": "user", "content": prompt}]
435 data["messages"] = cls.create_messages(messages, image_requests, ["search"] if web_search else None)
434 new_messages = messages
435 if conversation.conversation_id is not None:
436 for message in messages:
437 if message.get("role") == "assistant":
438 new_messages = []
439 else:
440 new_messages.append(message)
441 data["messages"] = cls.create_messages(new_messages, image_requests, ["search"] if web_search else None)
436 442 headers = {
437 443 **cls._headers,
438 444 "accept": "text/event-stream",
@@ -655,7 +661,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
655 661 async def nodriver_auth(cls, proxy: str = None):
656 662 browser, stop_browser = await get_nodriver(proxy=proxy)
657 663 try:
658 page = browser.main_tab
664 page = await browser.get(cls.url)
659 665 def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):
660 666 if event.request.url == start_url or event.request.url.startswith(conversation_url):
661 667 if cls.request_config.headers is None:
@@ -681,7 +687,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
681 687 )
682 688 await page.send(nodriver.cdp.network.enable())
683 689 page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
684 page = await browser.get(cls.url)
690 await page.reload()
685 691 user_agent = await page.evaluate("window.navigator.userAgent", return_by_value=True)
686 692 textarea = None
687 693 while not textarea:
Modified g4f/cli/client.py +10 -5
@@ -102,7 +102,6 @@ async def stream_response(
102 102 image = None
103 103 if isinstance(input_text, tuple):
104 104 image, input_text = input_text
105 input_text = input_text.strip()
106 105
107 106 if instructions:
108 107 # Add system instructions to conversation if provided
@@ -143,7 +142,7 @@ async def stream_response(
143 142 if output_file:
144 143 if save_content(response_content, output_file):
145 144 print(f"\nResponse saved to {output_file}")
146
145
147 146 if response_content:
148 147 # Add assistant message to conversation
149 148 conversation.add_message("assistant", str(response_content))
@@ -152,9 +151,12 @@ async def stream_response(
152 151
153 152 def save_content(content, filepath: str, allowed_types = None):
154 153 if hasattr(content, "urls"):
155 content = content.urls[0] if isinstance(content.urls, list) else content.urls
154 content = next(iter(content.urls), None) if isinstance(content.urls, list) else content.urls
156 155 elif hasattr(content, "data"):
157 156 content = content.data
157 if not content:
158 print("\nNo content to save.", file=sys.stderr)
159 return False
158 160 if content.startswith("/media/"):
159 161 os.rename(content.replace("/media", get_media_dir()).split("?")[0], filepath)
160 162 return True
@@ -169,11 +171,14 @@ def save_content(content, filepath: str, allowed_types = None):
169 171 with open(filepath, "wb") as f:
170 172 f.write(response.content)
171 173 return True
172 content = filter_markdown(content, allowed_types, content)
174 content = filter_markdown(content, allowed_types)
173 175 if content:
174 176 with open(filepath, "w") as f:
175 177 f.write(content)
176 178 return True
179 else:
180 print("\nNo valid content to save.", file=sys.stderr)
181 return False
177 182
178 183 def get_parser():
179 184 """Parse command line arguments."""
@@ -278,7 +283,7 @@ def run_client_args(args):
278 283 input_text = " ".join(args.input[1:]) + "\n"
279 284 input_text += f"```{os.path.basename(args.input[0])}\n" + file_content + "\n```"
280 285 elif args.input:
281 input_text = " ".join(args.input)
286 input_text = (" ".join(args.input)).strip()
282 287 if not input_text:
283 288 input_text = sys.stdin.read().strip()
284 289 if not input_text:
Modified g4f/requests/__init__.py +1 -2
@@ -100,8 +100,7 @@ async def get_args_from_nodriver(
100 100 def stop_browser():
101 101 ...
102 102 try:
103 if debug.logging:
104 print(f"Open nodriver with url: {url}")
103 debug.log(f"Open nodriver with url: {url}")
105 104 domain = urlparse(url).netloc
106 105 if cookies is None:
107 106 cookies = {}