mirror of https://github.com/xtekky/gpt4free
~ | Merge pull request #844
Add OpenAssistant and HuggingChat provider, Remove HugChatpull/859/head 0.0.2.6
commit
7e687b3d17
@ -1,65 +0,0 @@
|
||||
has_module = False
|
||||
try:
|
||||
from hugchat.hugchat import ChatBot
|
||||
except ImportError:
|
||||
has_module = False
|
||||
|
||||
from .base_provider import BaseProvider, get_cookies
|
||||
from g4f.typing import CreateResult
|
||||
|
||||
class Hugchat(BaseProvider):
|
||||
url = "https://huggingface.co/chat/"
|
||||
needs_auth = True
|
||||
working = has_module
|
||||
llms = ['OpenAssistant/oasst-sft-6-llama-30b-xor', 'meta-llama/Llama-2-70b-chat-hf']
|
||||
|
||||
@classmethod
|
||||
def create_completion(
|
||||
cls,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
stream: bool = False,
|
||||
proxy: str = None,
|
||||
cookies: str = get_cookies(".huggingface.co"), **kwargs) -> CreateResult:
|
||||
|
||||
bot = ChatBot(
|
||||
cookies=cookies)
|
||||
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
bot.session.proxies = {"http": proxy, "https": proxy}
|
||||
|
||||
if model:
|
||||
try:
|
||||
if not isinstance(model, int):
|
||||
model = cls.llms.index(model)
|
||||
bot.switch_llm(model)
|
||||
except:
|
||||
raise RuntimeError(f"Model are not supported: {model}")
|
||||
|
||||
if len(messages) > 1:
|
||||
formatted = "\n".join(
|
||||
["%s: %s" % (message["role"], message["content"]) for message in messages]
|
||||
)
|
||||
prompt = f"{formatted}\nAssistant:"
|
||||
else:
|
||||
prompt = messages.pop()["content"]
|
||||
|
||||
try:
|
||||
yield bot.chat(prompt, **kwargs)
|
||||
finally:
|
||||
bot.delete_conversation(bot.current_conversation)
|
||||
bot.current_conversation = ""
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
@property
|
||||
def params(cls):
|
||||
params = [
|
||||
("model", "str"),
|
||||
("messages", "list[dict[str, str]]"),
|
||||
("stream", "bool"),
|
||||
("proxy", "str"),
|
||||
]
|
||||
param = ", ".join([": ".join(p) for p in params])
|
||||
return f"g4f.provider.{cls.__name__} supports: ({param})"
|
@ -0,0 +1,107 @@
|
||||
import json
|
||||
from aiohttp import ClientSession
|
||||
|
||||
from ..typing import AsyncGenerator
|
||||
from .base_provider import AsyncGeneratorProvider, get_cookies, format_prompt
|
||||
|
||||
|
||||
class HuggingChat(AsyncGeneratorProvider):
|
||||
url = "https://huggingface.co/chat/"
|
||||
needs_auth = True
|
||||
working = True
|
||||
model = "OpenAssistant/oasst-sft-6-llama-30b-xor"
|
||||
|
||||
@classmethod
|
||||
async def create_async_generator(
|
||||
cls,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
stream: bool = True,
|
||||
proxy: str = None,
|
||||
cookies: dict = None,
|
||||
**kwargs
|
||||
) -> AsyncGenerator:
|
||||
if not cookies:
|
||||
cookies = get_cookies(".huggingface.co")
|
||||
model = model if model else cls.model
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
||||
}
|
||||
async with ClientSession(
|
||||
cookies=cookies,
|
||||
headers=headers
|
||||
) as session:
|
||||
async with session.post("https://huggingface.co/chat/conversation", proxy=proxy, json={"model": model}) as response:
|
||||
conversation_id = (await response.json())["conversationId"]
|
||||
|
||||
send = {
|
||||
"inputs": format_prompt(messages),
|
||||
"parameters": {
|
||||
"temperature": 0.2,
|
||||
"truncate": 1000,
|
||||
"max_new_tokens": 1024,
|
||||
"stop": ["</s>"],
|
||||
"top_p": 0.95,
|
||||
"repetition_penalty": 1.2,
|
||||
"top_k": 50,
|
||||
"return_full_text": False,
|
||||
**kwargs
|
||||
},
|
||||
"stream": stream,
|
||||
"options": {
|
||||
"id": "9e9b8bc4-6604-40c6-994e-8eb78fa32e37",
|
||||
"response_id": "04ce2602-3bea-45e8-8efc-cef00680376a",
|
||||
"is_retry": False,
|
||||
"use_cache": False,
|
||||
"web_search_id": ""
|
||||
}
|
||||
}
|
||||
start = "data:"
|
||||
first = True
|
||||
async with session.post(f"https://huggingface.co/chat/conversation/{conversation_id}", proxy=proxy, json=send) as response:
|
||||
async for line in response.content:
|
||||
line = line.decode("utf-8")
|
||||
if not line:
|
||||
continue
|
||||
if not stream:
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except json.decoder.JSONDecodeError:
|
||||
raise RuntimeError(f"No json: {line}")
|
||||
if "error" in data:
|
||||
raise RuntimeError(data["error"])
|
||||
elif isinstance(data, list):
|
||||
yield data[0]["generated_text"]
|
||||
else:
|
||||
raise RuntimeError(f"Response: {line}")
|
||||
elif line.startswith(start):
|
||||
line = json.loads(line[len(start):-1])
|
||||
if not line:
|
||||
continue
|
||||
if "token" not in line:
|
||||
raise RuntimeError(f"Response: {line}")
|
||||
if not line["token"]["special"]:
|
||||
if first:
|
||||
yield line["token"]["text"].lstrip()
|
||||
first = False
|
||||
else:
|
||||
yield line["token"]["text"]
|
||||
|
||||
async with session.delete(f"https://huggingface.co/chat/conversation/{conversation_id}", proxy=proxy) as response:
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
@classmethod
|
||||
@property
|
||||
def params(cls):
|
||||
params = [
|
||||
("model", "str"),
|
||||
("messages", "list[dict[str, str]]"),
|
||||
("stream", "bool"),
|
||||
("proxy", "str"),
|
||||
]
|
||||
param = ", ".join([": ".join(p) for p in params])
|
||||
return f"g4f.provider.{cls.__name__} supports: ({param})"
|
@ -0,0 +1,98 @@
|
||||
import json
|
||||
from aiohttp import ClientSession
|
||||
|
||||
from ..typing import Any, AsyncGenerator
|
||||
from .base_provider import AsyncGeneratorProvider, get_cookies, format_prompt
|
||||
|
||||
class OpenAssistant(AsyncGeneratorProvider):
|
||||
url = "https://open-assistant.io/chat"
|
||||
needs_auth = True
|
||||
working = True
|
||||
model = "OA_SFT_Llama_30B_6"
|
||||
|
||||
@classmethod
|
||||
async def create_async_generator(
|
||||
cls,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
proxy: str = None,
|
||||
cookies: dict = None,
|
||||
**kwargs: Any
|
||||
) -> AsyncGenerator:
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
if not cookies:
|
||||
cookies = get_cookies("open-assistant.io")
|
||||
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
||||
}
|
||||
async with ClientSession(
|
||||
cookies=cookies,
|
||||
headers=headers
|
||||
) as session:
|
||||
async with session.post("https://open-assistant.io/api/chat", proxy=proxy) as response:
|
||||
chat_id = (await response.json())["id"]
|
||||
|
||||
data = {
|
||||
"chat_id": chat_id,
|
||||
"content": f"<s>[INST]\n{format_prompt(messages)}\n[/INST]",
|
||||
"parent_id": None
|
||||
}
|
||||
async with session.post("https://open-assistant.io/api/chat/prompter_message", proxy=proxy, json=data) as response:
|
||||
parent_id = (await response.json())["id"]
|
||||
|
||||
data = {
|
||||
"chat_id": chat_id,
|
||||
"parent_id": parent_id,
|
||||
"model_config_name": model if model else cls.model,
|
||||
"sampling_parameters":{
|
||||
"top_k": 50,
|
||||
"top_p": None,
|
||||
"typical_p": None,
|
||||
"temperature": 0.35,
|
||||
"repetition_penalty": 1.1111111111111112,
|
||||
"max_new_tokens": 1024,
|
||||
**kwargs
|
||||
},
|
||||
"plugins":[]
|
||||
}
|
||||
async with session.post("https://open-assistant.io/api/chat/assistant_message", proxy=proxy, json=data) as response:
|
||||
data = await response.json()
|
||||
if "id" in data:
|
||||
message_id = data["id"]
|
||||
elif "message" in data:
|
||||
raise RuntimeError(data["message"])
|
||||
else:
|
||||
response.raise_for_status()
|
||||
|
||||
params = {
|
||||
'chat_id': chat_id,
|
||||
'message_id': message_id,
|
||||
}
|
||||
async with session.post("https://open-assistant.io/api/chat/events", proxy=proxy, params=params) as response:
|
||||
start = "data: "
|
||||
async for line in response.content:
|
||||
line = line.decode("utf-8")
|
||||
if line and line.startswith(start):
|
||||
line = json.loads(line[len(start):])
|
||||
if line["event_type"] == "token":
|
||||
yield line["text"]
|
||||
|
||||
params = {
|
||||
'chat_id': chat_id,
|
||||
}
|
||||
async with session.delete("https://open-assistant.io/api/chat", proxy=proxy, params=params) as response:
|
||||
response.raise_for_status()
|
||||
|
||||
@classmethod
|
||||
@property
|
||||
def params(cls):
|
||||
params = [
|
||||
("model", "str"),
|
||||
("messages", "list[dict[str, str]]"),
|
||||
("stream", "bool"),
|
||||
("proxy", "str"),
|
||||
]
|
||||
param = ", ".join([": ".join(p) for p in params])
|
||||
return f"g4f.provider.{cls.__name__} supports: ({param})"
|
@ -1,55 +1,37 @@
|
||||
import urllib.parse, json
|
||||
from aiohttp import ClientSession
|
||||
import json
|
||||
|
||||
from curl_cffi import requests
|
||||
from ..typing import Any, CreateResult
|
||||
from .base_provider import BaseProvider
|
||||
from ..typing import AsyncGenerator
|
||||
from .base_provider import AsyncGeneratorProvider, format_prompt, get_cookies
|
||||
|
||||
|
||||
class You(BaseProvider):
|
||||
class You(AsyncGeneratorProvider):
|
||||
url = "https://you.com"
|
||||
working = True
|
||||
supports_gpt_35_turbo = True
|
||||
supports_stream = True
|
||||
|
||||
@staticmethod
|
||||
def create_completion(
|
||||
async def create_async_generator(
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
stream: bool, **kwargs: Any) -> CreateResult:
|
||||
|
||||
url_param = _create_url_param(messages, kwargs.get("history", []))
|
||||
headers = _create_header()
|
||||
|
||||
response = requests.get(f"https://you.com/api/streamingSearch?{url_param}",
|
||||
headers=headers, impersonate="chrome107")
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
cookies: dict = None,
|
||||
**kwargs,
|
||||
) -> AsyncGenerator:
|
||||
if not cookies:
|
||||
cookies = get_cookies("you.com")
|
||||
headers = {
|
||||
"Accept": "text/event-stream",
|
||||
"Referer": "https://you.com/search?fromSearchBar=true&tbm=youchat",
|
||||
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/116.0"
|
||||
}
|
||||
async with ClientSession(headers=headers, cookies=cookies) as session:
|
||||
async with session.get(
|
||||
"https://you.com/api/streamingSearch",
|
||||
params={"q": format_prompt(messages), "domain": "youchat", "chat": ""},
|
||||
) as response:
|
||||
start = 'data: {"youChatToken": '
|
||||
for line in response.content.splitlines():
|
||||
async for line in response.content:
|
||||
line = line.decode('utf-8')
|
||||
if line.startswith(start):
|
||||
yield json.loads(line[len(start): -1])
|
||||
|
||||
def _create_url_param(messages: list[dict[str, str]], history: list[dict[str, str]]):
|
||||
prompt = ""
|
||||
for message in messages:
|
||||
prompt += "%s: %s\n" % (message["role"], message["content"])
|
||||
prompt += "assistant:"
|
||||
chat = _convert_chat(history)
|
||||
param = {"q": prompt, "domain": "youchat", "chat": chat}
|
||||
return urllib.parse.urlencode(param)
|
||||
|
||||
|
||||
def _convert_chat(messages: list[dict[str, str]]):
|
||||
message_iter = iter(messages)
|
||||
return [
|
||||
{"question": user["content"], "answer": assistant["content"]}
|
||||
for user, assistant in zip(message_iter, message_iter)
|
||||
]
|
||||
|
||||
|
||||
def _create_header():
|
||||
return {
|
||||
"accept": "text/event-stream",
|
||||
"referer": "https://you.com/search?fromSearchBar=true&tbm=youchat",
|
||||
}
|
||||
yield json.loads(line[len(start): -2])
|
@ -0,0 +1,25 @@
|
||||
from time import time
|
||||
|
||||
|
||||
async def log_time_async(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = await method(**kwargs)
|
||||
secs = f"{round(time() - start, 2)} secs"
|
||||
if result:
|
||||
return " ".join([result, secs])
|
||||
return secs
|
||||
|
||||
|
||||
def log_time_yield(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = yield from method(**kwargs)
|
||||
yield f" {round(time() - start, 2)} secs"
|
||||
|
||||
|
||||
def log_time(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = method(**kwargs)
|
||||
secs = f"{round(time() - start, 2)} secs"
|
||||
if result:
|
||||
return " ".join([result, secs])
|
||||
return secs
|
@ -1,95 +1,96 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import asyncio
|
||||
from time import time
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
|
||||
import g4f
|
||||
from testing.log_time import log_time, log_time_async, log_time_yield
|
||||
|
||||
providers = [g4f.Provider.OpenaiChat, g4f.Provider.Bard, g4f.Provider.Bing]
|
||||
|
||||
# Async support
|
||||
async def log_time_async(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = await method(**kwargs)
|
||||
secs = f"{round(time() - start, 2)} secs"
|
||||
if result:
|
||||
return " ".join([result, secs])
|
||||
return secs
|
||||
_providers = [
|
||||
g4f.Provider.H2o,
|
||||
g4f.Provider.You,
|
||||
g4f.Provider.HuggingChat,
|
||||
g4f.Provider.OpenAssistant,
|
||||
g4f.Provider.Bing,
|
||||
g4f.Provider.Bard
|
||||
]
|
||||
|
||||
def log_time_yield(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = yield from method(**kwargs)
|
||||
yield f" {round(time() - start, 2)} secs"
|
||||
_instruct = "Hello, tell about you in one sentence."
|
||||
|
||||
_example = """
|
||||
OpenaiChat: Hello! How can I assist you today? 2.0 secs
|
||||
Bard: Hello! How can I help you today? 3.44 secs
|
||||
Bing: Hello, this is Bing. How can I help? 😊 4.14 secs
|
||||
Async Total: 4.25 secs
|
||||
|
||||
OpenaiChat: Hello! How can I assist you today? 1.85 secs
|
||||
Bard: Hello! How can I help you today? 3.38 secs
|
||||
Bing: Hello, this is Bing. How can I help? 😊 6.14 secs
|
||||
Stream Total: 11.37 secs
|
||||
|
||||
OpenaiChat: Hello! How can I help you today? 3.28 secs
|
||||
Bard: Hello there! How can I help you today? 3.58 secs
|
||||
Bing: Hello! How can I help you today? 3.28 secs
|
||||
No Stream Total: 10.14 secs
|
||||
"""
|
||||
|
||||
print("Yqcloud:", end="")
|
||||
for response in log_time_yield(
|
||||
g4f.ChatCompletion.create,
|
||||
model=g4f.models.gpt_35_turbo,
|
||||
messages=[{"role": "user", "content": _instruct}],
|
||||
provider=g4f.Provider.Yqcloud,
|
||||
#cookies=g4f.get_cookies(".huggingface.co"),
|
||||
stream=True,
|
||||
auth=True
|
||||
):
|
||||
print(response, end="")
|
||||
print()
|
||||
print()
|
||||
|
||||
def log_time(method: callable, **kwargs):
|
||||
start = time()
|
||||
result = method(**kwargs)
|
||||
secs = f"{round(time() - start, 2)} secs"
|
||||
if result:
|
||||
return " ".join([result, secs])
|
||||
return secs
|
||||
|
||||
async def run_async():
|
||||
responses = []
|
||||
for provider in providers:
|
||||
responses.append(log_time_async(
|
||||
responses = [
|
||||
log_time_async(
|
||||
provider.create_async,
|
||||
model=None,
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
log_time=True
|
||||
))
|
||||
messages=[{"role": "user", "content": _instruct}],
|
||||
)
|
||||
for provider in _providers
|
||||
]
|
||||
responses = await asyncio.gather(*responses)
|
||||
for idx, provider in enumerate(providers):
|
||||
for idx, provider in enumerate(_providers):
|
||||
print(f"{provider.__name__}:", responses[idx])
|
||||
print("Async Total:", asyncio.run(log_time_async(run_async)))
|
||||
print()
|
||||
|
||||
|
||||
# Streaming support:
|
||||
def run_stream():
|
||||
for provider in providers:
|
||||
for provider in _providers:
|
||||
print(f"{provider.__name__}: ", end="")
|
||||
for response in log_time_yield(
|
||||
provider.create_completion,
|
||||
model=None,
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
messages=[{"role": "user", "content": _instruct}],
|
||||
):
|
||||
print(response, end="")
|
||||
print()
|
||||
print("Stream Total:", log_time(run_stream))
|
||||
print()
|
||||
|
||||
|
||||
# No streaming support:
|
||||
def create_completion():
|
||||
for provider in providers:
|
||||
def create_no_stream():
|
||||
for provider in _providers:
|
||||
print(f"{provider.__name__}:", end=" ")
|
||||
for response in log_time_yield(
|
||||
g4f.Provider.Bard.create_completion,
|
||||
provider.create_completion,
|
||||
model=None,
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
messages=[{"role": "user", "content": _instruct}],
|
||||
stream=False
|
||||
):
|
||||
print(response, end="")
|
||||
print()
|
||||
print("No Stream Total:", log_time(create_completion))
|
||||
|
||||
for response in g4f.Provider.Hugchat.create_completion(
|
||||
model=None,
|
||||
messages=[{"role": "user", "content": "Hello, tell about you."}],
|
||||
):
|
||||
print("Hugchat:", response)
|
||||
|
||||
"""
|
||||
OpenaiChat: Hello! How can I assist you today? 2.0 secs
|
||||
Bard: Hello! How can I help you today? 3.44 secs
|
||||
Bing: Hello, this is Bing. How can I help? 😊 4.14 secs
|
||||
Async Total: 4.25 secs
|
||||
|
||||
OpenaiChat: Hello! How can I assist you today? 1.85 secs
|
||||
Bard: Hello! How can I help you today? 3.38 secs
|
||||
Bing: Hello, this is Bing. How can I help? 😊 6.14 secs
|
||||
Stream Total: 11.37 secs
|
||||
|
||||
OpenaiChat: Hello! How can I help you today? 3.28 secs
|
||||
Bard: Hello there! How can I help you today? 3.58 secs
|
||||
Bing: Hello! How can I help you today? 3.28 secs
|
||||
No Stream Total: 10.14 secs
|
||||
"""
|
||||
print("No Stream Total:", log_time(create_no_stream))
|
||||
print()
|
Loading…
Reference in New Issue