Skip to content

Commit

Permalink
- Dynamic provider g4fauto. Resolves #29
Browse files Browse the repository at this point in the history
- Test and save working g4f providers. #29
   ```sh
   pytgpt gpt4free test -y
   ```
- Order providers in ascending. Resolves #31
  • Loading branch information
Simatwa committed Feb 9, 2024
1 parent 5045d59 commit 0e91640
Show file tree
Hide file tree
Showing 6 changed files with 296 additions and 5 deletions.
13 changes: 12 additions & 1 deletion docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,4 +366,15 @@ For instance:
**What's new?**

- New model : **GPT4ALL** - Support offline LLM.
- New model : **GPT4ALL** - Support offline LLM.

## v0.4.6

**What's new?**
- Dynamic provider `g4fauto`. #29
- Test and save working g4f providers . #29
```sh
pytgpt gpt4free test -y
```
- Order providers in ascending. #31
11 changes: 10 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ These are simply the hosts of the LLMs, which include:

41+ Other models proudly offered by [gpt4free](https://github.com/xtekky/gpt4free).

- To list working providers run:
```sh
$ pytgpt gpt4free test -y
```

</summary>

- AiChatOnline
Expand Down Expand Up @@ -529,7 +534,7 @@ This can be useful in some ways. For instance :

## Passing Environment Variables

Pytgpt **v0.4.6** onwards introduces a convention way of taking variables from the environment.
Pytgpt **v0.4.6** introduces a convention way of taking variables from the environment.
To achieve that, set the environment variables in your operating system or script with prefix `PYTGPT_` followed by the option name in uppercase, replacing dashes with underscores.

For example, for the option `--provider`, you would set an environment variable `PYTGPT_PROVIDER` to provide a default value for that option. Same case applies to boolean flags such as `--rawdog` whose environment variable will be `PYTGPT_RAWDOG` with value being either `true/false`. Finally, `--awesome-prompt` will take the environment variable `PYTGPT_AWESOME_PROMPT`.
Expand All @@ -538,6 +543,10 @@ The environment variables can be overridden by explicitly declaring new value.

> **Note** : This is not limited to any command.

## Dynamic Provider

Version **0.4.6** also introduces dynamic provider called `g4fauto`, which represents the fastest working g4f-based provider.

For more usage info run `$ pytgpt --help`

</summary>
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

setup(
name="python-tgpt",
version="0.4.5",
version="0.4.6",
license="MIT",
author="Smartwa",
maintainer="Smartwa",
Expand Down
3 changes: 2 additions & 1 deletion src/pytgpt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from .utils import appdir
import g4f

__version__ = "0.4.5"
__version__ = "0.4.6"
__author__ = "Smartwa"
__repo__ = "https://github.com/Simatwa/python-tgpt"

Expand All @@ -16,6 +16,7 @@
"blackboxai",
"gpt4all",
"webchatgpt",
"g4fauto",
]

gpt4free_providers = [
Expand Down
95 changes: 94 additions & 1 deletion src/pytgpt/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,32 @@ def __init__(
intro = self.RawDog.intro_prompt
getpass.getuser = lambda: "RawDog"

if provider == "leo":
if provider == "g4fauto":
from pytgpt.gpt4free.utils import TestProviders

test = TestProviders(quiet=quiet, timeout=timeout)
g4fauto = test.best if ignore_working else test.auto
if isinstance(g4fauto, str):
provider = "g4fauto+" + g4fauto
from pytgpt.gpt4free import GPT4FREE

self.bot = GPT4FREE(
provider=g4fauto,
auth=auth,
max_tokens=max_tokens,
model=model,
chat_completion=chat_completion,
ignore_working=ignore_working,
timeout=timeout,
intro=intro,
filepath=filepath,
update_file=update_file,
proxies=proxies,
history_offset=history_offset,
act=awesome_prompt,
)

elif provider == "leo":
import pytgpt.leo as leo

self.bot = leo.LEO(
Expand Down Expand Up @@ -1892,6 +1917,7 @@ def show(target, working, url, stream, context, gpt35, gpt4, json):
if hunted_providers[0] is None
else hunted_providers
)
hunted_providers.sort()
if json:
rich.print_json(data=dict(providers=hunted_providers), indent=4)

Expand Down Expand Up @@ -1986,6 +2012,72 @@ def gui(port, address, debug, open):
click.launch(f"http://{address}:{port}")
t1.join()

@staticmethod
@click.command(context_settings=this.context_settings)
@click.option(
"-t",
"--timeout",
type=click.INT,
help="Provider response generation tiemout",
default=20,
)
@click.option(
"-r",
"--thread",
type=click.INT,
help="Test n amount of providers at once",
default=5,
)
@click.option("-q", "--quiet", is_flag=True, help="Suppress all stdout")
@click.option(
"-j", "--json", is_flag=True, help="Stdout test results in json format"
)
@click.option("-d", "--dry-test", is_flag=True, help="Return previous test results")
@click.option(
"-b", "--best", is_flag=True, help="Stdout the fastest provider <name only>"
)
@click.option("-y", "--yes", is_flag=True, help="Okay to all confirmations")
@click.help_option("-h", "--help")
def test(timeout, thread, quiet, json, dry_test, best, yes):
"""Test and save working providers"""
from pytgpt.gpt4free import utils

test = utils.TestProviders(test_at_once=thread, quiet=quiet, timeout=timeout)
if best:
click.secho(test.best)
return
elif dry_test:
results = test.get_results(
run=False,
)
else:
if (
yes
or os.path.isfile(utils.results_path)
and click.confirm("Are you sure to run new test")
):
results = test.get_results(run=True)
else:
results = test.get_results(
run=False,
)
if json:
rich.print_json(data=dict(results=results))
else:
table = Table(
title="G4f Providers Test Results",
show_lines=True,
)
table.add_column("No.", style="white", justify="center")
table.add_column("Provider", style="yellow", justify="left")
table.add_column("Response Time(s)", style="cyan")

for no, provider in enumerate(results, start=1):
table.add_row(
str(no), provider["name"], str(round(provider["time"], 2))
)
rich.print(table)


class Utils:
"""Utilities command"""
Expand Down Expand Up @@ -2072,6 +2164,7 @@ def make_commands():
EntryGroup.gpt4free.add_command(Gpt4free.update)
EntryGroup.gpt4free.add_command(Gpt4free.show)
EntryGroup.gpt4free.add_command(Gpt4free.gui)
EntryGroup.gpt4free.add_command(Gpt4free.test)

# Awesome
EntryGroup.awesome.add_command(Awesome.add)
Expand Down
177 changes: 177 additions & 0 deletions src/pytgpt/gpt4free/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import g4f
from .main import GPT4FREE
from pathlib import Path
from pytgpt.utils import default_path
from json import dump, load
from time import time
from threading import Thread as thr
from functools import wraps
import datetime
from rich.progress import Progress
import click
import logging

results_path = Path(default_path) / "provider_test.json"


def exception_handler(func):

@wraps(func)
def decorator(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
pass

return decorator


@exception_handler
def is_working(provider: str) -> bool:
"""Test working status of a provider
Args:
provider (str): Provider name
Returns:
bool: is_working status
"""
bot = GPT4FREE(provider=provider, is_conversation=False)
text = bot.chat("hello")
assert isinstance(text, str)
assert bool(text.strip())
assert "<" not in text
assert len(text) > 2
return True


class TestProviders:

def __init__(self, test_at_once: int = 5, quiet: bool = False, timeout: int = 20):
"""Constructor
Args:
test_at_once (int, optional): Test n providers at once. Defaults to 5.
quiet (bool, optinal): Disable stdout. Defaults to False.
timout (int, optional): Thread timeout for each provider. Defaults to 20.
"""
self.test_at_once: int = test_at_once
self.quiet = quiet
self.timeout = timeout
self.working_providers: list = [
provider.__name__
for provider in g4f.Provider.__providers__
if provider.working
]
self.results_path: Path = results_path
self.__create_empty_file(ignore_if_found=True)

def __create_empty_file(self, ignore_if_found: bool = False):
if ignore_if_found and self.results_path.is_file():
return
with self.results_path.open("w") as fh:
dump({"results": []}, fh)

def test_provider(self, name: str):
"""Test each provider and save successful ones
Args:
name (str): Provider name
"""

try:
bot = GPT4FREE(provider=name, is_conversation=False)
start_time = time()
text = bot.chat("hello there")
assert isinstance(text, str), "Non-string response returned"
assert bool(text.strip()), "Empty string"
assert "<" not in text, "Html code returned."
assert len(text) > 2
except Exception as e:
pass
else:
with self.results_path.open() as fh:
current_results = load(fh)
new_result = dict(time=time() - start_time, name=name)
current_results["results"].append(new_result)
logging.info(f"Test result - {new_result['name']} - {new_result['time']}")

with self.results_path.open("w") as fh:
dump(current_results, fh)

@exception_handler
def main(
self,
):
self.__create_empty_file()
threads = []
# Create a progress bar
total = len(self.working_providers)
with Progress() as progress:
logging.info(f"Testing {total} providers : {self.working_providers}")
task = progress.add_task(
f"[cyan]Testing...[{self.test_at_once}]",
total=total,
visible=self.quiet == False,
)
while not progress.finished:
for count, provider in enumerate(self.working_providers, start=1):
t1 = thr(
target=self.test_provider,
args=(provider,),
)
t1.start()
if count % self.test_at_once == 0 or count == len(provider):
for t in threads:
try:
t.join(self.timeout)
except Exception as e:
pass
threads.clear()
else:
threads.append(t1)
progress.update(task, advance=1)

def get_results(self, run: bool = False, best: bool = False) -> list[dict]:
"""Get test results
Args:
run (bool, optional): Run the test first. Defaults to False.
best (bool, optional): Return name of the best provider. Defaults to False.
Returns:
list[dict]|str: Test results.
"""
if run:
self.main()

with self.results_path.open() as fh:
results: dict = load(fh)

results = results["results"]
time_list = []

sorted_list = []
for entry in results:
time_list.append(entry["time"])

time_list.sort()

for time_value in time_list:
for entry in results:
if entry["time"] == time_value:
sorted_list.append(entry)
return sorted_list[0]["name"] if best else sorted_list

@property
def best(self):
"""Fastest provider overally"""
return self.get_results(run=False, best=True)

@property
def auto(self):
"""Best working provider"""
for result in self.get_results(run=False, best=False):
logging.info("Confirming working status of provider : " + result["name"])
if is_working(result["name"]):
return result["name"]

0 comments on commit 0e91640

Please sign in to comment.