返回提交历史
Modified
g4f/Provider/Cloudflare.py
+5
-0
Modified
g4f/Provider/Copilot.py
+36
-38
XFEstudio/gpt4free
refactor: simplify websocket message handling and add cache load logic
- Modified `Cloudflare` class in `Cloudflare.py` to add logic for loading `_args` from a cache file if it exists and `_args` is `None` - Inserted code in `Cloudflare.py` to check existence of cache file and read JSON content into `_args` - Refactored `Copilot` class in `Copilot.py` by removing `try`/`finally` block around websocket message loop - Moved websocket close logic to the end of the message handling loop in `Copilot.py` - Removed nested `try`/`except` block inside the websocket loop in `Copilot.py` - Preserved original message handling structure while simplifying control flow in `Copilot.py
5ff7c884
代码差异
2 个文件
+41
-38
@@ -66,6 +66,11 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
66
66
cls.model_aliases = {**cls.model_aliases, **model_map}
67
67
if not cls.models:
68
68
try:
69
cache_file = cls.get_cache_file()
70
if cls._args is None:
71
if cache_file.exists():
72
with cache_file.open("r") as f:
73
cls._args = json.load(f)
69
74
if cls._args is None:
70
75
cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}}
71
76
read_models()
@@ -158,44 +158,42 @@ class Copilot(AsyncGeneratorProvider, ProviderModelMixin):
158
158
image_prompt: str = None
159
159
last_msg = None
160
160
sources = {}
161
try:
162
while not wss.closed:
163
try:
164
msg = await asyncio.wait_for(wss.recv(), 3 if done else timeout)
165
msg = json.loads(msg[0])
166
except:
167
break
168
last_msg = msg
169
if msg.get("event") == "appendText":
170
yield msg.get("text")
171
elif msg.get("event") == "generatingImage":
172
image_prompt = msg.get("prompt")
173
elif msg.get("event") == "imageGenerated":
174
yield ImageResponse(msg.get("url"), image_prompt, {"preview": msg.get("thumbnailUrl")})
175
elif msg.get("event") == "done":
176
yield FinishReason("stop")
177
done = True
178
elif msg.get("event") == "suggestedFollowups":
179
yield SuggestedFollowups(msg.get("suggestions"))
180
break
181
elif msg.get("event") == "replaceText":
182
yield msg.get("text")
183
elif msg.get("event") == "titleUpdate":
184
yield TitleGeneration(msg.get("title"))
185
elif msg.get("event") == "citation":
186
sources[msg.get("url")] = msg
187
yield SourceLink(list(sources.keys()).index(msg.get("url")), msg.get("url"))
188
elif msg.get("event") == "error":
189
raise RuntimeError(f"Error: {msg}")
190
elif msg.get("event") not in ["received", "startMessage", "partCompleted"]:
191
debug.log(f"Copilot Message: {msg}")
192
if not done:
193
raise RuntimeError(f"Invalid response: {last_msg}")
194
if sources:
195
yield Sources(sources.values())
196
finally:
197
if not wss.closed:
198
await wss.close()
161
while not wss.closed:
162
try:
163
msg = await asyncio.wait_for(wss.recv(), 3 if done else timeout)
164
msg = json.loads(msg[0])
165
except:
166
break
167
last_msg = msg
168
if msg.get("event") == "appendText":
169
yield msg.get("text")
170
elif msg.get("event") == "generatingImage":
171
image_prompt = msg.get("prompt")
172
elif msg.get("event") == "imageGenerated":
173
yield ImageResponse(msg.get("url"), image_prompt, {"preview": msg.get("thumbnailUrl")})
174
elif msg.get("event") == "done":
175
yield FinishReason("stop")
176
done = True
177
elif msg.get("event") == "suggestedFollowups":
178
yield SuggestedFollowups(msg.get("suggestions"))
179
break
180
elif msg.get("event") == "replaceText":
181
yield msg.get("text")
182
elif msg.get("event") == "titleUpdate":
183
yield TitleGeneration(msg.get("title"))
184
elif msg.get("event") == "citation":
185
sources[msg.get("url")] = msg
186
yield SourceLink(list(sources.keys()).index(msg.get("url")), msg.get("url"))
187
elif msg.get("event") == "error":
188
raise RuntimeError(f"Error: {msg}")
189
elif msg.get("event") not in ["received", "startMessage", "partCompleted"]:
190
debug.log(f"Copilot Message: {msg}")
191
if not done:
192
raise RuntimeError(f"Invalid response: {last_msg}")
193
if sources:
194
yield Sources(sources.values())
195
if not wss.closed:
196
await wss.close()
199
197
200
198
async def get_access_token_and_cookies(url: str, proxy: str = None, target: str = "ChatAI",):
201
199
browser, stop_browser = await get_nodriver(proxy=proxy, user_data_dir="copilot")