Add auto support params method

pull/1274/head
Heiner Lohaus 11 months ago
parent d4c8f3e8d5
commit 702837a33a

@ -71,21 +71,8 @@ class AItianhu(AsyncGeneratorProvider):
if "detail" not in line: if "detail" not in line:
raise RuntimeError(f"Response: {line}") raise RuntimeError(f"Response: {line}")
content = line["detail"]["choices"][0]["delta"].get("content")
if content:
yield content
@classmethod if content := line["detail"]["choices"][0]["delta"].get(
@property "content"
def params(cls): ):
params = [ yield content
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("proxy", "str"),
("temperature", "float"),
("top_p", "int"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -58,15 +58,4 @@ class ChatBase(AsyncGeneratorProvider):
for incorrect_response in cls.list_incorrect_responses: for incorrect_response in cls.list_incorrect_responses:
if incorrect_response in response_data: if incorrect_response in response_data:
raise RuntimeError("Incorrect response") raise RuntimeError("Incorrect response")
yield stream.decode() yield stream.decode()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -57,16 +57,6 @@ class ChatForAi(AsyncGeneratorProvider):
raise RuntimeError(f"Response: {chunk.decode()}") raise RuntimeError(f"Response: {chunk.decode()}")
yield chunk.decode() yield chunk.decode()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
def generate_signature(timestamp: int, message: str, id: str): def generate_signature(timestamp: int, message: str, id: str):
buffer = f"{timestamp}:{id}:{message}:7YN8z6d6" buffer = f"{timestamp}:{id}:{message}:7YN8z6d6"

@ -47,16 +47,6 @@ class FreeGpt(AsyncGeneratorProvider):
raise RuntimeError("Rate limit reached") raise RuntimeError("Rate limit reached")
yield chunk yield chunk
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
def generate_signature(timestamp: int, message: str, secret: str = ""): def generate_signature(timestamp: int, message: str, secret: str = ""):
data = f"{timestamp}:{message}:{secret}" data = f"{timestamp}:{message}:{secret}"

@ -70,16 +70,4 @@ class GeekGpt(BaseProvider):
raise RuntimeError(f'error | {e} :', json_data) raise RuntimeError(f'error | {e} :', json_data)
if content: if content:
yield content yield content
@classmethod
@property
def params(cls):
params = [
('model', 'str'),
('messages', 'list[dict[str, str]]'),
('stream', 'bool'),
('temperature', 'float'),
]
param = ', '.join([': '.join(p) for p in params])
return f'g4f.provider.{cls.__name__} supports: ({param})'

@ -62,21 +62,5 @@ class GptGo(AsyncGeneratorProvider):
line = json.loads(line[len(start):-1]) line = json.loads(line[len(start):-1])
if line["choices"][0]["finish_reason"] == "stop": if line["choices"][0]["finish_reason"] == "stop":
break break
if content := line["choices"][0]["delta"].get("content"):
content = line["choices"][0]["delta"].get("content"): yield content
if content:
yield content
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("proxy", "str"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -97,17 +97,3 @@ class Liaobots(AsyncGeneratorProvider):
async for stream in response.content.iter_any(): async for stream in response.content.iter_any():
if stream: if stream:
yield stream.decode() yield stream.decode()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("proxy", "str"),
("auth", "str"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -56,16 +56,4 @@ class Opchatgpts(AsyncGeneratorProvider):
if line["type"] == "live": if line["type"] == "live":
yield line["data"] yield line["data"]
elif line["type"] == "end": elif line["type"] == "end":
break break
@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})"

@ -55,21 +55,4 @@ class Ylokh(AsyncGeneratorProvider):
yield content yield content
else: else:
chat = await response.json() chat = await response.json()
yield chat["choices"][0]["message"].get("content") yield chat["choices"][0]["message"].get("content")
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("proxy", "str"),
("timeout", "int"),
("temperature", "float"),
("top_p", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -3,6 +3,8 @@ from __future__ import annotations
from asyncio import AbstractEventLoop from asyncio import AbstractEventLoop
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from inspect import signature, Parameter
from types import NoneType
from .helper import get_event_loop, get_cookies, format_prompt from .helper import get_event_loop, get_cookies, format_prompt
from ..typing import CreateResult, AsyncResult, Messages from ..typing import CreateResult, AsyncResult, Messages
@ -52,17 +54,42 @@ class BaseProvider(ABC):
executor, executor,
create_func create_func
) )
@classmethod @classmethod
@property @property
def params(cls) -> str: def params(cls) -> str:
params = [ if issubclass(cls, AsyncGeneratorProvider):
("model", "str"), sig = signature(cls.create_async_generator)
("messages", "list[dict[str, str]]"), elif issubclass(cls, AsyncProvider):
("stream", "bool"), sig = signature(cls.create_async)
] else:
param = ", ".join([": ".join(p) for p in params]) sig = signature(cls.create_completion)
return f"g4f.provider.{cls.__name__} supports: ({param})"
def get_type_name(annotation: type) -> str:
if hasattr(annotation, "__name__"):
annotation = annotation.__name__
elif isinstance(annotation, NoneType):
annotation = "None"
return str(annotation)
args = "";
for name, param in sig.parameters.items():
if name in ("self", "kwargs"):
continue
if name == "stream" and not cls.supports_stream:
continue
if args:
args += ", "
args += "\n"
args += " " + name
if name != "model" and param.annotation is not Parameter.empty:
args += f": {get_type_name(param.annotation)}"
if param.default == "":
args += ' = ""'
elif param.default is not Parameter.empty:
args += f" = {param.default}"
return f"g4f.Provider.{cls.__name__} supports: ({args}\n)"
class AsyncProvider(BaseProvider): class AsyncProvider(BaseProvider):

@ -39,18 +39,6 @@ class Aibn(AsyncGeneratorProvider):
response.raise_for_status() response.raise_for_status()
async for chunk in response.iter_content(): async for chunk in response.iter_content():
yield chunk.decode() yield chunk.decode()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
def generate_signature(timestamp: int, message: str, secret: str = "undefined"): def generate_signature(timestamp: int, message: str, secret: str = "undefined"):

@ -77,19 +77,6 @@ class Ails(AsyncGeneratorProvider):
yield token yield token
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
def _hash(json_data: dict[str, str]) -> SHA256: def _hash(json_data: dict[str, str]) -> SHA256:
base_string: str = f'{json_data["t"]}:{json_data["m"]}:WI,2rU#_r:r~aF4aJ36[.Z(/8Rv93Rf:{len(json_data["m"])}' base_string: str = f'{json_data["t"]}:{json_data["m"]}:WI,2rU#_r:r~aF4aJ36[.Z(/8Rv93Rf:{len(json_data["m"])}'

@ -69,16 +69,4 @@ class Aivvm(BaseProvider):
try: try:
yield chunk.decode("utf-8") yield chunk.decode("utf-8")
except UnicodeDecodeError: except UnicodeDecodeError:
yield chunk.decode("unicode-escape") yield chunk.decode("unicode-escape")
@classmethod
@property
def params(cls):
params = [
('model', 'str'),
('messages', 'list[dict[str, str]]'),
('stream', 'bool'),
('temperature', 'float'),
]
param = ', '.join([': '.join(p) for p in params])
return f'g4f.provider.{cls.__name__} supports: ({param})'

@ -44,15 +44,4 @@ class ChatgptDuo(AsyncProvider):
@classmethod @classmethod
def get_sources(cls): def get_sources(cls):
return cls._sources return cls._sources
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -47,17 +47,4 @@ class CodeLinkAva(AsyncGeneratorProvider):
break break
line = json.loads(line[6:-1]) line = json.loads(line[6:-1])
if content := line["choices"][0]["delta"].get("content"): if content := line["choices"][0]["delta"].get("content"):
yield content yield content
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -60,18 +60,3 @@ class DfeHub(BaseProvider):
if b"content" in chunk: if b"content" in chunk:
data = json.loads(chunk.decode().split("data: ")[1]) data = json.loads(chunk.decode().split("data: ")[1])
yield (data["choices"][0]["delta"]["content"]) yield (data["choices"][0]["delta"]["content"])
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
("presence_penalty", "int"),
("frequency_penalty", "int"),
("top_p", "int"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -87,21 +87,4 @@ class EasyChat(BaseProvider):
splitData = chunk.decode().split("data:") splitData = chunk.decode().split("data:")
if len(splitData) > 1: if len(splitData) > 1:
yield json.loads(splitData[1])["choices"][0]["delta"]["content"] yield json.loads(splitData[1])["choices"][0]["delta"]["content"]
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
("presence_penalty", "int"),
("frequency_penalty", "int"),
("top_p", "int"),
("active_server", "int"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -66,15 +66,4 @@ class Equing(BaseProvider):
if b'content' in line: if b'content' in line:
line_json = json.loads(line.decode('utf-8').split('data: ')[1]) line_json = json.loads(line.decode('utf-8').split('data: ')[1])
if token := line_json['choices'][0]['delta'].get('content'): if token := line_json['choices'][0]['delta'].get('content'):
yield token yield token
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -74,15 +74,4 @@ class FastGpt(BaseProvider):
): ):
yield token yield token
except: except:
continue continue
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -55,22 +55,6 @@ class GetGpt(BaseProvider):
line_json = json.loads(line.decode('utf-8').split('data: ')[1]) line_json = json.loads(line.decode('utf-8').split('data: ')[1])
yield (line_json['choices'][0]['delta']['content']) yield (line_json['choices'][0]['delta']['content'])
@classmethod
@property
def params(cls):
params = [
('model', 'str'),
('messages', 'list[dict[str, str]]'),
('stream', 'bool'),
('temperature', 'float'),
('presence_penalty', 'int'),
('frequency_penalty', 'int'),
('top_p', 'int'),
('max_tokens', 'int'),
]
param = ', '.join([': '.join(p) for p in params])
return f'g4f.provider.{cls.__name__} supports: ({param})'
def _encrypt(e: str): def _encrypt(e: str):
t = os.urandom(8).hex().encode('utf-8') t = os.urandom(8).hex().encode('utf-8')

@ -86,22 +86,4 @@ class H2o(AsyncGeneratorProvider):
f"{cls.url}/conversation/{conversationId}", f"{cls.url}/conversation/{conversationId}",
proxy=proxy, proxy=proxy,
) as response: ) as response:
response.raise_for_status() response.raise_for_status()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
("truncate", "int"),
("max_new_tokens", "int"),
("do_sample", "bool"),
("repetition_penalty", "float"),
("return_full_text", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -48,16 +48,4 @@ class Lockchat(BaseProvider):
if b"content" in token: if b"content" in token:
token = json.loads(token.decode("utf-8").split("data: ")[1]) token = json.loads(token.decode("utf-8").split("data: ")[1])
if token := token["choices"][0]["delta"].get("content"): if token := token["choices"][0]["delta"].get("content"):
yield (token) yield (token)
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -98,18 +98,6 @@ class Myshell(AsyncGeneratorProvider):
raise RuntimeError(f"Received unexpected message: {data_type}") raise RuntimeError(f"Received unexpected message: {data_type}")
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
def generate_timestamp() -> str: def generate_timestamp() -> str:
return str( return str(
int( int(

@ -58,17 +58,4 @@ class V50(BaseProvider):
) )
if "https://fk1.v50.ltd" not in response.text: if "https://fk1.v50.ltd" not in response.text:
yield response.text yield response.text
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("temperature", "float"),
("top_p", "int"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -50,18 +50,4 @@ class Vitalentum(AsyncGeneratorProvider):
break break
line = json.loads(line[6:-1]) line = json.loads(line[6:-1])
if content := line["choices"][0]["delta"].get("content"): if content := line["choices"][0]["delta"].get("content"):
yield content yield content
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool"),
("proxy", "str"),
("temperature", "float"),
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"

@ -54,15 +54,4 @@ class Wuguokai(BaseProvider):
if len(_split) > 1: if len(_split) > 1:
yield _split[1].strip() yield _split[1].strip()
else: else:
yield _split[0].strip() yield _split[0].strip()
@classmethod
@property
def params(cls):
params = [
("model", "str"),
("messages", "list[dict[str, str]]"),
("stream", "bool")
]
param = ", ".join([": ".join(p) for p in params])
return f"g4f.provider.{cls.__name__} supports: ({param})"
Loading…
Cancel
Save