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

XFEstudio/gpt4free

Add OpenaiChat and Hugchat Provider Add tests for providers with auth Improve async support / 2x faster Shared get_cookies by domain function

126496d3
Heiner Lohaus <heiner.lohaus@netformic.com>
提交于

代码差异

7 个文件 +354 -79
Modified g4f/Provider/Bard.py +3 -19
@@ -2,42 +2,26 @@ import json
2 2 import random
3 3 import re
4 4
5 import browser_cookie3
6 5 from aiohttp import ClientSession
7 6 import asyncio
8 7
9 8 from ..typing import Any, CreateResult
10 from .base_provider import BaseProvider
9 from .base_provider import AsyncProvider, get_cookies
11 10
12 class Bard(BaseProvider):
11 class Bard(AsyncProvider):
13 12 url = "https://bard.google.com"
14 13 needs_auth = True
15 14 working = True
16 15
17 @classmethod
18 def create_completion(
19 cls,
20 model: str,
21 messages: list[dict[str, str]],
22 stream: bool,
23 proxy: str = None,
24 cookies: dict = {},
25 **kwargs: Any,
26 ) -> CreateResult:
27 yield asyncio.run(cls.create_async(str, messages, proxy, cookies))
28
29 16 @classmethod
30 17 async def create_async(
31 18 cls,
32 19 model: str,
33 20 messages: list[dict[str, str]],
34 21 proxy: str = None,
35 cookies: dict = {},
22 cookies: dict = get_cookies(".google.com"),
36 23 **kwargs: Any,
37 24 ) -> str:
38 if not cookies:
39 for cookie in browser_cookie3.load(domain_name='.google.com'):
40 cookies[cookie.name] = cookie.value
41 25
42 26 formatted = "\n".join(
43 27 ["%s: %s" % (message["role"], message["content"]) for message in messages]
Modified g4f/Provider/Bing.py +28 -58
@@ -5,48 +5,24 @@ import random
5 5
6 6 import aiohttp
7 7 import asyncio
8 import browser_cookie3
9 8 from aiohttp import ClientSession
10 9
11 10 from ..typing import Any, AsyncGenerator, CreateResult, Union
12 from .base_provider import BaseProvider
11 from .base_provider import AsyncGeneratorProvider, get_cookies
13 12
14 class Bing(BaseProvider):
13 class Bing(AsyncGeneratorProvider):
15 14 url = "https://bing.com/chat"
15 needs_auth = True
16 16 working = True
17 17 supports_gpt_4 = True
18
19 @classmethod
20 def create_completion(
21 cls,
22 model: str,
23 messages: list[dict[str, str]],
24 stream: bool,
25 **kwargs: Any
26 ) -> CreateResult:
27 if stream:
28 yield from run(cls.create_async_generator(model, messages, **kwargs))
29 else:
30 yield asyncio.run(cls.create_async(model, messages, **kwargs))
31
32 @classmethod
33 async def create_async(
34 cls,
35 model: str,
36 messages: list[dict[str, str]],
37 **kwargs: Any,
38 ) -> str:
39 result = []
40 async for chunk in cls.create_async_generator(model, messages, **kwargs):
41 result.append(chunk)
42 if result:
43 return "".join(result)
18 supports_stream=True
44 19
45 20 @staticmethod
46 21 def create_async_generator(
47 22 model: str,
48 23 messages: list[dict[str, str]],
49 cookies: dict = {}
24 cookies: dict = get_cookies(".bing.com"),
25 **kwargs
50 26 ) -> AsyncGenerator:
51 27 if len(messages) < 2:
52 28 prompt = messages[0]["content"]
@@ -54,15 +30,11 @@ class Bing(BaseProvider):
54 30
55 31 else:
56 32 prompt = messages[-1]["content"]
57 context = convert(messages[:-1])
58
59 if not cookies:
60 for cookie in browser_cookie3.load(domain_name='.bing.com'):
61 cookies[cookie.name] = cookie.value
33 context = create_context(messages[:-1])
62 34
63 35 return stream_generate(prompt, context, cookies)
64 36
65 def convert(messages: list[dict[str, str]]):
37 def create_context(messages: list[dict[str, str]]):
66 38 context = ""
67 39
68 40 for message in messages:
@@ -187,34 +159,32 @@ class Defaults:
187 159 'x-forwarded-for': ip_address,
188 160 }
189 161
190 optionsSets = {
191 "optionsSets": [
192 'saharasugg',
193 'enablenewsfc',
194 'clgalileo',
195 'gencontentv3',
196 "nlu_direct_response_filter",
197 "deepleo",
198 "disable_emoji_spoken_text",
199 "responsible_ai_policy_235",
200 "enablemm",
201 "h3precise"
202 "dtappid",
203 "cricinfo",
204 "cricinfov2",
205 "dv3sugg",
206 "nojbfedge"
207 ]
208 }
162 optionsSets = [
163 'saharasugg',
164 'enablenewsfc',
165 'clgalileo',
166 'gencontentv3',
167 "nlu_direct_response_filter",
168 "deepleo",
169 "disable_emoji_spoken_text",
170 "responsible_ai_policy_235",
171 "enablemm",
172 "h3precise"
173 "dtappid",
174 "cricinfo",
175 "cricinfov2",
176 "dv3sugg",
177 "nojbfedge"
178 ]
209 179
210 def format_message(msg: dict) -> str:
211 return json.dumps(msg, ensure_ascii=False) + Defaults.delimiter
180 def format_message(message: dict) -> str:
181 return json.dumps(message, ensure_ascii=False) + Defaults.delimiter
212 182
213 183 def create_message(conversation: Conversation, prompt: str, context: str=None) -> str:
214 184 struct = {
215 185 'arguments': [
216 186 {
217 **Defaults.optionsSets,
187 'optionsSets': Defaults.optionsSets,
218 188 'source': 'cib',
219 189 'allowedMessageTypes': Defaults.allowedMessageTypes,
220 190 'sliceIds': Defaults.sliceIds,
Added g4f/Provider/Hugchat.py +67 -0
@@ -0,0 +1,67 @@
1 has_module = False
2 try:
3 from hugchat.hugchat import ChatBot
4 except ImportError:
5 has_module = False
6
7 from .base_provider import BaseProvider, get_cookies
8 from g4f.typing import CreateResult
9
10 class Hugchat(BaseProvider):
11 url = "https://huggingface.co/chat/"
12 needs_auth = True
13 working = has_module
14 llms = ['OpenAssistant/oasst-sft-6-llama-30b-xor', 'meta-llama/Llama-2-70b-chat-hf']
15
16 @classmethod
17 def create_completion(
18 cls,
19 model: str,
20 messages: list[dict[str, str]],
21 stream: bool = False,
22 proxy: str = None,
23 cookies: str = get_cookies(".huggingface.co"),
24 **kwargs
25 ) -> CreateResult:
26 bot = ChatBot(
27 cookies=cookies
28 )
29
30 if proxy and "://" not in proxy:
31 proxy = f"http://{proxy}"
32 bot.session.proxies = {"http": proxy, "https": proxy}
33
34 if model:
35 try:
36 if not isinstance(model, int):
37 model = cls.llms.index(model)
38 bot.switch_llm(model)
39 except:
40 raise RuntimeError(f"Model are not supported: {model}")
41
42 if len(messages) > 1:
43 formatted = "\n".join(
44 ["%s: %s" % (message["role"], message["content"]) for message in messages]
45 )
46 prompt = f"{formatted}\nAssistant:"
47 else:
48 prompt = messages.pop()["content"]
49
50 try:
51 yield bot.chat(prompt, **kwargs)
52 finally:
53 bot.delete_conversation(bot.current_conversation)
54 bot.current_conversation = ""
55 pass
56
57 @classmethod
58 @property
59 def params(cls):
60 params = [
61 ("model", "str"),
62 ("messages", "list[dict[str, str]]"),
63 ("stream", "bool"),
64 ("proxy", "str"),
65 ]
66 param = ", ".join([": ".join(p) for p in params])
67 return f"g4f.provider.{cls.__name__} supports: ({param})"
Added g4f/Provider/OpenaiChat.py +74 -0
@@ -0,0 +1,74 @@
1 has_module = True
2 try:
3 from revChatGPT.V1 import AsyncChatbot
4 except ImportError:
5 has_module = False
6 from .base_provider import AsyncGeneratorProvider, get_cookies
7 from ..typing import AsyncGenerator
8
9 class OpenaiChat(AsyncGeneratorProvider):
10 url = "https://chat.openai.com"
11 needs_auth = True
12 working = has_module
13 supports_gpt_35_turbo = True
14 supports_gpt_4 = True
15 supports_stream = True
16
17 @classmethod
18 async def create_async_generator(
19 cls,
20 model: str,
21 messages: list[dict[str, str]],
22 proxy: str = None,
23 access_token: str = None,
24 cookies: dict = None,
25 **kwargs
26 ) -> AsyncGenerator:
27
28 config = {"access_token": access_token, "model": model}
29 if proxy:
30 if "://" not in proxy:
31 proxy = f"http://{proxy}"
32 config["proxy"] = proxy
33
34 bot = AsyncChatbot(
35 config=config
36 )
37
38 if not access_token:
39 cookies = cookies if cookies else get_cookies("chat.openai.com")
40 response = await bot.session.get("https://chat.openai.com/api/auth/session", cookies=cookies)
41 access_token = response.json()["accessToken"]
42 bot.set_access_token(access_token)
43
44 if len(messages) > 1:
45 formatted = "\n".join(
46 ["%s: %s" % ((message["role"]).capitalize(), message["content"]) for message in messages]
47 )
48 prompt = f"{formatted}\nAssistant:"
49 else:
50 prompt = messages.pop()["content"]
51
52 returned = None
53 async for message in bot.ask(prompt):
54 message = message["message"]
55 if returned:
56 if message.startswith(returned):
57 new = message[len(returned):]
58 if new:
59 yield new
60 else:
61 yield message
62 returned = message
63
64 @classmethod
65 @property
66 def params(cls):
67 params = [
68 ("model", "str"),
69 ("messages", "list[dict[str, str]]"),
70 ("stream", "bool"),
71 ("proxy", "str"),
72 ]
73 param = ", ".join([": ".join(p) for p in params])
74 return f"g4f.provider.{cls.__name__} supports: ({param})"
Modified g4f/Provider/__init__.py +4 -0
@@ -14,9 +14,11 @@ from .EasyChat import EasyChat
14 14 from .Forefront import Forefront
15 15 from .GetGpt import GetGpt
16 16 from .H2o import H2o
17 from .Hugchat import Hugchat
17 18 from .Liaobots import Liaobots
18 19 from .Lockchat import Lockchat
19 20 from .Opchatgpts import Opchatgpts
21 from .OpenaiChat import OpenaiChat
20 22 from .Raycast import Raycast
21 23 from .Theb import Theb
22 24 from .Vercel import Vercel
@@ -44,10 +46,12 @@ __all__ = [
44 46 "Forefront",
45 47 "GetGpt",
46 48 "H2o",
49 "Hugchat",
47 50 "Liaobots",
48 51 "Lockchat",
49 52 "Opchatgpts",
50 53 "Raycast",
54 "OpenaiChat",
51 55 "Theb",
52 56 "Vercel",
53 57 "Wewordle",
Modified g4f/Provider/base_provider.py +83 -2
@@ -1,7 +1,11 @@
1 1 from abc import ABC, abstractmethod
2 2
3 from ..typing import Any, CreateResult
3 from ..typing import Any, CreateResult, AsyncGenerator, Union
4 4
5 import browser_cookie3
6 import asyncio
7 from time import time
8 import math
5 9
6 10 class BaseProvider(ABC):
7 11 url: str
@@ -30,4 +34,81 @@ class BaseProvider(ABC):
30 34 ("stream", "bool"),
31 35 ]
32 36 param = ", ".join([": ".join(p) for p in params])
33 return f"g4f.provider.{cls.__name__} supports: ({param})"
37 return f"g4f.provider.{cls.__name__} supports: ({param})"
38
39
40 _cookies = {}
41
42 def get_cookies(cookie_domain: str) -> dict:
43 if cookie_domain not in _cookies:
44 _cookies[cookie_domain] = {}
45 for cookie in browser_cookie3.load(cookie_domain):
46 _cookies[cookie_domain][cookie.name] = cookie.value
47 return _cookies[cookie_domain]
48
49
50 class AsyncProvider(BaseProvider):
51 @classmethod
52 def create_completion(
53 cls,
54 model: str,
55 messages: list[dict[str, str]],
56 stream: bool = False,
57 **kwargs: Any
58 ) -> CreateResult:
59 yield asyncio.run(cls.create_async(model, messages, **kwargs))
60
61 @staticmethod
62 @abstractmethod
63 async def create_async(
64 model: str,
65 messages: list[dict[str, str]],
66 **kwargs: Any,
67 ) -> str:
68 raise NotImplementedError()
69
70
71 class AsyncGeneratorProvider(AsyncProvider):
72 @classmethod
73 def create_completion(
74 cls,
75 model: str,
76 messages: list[dict[str, str]],
77 stream: bool = True,
78 **kwargs: Any
79 ) -> CreateResult:
80 if stream:
81 yield from run_generator(cls.create_async_generator(model, messages, **kwargs))
82 else:
83 yield from AsyncProvider.create_completion(cls=cls, model=model, messages=messages, **kwargs)
84
85 @classmethod
86 async def create_async(
87 cls,
88 model: str,
89 messages: list[dict[str, str]],
90 **kwargs: Any,
91 ) -> str:
92 chunks = [chunk async for chunk in cls.create_async_generator(model, messages, **kwargs)]
93 if chunks:
94 return "".join(chunks)
95
96 @staticmethod
97 @abstractmethod
98 def create_async_generator(
99 model: str,
100 messages: list[dict[str, str]],
101 ) -> AsyncGenerator:
102 raise NotImplementedError()
103
104
105 def run_generator(generator: AsyncGenerator[Union[Any, str], Any]):
106 loop = asyncio.new_event_loop()
107 gen = generator.__aiter__()
108
109 while True:
110 try:
111 yield loop.run_until_complete(gen.__anext__())
112
113 except StopAsyncIteration:
114 break
Added testing/test_needs_auth.py +95 -0
@@ -0,0 +1,95 @@
1 import sys
2 from pathlib import Path
3 import asyncio
4 from time import time
5
6 sys.path.append(str(Path(__file__).parent.parent))
7
8 import g4f
9
10 providers = [g4f.Provider.OpenaiChat, g4f.Provider.Bard, g4f.Provider.Bing]
11
12 # Async support
13 async def log_time_async(method: callable, **kwargs):
14 start = time()
15 result = await method(**kwargs)
16 secs = f"{round(time() - start, 2)} secs"
17 if result:
18 return " ".join([result, secs])
19 return secs
20
21 def log_time_yield(method: callable, **kwargs):
22 start = time()
23 result = yield from method(**kwargs)
24 yield f" {round(time() - start, 2)} secs"
25
26 def log_time(method: callable, **kwargs):
27 start = time()
28 result = method(**kwargs)
29 secs = f"{round(time() - start, 2)} secs"
30 if result:
31 return " ".join([result, secs])
32 return secs
33
34 async def run_async():
35 responses = []
36 for provider in providers:
37 responses.append(log_time_async(
38 provider.create_async,
39 model=None,
40 messages=[{"role": "user", "content": "Hello"}],
41 log_time=True
42 ))
43 responses = await asyncio.gather(*responses)
44 for idx, provider in enumerate(providers):
45 print(f"{provider.__name__}:", responses[idx])
46 print("Async Total:", asyncio.run(log_time_async(run_async)))
47
48 # Streaming support:
49 def run_stream():
50 for provider in providers:
51 print(f"{provider.__name__}: ", end="")
52 for response in log_time_yield(
53 provider.create_completion,
54 model=None,
55 messages=[{"role": "user", "content": "Hello"}],
56 ):
57 print(response, end="")
58 print()
59 print("Stream Total:", log_time(run_stream))
60
61 # No streaming support:
62 def create_completion():
63 for provider in providers:
64 print(f"{provider.__name__}:", end=" ")
65 for response in log_time_yield(
66 g4f.Provider.Bard.create_completion,
67 model=None,
68 messages=[{"role": "user", "content": "Hello"}],
69 ):
70 print(response, end="")
71 print()
72 print("No Stream Total:", log_time(create_completion))
73
74 for response in g4f.Provider.Hugchat.create_completion(
75 model=None,
76 messages=[{"role": "user", "content": "Hello, tell about you."}],
77 ):
78 print("Hugchat:", response)
79
80 """
81 OpenaiChat: Hello! How can I assist you today? 2.0 secs
82 Bard: Hello! How can I help you today? 3.44 secs
83 Bing: Hello, this is Bing. How can I help? 😊 4.14 secs
84 Async Total: 4.25 secs
85
86 OpenaiChat: Hello! How can I assist you today? 1.85 secs
87 Bard: Hello! How can I help you today? 3.38 secs
88 Bing: Hello, this is Bing. How can I help? 😊 6.14 secs
89 Stream Total: 11.37 secs
90
91 OpenaiChat: Hello! How can I help you today? 3.28 secs
92 Bard: Hello there! How can I help you today? 3.58 secs
93 Bing: Hello! How can I help you today? 3.28 secs
94 No Stream Total: 10.14 secs
95 """