From 56e7d41fdf4c150cd179ac6d7d3d83f5aef9917a Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 10:48:36 -0700 Subject: [PATCH 01/10] Update "no OpenAPI API key" warning --- loopgpt/__init__.py | 11 ++------ loopgpt/models/openai_.py | 2 +- loopgpt/utils/add_openai_key.py | 45 +++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 10 deletions(-) create mode 100644 loopgpt/utils/add_openai_key.py diff --git a/loopgpt/__init__.py b/loopgpt/__init__.py index eb42a34..9923c31 100644 --- a/loopgpt/__init__.py +++ b/loopgpt/__init__.py @@ -11,10 +11,8 @@ from loopgpt.memory import from_config as memory_from_config from loopgpt.embeddings import from_config as embedding_provider_from_config -from loopgpt.logger import logger -from colorama import Fore, Style - from dotenv import load_dotenv +from loopgpt.utils.add_openai_key import AddKeyPrompt import os @@ -24,12 +22,7 @@ def check_openai_key(): if "OPENAI_API_KEY" not in os.environ: - logger.warn( - f"{Fore.RED}WARNING: OpenAI API Key not found. Please set the `OPENAI_API_KEY` environment variable. " - f"LoopGPT cannot work without it. " - f"See https://github.com/farizrahman4u/loopgpt#-requirements for more details{Style.RESET_ALL}" - ) - + AddKeyPrompt() def from_config(config): return globals()[config["type"] + "_from_config"](config) diff --git a/loopgpt/models/openai_.py b/loopgpt/models/openai_.py index 3a1df6e..ffe21a0 100644 --- a/loopgpt/models/openai_.py +++ b/loopgpt/models/openai_.py @@ -10,7 +10,7 @@ def _getkey(key: Optional[str] = None): key = key or os.getenv("OPENAI_API_KEY") if key is None: raise ValueError( - "OpenAI API Key not found. Please set the `OPENAI_API_KEY` environment variable. " + f"OpenAI API Key not found in the current working directory: {os.getcwd()}. Please set the `OPENAI_API_KEY` environment variable. " "See https://github.com/farizrahman4u/loopgpt#-requirements for more details" ) diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py new file mode 100644 index 0000000..61d0613 --- /dev/null +++ b/loopgpt/utils/add_openai_key.py @@ -0,0 +1,45 @@ +from loopgpt.logger import logger +from colorama import Fore, Style +import os + +key = "OPENAI_API_KEY" +env_file = ".env" + + +class AddKeyPrompt(): + if not os.path.isfile(env_file): + logger.warn( + f"{Fore.RED}WARNING: OpenAI API Key not found in the current working directory: {os.getcwd()}. " + "Please set the `OPENAI_API_KEY` environment variable. " + f"LoopGPT cannot work without it. " + f"See https://github.com/farizrahman4u/loopgpt#-requirements for more details{Style.RESET_ALL}" + "" + ) + response = input( + f"{env_file} not found in the current working directory: {os.getcwd()}. Would you like to create it and add the key now? (y/n) ") + if response.lower() == "y": + key_value = input("Please enter the value of the key: ") + with open(env_file, "w") as f: + f.write(f"{key}={key_value}\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") + else: + with open(env_file, "r+") as f: + env_lines = f.readlines() + key_exists = False + for i, line in enumerate(env_lines): + if line.startswith(key): + key_exists = True + break + + if key_exists: + print(f"Key already exists in {env_file}") + else: + response = input( + f"Key not found in {env_file}. Would you like to add it now? (y/n) ") + if response.lower() == "y": + f.write(f"\n{key}=\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") From 921b720e9e82ec2142e28c08e25c8ef3e90a6f3d Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 10:55:49 -0700 Subject: [PATCH 02/10] Update add_openai_key.py --- loopgpt/utils/add_openai_key.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py index 61d0613..b671e80 100644 --- a/loopgpt/utils/add_openai_key.py +++ b/loopgpt/utils/add_openai_key.py @@ -39,7 +39,8 @@ class AddKeyPrompt(): response = input( f"Key not found in {env_file}. Would you like to add it now? (y/n) ") if response.lower() == "y": - f.write(f"\n{key}=\n") + key_value = input("Please enter the value of the key: ") + f.write(f"\n{key}={key_value}\n") print(f"Key added to {env_file}") else: print("Exiting program...") From 016f2d223ac9d937499746ada24e8b4adcb16e68 Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 11:06:49 -0700 Subject: [PATCH 03/10] Update add_openai_key.py --- loopgpt/utils/add_openai_key.py | 110 +++++++++++++++++++++----------- 1 file changed, 71 insertions(+), 39 deletions(-) diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py index b671e80..ad2918a 100644 --- a/loopgpt/utils/add_openai_key.py +++ b/loopgpt/utils/add_openai_key.py @@ -1,46 +1,78 @@ -from loopgpt.logger import logger -from colorama import Fore, Style +# from loopgpt.logger import logger +# from colorama import Fore, Style +# import os + +# key = "OPENAI_API_KEY" +# env_file = ".env" + + +# class AddKeyPrompt(): +# if not os.path.isfile(env_file): +# logger.warn( +# f"{Fore.RED}WARNING: OpenAI API Key not found in the current working directory: {os.getcwd()}. " +# "Please set the `OPENAI_API_KEY` environment variable. " +# f"LoopGPT cannot work without it. " +# f"See https://github.com/farizrahman4u/loopgpt#-requirements for more details{Style.RESET_ALL}" +# "" +# ) +# response = input( +# f"{env_file} not found in the current working directory: {os.getcwd()}. Would you like to create it and add the key now? (y/n) ") +# if response.lower() == "y": +# key_value = input("Please enter the value of the key: ") +# with open(env_file, "w") as f: +# f.write(f"{key}={key_value}\n") +# print(f"Key added to {env_file}") +# else: +# print("Exiting program...") +# else: +# with open(env_file, "r+") as f: +# env_lines = f.readlines() +# key_exists = False +# for i, line in enumerate(env_lines): +# if line.startswith(key): +# key_exists = True +# break + +# if key_exists: +# print(f"Key already exists in {env_file}") +# else: +# response = input( +# f"Key not found in {env_file}. Would you like to add it now? (y/n) ") +# if response.lower() == "y": +# key_value = input("Please enter the value of the key: ") +# f.write(f"\n{key}={key_value}\n") +# print(f"Key added to {env_file}") +# else: +# print("Exiting program...") import os key = "OPENAI_API_KEY" env_file = ".env" - class AddKeyPrompt(): - if not os.path.isfile(env_file): - logger.warn( - f"{Fore.RED}WARNING: OpenAI API Key not found in the current working directory: {os.getcwd()}. " - "Please set the `OPENAI_API_KEY` environment variable. " - f"LoopGPT cannot work without it. " - f"See https://github.com/farizrahman4u/loopgpt#-requirements for more details{Style.RESET_ALL}" - "" - ) - response = input( - f"{env_file} not found in the current working directory: {os.getcwd()}. Would you like to create it and add the key now? (y/n) ") - if response.lower() == "y": - key_value = input("Please enter the value of the key: ") - with open(env_file, "w") as f: - f.write(f"{key}={key_value}\n") - print(f"Key added to {env_file}") - else: - print("Exiting program...") - else: - with open(env_file, "r+") as f: - env_lines = f.readlines() - key_exists = False - for i, line in enumerate(env_lines): - if line.startswith(key): - key_exists = True - break - - if key_exists: - print(f"Key already exists in {env_file}") - else: - response = input( - f"Key not found in {env_file}. Would you like to add it now? (y/n) ") - if response.lower() == "y": - key_value = input("Please enter the value of the key: ") - f.write(f"\n{key}={key_value}\n") - print(f"Key added to {env_file}") + if key not in os.environ: + if not os.path.isfile(env_file): + response = input( + f"Key not found in {env_file}. Would you like to add it now? (y/n) ") + if response.lower() == "y": + key_value = input("Please enter the value for the key: ") + with open(env_file, "w") as f: + f.write(f"{key}={key_value}\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") else: - print("Exiting program...") + with open(env_file) as f: + env = dict(line.strip().split("=") for line in f if line.strip()) + if key not in env: + response = input( + f"Key not found in {env_file}. Would you like to add it now? (y/n) ") + if response.lower() == "y": + key_value = input("Please enter the value for the key: ") + with open(env_file, "a") as f: + f.write(f"\n{key}={key_value}\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") + else: + print(f"{key} is already set to {os.environ[key]}") From fbf73ab68e183a1ad9080869cbcd61680caf2152 Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 11:12:32 -0700 Subject: [PATCH 04/10] update for pytest --- loopgpt/utils/add_openai_key.py | 102 ++++++++++---------------------- tests/test_serde.py | 14 +++++ 2 files changed, 46 insertions(+), 70 deletions(-) diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py index ad2918a..d4502a3 100644 --- a/loopgpt/utils/add_openai_key.py +++ b/loopgpt/utils/add_openai_key.py @@ -1,78 +1,40 @@ -# from loopgpt.logger import logger -# from colorama import Fore, Style -# import os - -# key = "OPENAI_API_KEY" -# env_file = ".env" - - -# class AddKeyPrompt(): -# if not os.path.isfile(env_file): -# logger.warn( -# f"{Fore.RED}WARNING: OpenAI API Key not found in the current working directory: {os.getcwd()}. " -# "Please set the `OPENAI_API_KEY` environment variable. " -# f"LoopGPT cannot work without it. " -# f"See https://github.com/farizrahman4u/loopgpt#-requirements for more details{Style.RESET_ALL}" -# "" -# ) -# response = input( -# f"{env_file} not found in the current working directory: {os.getcwd()}. Would you like to create it and add the key now? (y/n) ") -# if response.lower() == "y": -# key_value = input("Please enter the value of the key: ") -# with open(env_file, "w") as f: -# f.write(f"{key}={key_value}\n") -# print(f"Key added to {env_file}") -# else: -# print("Exiting program...") -# else: -# with open(env_file, "r+") as f: -# env_lines = f.readlines() -# key_exists = False -# for i, line in enumerate(env_lines): -# if line.startswith(key): -# key_exists = True -# break - -# if key_exists: -# print(f"Key already exists in {env_file}") -# else: -# response = input( -# f"Key not found in {env_file}. Would you like to add it now? (y/n) ") -# if response.lower() == "y": -# key_value = input("Please enter the value of the key: ") -# f.write(f"\n{key}={key_value}\n") -# print(f"Key added to {env_file}") -# else: -# print("Exiting program...") import os key = "OPENAI_API_KEY" env_file = ".env" + class AddKeyPrompt(): - if key not in os.environ: - if not os.path.isfile(env_file): - response = input( - f"Key not found in {env_file}. Would you like to add it now? (y/n) ") - if response.lower() == "y": - key_value = input("Please enter the value for the key: ") - with open(env_file, "w") as f: - f.write(f"{key}={key_value}\n") - print(f"Key added to {env_file}") + def __init__(self, user_input): + self.user_input = user_input + + def run(self): + if key not in os.environ: + if not os.path.isfile(env_file): + response = self.user_input( + f"Key not found in {env_file}. Would you like to add it now? (y/n) ") + if response.lower() == "y": + key_value = self.user_input( + "Please enter the value for the key: ") + with open(env_file, "w") as f: + f.write(f"{key}={key_value}\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") else: - print("Exiting program...") + with open(env_file) as f: + env = dict(line.strip().split("=") + for line in f if line.strip()) + if key not in env: + response = self.user_input( + f"Key not found in {env_file}. Would you like to add it now? (y/n) ") + if response.lower() == "y": + key_value = self.user_input( + "Please enter the value for the key: ") + with open(env_file, "a") as f: + f.write(f"\n{key}={key_value}\n") + print(f"Key added to {env_file}") + else: + print("Exiting program...") else: - with open(env_file) as f: - env = dict(line.strip().split("=") for line in f if line.strip()) - if key not in env: - response = input( - f"Key not found in {env_file}. Would you like to add it now? (y/n) ") - if response.lower() == "y": - key_value = input("Please enter the value for the key: ") - with open(env_file, "a") as f: - f.write(f"\n{key}={key_value}\n") - print(f"Key added to {env_file}") - else: - print("Exiting program...") - else: - print(f"{key} is already set to {os.environ[key]}") + print(f"{key} is already set to {os.environ[key]}") diff --git a/tests/test_serde.py b/tests/test_serde.py index c39c243..9c448c4 100644 --- a/tests/test_serde.py +++ b/tests/test_serde.py @@ -1,6 +1,7 @@ import loopgpt from loopgpt.tools import Browser +from loopgpt.utils.add_openai_key import AddKeyPrompt def test_serde_basic(): @@ -14,3 +15,16 @@ def test_serde_browser(): cfg = browser.config() browser = Browser.from_config(cfg) assert browser.browser_type == "firefox" + +def test_add_key_prompt(monkeypatch): + # Set up mock user input + monkeypatch.setattr('builtins.input', lambda _: 'y') + monkeypatch.setattr('builtins.input', lambda _: 'my-api-key') + + # Run the function + AddKeyPrompt() + + # Assert that the .env file was created with the correct key value + with open(".env") as f: + env = dict(line.strip().split("=") for line in f if line.strip()) + assert env["OPENAI_API_KEY"] == "my-api-key" From 8a744528ace87a2c2bb1edb7351097e4acb07a42 Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 11:36:23 -0700 Subject: [PATCH 05/10] fixes --- loopgpt/__init__.py | 7 +------ loopgpt/models/openai_.py | 6 ++++-- loopgpt/utils/add_openai_key.py | 22 +++++++++++----------- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/loopgpt/__init__.py b/loopgpt/__init__.py index 9923c31..e550b45 100644 --- a/loopgpt/__init__.py +++ b/loopgpt/__init__.py @@ -12,18 +12,13 @@ from loopgpt.embeddings import from_config as embedding_provider_from_config from dotenv import load_dotenv -from loopgpt.utils.add_openai_key import AddKeyPrompt +from loopgpt.utils.add_openai_key import check_openai_key import os load_dotenv() - -def check_openai_key(): - if "OPENAI_API_KEY" not in os.environ: - AddKeyPrompt() - def from_config(config): return globals()[config["type"] + "_from_config"](config) diff --git a/loopgpt/models/openai_.py b/loopgpt/models/openai_.py index ffe21a0..e2a8f81 100644 --- a/loopgpt/models/openai_.py +++ b/loopgpt/models/openai_.py @@ -1,19 +1,21 @@ from typing import * from loopgpt.logger import logger from loopgpt.models.base import BaseModel +from loopgpt.utils.add_openai_key import check_openai_key + import tiktoken import time import os - def _getkey(key: Optional[str] = None): + check_openai_key() # Check if OPENAI_API_KEY is set and prompt the user if it's not key = key or os.getenv("OPENAI_API_KEY") if key is None: raise ValueError( f"OpenAI API Key not found in the current working directory: {os.getcwd()}. Please set the `OPENAI_API_KEY` environment variable. " "See https://github.com/farizrahman4u/loopgpt#-requirements for more details" ) - + return key class OpenAIModel(BaseModel): def __init__(self, model: str = "gpt-3.5-turbo", api_key: Optional[str] = None): diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py index d4502a3..0ac397c 100644 --- a/loopgpt/utils/add_openai_key.py +++ b/loopgpt/utils/add_openai_key.py @@ -4,36 +4,36 @@ env_file = ".env" +def check_openai_key(): + if "OPENAI_API_KEY" not in os.environ: + AddKeyPrompt(user_input=input) + class AddKeyPrompt(): def __init__(self, user_input): - self.user_input = user_input - - def run(self): if key not in os.environ: if not os.path.isfile(env_file): - response = self.user_input( + response = user_input( f"Key not found in {env_file}. Would you like to add it now? (y/n) ") if response.lower() == "y": - key_value = self.user_input( - "Please enter the value for the key: ") + key_value = user_input("Please enter the value for the key: ") with open(env_file, "w") as f: f.write(f"{key}={key_value}\n") print(f"Key added to {env_file}") + os.environ[key] = key_value # set the environment variable here else: print("Exiting program...") else: with open(env_file) as f: - env = dict(line.strip().split("=") - for line in f if line.strip()) + env = dict(line.strip().split("=") for line in f if line.strip()) if key not in env: - response = self.user_input( + response = user_input( f"Key not found in {env_file}. Would you like to add it now? (y/n) ") if response.lower() == "y": - key_value = self.user_input( - "Please enter the value for the key: ") + key_value = user_input("Please enter the value for the key: ") with open(env_file, "a") as f: f.write(f"\n{key}={key_value}\n") print(f"Key added to {env_file}") + os.environ[key] = key_value # set the environment variable here else: print("Exiting program...") else: From 4fc48c9b547c71ed8547f4e615800c88a9dee2dc Mon Sep 17 00:00:00 2001 From: Iskandar Reza Date: Sun, 30 Apr 2023 11:37:57 -0700 Subject: [PATCH 06/10] Update test_serde.py --- tests/test_serde.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_serde.py b/tests/test_serde.py index 9c448c4..c3d6fb7 100644 --- a/tests/test_serde.py +++ b/tests/test_serde.py @@ -22,7 +22,7 @@ def test_add_key_prompt(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: 'my-api-key') # Run the function - AddKeyPrompt() + AddKeyPrompt(user_input=input) # Assert that the .env file was created with the correct key value with open(".env") as f: From e5268d65683a6a72dd7d3efce7652d8587cc7c50 Mon Sep 17 00:00:00 2001 From: FayazRahman Date: Wed, 3 May 2023 17:20:39 +0530 Subject: [PATCH 07/10] upds --- loopgpt/__init__.py | 7 +++--- loopgpt/models/openai_.py | 7 +++--- loopgpt/utils/add_openai_key.py | 40 --------------------------------- loopgpt/utils/openai_key.py | 18 +++++++++++++++ tests/test_serde.py | 18 ++++++++------- 5 files changed, 35 insertions(+), 55 deletions(-) delete mode 100644 loopgpt/utils/add_openai_key.py create mode 100644 loopgpt/utils/openai_key.py diff --git a/loopgpt/__init__.py b/loopgpt/__init__.py index e550b45..d7625e0 100644 --- a/loopgpt/__init__.py +++ b/loopgpt/__init__.py @@ -11,10 +11,10 @@ from loopgpt.memory import from_config as memory_from_config from loopgpt.embeddings import from_config as embedding_provider_from_config +from loopgpt.utils.openai_key import check_openai_key from dotenv import load_dotenv -from loopgpt.utils.add_openai_key import check_openai_key -import os +import sys load_dotenv() @@ -23,4 +23,5 @@ def from_config(config): return globals()[config["type"] + "_from_config"](config) -check_openai_key() +if "pytest" not in sys.modules: + check_openai_key() diff --git a/loopgpt/models/openai_.py b/loopgpt/models/openai_.py index e2a8f81..b384132 100644 --- a/loopgpt/models/openai_.py +++ b/loopgpt/models/openai_.py @@ -1,19 +1,18 @@ from typing import * from loopgpt.logger import logger from loopgpt.models.base import BaseModel -from loopgpt.utils.add_openai_key import check_openai_key import tiktoken import time import os def _getkey(key: Optional[str] = None): - check_openai_key() # Check if OPENAI_API_KEY is set and prompt the user if it's not key = key or os.getenv("OPENAI_API_KEY") if key is None: raise ValueError( - f"OpenAI API Key not found in the current working directory: {os.getcwd()}. Please set the `OPENAI_API_KEY` environment variable. " - "See https://github.com/farizrahman4u/loopgpt#-requirements for more details" + f"OpenAI API Key not found in the current working directory: {os.getcwd()}. " + "Please set the `OPENAI_API_KEY` environment variable or add it to `.env`. " + "See https://github.com/farizrahman4u/loopgpt#setup-your-openai-api-key- for more details" ) return key diff --git a/loopgpt/utils/add_openai_key.py b/loopgpt/utils/add_openai_key.py deleted file mode 100644 index 0ac397c..0000000 --- a/loopgpt/utils/add_openai_key.py +++ /dev/null @@ -1,40 +0,0 @@ -import os - -key = "OPENAI_API_KEY" -env_file = ".env" - - -def check_openai_key(): - if "OPENAI_API_KEY" not in os.environ: - AddKeyPrompt(user_input=input) - -class AddKeyPrompt(): - def __init__(self, user_input): - if key not in os.environ: - if not os.path.isfile(env_file): - response = user_input( - f"Key not found in {env_file}. Would you like to add it now? (y/n) ") - if response.lower() == "y": - key_value = user_input("Please enter the value for the key: ") - with open(env_file, "w") as f: - f.write(f"{key}={key_value}\n") - print(f"Key added to {env_file}") - os.environ[key] = key_value # set the environment variable here - else: - print("Exiting program...") - else: - with open(env_file) as f: - env = dict(line.strip().split("=") for line in f if line.strip()) - if key not in env: - response = user_input( - f"Key not found in {env_file}. Would you like to add it now? (y/n) ") - if response.lower() == "y": - key_value = user_input("Please enter the value for the key: ") - with open(env_file, "a") as f: - f.write(f"\n{key}={key_value}\n") - print(f"Key added to {env_file}") - os.environ[key] = key_value # set the environment variable here - else: - print("Exiting program...") - else: - print(f"{key} is already set to {os.environ[key]}") diff --git a/loopgpt/utils/openai_key.py b/loopgpt/utils/openai_key.py new file mode 100644 index 0000000..32c710a --- /dev/null +++ b/loopgpt/utils/openai_key.py @@ -0,0 +1,18 @@ +import os +import sys + +from dotenv import load_dotenv + + +def check_openai_key(): + if "OPENAI_API_KEY" not in os.environ: + yn = input("OpenAI API key not found. Would you like to add your key to `.env` now? (y/n): ") + if yn.lower() == "y": + key = input("Please enter your OpenAI API key: ") + with open(".env", "w") as f: + f.write(f'OPENAI_API_KEY = "{key}"') + print("Key added to `.env`") + load_dotenv() + assert os.environ["OPENAI_API_KEY"] == key + else: + print("Please set the `OPENAI_API_KEY` environment variable or add it to `.env`. LoopGPT cannot work without it.") diff --git a/tests/test_serde.py b/tests/test_serde.py index c3d6fb7..a72afe4 100644 --- a/tests/test_serde.py +++ b/tests/test_serde.py @@ -1,8 +1,8 @@ import loopgpt +import builtins +import os from loopgpt.tools import Browser -from loopgpt.utils.add_openai_key import AddKeyPrompt - def test_serde_basic(): agent = loopgpt.Agent() @@ -18,13 +18,15 @@ def test_serde_browser(): def test_add_key_prompt(monkeypatch): # Set up mock user input - monkeypatch.setattr('builtins.input', lambda _: 'y') - monkeypatch.setattr('builtins.input', lambda _: 'my-api-key') + responses = iter(["y", "my-api-key"]) + monkeypatch.setattr(builtins, "input", lambda _: next(responses)) + from loopgpt.utils.openai_key import check_openai_key # Run the function - AddKeyPrompt(user_input=input) + check_openai_key() # Assert that the .env file was created with the correct key value - with open(".env") as f: - env = dict(line.strip().split("=") for line in f if line.strip()) - assert env["OPENAI_API_KEY"] == "my-api-key" + with open(".env", "r") as f: + assert f.read().strip() == 'OPENAI_API_KEY = "my-api-key"' + + os.remove(".env") From 6a29853d8a9282f3f842b8cd2aff98ef5d6d696b Mon Sep 17 00:00:00 2001 From: FayazRahman Date: Wed, 3 May 2023 17:23:00 +0530 Subject: [PATCH 08/10] move test --- tests/test_keys.py | 17 +++++++++++++++++ tests/test_serde.py | 17 ----------------- 2 files changed, 17 insertions(+), 17 deletions(-) create mode 100644 tests/test_keys.py diff --git a/tests/test_keys.py b/tests/test_keys.py new file mode 100644 index 0000000..7c66694 --- /dev/null +++ b/tests/test_keys.py @@ -0,0 +1,17 @@ +import builtins +import os + +def test_add_key_prompt(monkeypatch): + # Set up mock user input + responses = iter(["y", "my-api-key"]) + monkeypatch.setattr(builtins, "input", lambda _: next(responses)) + + from loopgpt.utils.openai_key import check_openai_key + # Run the function + check_openai_key() + + # Assert that the .env file was created with the correct key value + with open(".env", "r") as f: + assert f.read().strip() == 'OPENAI_API_KEY = "my-api-key"' + + os.remove(".env") diff --git a/tests/test_serde.py b/tests/test_serde.py index a72afe4..8529551 100644 --- a/tests/test_serde.py +++ b/tests/test_serde.py @@ -1,6 +1,4 @@ import loopgpt -import builtins -import os from loopgpt.tools import Browser @@ -15,18 +13,3 @@ def test_serde_browser(): cfg = browser.config() browser = Browser.from_config(cfg) assert browser.browser_type == "firefox" - -def test_add_key_prompt(monkeypatch): - # Set up mock user input - responses = iter(["y", "my-api-key"]) - monkeypatch.setattr(builtins, "input", lambda _: next(responses)) - - from loopgpt.utils.openai_key import check_openai_key - # Run the function - check_openai_key() - - # Assert that the .env file was created with the correct key value - with open(".env", "r") as f: - assert f.read().strip() == 'OPENAI_API_KEY = "my-api-key"' - - os.remove(".env") From eee4fc9cf86ce424f9726483648d1d6e67ed6d48 Mon Sep 17 00:00:00 2001 From: FayazRahman Date: Wed, 3 May 2023 17:39:17 +0530 Subject: [PATCH 09/10] upd --- loopgpt/utils/openai_key.py | 1 - 1 file changed, 1 deletion(-) diff --git a/loopgpt/utils/openai_key.py b/loopgpt/utils/openai_key.py index 32c710a..60654ba 100644 --- a/loopgpt/utils/openai_key.py +++ b/loopgpt/utils/openai_key.py @@ -13,6 +13,5 @@ def check_openai_key(): f.write(f'OPENAI_API_KEY = "{key}"') print("Key added to `.env`") load_dotenv() - assert os.environ["OPENAI_API_KEY"] == key else: print("Please set the `OPENAI_API_KEY` environment variable or add it to `.env`. LoopGPT cannot work without it.") From 7d97aacd9dd2afbd04f05dc764d4b81d84b92367 Mon Sep 17 00:00:00 2001 From: FayazRahman Date: Wed, 3 May 2023 17:42:31 +0530 Subject: [PATCH 10/10] black --- loopgpt/__init__.py | 1 + loopgpt/agent.py | 8 +++++--- loopgpt/constants.py | 2 ++ loopgpt/loops/cli.py | 4 +++- loopgpt/models/openai_.py | 2 ++ loopgpt/tools/filesystem.py | 11 +++++++++-- loopgpt/utils/openai_key.py | 8 ++++++-- tests/test_keys.py | 4 +++- tests/test_serde.py | 1 + 9 files changed, 32 insertions(+), 9 deletions(-) diff --git a/loopgpt/__init__.py b/loopgpt/__init__.py index d7625e0..b03a37b 100644 --- a/loopgpt/__init__.py +++ b/loopgpt/__init__.py @@ -19,6 +19,7 @@ load_dotenv() + def from_config(config): return globals()[config["type"] + "_from_config"](config) diff --git a/loopgpt/agent.py b/loopgpt/agent.py index c0c3cd9..f07d8f4 100644 --- a/loopgpt/agent.py +++ b/loopgpt/agent.py @@ -5,7 +5,7 @@ DEFAULT_AGENT_DESCRIPTION, NEXT_PROMPT, NEXT_PROMPT_SMALL, - AgentStates + AgentStates, ) from loopgpt.memory import from_config as memory_from_config from loopgpt.models import OpenAIModel, from_config as model_from_config @@ -132,7 +132,7 @@ def _get_compressed_history(self): user_msgs = [i for i in range(len(hist)) if hist[i]["role"] == "user"] hist = [hist[i] for i in range(len(hist)) if i not in user_msgs] return hist - + def get_full_message(self, message: Optional[str]): if self.state == AgentStates.START: return self.init_prompt + "\n\n" + (message or "") @@ -140,7 +140,9 @@ def get_full_message(self, message: Optional[str]): return self.next_prompt + "\n\n" + (message or "") @spinner - def chat(self, message: Optional[str] = None, run_tool=False) -> Optional[Union[str, Dict]]: + def chat( + self, message: Optional[str] = None, run_tool=False + ) -> Optional[Union[str, Dict]]: if self.state == AgentStates.STOP: raise ValueError( "This agent has completed its tasks. It will not accept any more messages." diff --git a/loopgpt/constants.py b/loopgpt/constants.py index 0e105e6..ca2d50a 100644 --- a/loopgpt/constants.py +++ b/loopgpt/constants.py @@ -86,12 +86,14 @@ "Always execute plans to completion", ] + class AgentStates: START = "START" IDLE = "IDLE" TOOL_STAGED = "TOOL_STAGED" STOP = "STOP" + # SPINNER SPINNER_ENABLED = True SPINNER_START_DELAY = 2 diff --git a/loopgpt/loops/cli.py b/loopgpt/loops/cli.py index 5261afe..d8b7d94 100644 --- a/loopgpt/loops/cli.py +++ b/loopgpt/loops/cli.py @@ -13,7 +13,9 @@ def main(): help="Action to perform. If no file is specified, a new agent is created.", ) parser.add_argument("filename", nargs="?", help="Agent state JSON.", default=None) - parser.add_argument("--model", help="Model to use, uses gpt-3.5-turbo by default.", default=None) + parser.add_argument( + "--model", help="Model to use, uses gpt-3.5-turbo by default.", default=None + ) parser.add_argument( "--readonly", help="Read only mode. Does not write agent state to disk.", diff --git a/loopgpt/models/openai_.py b/loopgpt/models/openai_.py index b384132..44c74fa 100644 --- a/loopgpt/models/openai_.py +++ b/loopgpt/models/openai_.py @@ -6,6 +6,7 @@ import time import os + def _getkey(key: Optional[str] = None): key = key or os.getenv("OPENAI_API_KEY") if key is None: @@ -16,6 +17,7 @@ def _getkey(key: Optional[str] = None): ) return key + class OpenAIModel(BaseModel): def __init__(self, model: str = "gpt-3.5-turbo", api_key: Optional[str] = None): self.model = model diff --git a/loopgpt/tools/filesystem.py b/loopgpt/tools/filesystem.py index b4577d0..93635b0 100644 --- a/loopgpt/tools/filesystem.py +++ b/loopgpt/tools/filesystem.py @@ -106,7 +106,7 @@ def resp(self): return { "result": "list of files and directories", } - + @property def desc(self): return "List files and directories in a given path. Directories end with a trailing slash." @@ -120,7 +120,14 @@ def run(self, path, recursive, show_hidden=False, exclude_dirs=False): if not exclude_dirs: entries_list.append(f"{entry.name}/") if recursive: - entries_list.extend(self.run(os.path.join(path, entry.name), recursive, show_hidden, exclude_dirs)["result"]) + entries_list.extend( + self.run( + os.path.join(path, entry.name), + recursive, + show_hidden, + exclude_dirs, + )["result"] + ) else: entries_list.append(entry.name) return {"result": entries_list} diff --git a/loopgpt/utils/openai_key.py b/loopgpt/utils/openai_key.py index 60654ba..a34c8ba 100644 --- a/loopgpt/utils/openai_key.py +++ b/loopgpt/utils/openai_key.py @@ -6,7 +6,9 @@ def check_openai_key(): if "OPENAI_API_KEY" not in os.environ: - yn = input("OpenAI API key not found. Would you like to add your key to `.env` now? (y/n): ") + yn = input( + "OpenAI API key not found. Would you like to add your key to `.env` now? (y/n): " + ) if yn.lower() == "y": key = input("Please enter your OpenAI API key: ") with open(".env", "w") as f: @@ -14,4 +16,6 @@ def check_openai_key(): print("Key added to `.env`") load_dotenv() else: - print("Please set the `OPENAI_API_KEY` environment variable or add it to `.env`. LoopGPT cannot work without it.") + print( + "Please set the `OPENAI_API_KEY` environment variable or add it to `.env`. LoopGPT cannot work without it." + ) diff --git a/tests/test_keys.py b/tests/test_keys.py index 7c66694..914410d 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -1,17 +1,19 @@ import builtins import os + def test_add_key_prompt(monkeypatch): # Set up mock user input responses = iter(["y", "my-api-key"]) monkeypatch.setattr(builtins, "input", lambda _: next(responses)) from loopgpt.utils.openai_key import check_openai_key + # Run the function check_openai_key() # Assert that the .env file was created with the correct key value with open(".env", "r") as f: assert f.read().strip() == 'OPENAI_API_KEY = "my-api-key"' - + os.remove(".env") diff --git a/tests/test_serde.py b/tests/test_serde.py index 8529551..c39c243 100644 --- a/tests/test_serde.py +++ b/tests/test_serde.py @@ -2,6 +2,7 @@ from loopgpt.tools import Browser + def test_serde_basic(): agent = loopgpt.Agent() cfg = agent.config()