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

XFEstudio/gpt4free

Add ProviderModelMixin for model selection

91feb340
Heiner Lohaus <hlohaus@users.noreply.github.com>
提交于

代码差异

8 个文件 +104 -88
Modified g4f/Provider/DeepInfra.py +17 -9
@@ -1,18 +1,27 @@
1 1 from __future__ import annotations
2 2
3 3 import json
4 from ..typing import AsyncResult, Messages
5 from .base_provider import AsyncGeneratorProvider
6 from ..requests import StreamSession
4 import requests
5 from ..typing import AsyncResult, Messages
6 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
7 from ..requests import StreamSession
7 8
8 class DeepInfra(AsyncGeneratorProvider):
9 class DeepInfra(AsyncGeneratorProvider, ProviderModelMixin):
9 10 url = "https://deepinfra.com"
10 11 working = True
11 12 supports_stream = True
12 13 supports_message_history = True
13
14 default_model = 'meta-llama/Llama-2-70b-chat-hf'
15
14 16 @staticmethod
17 def get_models():
18 url = 'https://api.deepinfra.com/models/featured'
19 models = requests.get(url).json()
20 return [model['model_name'] for model in models]
21
22 @classmethod
15 23 async def create_async_generator(
24 cls,
16 25 model: str,
17 26 messages: Messages,
18 27 stream: bool,
@@ -21,8 +30,6 @@ class DeepInfra(AsyncGeneratorProvider):
21 30 auth: str = None,
22 31 **kwargs
23 32 ) -> AsyncResult:
24 if not model:
25 model = 'meta-llama/Llama-2-70b-chat-hf'
26 33 headers = {
27 34 'Accept-Encoding': 'gzip, deflate, br',
28 35 'Accept-Language': 'en-US',
@@ -49,7 +56,7 @@ class DeepInfra(AsyncGeneratorProvider):
49 56 impersonate="chrome110"
50 57 ) as session:
51 58 json_data = {
52 'model' : model,
59 'model' : cls.get_model(model),
53 60 'messages': messages,
54 61 'stream' : True
55 62 }
@@ -70,7 +77,8 @@ class DeepInfra(AsyncGeneratorProvider):
70 77 if token:
71 78 if first:
72 79 token = token.lstrip()
80 if token:
73 81 first = False
74 yield token
82 yield token
75 83 except Exception:
76 84 raise RuntimeError(f"Response: {line}")
Modified g4f/Provider/HuggingChat.py +4 -10
@@ -5,11 +5,11 @@ import json, uuid
5 5 from aiohttp import ClientSession
6 6
7 7 from ..typing import AsyncResult, Messages
8 from .base_provider import AsyncGeneratorProvider
8 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
9 9 from .helper import format_prompt, get_cookies
10 10
11 11
12 class HuggingChat(AsyncGeneratorProvider):
12 class HuggingChat(AsyncGeneratorProvider, ProviderModelMixin):
13 13 url = "https://huggingface.co/chat"
14 14 working = True
15 15 default_model = "meta-llama/Llama-2-70b-chat-hf"
@@ -21,7 +21,7 @@ class HuggingChat(AsyncGeneratorProvider):
21 21 "mistralai/Mistral-7B-Instruct-v0.2",
22 22 "openchat/openchat-3.5-0106"
23 23 ]
24 model_map = {
24 model_aliases = {
25 25 "openchat/openchat_3.5": "openchat/openchat-3.5-1210",
26 26 "mistralai/Mixtral-8x7B-Instruct-v0.1": "mistralai/Mistral-7B-Instruct-v0.2"
27 27 }
@@ -37,12 +37,6 @@ class HuggingChat(AsyncGeneratorProvider):
37 37 cookies: dict = None,
38 38 **kwargs
39 39 ) -> AsyncResult:
40 if not model:
41 model = cls.default_model
42 elif model in cls.model_map:
43 model = cls.model_map[model]
44 elif model not in cls.models:
45 raise ValueError(f"Model is not supported: {model}")
46 40 if not cookies:
47 41 cookies = get_cookies(".huggingface.co")
48 42
@@ -53,7 +47,7 @@ class HuggingChat(AsyncGeneratorProvider):
53 47 cookies=cookies,
54 48 headers=headers
55 49 ) as session:
56 async with session.post(f"{cls.url}/conversation", json={"model": model}, proxy=proxy) as response:
50 async with session.post(f"{cls.url}/conversation", json={"model": cls.get_model(model)}, proxy=proxy) as response:
57 51 conversation_id = (await response.json())["conversationId"]
58 52
59 53 send = {
Modified g4f/Provider/Liaobots.py +8 -5
@@ -5,7 +5,7 @@ import uuid
5 5 from aiohttp import ClientSession
6 6
7 7 from ..typing import AsyncResult, Messages
8 from .base_provider import AsyncGeneratorProvider
8 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
9 9
10 10 models = {
11 11 "gpt-4": {
@@ -70,13 +70,17 @@ models = {
70 70 }
71 71 }
72 72
73
74 class Liaobots(AsyncGeneratorProvider):
73 class Liaobots(AsyncGeneratorProvider, ProviderModelMixin):
75 74 url = "https://liaobots.site"
76 75 working = True
77 76 supports_message_history = True
78 77 supports_gpt_35_turbo = True
79 78 supports_gpt_4 = True
79 default_model = "gpt-3.5-turbo"
80 models = [m for m in models]
81 model_aliases = {
82 "claude-v2": "claude-2"
83 }
80 84 _auth_code = None
81 85 _cookie_jar = None
82 86
@@ -89,7 +93,6 @@ class Liaobots(AsyncGeneratorProvider):
89 93 proxy: str = None,
90 94 **kwargs
91 95 ) -> AsyncResult:
92 model = model if model in models else "gpt-3.5-turbo"
93 96 headers = {
94 97 "authority": "liaobots.com",
95 98 "content-type": "application/json",
@@ -122,7 +125,7 @@ class Liaobots(AsyncGeneratorProvider):
122 125
123 126 data = {
124 127 "conversationId": str(uuid.uuid4()),
125 "model": models[model],
128 "model": models[cls.get_model(model)],
126 129 "messages": messages,
127 130 "key": "",
128 131 "prompt": kwargs.get("system_message", "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully."),
Modified g4f/Provider/Llama2.py +14 -12
@@ -3,18 +3,24 @@ from __future__ import annotations
3 3 from aiohttp import ClientSession
4 4
5 5 from ..typing import AsyncResult, Messages
6 from .base_provider import AsyncGeneratorProvider
6 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
7 7
8 models = {
9 "meta-llama/Llama-2-7b-chat-hf": "meta/llama-2-7b-chat",
10 "meta-llama/Llama-2-13b-chat-hf": "meta/llama-2-13b-chat",
11 "meta-llama/Llama-2-70b-chat-hf": "meta/llama-2-70b-chat",
12 }
13 8
14 class Llama2(AsyncGeneratorProvider):
9 class Llama2(AsyncGeneratorProvider, ProviderModelMixin):
15 10 url = "https://www.llama2.ai"
16 11 working = True
17 12 supports_message_history = True
13 default_model = "meta/llama-2-70b-chat"
14 models = [
15 "meta/llama-2-7b-chat",
16 "meta/llama-2-13b-chat",
17 "meta/llama-2-70b-chat",
18 ]
19 model_aliases = {
20 "meta-llama/Llama-2-7b-chat-hf": "meta/llama-2-7b-chat",
21 "meta-llama/Llama-2-13b-chat-hf": "meta/llama-2-13b-chat",
22 "meta-llama/Llama-2-70b-chat-hf": "meta/llama-2-70b-chat",
23 }
18 24
19 25 @classmethod
20 26 async def create_async_generator(
@@ -24,10 +30,6 @@ class Llama2(AsyncGeneratorProvider):
24 30 proxy: str = None,
25 31 **kwargs
26 32 ) -> AsyncResult:
27 if not model:
28 model = "meta/llama-2-70b-chat"
29 elif model in models:
30 model = models[model]
31 33 headers = {
32 34 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0",
33 35 "Accept": "*/*",
@@ -48,7 +50,7 @@ class Llama2(AsyncGeneratorProvider):
48 50 prompt = format_prompt(messages)
49 51 data = {
50 52 "prompt": prompt,
51 "model": model,
53 "model": cls.get_model(model),
52 54 "systemPrompt": kwargs.get("system_message", "You are a helpful assistant."),
53 55 "temperature": kwargs.get("temperature", 0.75),
54 56 "topP": kwargs.get("top_p", 0.9),
Modified g4f/Provider/PerplexityLabs.py +8 -13
@@ -5,20 +5,21 @@ import json
5 5 from aiohttp import ClientSession
6 6
7 7 from ..typing import AsyncResult, Messages
8 from .base_provider import AsyncGeneratorProvider
8 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
9 9
10 10 API_URL = "https://labs-api.perplexity.ai/socket.io/"
11 11 WS_URL = "wss://labs-api.perplexity.ai/socket.io/"
12 12
13 class PerplexityLabs(AsyncGeneratorProvider):
13 class PerplexityLabs(AsyncGeneratorProvider, ProviderModelMixin):
14 14 url = "https://labs.perplexity.ai"
15 15 working = True
16 supports_gpt_35_turbo = True
17 models = ['pplx-7b-online', 'pplx-70b-online', 'pplx-7b-chat', 'pplx-70b-chat', 'mistral-7b-instruct',
16 models = [
17 'pplx-7b-online', 'pplx-70b-online', 'pplx-7b-chat', 'pplx-70b-chat', 'mistral-7b-instruct',
18 18 'codellama-34b-instruct', 'llama-2-70b-chat', 'llava-7b-chat', 'mixtral-8x7b-instruct',
19 'mistral-medium', 'related']
19 'mistral-medium', 'related'
20 ]
20 21 default_model = 'pplx-70b-online'
21 model_map = {
22 model_aliases = {
22 23 "mistralai/Mistral-7B-Instruct-v0.1": "mistral-7b-instruct",
23 24 "meta-llama/Llama-2-70b-chat-hf": "llama-2-70b-chat",
24 25 "mistralai/Mixtral-8x7B-Instruct-v0.1": "mixtral-8x7b-instruct",
@@ -33,12 +34,6 @@ class PerplexityLabs(AsyncGeneratorProvider):
33 34 proxy: str = None,
34 35 **kwargs
35 36 ) -> AsyncResult:
36 if not model:
37 model = cls.default_model
38 elif model in cls.model_map:
39 model = cls.model_map[model]
40 elif model not in cls.models:
41 raise ValueError(f"Model is not supported: {model}")
42 37 headers = {
43 38 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0",
44 39 "Accept": "*/*",
@@ -78,7 +73,7 @@ class PerplexityLabs(AsyncGeneratorProvider):
78 73 message_data = {
79 74 'version': '2.2',
80 75 'source': 'default',
81 'model': model,
76 'model': cls.get_model(model),
82 77 'messages': messages
83 78 }
84 79 await ws.send_str('42' + json.dumps(['perplexity_playground', message_data]))
Modified g4f/Provider/base_provider.py +21 -2
@@ -8,7 +8,7 @@ from inspect import signature, Parameter
8 8 from .helper import get_cookies, format_prompt
9 9 from ..typing import CreateResult, AsyncResult, Messages, Union
10 10 from ..base_provider import BaseProvider
11 from ..errors import NestAsyncioError
11 from ..errors import NestAsyncioError, ModelNotSupportedError
12 12
13 13 if sys.version_info < (3, 10):
14 14 NoneType = type(None)
@@ -251,4 +251,23 @@ class AsyncGeneratorProvider(AsyncProvider):
251 251 Returns:
252 252 AsyncResult: An asynchronous generator yielding results.
253 253 """
254 raise NotImplementedError()
254 raise NotImplementedError()
255
256 class ProviderModelMixin:
257 default_model: str
258 models: list[str] = []
259 model_aliases: dict[str, str] = {}
260
261 @classmethod
262 def get_models(cls) -> list[str]:
263 return cls.models
264
265 @classmethod
266 def get_model(cls, model: str) -> str:
267 if not model:
268 return cls.default_model
269 elif model in cls.model_aliases:
270 return cls.model_aliases[model]
271 elif model not in cls.get_models():
272 raise ModelNotSupportedError(f"Model is not supported: {model} in: {cls.__name__}")
273 return model
Modified g4f/Provider/needs_auth/OpenaiChat.py +29 -37
@@ -10,22 +10,15 @@ from selenium.webdriver.common.by import By
10 10 from selenium.webdriver.support.ui import WebDriverWait
11 11 from selenium.webdriver.support import expected_conditions as EC
12 12
13 from ..base_provider import AsyncGeneratorProvider
13 from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
14 14 from ..helper import format_prompt, get_cookies
15 15 from ...webdriver import get_browser, get_driver_cookies
16 16 from ...typing import AsyncResult, Messages
17 17 from ...requests import StreamSession
18 18 from ...image import to_image, to_bytes, ImageType, ImageResponse
19 19
20 # Aliases for model names
21 MODELS = {
22 "gpt-3.5": "text-davinci-002-render-sha",
23 "gpt-3.5-turbo": "text-davinci-002-render-sha",
24 "gpt-4": "gpt-4",
25 "gpt-4-gizmo": "gpt-4-gizmo"
26 }
27 20
28 class OpenaiChat(AsyncGeneratorProvider):
21 class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
29 22 """A class for creating and managing conversations with OpenAI chat service"""
30 23
31 24 url = "https://chat.openai.com"
@@ -33,6 +26,11 @@ class OpenaiChat(AsyncGeneratorProvider):
33 26 needs_auth = True
34 27 supports_gpt_35_turbo = True
35 28 supports_gpt_4 = True
29 default_model = None
30 models = ["text-davinci-002-render-sha", "gpt-4", "gpt-4-gizmo"]
31 model_aliases = {
32 "gpt-3.5-turbo": "text-davinci-002-render-sha",
33 }
36 34 _cookies: dict = {}
37 35 _default_model: str = None
38 36
@@ -91,7 +89,7 @@ class OpenaiChat(AsyncGeneratorProvider):
91 89 )
92 90
93 91 @classmethod
94 async def _upload_image(
92 async def upload_image(
95 93 cls,
96 94 session: StreamSession,
97 95 headers: dict,
@@ -150,7 +148,7 @@ class OpenaiChat(AsyncGeneratorProvider):
150 148 return ImageResponse(download_url, image_data["file_name"], image_data)
151 149
152 150 @classmethod
153 async def _get_default_model(cls, session: StreamSession, headers: dict):
151 async def get_default_model(cls, session: StreamSession, headers: dict):
154 152 """
155 153 Get the default model name from the service
156 154
@@ -161,20 +159,17 @@ class OpenaiChat(AsyncGeneratorProvider):
161 159 Returns:
162 160 The default model name as a string
163 161 """
164 # Check the cache for the default model
165 if cls._default_model:
166 return cls._default_model
167 # Get the models data from the service
168 async with session.get(f"{cls.url}/backend-api/models", headers=headers) as response:
169 data = await response.json()
170 if "categories" in data:
171 cls._default_model = data["categories"][-1]["default_model"]
172 else:
173 raise RuntimeError(f"Response: {data}")
174 return cls._default_model
162 if not cls.default_model:
163 async with session.get(f"{cls.url}/backend-api/models", headers=headers) as response:
164 data = await response.json()
165 if "categories" in data:
166 cls.default_model = data["categories"][-1]["default_model"]
167 else:
168 raise RuntimeError(f"Response: {data}")
169 return cls.default_model
175 170
176 171 @classmethod
177 def _create_messages(cls, prompt: str, image_response: ImageResponse = None):
172 def create_messages(cls, prompt: str, image_response: ImageResponse = None):
178 173 """
179 174 Create a list of messages for the user input
180 175
@@ -222,7 +217,7 @@ class OpenaiChat(AsyncGeneratorProvider):
222 217 return messages
223 218
224 219 @classmethod
225 async def _get_generated_image(cls, session: StreamSession, headers: dict, line: dict) -> ImageResponse:
220 async def get_generated_image(cls, session: StreamSession, headers: dict, line: dict) -> ImageResponse:
226 221 """
227 222 Retrieves the image response based on the message content.
228 223
@@ -257,7 +252,7 @@ class OpenaiChat(AsyncGeneratorProvider):
257 252 raise RuntimeError(f"Error in downloading image: {e}")
258 253
259 254 @classmethod
260 async def _delete_conversation(cls, session: StreamSession, headers: dict, conversation_id: str):
255 async def delete_conversation(cls, session: StreamSession, headers: dict, conversation_id: str):
261 256 """
262 257 Deletes a conversation by setting its visibility to False.
263 258
@@ -322,7 +317,6 @@ class OpenaiChat(AsyncGeneratorProvider):
322 317 Raises:
323 318 RuntimeError: If an error occurs during processing.
324 319 """
325 model = MODELS.get(model, model)
326 320 if not parent_id:
327 321 parent_id = str(uuid.uuid4())
328 322 if not cookies:
@@ -333,7 +327,7 @@ class OpenaiChat(AsyncGeneratorProvider):
333 327 login_url = os.environ.get("G4F_LOGIN_URL")
334 328 if login_url:
335 329 yield f"Please login: [ChatGPT]({login_url})\n\n"
336 access_token, cookies = cls._browse_access_token(proxy)
330 access_token, cookies = cls.browse_access_token(proxy)
337 331 cls._cookies = cookies
338 332
339 333 headers = {"Authorization": f"Bearer {access_token}"}
@@ -344,12 +338,10 @@ class OpenaiChat(AsyncGeneratorProvider):
344 338 timeout=timeout,
345 339 cookies=dict([(name, value) for name, value in cookies.items() if name == "_puid"])
346 340 ) as session:
347 if not model:
348 model = await cls._get_default_model(session, headers)
349 341 try:
350 342 image_response = None
351 343 if image:
352 image_response = await cls._upload_image(session, headers, image)
344 image_response = await cls.upload_image(session, headers, image)
353 345 yield image_response
354 346 except Exception as e:
355 347 yield e
@@ -357,15 +349,15 @@ class OpenaiChat(AsyncGeneratorProvider):
357 349 while not end_turn.is_end:
358 350 data = {
359 351 "action": action,
360 "arkose_token": await cls._get_arkose_token(session),
352 "arkose_token": await cls.get_arkose_token(session),
361 353 "conversation_id": conversation_id,
362 354 "parent_message_id": parent_id,
363 "model": model,
355 "model": cls.get_model(model or await cls.get_default_model(session, headers)),
364 356 "history_and_training_disabled": history_disabled and not auto_continue,
365 357 }
366 358 if action != "continue":
367 359 prompt = format_prompt(messages) if not conversation_id else messages[-1]["content"]
368 data["messages"] = cls._create_messages(prompt, image_response)
360 data["messages"] = cls.create_messages(prompt, image_response)
369 361 async with session.post(
370 362 f"{cls.url}/backend-api/conversation",
371 363 json=data,
@@ -391,7 +383,7 @@ class OpenaiChat(AsyncGeneratorProvider):
391 383 if "message_type" not in line["message"]["metadata"]:
392 384 continue
393 385 try:
394 image_response = await cls._get_generated_image(session, headers, line)
386 image_response = await cls.get_generated_image(session, headers, line)
395 387 if image_response:
396 388 yield image_response
397 389 except Exception as e:
@@ -422,10 +414,10 @@ class OpenaiChat(AsyncGeneratorProvider):
422 414 action = "continue"
423 415 await asyncio.sleep(5)
424 416 if history_disabled and auto_continue:
425 await cls._delete_conversation(session, headers, conversation_id)
417 await cls.delete_conversation(session, headers, conversation_id)
426 418
427 419 @classmethod
428 def _browse_access_token(cls, proxy: str = None, timeout: int = 1200) -> tuple[str, dict]:
420 def browse_access_token(cls, proxy: str = None, timeout: int = 1200) -> tuple[str, dict]:
429 421 """
430 422 Browse to obtain an access token.
431 423
@@ -452,7 +444,7 @@ class OpenaiChat(AsyncGeneratorProvider):
452 444 driver.quit()
453 445
454 446 @classmethod
455 async def _get_arkose_token(cls, session: StreamSession) -> str:
447 async def get_arkose_token(cls, session: StreamSession) -> str:
456 448 """
457 449 Obtain an Arkose token for the session.
458 450
Modified g4f/errors.py +3 -0
@@ -26,4 +26,7 @@ class VersionNotFoundError(Exception):
26 26 pass
27 27
28 28 class NestAsyncioError(Exception):
29 pass
30
31 class ModelNotSupportedError(Exception):
29 32 pass