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

XFEstudio/gpt4free

refactor(g4f/Provider/Blackbox.py): streamline model handling and improve image generation

a15578e2
kqlio67 <kqlio67@users.noreply.github.com>
提交于

代码差异

1 个文件 +71 -104
Modified g4f/Provider/Blackbox.py +71 -104
@@ -1,43 +1,38 @@
1 1 from __future__ import annotations
2 2
3 import uuid
4 import secrets
5 3 import re
6 import base64
4 import json
7 5 from aiohttp import ClientSession
8 from typing import AsyncGenerator, Optional
9 6
10 7 from ..typing import AsyncResult, Messages, ImageType
11 from ..image import to_data_uri, ImageResponse
8 from ..image import ImageResponse, to_data_uri
12 9 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
13 10
14 11 class Blackbox(AsyncGeneratorProvider, ProviderModelMixin):
15 12 url = "https://www.blackbox.ai"
13 api_endpoint = "https://www.blackbox.ai/api/chat"
16 14 working = True
15 supports_stream = True
16 supports_system_message = True
17 supports_message_history = True
18
17 19 default_model = 'blackbox'
18 20 models = [
19 default_model,
20 "gemini-1.5-flash",
21 'blackbox',
22 'gemini-1.5-flash',
21 23 "llama-3.1-8b",
22 24 'llama-3.1-70b',
23 25 'llama-3.1-405b',
24 'ImageGeneration',
26 'ImageGenerationLV45LJp'
25 27 ]
26
27 model_aliases = {
28 "gemini-flash": "gemini-1.5-flash",
29 }
30
31 agent_mode_map = {
32 'ImageGeneration': {"mode": True, "id": "ImageGenerationLV45LJp", "name": "Image Generation"},
33 }
34 28
35 model_id_map = {
36 "blackbox": {},
29 model_config = {
30 "blackbox": {'mode': True, 'id': 'blackbox'},
37 31 "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
38 32 "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
39 33 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
40 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405b"}
34 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405b"},
35 'ImageGenerationLV45LJp': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "Image Generation"},
41 36 }
42 37
43 38 @classmethod
@@ -49,108 +44,80 @@ class Blackbox(AsyncGeneratorProvider, ProviderModelMixin):
49 44 else:
50 45 return cls.default_model
51 46
52 @classmethod
53 async def download_image_to_base64_url(cls, url: str) -> str:
54 async with ClientSession() as session:
55 async with session.get(url) as response:
56 image_data = await response.read()
57 base64_data = base64.b64encode(image_data).decode('utf-8')
58 mime_type = response.headers.get('Content-Type', 'image/jpeg')
59 return f"data:{mime_type};base64,{base64_data}"
60
61 47 @classmethod
62 48 async def create_async_generator(
63 49 cls,
64 50 model: str,
65 51 messages: Messages,
66 proxy: Optional[str] = None,
67 image: Optional[ImageType] = None,
68 image_name: Optional[str] = None,
52 proxy: str = None,
53 image: ImageType = None,
54 image_name: str = None,
69 55 **kwargs
70 ) -> AsyncGenerator[AsyncResult, None]:
71 if image is not None:
72 messages[-1]["data"] = {
73 "fileText": image_name,
74 "imageBase64": to_data_uri(image),
75 "title": str(uuid.uuid4())
76 }
77
56 ) -> AsyncResult:
57 model = cls.get_model(model)
58
78 59 headers = {
79 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
80 "Accept": "*/*",
81 "Accept-Language": "en-US,en;q=0.5",
82 "Accept-Encoding": "gzip, deflate, br",
83 "Referer": cls.url,
84 "Content-Type": "application/json",
85 "Origin": cls.url,
86 "DNT": "1",
87 "Sec-GPC": "1",
88 "Alt-Used": "www.blackbox.ai",
89 "Connection": "keep-alive",
60 "accept": "*/*",
61 "accept-language": "en-US,en;q=0.9",
62 "cache-control": "no-cache",
63 "content-type": "application/json",
64 "origin": cls.url,
65 "pragma": "no-cache",
66 "referer": f"{cls.url}/",
67 "sec-ch-ua": '"Not;A=Brand";v="24", "Chromium";v="128"',
68 "sec-ch-ua-mobile": "?0",
69 "sec-ch-ua-platform": '"Linux"',
70 "sec-fetch-dest": "empty",
71 "sec-fetch-mode": "cors",
72 "sec-fetch-site": "same-origin",
73 "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
90 74 }
91
75
92 76 async with ClientSession(headers=headers) as session:
93 random_id = secrets.token_hex(16)
94 random_user_id = str(uuid.uuid4())
95
96 model = cls.get_model(model) # Resolve the model alias
77 if image is not None:
78 messages[-1]["data"] = {
79 "fileText": image_name,
80 "imageBase64": to_data_uri(image)
81 }
97 82
98 83 data = {
99 84 "messages": messages,
100 "id": random_id,
101 "userId": random_user_id,
85 "id": "MRtAuMi",
86 "previewToken": None,
87 "userId": None,
102 88 "codeModelMode": True,
103 "agentMode": cls.agent_mode_map.get(model, {}),
89 "agentMode": {},
104 90 "trendingAgentMode": {},
105 91 "isMicMode": False,
92 "maxTokens": 1024,
106 93 "isChromeExt": False,
107 "playgroundMode": False,
108 "webSearchMode": False,
109 "userSystemPrompt": "",
110 94 "githubToken": None,
111 "trendingAgentModel": cls.model_id_map.get(model, {}),
112 "maxTokens": None
95 "clickedAnswer2": False,
96 "clickedAnswer3": False,
97 "clickedForceWebSearch": False,
98 "visitFromDelta": False,
99 "mobileClient": False
113 100 }
114 101
115 async with session.post(
116 f"{cls.url}/api/chat", json=data, proxy=proxy
117 ) as response:
102 if model == 'ImageGenerationLV45LJp':
103 data["agentMode"] = cls.model_config[model]
104 else:
105 data["trendingAgentMode"] = cls.model_config[model]
106
107 async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
118 108 response.raise_for_status()
119 full_response = ""
120 buffer = ""
121 image_base64_url = None
122 async for chunk in response.content.iter_any():
123 if chunk:
124 decoded_chunk = chunk.decode()
125 cleaned_chunk = re.sub(r'\$@\$.+?\$@\$|\$@\$', '', decoded_chunk)
126
127 buffer += cleaned_chunk
128
129 # Check if there's a complete image line in the buffer
130 image_match = re.search(r'!\[Generated Image\]\((https?://[^\s\)]+)\)', buffer)
131 if image_match:
132 image_url = image_match.group(1)
133 # Download the image and convert to base64 URL
134 image_base64_url = await cls.download_image_to_base64_url(image_url)
135
136 # Remove the image line from the buffer
137 buffer = re.sub(r'!\[Generated Image\]\(https?://[^\s\)]+\)', '', buffer)
138
139 # Send text line by line
140 lines = buffer.split('\n')
141 for line in lines[:-1]:
142 if line.strip():
143 full_response += line + '\n'
144 yield line + '\n'
145 buffer = lines[-1] # Keep the last incomplete line in the buffer
146
147 # Send the remaining buffer if it's not empty
148 if buffer.strip():
149 full_response += buffer
150 yield buffer
151
152 # If an image was found, send it as ImageResponse
153 if image_base64_url:
154 alt_text = "Generated Image"
155 image_response = ImageResponse(image_base64_url, alt=alt_text)
156 yield image_response
109 if model == 'ImageGenerationLV45LJp':
110 response_text = await response.text()
111 url_match = re.search(r'https://storage\.googleapis\.com/[^\s\)]+', response_text)
112 if url_match:
113 image_url = url_match.group(0)
114 yield ImageResponse(image_url, alt=messages[-1]['content'])
115 else:
116 raise Exception("Image URL not found in the response")
117 else:
118 async for chunk in response.content:
119 if chunk:
120 decoded_chunk = chunk.decode()
121 if decoded_chunk.startswith('$@$v=undefined-rv1$@$'):
122 decoded_chunk = decoded_chunk[len('$@$v=undefined-rv1$@$'):]
123 yield decoded_chunk