返回提交历史
Modified
g4f/Provider/Copilot.py
+70
-45
XFEstudio/gpt4free
Handle bucket items with name vs plain text content based on user feedback
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
37b79b6d
代码差异
1 个文件
+70
-45
@@ -30,7 +30,7 @@ from ..requests import get_nodriver
30
30
from ..image import to_bytes, is_accepted_format
31
31
from .helper import get_last_user_message
32
32
from ..files import get_bucket_dir
33
from ..tools.files import get_filenames
33
from ..tools.files import get_filenames, read_bucket
34
34
from pathlib import Path
35
35
from .. import debug
36
36
@@ -40,15 +40,15 @@ class Conversation(JsonConversation):
40
40
def __init__(self, conversation_id: str):
41
41
self.conversation_id = conversation_id
42
42
43
def extract_bucket_ids(messages: Messages) -> list[str]:
44
"""Extract bucket_ids from messages content."""
45
bucket_ids = []
43
def extract_bucket_items(messages: Messages) -> list[dict]:
44
"""Extract bucket items from messages content."""
45
bucket_items = []
46
46
for message in messages:
47
47
if isinstance(message, dict) and isinstance(message.get("content"), list):
48
48
for content_item in message["content"]:
49
if isinstance(content_item, dict) and "bucket_id" in content_item:
50
bucket_ids.append(content_item["bucket_id"])
51
return bucket_ids
49
if isinstance(content_item, dict) and ("bucket_id" in content_item or "bucket" in content_item):
50
bucket_items.append(content_item)
51
return bucket_items
52
52
53
53
class Copilot(AsyncAuthedProvider, ProviderModelMixin):
54
54
label = "Microsoft Copilot"
@@ -188,45 +188,70 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
188
188
uploaded_attachments.append({"type":"image", "url": media})
189
189
190
190
# Upload bucket files
191
bucket_ids = extract_bucket_ids(messages)
192
for bucket_id in bucket_ids:
193
bucket_dir = Path(get_bucket_dir(bucket_id))
194
if bucket_dir.exists():
195
filenames = get_filenames(bucket_dir)
196
for filename in filenames:
197
file_path = bucket_dir / filename
191
bucket_items = extract_bucket_items(messages)
192
for item in bucket_items:
193
try:
194
if "name" in item:
195
# Handle specific file from bucket with name
196
file_path = Path(get_bucket_dir(item["bucket_id"], "media", item["name"]))
198
197
if file_path.exists() and file_path.is_file():
199
try:
200
with open(file_path, "rb") as f:
201
file_data = f.read()
202
203
# Determine content type based on file extension
204
content_type = "application/octet-stream"
205
if filename.endswith(".pdf"):
206
content_type = "application/pdf"
207
elif filename.endswith(".docx"):
208
content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
209
elif filename.endswith(".txt"):
210
content_type = "text/plain"
211
elif filename.endswith(".md"):
212
content_type = "text/markdown"
213
214
response = await session.post(
215
"https://copilot.microsoft.com/c/api/attachments",
216
headers={
217
"content-type": content_type,
218
"content-length": str(len(file_data)),
219
},
220
data=file_data
221
)
222
response.raise_for_status()
223
file_url = response.json().get("url")
224
uploaded_attachments.append({"type": "file", "url": file_url, "name": filename})
225
debug.log(f"Copilot: Uploaded bucket file: {filename}")
226
except Exception as e:
227
debug.log(f"Copilot: Failed to upload bucket file {filename}: {e}")
228
else:
229
debug.log(f"Copilot: Bucket directory not found: {bucket_id}")
198
with open(file_path, "rb") as f:
199
file_data = f.read()
200
201
filename = item["name"]
202
# Determine content type based on file extension
203
content_type = "application/octet-stream"
204
if filename.endswith(".pdf"):
205
content_type = "application/pdf"
206
elif filename.endswith(".docx"):
207
content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
208
elif filename.endswith(".txt"):
209
content_type = "text/plain"
210
elif filename.endswith(".md"):
211
content_type = "text/markdown"
212
elif filename.endswith(".json"):
213
content_type = "application/json"
214
215
response = await session.post(
216
"https://copilot.microsoft.com/c/api/attachments",
217
headers={
218
"content-type": content_type,
219
"content-length": str(len(file_data)),
220
},
221
data=file_data
222
)
223
response.raise_for_status()
224
file_url = response.json().get("url")
225
uploaded_attachments.append({"type": "file", "url": file_url, "name": filename})
226
debug.log(f"Copilot: Uploaded bucket file: {filename}")
227
else:
228
debug.log(f"Copilot: Bucket file not found: {item.get('name')}")
229
else:
230
# Handle plain text content from bucket
231
bucket_path = Path(get_bucket_dir(item["bucket"]))
232
plain_text_content = ""
233
for text_chunk in read_bucket(bucket_path):
234
plain_text_content += text_chunk
235
236
if plain_text_content.strip():
237
# Upload plain text as a text file
238
text_data = plain_text_content.encode('utf-8')
239
response = await session.post(
240
"https://copilot.microsoft.com/c/api/attachments",
241
headers={
242
"content-type": "text/plain",
243
"content-length": str(len(text_data)),
244
},
245
data=text_data
246
)
247
response.raise_for_status()
248
file_url = response.json().get("url")
249
uploaded_attachments.append({"type": "file", "url": file_url, "name": f"bucket_{item['bucket']}.txt"})
250
debug.log(f"Copilot: Uploaded bucket text content: {item['bucket']}")
251
else:
252
debug.log(f"Copilot: No text content found in bucket: {item['bucket']}")
253
except Exception as e:
254
debug.log(f"Copilot: Failed to upload bucket item {item}: {e}")
230
255
231
256
wss = await session.ws_connect(cls.websocket_url, timeout=3)
232
257
if "Think" in model: