返回提交历史
Modified
g4f/Provider/Copilot.py
+220
-126
Added
g4f/Provider/CopilotSession.py
+203
-0
Modified
g4f/Provider/PollinationsAI.py
+73
-72
Modified
g4f/Provider/PollinationsImage.py
+0
-3
Modified
g4f/Provider/__init__.py
+1
-0
Modified
g4f/cookies.py
+2
-0
Modified
g4f/requests/curl_cffi.py
+5
-0
XFEstudio/gpt4free
Add CopilotSession provider and enhance PollinationsAI endpoints
f2d8a163
代码差异
7 个文件
+504
-201
@@ -10,10 +10,14 @@ import urllib.parse
10
10
from typing import AsyncIterator
11
11
from urllib.parse import quote
12
12
13
13
try:
14
from curl_cffi.requests import AsyncSession
15
from curl_cffi import CurlWsFlag, CurlMime
16
has_curl_cffi = True
17
except ImportError:
18
has_curl_cffi = False
14
19
try:
15
20
import nodriver
16
from nodriver import cdp
17
21
has_nodriver = True
18
22
except ImportError:
19
23
has_nodriver = False
@@ -72,6 +76,8 @@ def get_fake_cookie():
72
76
class Copilot(AsyncAuthedProvider, ProviderModelMixin):
73
77
label = "Microsoft Copilot"
74
78
url = "https://copilot.microsoft.com"
79
cookie_domain = ".microsoft.com"
80
anon_cookie_name = "__Host-copilot-anon"
75
81
76
82
working = True
77
83
use_nodriver = has_nodriver
@@ -86,12 +92,31 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
86
92
"gpt-5": "GPT-5",
87
93
"study": "Study",
88
94
}
89
lock = asyncio.Lock()
90
nodriver = None
95
96
websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
97
conversation_url = f"{url}/c/api/conversations"
91
98
92
99
@classmethod
93
100
async def on_auth_async(cls, cookies: dict = None, proxy: str = None, **kwargs) -> AsyncIterator:
94
yield AuthResult()
101
if cookies is None:
102
cookies = get_fake_cookie() or get_cookies(cls.cookie_domain, False, cache_result=False)
103
access_token = None
104
useridentitytype = None
105
if cls.needs_auth or cls.anon_cookie_name not in cookies:
106
try:
107
access_token, useridentitytype, cookies = readHAR(cls.url)
108
except NoValidHarFileError as h:
109
debug.log(f"Copilot: {h}")
110
if has_nodriver:
111
yield RequestLogin(cls.label, os.environ.get("G4F_LOGIN_URL", ""))
112
access_token, useridentitytype, cookies = await get_access_token_and_cookies(cls.url, proxy, cls.needs_auth)
113
else:
114
raise h
115
yield AuthResult(
116
access_token=access_token,
117
useridentitytype=useridentitytype,
118
cookies=cookies
119
)
95
120
96
121
@classmethod
97
122
async def create_authed(
@@ -104,133 +129,202 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
104
129
prompt: str = None,
105
130
media: MediaListType = None,
106
131
conversation: BaseConversation = None,
132
return_conversation: bool = True,
107
133
**kwargs
108
134
) -> AsyncResult:
109
async with cls.lock:
110
if cls.nodriver is None:
111
cls.nodriver, cls.stop_nodriver = await get_nodriver(proxy=proxy)
112
if prompt is None:
113
prompt = get_last_user_message(messages, False)
114
if conversation is not None:
115
conversation_id = conversation.conversation_id
116
url = f"{cls.url}/chats/{conversation_id}"
135
if not has_curl_cffi:
136
raise MissingRequirementsError('Install or update "curl_cffi" package | pip install -U curl_cffi')
137
model = cls.get_model(model)
138
websocket_url = cls.websocket_url
139
headers = DEFAULT_HEADERS.copy()
140
headers["origin"] = cls.url
141
headers["referer"] = cls.url + "/"
142
if getattr(auth_result, "access_token", None):
143
websocket_url = f"{websocket_url}&accessToken={quote(auth_result.access_token)}" + (f"&X-UserIdentityType={quote(auth_result.useridentitytype)}" if getattr(auth_result, "useridentitytype", None) else "")
144
headers["authorization"] = f"Bearer {auth_result.access_token}"
145
146
async with AsyncSession(
147
timeout=timeout,
148
proxy=proxy,
149
impersonate="chrome",
150
headers=headers,
151
cookies=auth_result.cookies
152
) as session:
153
if conversation is None:
154
# har_file = os.path.join(os.path.dirname(__file__), "copilot", "copilot.microsoft.com.har")
155
# with open(har_file, "r") as f:
156
# har_entries = json.load(f).get("log", {}).get("entries", [])
157
# conversationId = ""
158
# for har_entry in har_entries:
159
# if har_entry.get("request"):
160
# if "/c/api/" in har_entry.get("request").get("url", ""):
161
# try:
162
# response = await getattr(session, har_entry.get("request").get("method").lower())(
163
# har_entry.get("request").get("url", "").replace("cvqBJw7kyPAp1RoMTmzC6", conversationId),
164
# data=har_entry.get("request").get("postData", {}).get("text"),
165
# headers={header["name"]: header["value"] for header in har_entry.get("request").get("headers")}
166
# )
167
# response.raise_for_status()
168
# if response.headers.get("content-type", "").startswith("application/json"):
169
# conversationId = response.json().get("currentConversationId", conversationId)
170
# except Exception as e:
171
# debug.log(f"Copilot: Failed request to {har_entry.get('request').get('url', '')}: {e}")
172
data = {
173
"timeZone": "America/Los_Angeles",
174
"startNewConversation": True,
175
"teenSupportEnabled": True,
176
"correctPersonalizationSetting": True,
177
"performUserMerge": True,
178
"deferredDataUseCapable": True
179
}
180
response = await session.post(
181
"https://copilot.microsoft.com/c/api/start",
182
headers={
183
"content-type": "application/json",
184
**({"x-useridentitytype": auth_result.useridentitytype} if getattr(auth_result, "useridentitytype", None) else {}),
185
**(headers or {})
186
},
187
json=data
188
)
189
if response.status_code == 401:
190
raise MissingAuthError("Status 401: Invalid session")
191
response.raise_for_status()
192
debug.log(f"Copilot: Update cookies: [{', '.join(key for key in response.cookies)}]")
193
auth_result.cookies.update({key: value for key, value in response.cookies.items()})
194
if not cls.needs_auth and cls.anon_cookie_name not in auth_result.cookies:
195
raise MissingAuthError(f"Missing cookie: {cls.anon_cookie_name}")
196
conversation = Conversation(response.json().get("currentConversationId"))
197
debug.log(f"Copilot: Created conversation: {conversation.conversation_id}")
117
198
else:
118
url = cls.url
119
page = await cls.nodriver.get(url)
120
await page.send(cdp.network.enable())
121
queue = asyncio.Queue()
122
page.add_handler(
123
cdp.network.WebSocketFrameReceived,
124
lambda event: queue.put_nowait((event.request_id, event.response.payload_data)),
125
)
126
textarea = await page.select("textarea")
127
if textarea is not None:
128
await textarea.send_keys(prompt)
129
await asyncio.sleep(1)
130
button = await page.select("[data-testid=\"submit-button\"]")
131
if button:
132
await button.click()
133
turnstile = await page.select('#cf-turnstile')
134
if turnstile:
135
debug.log("Found Element: 'cf-turnstile'")
136
await asyncio.sleep(3)
137
await click_trunstile(page)
199
debug.log(f"Copilot: Use conversation: {conversation.conversation_id}")
138
200
139
# uploaded_attachments = []
140
# if auth_result.access_token:
141
# # Upload regular media (images)
142
# for media, _ in merge_media(media, messages):
143
# if not isinstance(media, str):
144
# data_bytes = to_bytes(media)
145
# response_json = await page.evaluate(f'''
146
# fetch('https://copilot.microsoft.com/c/api/attachments', {{
147
# method: 'POST',
148
# headers: {{
149
# 'content-type': '{is_accepted_format(data_bytes)}',
150
# 'content-length': '{len(data_bytes)}',
151
# "'x-useridentitytype': '{auth_result.useridentitytype}'," if getattr(auth_result, "useridentitytype", None) else ""
152
# }},
153
# body: new Uint8Array({list(data_bytes)})
154
# }}).then(r => r.json())
155
# ''')
156
# media = response_json.get("url")
157
# uploaded_attachments.append({{"type":"image", "url": media}})
201
# response = await session.get("https://copilot.microsoft.com/c/api/user?api-version=4", headers={"x-useridentitytype": useridentitytype} if cls._access_token else {})
202
# if response.status_code == 401:
203
# raise MissingAuthError("Status 401: Invalid session")
204
# response.raise_for_status()
205
# print(response.json())
206
# user = response.json().get('firstName')
207
# if user is None:
208
# if cls.needs_auth:
209
# raise MissingAuthError("No user found, please login first")
210
# cls._access_token = None
211
# else:
212
# debug.log(f"Copilot: User: {user}")
158
213
159
# # Upload bucket files
160
# bucket_items = extract_bucket_items(messages)
161
# for item in bucket_items:
162
# try:
163
# # Handle plain text content from bucket
164
# bucket_path = Path(get_bucket_dir(item["bucket_id"]))
165
# for text_chunk in read_bucket(bucket_path):
166
# if text_chunk.strip():
167
# # Upload plain text as a text file
168
# response_json = await page.evaluate(f'''
169
# const formData = new FormData();
170
# formData.append('file', new Blob(['{text_chunk.replace(chr(39), "\\'").replace(chr(10), "\\n").replace(chr(13), "\\r")}'], {{type: 'text/plain'}}), 'bucket_{item['bucket_id']}.txt');
171
# fetch('https://copilot.microsoft.com/c/api/attachments', {{
172
# method: 'POST',
173
# headers: {{
174
# "'x-useridentitytype': '{auth_result.useridentitytype}'," if auth_result.useridentitytype else ""
175
# }},
176
# body: formData
177
# }}).then(r => r.json())
178
# ''')
179
# data = response_json
180
# uploaded_attachments.append({{"type": "document", "attachmentId": data.get("id")}})
181
# debug.log(f"Copilot: Uploaded bucket text content: {item['bucket_id']}")
182
# else:
183
# debug.log(f"Copilot: No text content found in bucket: {item['bucket_id']}")
184
# except Exception as e:
185
# debug.log(f"Copilot: Failed to upload bucket item: {item}")
186
# debug.error(e)
214
uploaded_attachments = []
215
if auth_result.access_token:
216
# Upload regular media (images)
217
for media, _ in merge_media(media, messages):
218
if not isinstance(media, str):
219
data = to_bytes(media)
220
response = await session.post(
221
"https://copilot.microsoft.com/c/api/attachments",
222
headers={
223
"content-type": is_accepted_format(data),
224
"content-length": str(len(data)),
225
**({"x-useridentitytype": auth_result.useridentitytype} if getattr(auth_result, "useridentitytype", None) else {})
226
},
227
data=data
228
)
229
response.raise_for_status()
230
media = response.json().get("url")
231
uploaded_attachments.append({"type":"image", "url": media})
187
232
188
done = False
189
msg = None
190
image_prompt: str = None
191
last_msg = None
192
sources = {}
193
while not done:
194
try:
195
request_id, msg_txt = await asyncio.wait_for(queue.get(), 1 if done else timeout)
196
msg = json.loads(msg_txt)
197
except:
198
break
199
last_msg = msg
200
if msg.get("event") == "startMessage":
201
yield Conversation(msg.get("conversationId"))
202
elif msg.get("event") == "appendText":
203
yield msg.get("text")
204
elif msg.get("event") == "generatingImage":
205
image_prompt = msg.get("prompt")
206
elif msg.get("event") == "imageGenerated":
207
yield ImageResponse(msg.get("url"), image_prompt, {{"preview": msg.get("thumbnailUrl")}})
208
elif msg.get("event") == "done":
209
yield FinishReason("stop")
210
done = True
211
elif msg.get("event") == "suggestedFollowups":
212
yield SuggestedFollowups(msg.get("suggestions"))
213
break
214
elif msg.get("event") == "replaceText":
215
yield msg.get("text")
216
elif msg.get("event") == "titleUpdate":
217
yield TitleGeneration(msg.get("title"))
218
elif msg.get("event") == "citation":
219
sources[msg.get("url")] = msg
220
yield SourceLink(list(sources.keys()).index(msg.get("url")), msg.get("url"))
221
elif msg.get("event") == "partialImageGenerated":
222
mime_type = is_accepted_format(base64.b64decode(msg.get("content")[:12]))
223
yield ImagePreview(f"data:{mime_type};base64,{msg.get('content')}", image_prompt)
224
elif msg.get("event") == "chainOfThought":
225
yield Reasoning(msg.get("text"))
226
elif msg.get("event") == "error":
227
raise RuntimeError(f"Error: {msg}")
228
elif msg.get("event") not in ["received", "startMessage", "partCompleted", "connected"]:
229
debug.log(f"Copilot Message: {msg_txt[:100]}...")
230
if not done:
231
raise MissingAuthError(f"Invalid response: {last_msg}")
232
if sources:
233
yield Sources(sources.values())
233
# Upload bucket files
234
bucket_items = extract_bucket_items(messages)
235
for item in bucket_items:
236
try:
237
# Handle plain text content from bucket
238
bucket_path = Path(get_bucket_dir(item["bucket_id"]))
239
for text_chunk in read_bucket(bucket_path):
240
if text_chunk.strip():
241
# Upload plain text as a text file
242
text_data = text_chunk.encode('utf-8')
243
data = CurlMime()
244
data.addpart("file", filename=f"bucket_{item['bucket_id']}.txt", content_type="text/plain", data=text_data)
245
response = await session.post(
246
"https://copilot.microsoft.com/c/api/attachments",
247
multipart=data,
248
headers={"x-useridentitytype": auth_result.useridentitytype} if getattr(auth_result, "useridentitytype", None) else {}
249
)
250
response.raise_for_status()
251
data = response.json()
252
uploaded_attachments.append({"type": "document", "attachmentId": data.get("id")})
253
debug.log(f"Copilot: Uploaded bucket text content: {item['bucket_id']}")
254
else:
255
debug.log(f"Copilot: No text content found in bucket: {item['bucket_id']}")
256
except Exception as e:
257
debug.log(f"Copilot: Failed to upload bucket item: {item}")
258
debug.error(e)
259
260
if prompt is None:
261
prompt = get_last_user_message(messages, False)
262
263
wss = await session.ws_connect(websocket_url, timeout=3)
264
if "Think" in model:
265
mode = "reasoning"
266
elif model.startswith("gpt-5") or "GPT-5" in model:
267
mode = "smart"
268
else:
269
mode = "chat"
270
await wss.send(json.dumps({
271
"event": "send",
272
"conversationId": conversation.conversation_id,
273
"content": [*uploaded_attachments, {
274
"type": "text",
275
"text": prompt,
276
}],
277
"mode": mode,
278
}).encode(), CurlWsFlag.TEXT)
279
280
done = False
281
msg = None
282
image_prompt: str = None
283
last_msg = None
284
sources = {}
285
while not wss.closed:
286
try:
287
msg_txt, _ = await asyncio.wait_for(wss.recv(), 1 if done else timeout)
288
msg = json.loads(msg_txt)
289
except:
290
break
291
last_msg = msg
292
if msg.get("event") == "appendText":
293
yield msg.get("text")
294
elif msg.get("event") == "generatingImage":
295
image_prompt = msg.get("prompt")
296
elif msg.get("event") == "imageGenerated":
297
yield ImageResponse(msg.get("url"), image_prompt, {"preview": msg.get("thumbnailUrl")})
298
elif msg.get("event") == "done":
299
yield FinishReason("stop")
300
done = True
301
elif msg.get("event") == "suggestedFollowups":
302
yield SuggestedFollowups(msg.get("suggestions"))
303
break
304
elif msg.get("event") == "replaceText":
305
yield msg.get("text")
306
elif msg.get("event") == "titleUpdate":
307
yield TitleGeneration(msg.get("title"))
308
elif msg.get("event") == "citation":
309
sources[msg.get("url")] = msg
310
yield SourceLink(list(sources.keys()).index(msg.get("url")), msg.get("url"))
311
elif msg.get("event") == "partialImageGenerated":
312
mime_type = is_accepted_format(base64.b64decode(msg.get("content")[:12]))
313
yield ImagePreview(f"data:{mime_type};base64,{msg.get('content')}", image_prompt)
314
elif msg.get("event") == "chainOfThought":
315
yield Reasoning(msg.get("text"))
316
elif msg.get("event") == "error":
317
raise RuntimeError(f"Error: {msg}")
318
elif msg.get("event") not in ["received", "startMessage", "partCompleted", "connected"]:
319
debug.log(f"Copilot Message: {msg_txt[:100]}...")
320
if not done:
321
raise MissingAuthError(f"Invalid response: {last_msg}")
322
if return_conversation:
323
yield conversation
324
if sources:
325
yield Sources(sources.values())
326
if not wss.closed:
327
await wss.close()
234
328
235
329
async def get_access_token_and_cookies(url: str, proxy: str = None, needs_auth: bool = False):
236
330
browser, stop_browser = await get_nodriver(proxy=proxy)
@@ -0,0 +1,203 @@
1
from __future__ import annotations
2
3
import json
4
import asyncio
5
import base64
6
from typing import AsyncIterator
7
8
try:
9
import nodriver
10
from nodriver import cdp
11
has_nodriver = True
12
except ImportError:
13
has_nodriver = False
14
15
from .base_provider import AsyncAuthedProvider, ProviderModelMixin
16
from .openai.har_file import get_headers, get_har_files
17
from ..typing import AsyncResult, Messages, MediaListType
18
from ..errors import NoValidHarFileError, MissingAuthError
19
from ..providers.response import *
20
from ..requests import get_nodriver_session
21
from ..image import to_bytes, is_accepted_format
22
from .helper import get_last_user_message
23
from .. import debug
24
25
class Conversation(JsonConversation):
26
conversation_id: str
27
28
def __init__(self, conversation_id: str):
29
self.conversation_id = conversation_id
30
31
def extract_bucket_items(messages: Messages) -> list[dict]:
32
"""Extract bucket items from messages content."""
33
bucket_items = []
34
for message in messages:
35
if isinstance(message, dict) and isinstance(message.get("content"), list):
36
for content_item in message["content"]:
37
if isinstance(content_item, dict) and "bucket_id" in content_item and "name" not in content_item:
38
bucket_items.append(content_item)
39
if message.get("role") == "assistant":
40
bucket_items = []
41
return bucket_items
42
43
class CopilotSession(AsyncAuthedProvider, ProviderModelMixin):
44
parent = "Copilot"
45
label = "Microsoft Copilot (Session)"
46
url = "https://copilot.microsoft.com"
47
48
working = has_nodriver
49
use_nodriver = has_nodriver
50
active_by_default = True
51
use_stream_timeout = False
52
53
default_model = "Copilot"
54
models = [default_model, "Think Deeper", "Smart (GPT-5)", "Study"]
55
model_aliases = {
56
"o1": "Think Deeper",
57
"gpt-4": default_model,
58
"gpt-4o": default_model,
59
"gpt-5": "GPT-5",
60
"study": "Study",
61
}
62
lock = asyncio.Lock()
63
64
@classmethod
65
async def on_auth_async(cls, cookies: dict = None, proxy: str = None, **kwargs) -> AsyncIterator:
66
yield AuthResult()
67
68
@classmethod
69
async def create_authed(
70
cls,
71
model: str,
72
messages: Messages,
73
auth_result: AuthResult,
74
proxy: str = None,
75
timeout: int = 30,
76
prompt: str = None,
77
media: MediaListType = None,
78
conversation: BaseConversation = None,
79
**kwargs
80
) -> AsyncResult:
81
async with get_nodriver_session(proxy=proxy) as session:
82
if prompt is None:
83
prompt = get_last_user_message(messages, False)
84
if conversation is not None:
85
conversation_id = conversation.conversation_id
86
url = f"{cls.url}/chats/{conversation_id}"
87
else:
88
url = cls.url
89
page = await session.get(url)
90
await page.send(cdp.network.enable())
91
queue = asyncio.Queue()
92
page.add_handler(
93
cdp.network.WebSocketFrameReceived,
94
lambda event: queue.put_nowait((event.request_id, event.response.payload_data)),
95
)
96
textarea = await page.select("textarea")
97
if textarea is not None:
98
await textarea.send_keys(prompt)
99
await asyncio.sleep(1)
100
button = await page.select("[data-testid=\"submit-button\"]")
101
if button:
102
await button.click()
103
turnstile = await page.select('#cf-turnstile')
104
if turnstile:
105
debug.log("Found Element: 'cf-turnstile'")
106
await asyncio.sleep(3)
107
await click_trunstile(page)
108
109
# uploaded_attachments = []
110
# if auth_result.access_token:
111
# # Upload regular media (images)
112
# for media, _ in merge_media(media, messages):
113
# if not isinstance(media, str):
114
# data_bytes = to_bytes(media)
115
# response_json = await page.evaluate(f'''
116
# fetch('https://copilot.microsoft.com/c/api/attachments', {{
117
# method: 'POST',
118
# headers: {{
119
# 'content-type': '{is_accepted_format(data_bytes)}',
120
# 'content-length': '{len(data_bytes)}',
121
# "'x-useridentitytype': '{auth_result.useridentitytype}'," if getattr(auth_result, "useridentitytype", None) else ""
122
# }},
123
# body: new Uint8Array({list(data_bytes)})
124
# }}).then(r => r.json())
125
# ''')
126
# media = response_json.get("url")
127
# uploaded_attachments.append({{"type":"image", "url": media}})
128
129
# # Upload bucket files
130
# bucket_items = extract_bucket_items(messages)
131
# for item in bucket_items:
132
# try:
133
# # Handle plain text content from bucket
134
# bucket_path = Path(get_bucket_dir(item["bucket_id"]))
135
# for text_chunk in read_bucket(bucket_path):
136
# if text_chunk.strip():
137
# # Upload plain text as a text file
138
# response_json = await page.evaluate(f'''
139
# const formData = new FormData();
140
# formData.append('file', new Blob(['{text_chunk.replace(chr(39), "\\'").replace(chr(10), "\\n").replace(chr(13), "\\r")}'], {{type: 'text/plain'}}), 'bucket_{item['bucket_id']}.txt');
141
# fetch('https://copilot.microsoft.com/c/api/attachments', {{
142
# method: 'POST',
143
# headers: {{
144
# "'x-useridentitytype': '{auth_result.useridentitytype}'," if auth_result.useridentitytype else ""
145
# }},
146
# body: formData
147
# }}).then(r => r.json())
148
# ''')
149
# data = response_json
150
# uploaded_attachments.append({{"type": "document", "attachmentId": data.get("id")}})
151
# debug.log(f"Copilot: Uploaded bucket text content: {item['bucket_id']}")
152
# else:
153
# debug.log(f"Copilot: No text content found in bucket: {item['bucket_id']}")
154
# except Exception as e:
155
# debug.log(f"Copilot: Failed to upload bucket item: {item}")
156
# debug.error(e)
157
158
done = False
159
msg = None
160
image_prompt: str = None
161
last_msg = None
162
sources = {}
163
while not done:
164
try:
165
request_id, msg_txt = await asyncio.wait_for(queue.get(), 1 if done else timeout)
166
msg = json.loads(msg_txt)
167
except:
168
break
169
last_msg = msg
170
if msg.get("event") == "startMessage":
171
yield Conversation(msg.get("conversationId"))
172
elif msg.get("event") == "appendText":
173
yield msg.get("text")
174
elif msg.get("event") == "generatingImage":
175
image_prompt = msg.get("prompt")
176
elif msg.get("event") == "imageGenerated":
177
yield ImageResponse(msg.get("url"), image_prompt, {{"preview": msg.get("thumbnailUrl")}})
178
elif msg.get("event") == "done":
179
yield FinishReason("stop")
180
done = True
181
elif msg.get("event") == "suggestedFollowups":
182
yield SuggestedFollowups(msg.get("suggestions"))
183
break
184
elif msg.get("event") == "replaceText":
185
yield msg.get("text")
186
elif msg.get("event") == "titleUpdate":
187
yield TitleGeneration(msg.get("title"))
188
elif msg.get("event") == "citation":
189
sources[msg.get("url")] = msg
190
yield SourceLink(list(sources.keys()).index(msg.get("url")), msg.get("url"))
191
elif msg.get("event") == "partialImageGenerated":
192
mime_type = is_accepted_format(base64.b64decode(msg.get("content")[:12]))
193
yield ImagePreview(f"data:{mime_type};base64,{msg.get('content')}", image_prompt)
194
elif msg.get("event") == "chainOfThought":
195
yield Reasoning(msg.get("text"))
196
elif msg.get("event") == "error":
197
raise RuntimeError(f"Error: {msg}")
198
elif msg.get("event") not in ["received", "startMessage", "partCompleted", "connected"]:
199
debug.log(f"Copilot Message: {msg_txt[:100]}...")
200
if not done:
201
raise MissingAuthError(f"Invalid response: {last_msg}")
202
if sources:
203
yield Sources(sources.values())
@@ -21,7 +21,6 @@ from ..requests.aiohttp import get_connector
21
21
from ..image import use_aspect_ratio
22
22
from ..providers.response import ImageResponse, Reasoning, VideoResponse, JsonRequest
23
23
from ..tools.media import render_messages
24
from ..config import REFFERER_URL
25
24
from ..tools.run_tools import AuthManager
26
25
from ..cookies import get_cookies_dir
27
26
from .template.OpenaiTemplate import read_response
@@ -45,12 +44,10 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
45
44
supports_message_history = True
46
45
47
46
# API endpoints
48
text_api_endpoint = "https://text.pollinations.ai/openai"
49
image_api_endpoint = "https://image.pollinations.ai/prompt/{}"
47
text_api_endpoint = "https://g4f.dev/api/pollinations/chat/completions"
48
image_api_endpoint = "https://g4f.dev/prompt/{}"
50
49
gen_image_api_endpoint = "https://gen.pollinations.ai/image/{}"
51
50
gen_text_api_endpoint = "https://gen.pollinations.ai/v1/chat/completions"
52
image_models_endpoint = "https://image.pollinations.ai/models"
53
text_models_endpoint = "https://text.pollinations.ai/models"
54
51
gen_image_models_endpoint = "https://gen.pollinations.ai/image/models"
55
52
gen_text_models_endpoint = "https://gen.pollinations.ai/text/models"
56
53
@@ -108,7 +105,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
108
105
debug.error(f"Failed to load cached models from {path}: {e}")
109
106
try:
110
107
# Update of image models
111
image_response = requests.get(cls.gen_image_models_endpoint if api_key else cls.image_models_endpoint, timeout=timeout)
108
image_response = requests.get(cls.gen_image_models_endpoint, timeout=timeout)
112
109
if image_response.ok:
113
110
new_image_models = image_response.json()
114
111
else:
@@ -129,9 +126,9 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
129
126
cls.image_models = image_models
130
127
cls.video_models = [get_alias(model) for model in new_image_models if isinstance(model, dict) and "video" in model.get("output_modalities", [])]
131
128
132
text_response = requests.get(cls.gen_text_models_endpoint if api_key else cls.text_models_endpoint, timeout=timeout)
129
text_response = requests.get(cls.gen_text_models_endpoint, timeout=timeout)
133
130
if not text_response.ok:
134
text_response = requests.get(cls.gen_text_models_endpoint if api_key else cls.text_models_endpoint, timeout=timeout)
131
text_response = requests.get(cls.gen_text_models_endpoint, timeout=timeout)
135
132
text_response.raise_for_status()
136
133
models = text_response.json()
137
134
@@ -183,7 +180,8 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
183
180
"audio_models": cls.audio_models,
184
181
"vision_models": cls.vision_models,
185
182
"model_aliases": cls.model_aliases,
186
"models": cls.models
183
"models": cls.models,
184
"swap_model_aliases": cls.swap_model_aliases,
187
185
}, f, indent=4)
188
186
except Exception as e:
189
187
debug.error(f"Failed to cache models to {path}: {e}")
@@ -207,7 +205,6 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
207
205
stream: bool = True,
208
206
proxy: str = None,
209
207
cache: bool = None,
210
referrer: str = REFFERER_URL,
211
208
api_key: str = None,
212
209
extra_body: dict = None,
213
210
# Image generation parameters
@@ -252,24 +249,23 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
252
249
alias = cls.swap_model_aliases.get(model, model)
253
250
if alias in cls.image_models or alias in cls.video_models:
254
251
async for chunk in cls._generate_image(
255
model="gptimage" if model == "transparent" else model,
256
alias=alias,
257
prompt=format_media_prompt(messages, prompt),
258
media=media,
259
proxy=proxy,
260
aspect_ratio=aspect_ratio,
261
width=width,
262
height=height,
263
seed=seed,
264
cache=cache,
265
nologo=nologo,
266
private=private,
267
enhance=enhance,
268
safe=safe,
269
transparent=transparent or model == "transparent",
270
n=n,
271
referrer=referrer,
272
api_key=api_key
252
model="gptimage" if model == "transparent" else model,
253
alias=alias,
254
prompt=format_media_prompt(messages, prompt),
255
media=media,
256
proxy=proxy,
257
aspect_ratio=aspect_ratio,
258
width=width,
259
height=height,
260
seed=seed,
261
cache=cache,
262
nologo=nologo,
263
private=private,
264
enhance=enhance,
265
safe=safe,
266
transparent=transparent or model == "transparent",
267
n=n,
268
api_key=api_key
273
269
):
274
270
yield chunk
275
271
else:
@@ -292,7 +288,6 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
292
288
cache=cache,
293
289
stream=stream,
294
290
extra_parameters=extra_parameters,
295
referrer=referrer,
296
291
api_key=api_key,
297
292
extra_body=extra_body,
298
293
**kwargs
@@ -301,26 +296,25 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
301
296
302
297
@classmethod
303
298
async def _generate_image(
304
cls,
305
model: str,
306
alias: str,
307
prompt: str,
308
media: MediaListType,
309
proxy: str,
310
aspect_ratio: str,
311
width: int,
312
height: int,
313
seed: Optional[int],
314
cache: bool,
315
nologo: bool,
316
private: bool,
317
enhance: bool,
318
safe: bool,
319
transparent: bool,
320
n: int,
321
referrer: str,
322
api_key: str,
323
timeout: int = 120
299
cls,
300
model: str,
301
alias: str,
302
prompt: str,
303
media: MediaListType,
304
proxy: str,
305
aspect_ratio: str,
306
width: int,
307
height: int,
308
seed: Optional[int],
309
cache: bool,
310
nologo: bool,
311
private: bool,
312
enhance: bool,
313
safe: bool,
314
transparent: bool,
315
n: int,
316
api_key: str,
317
timeout: int = 120
324
318
) -> AsyncResult:
325
319
if enhance is None:
326
320
enhance = True if model == "flux" else False
@@ -330,14 +324,15 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
330
324
"private": str(private).lower(),
331
325
"enhance": str(enhance).lower(),
332
326
"safe": str(safe).lower(),
333
"referrer": referrer
334
327
}
335
328
if transparent:
336
329
params["transparent"] = "true"
337
330
image = [data for data, _ in media if isinstance(data, str) and data.startswith("http")] if media else []
338
331
if image:
339
332
params["image"] = ",".join(image)
340
if model != "gptimage":
333
if alias in cls.video_models:
334
params["aspectRatio"] = aspect_ratio
335
elif model != "gptimage":
341
336
params = use_aspect_ratio({
342
337
"width": width,
343
338
"height": height,
@@ -348,7 +343,11 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
348
343
if model == "gptimage" and aspect_ratio is not None:
349
344
encoded_prompt = f"{encoded_prompt} aspect-ratio: {aspect_ratio}"
350
345
encoded_prompt = quote_plus(encoded_prompt)[:4096 - len(cls.image_api_endpoint) - len(query) - 8].rstrip("%")
351
url = (cls.gen_image_api_endpoint if api_key else cls.image_api_endpoint).format(f"{encoded_prompt}?{query}")
346
if api_key and not api_key.startswith("g4f_"):
347
url = cls.gen_image_api_endpoint
348
else:
349
url = cls.image_api_endpoint
350
url = url.format(f"{encoded_prompt}?{query}")
352
351
353
352
def get_url_with_seed(i: int, seed: Optional[int] = None):
354
353
if i == 0:
@@ -414,24 +413,23 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
414
413
415
414
@classmethod
416
415
async def _generate_text(
417
cls,
418
model: str,
419
messages: Messages,
420
media: MediaListType,
421
proxy: str,
422
temperature: float,
423
presence_penalty: float,
424
top_p: float,
425
frequency_penalty: float,
426
response_format: Optional[dict],
427
seed: Optional[int],
428
cache: bool,
429
stream: bool,
430
extra_parameters: list[str],
431
referrer: str,
432
api_key: str,
433
extra_body: dict,
434
**kwargs
416
cls,
417
model: str,
418
messages: Messages,
419
media: MediaListType,
420
proxy: str,
421
temperature: float,
422
presence_penalty: float,
423
top_p: float,
424
frequency_penalty: float,
425
response_format: Optional[dict],
426
seed: Optional[int],
427
cache: bool,
428
stream: bool,
429
extra_parameters: list[str],
430
api_key: str,
431
extra_body: dict,
432
**kwargs
435
433
) -> AsyncResult:
436
434
if not cache and seed is None:
437
435
seed = random.randint(0, 2 ** 32)
@@ -458,14 +456,17 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
458
456
response_format=response_format,
459
457
stream=stream,
460
458
seed=None if "tools" in extra_body else seed,
461
referrer=referrer,
462
459
**extra_body
463
460
)
464
461
headers = None
465
462
if api_key:
466
463
headers = {"authorization": f"Bearer {api_key}"}
467
464
yield JsonRequest.from_dict(data)
468
async with session.post(cls.gen_text_api_endpoint if api_key else cls.text_api_endpoint, json=data, headers=headers) as response:
465
if api_key and not api_key.startswith("g4f_"):
466
url = cls.gen_text_api_endpoint
467
else:
468
url = cls.text_api_endpoint
469
async with session.post(url, json=data, headers=headers) as response:
469
470
if response.status in (400, 500):
470
471
debug.error(f"Error: {response.status} - Bad Request: {data}")
471
472
async for chunk in read_response(response, stream, format_media_prompt(messages), cls.get_dict(),
@@ -4,7 +4,6 @@ from typing import Optional
4
4
5
5
from .helper import format_media_prompt
6
6
from ..typing import AsyncResult, Messages, MediaListType
7
from ..config import REFFERER_URL
8
7
from .PollinationsAI import PollinationsAI
9
8
10
9
class PollinationsImage(PollinationsAI):
@@ -37,7 +36,6 @@ class PollinationsImage(PollinationsAI):
37
36
messages: Messages,
38
37
media: MediaListType = None,
39
38
proxy: str = None,
40
referrer: str = REFFERER_URL,
41
39
api_key: str = None,
42
40
prompt: str = None,
43
41
aspect_ratio: str = None,
@@ -75,7 +73,6 @@ class PollinationsImage(PollinationsAI):
75
73
safe=safe,
76
74
transparent=transparent,
77
75
n=n,
78
referrer=referrer,
79
76
api_key=api_key
80
77
):
81
78
yield chunk
@@ -36,6 +36,7 @@ from .ApiAirforce import ApiAirforce
36
36
from .Chatai import Chatai
37
37
from .Cloudflare import Cloudflare
38
38
from .Copilot import Copilot
39
from .CopilotSession import CopilotSession
39
40
from .DeepInfra import DeepInfra
40
41
from .EasyChat import EasyChat
41
42
from .GLM import GLM
@@ -50,6 +50,7 @@ class CookiesConfig:
50
50
class BrowserConfig:
51
51
port: int = None
52
52
host: str = "127.0.0.1"
53
impersonate: str = "chrome"
53
54
54
55
@staticmethod
55
56
def stop_browser():
@@ -199,6 +200,7 @@ def read_cookie_files(dir_path: Optional[str] = None, domains_filter: Optional[L
199
200
if BrowserConfig.port:
200
201
BrowserConfig.port = int(BrowserConfig.port)
201
202
debug.log(f"Using browser: {BrowserConfig.host}:{BrowserConfig.port}")
203
BrowserConfig.impersonate = os.environ.get("G4F_BROWSER_IMPERSONATE", BrowserConfig.impersonate)
202
204
203
205
har_files, json_files = [], []
204
206
for root, _, files in os.walk(dir_path):
@@ -30,6 +30,7 @@ else:
30
30
from typing import AsyncGenerator, Any
31
31
from functools import partialmethod
32
32
import json
33
from ..cookies import BrowserConfig
33
34
34
35
if has_curl_cffi:
35
36
class StreamResponse:
@@ -100,6 +101,10 @@ if has_curl_cffi:
100
101
101
102
Inherits from AsyncSession.
102
103
"""
104
def __init__(self, impersonate: str = None, **kwargs) -> None:
105
if impersonate == "chrome":
106
impersonate = BrowserConfig.impersonate
107
super().__init__(impersonate=impersonate, **kwargs)
103
108
104
109
def request(
105
110
self, method: str, url: str, ssl = None, **kwargs