signebedi / gptty

ChatGPT wrapper in your TTY
MIT License
47 stars 7 forks source link

[runtime] add a check for internet connectivity and return error if no connection #48

Closed signebedi closed 1 year ago

signebedi commented 1 year ago

See eg. https://stackoverflow.com/a/62115290/13301284.

If the user runs the chatroom or query, but there is no internet connection, return an error message in main.py.

import socket
from contextlib import closing

def has_internet_connection(host="google.com", port=443, timeout=3):
    """Check if the system has a valid internet connection.

    Args:
        host (str, optional): A well-known website to test the connection. Default is 'www.google.com'.
        port (int, optional): The port number to use for the connection. Default is 80.
        timeout (int, optional): The time in seconds to wait for a response before giving up. Default is 3.

    Returns:
        bool: True if the system has an internet connection, False otherwise.
    """
    try:
        with closing(socket.create_connection((host, port), timeout=timeout)):
            return True
    except OSError:
        return False

....

  # Print the text in cyan
  click.echo(f"{CYAN}{title}\nWelcome to gptty (v.{__version__}), a ChatGPT wrapper in your TTY.\nType :help in the chat interface if you need help getting started.{' Verbose / Debug mode is on.' if verbose else ''}{RESET}\n")

  if not os.path.exists(config_path):
      click.echo(f"{RED}FAILED to access app config file at {config_path}. Are you sure this is a valid config file? Run `gptty chat --help` for more information. You can get a sample config at <https://github.com/signebedi/gptty/blob/master/assets/gptty.ini.example>.")
      return

  # load the app configs
  configs = get_config_data(config_file=config_path)

  if not has_internet_connection(config('verify_internet_endpoint')):
      click.echo(f"{RED}FAILED to verify connection at {config('verify_internet_endpoint')}. Are you sure you are connected to the internet?")
      return

  # create the output file if it doesn't exist
  with open (configs['output_file'], 'a'): pass
signebedi commented 1 year ago

We should add a verify_internet_endpoint config that defaults to google.com. We'll need to document this in the README.

# parse config data
def get_config_data(config_file='gptty.ini'):
    # create a configuration object
    config = configparser.ConfigParser()

    config['DEFAULT'] = {
        'api_key': "",
        'your_name': 'question',
        'gpt_name': 'response',
        'output_file': 'output.txt',
        'model': 'text-davinci-003',
        'temperature': 0.0,
        'max_tokens': 250,
        'max_context_length': 150,
        'context_keywords_only': True,
        'preserve_new_lines': False,
        'verify_internet_endpoint': 'google.com',
    }

    # read the configuration file (if it exists)
    config.read(config_file)

    parsed_data = {
        'api_key': config.get('main', 'api_key', fallback="",),
        'your_name': config.get('main', 'your_name', fallback='question'),
        'gpt_name': config.get('main', 'gpt_name', fallback='response'),
        'output_file': config.get('main', 'output_file', fallback='output.txt'),
        'model': config.get('main', 'model', fallback='text-davinci-003'),
        'temperature': config.getfloat('main', 'temperature', fallback=0.0),
        'max_tokens': config.getint('main', 'max_tokens', fallback=25),
        'max_context_length': config.getint('main', 'max_context_length', fallback=150),
        'context_keywords_only': config.getboolean('main', 'context_keywords_only', fallback=True),
        'preserve_new_lines': config.getboolean('main', 'preserve_new_lines', fallback=False),
        'verify_internet_endpoint': config.get('main', 'verify_internet_endpoint', fallback='google.com'),
    }
hyp-er commented 1 year ago

Hey, I think i can fix this issue.

signebedi commented 1 year ago

Great work @hyp-er! Merged!