This commit is contained in:
BillSchumacher
2023-04-16 22:51:39 -05:00
parent c0aa423d7b
commit 81c65af560
13 changed files with 86 additions and 64 deletions

View File

@@ -89,10 +89,9 @@ class Agent:
for plugin in cfg.plugins: for plugin in cfg.plugins:
assistant_reply_json = plugin.post_planning(self, assistant_reply_json) assistant_reply_json = plugin.post_planning(self, assistant_reply_json)
# Print Assistant thoughts # Print Assistant thoughts
if assistant_reply_json != {}: if assistant_reply_json != {}:
validate_json(assistant_reply_json, 'llm_response_format_1') validate_json(assistant_reply_json, "llm_response_format_1")
# Get command name and arguments # Get command name and arguments
try: try:
print_assistant_thoughts(self.ai_name, assistant_reply_json) print_assistant_thoughts(self.ai_name, assistant_reply_json)
@@ -199,7 +198,9 @@ class Agent:
# Check if there's a result from the command append it to the message # Check if there's a result from the command append it to the message
# history # history
if result is not None: if result is not None:
self.full_message_history.append(create_chat_message("system", result)) self.full_message_history.append(
create_chat_message("system", result)
)
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)
else: else:
self.full_message_history.append( self.full_message_history.append(

View File

@@ -12,7 +12,7 @@ from autogpt.commands.file_operations import (
read_file, read_file,
search_files, search_files,
write_to_file, write_to_file,
download_file download_file,
) )
from autogpt.commands.git_operations import clone_repository from autogpt.commands.git_operations import clone_repository
from autogpt.commands.google_search import google_official_search, google_search from autogpt.commands.google_search import google_official_search, google_search

View File

@@ -64,10 +64,10 @@ def parse_arguments() -> None:
" skip the re-prompt.", " skip the re-prompt.",
) )
parser.add_argument( parser.add_argument(
'--allow-downloads', "--allow-downloads",
action='store_true', action="store_true",
dest='allow_downloads', dest="allow_downloads",
help='Dangerous: Allows Auto-GPT to download files natively.' help="Dangerous: Allows Auto-GPT to download files natively.",
) )
args = parser.parse_args() args = parser.parse_args()
@@ -141,10 +141,17 @@ def parse_arguments() -> None:
if args.allow_downloads: if args.allow_downloads:
logger.typewriter_log("Native Downloading:", Fore.GREEN, "ENABLED") logger.typewriter_log("Native Downloading:", Fore.GREEN, "ENABLED")
logger.typewriter_log("WARNING: ", Fore.YELLOW, logger.typewriter_log(
f"{Back.LIGHTYELLOW_EX}Auto-GPT will now be able to download and save files to your machine.{Back.RESET} " + "WARNING: ",
"It is recommended that you monitor any files it downloads carefully.") Fore.YELLOW,
logger.typewriter_log("WARNING: ", Fore.YELLOW, f"{Back.RED + Style.BRIGHT}ALWAYS REMEMBER TO NEVER OPEN FILES YOU AREN'T SURE OF!{Style.RESET_ALL}") f"{Back.LIGHTYELLOW_EX}Auto-GPT will now be able to download and save files to your machine.{Back.RESET} "
+ "It is recommended that you monitor any files it downloads carefully.",
)
logger.typewriter_log(
"WARNING: ",
Fore.YELLOW,
f"{Back.RED + Style.BRIGHT}ALWAYS REMEMBER TO NEVER OPEN FILES YOU AREN'T SURE OF!{Style.RESET_ALL}",
)
CFG.allow_downloads = True CFG.allow_downloads = True
if args.browser_name: if args.browser_name:

View File

@@ -1,8 +1,6 @@
import importlib import importlib
import inspect import inspect
import os from typing import Any, Callable, Optional
import sys
from typing import Any, Callable, List, Optional
# Unique identifier for auto-gpt commands # Unique identifier for auto-gpt commands
AUTO_GPT_COMMAND_IDENTIFIER = "auto_gpt_command" AUTO_GPT_COMMAND_IDENTIFIER = "auto_gpt_command"

View File

@@ -243,23 +243,23 @@ def download_file(url, filename):
session = requests.Session() session = requests.Session()
retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504]) retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
adapter = HTTPAdapter(max_retries=retry) adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter) session.mount("http://", adapter)
session.mount('https://', adapter) session.mount("https://", adapter)
total_size = 0 total_size = 0
downloaded_size = 0 downloaded_size = 0
with session.get(url, allow_redirects=True, stream=True) as r: with session.get(url, allow_redirects=True, stream=True) as r:
r.raise_for_status() r.raise_for_status()
total_size = int(r.headers.get('Content-Length', 0)) total_size = int(r.headers.get("Content-Length", 0))
downloaded_size = 0 downloaded_size = 0
with open(safe_filename, 'wb') as f: with open(safe_filename, "wb") as f:
for chunk in r.iter_content(chunk_size=8192): for chunk in r.iter_content(chunk_size=8192):
f.write(chunk) f.write(chunk)
downloaded_size += len(chunk) downloaded_size += len(chunk)
# Update the progress message # Update the progress message
progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}" progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}"
spinner.update_message(f"{message} {progress}") spinner.update_message(f"{message} {progress}")

View File

@@ -14,8 +14,7 @@ from autogpt.workspace import path_in_workspace
CFG = Config() CFG = Config()
@command("generate_image", "Generate Image", '"prompt": "<prompt>"', @command("generate_image", "Generate Image", '"prompt": "<prompt>"', CFG.image_provider)
CFG.image_provider)
def generate_image(prompt: str) -> str: def generate_image(prompt: str) -> str:
"""Generate an image from a prompt. """Generate an image from a prompt.

View File

@@ -3,11 +3,14 @@ from typing import Any, Dict
from autogpt.config import Config from autogpt.config import Config
from autogpt.logs import logger from autogpt.logs import logger
from autogpt.speech import say_text from autogpt.speech import say_text
CFG = Config() CFG = Config()
def fix_json_using_multiple_techniques(assistant_reply: str) -> Dict[Any, Any]: def fix_json_using_multiple_techniques(assistant_reply: str) -> Dict[Any, Any]:
from autogpt.json_fixes.parsing import attempt_to_fix_json_by_finding_outermost_brackets from autogpt.json_fixes.parsing import (
attempt_to_fix_json_by_finding_outermost_brackets,
)
from autogpt.json_fixes.parsing import fix_and_parse_json from autogpt.json_fixes.parsing import fix_and_parse_json
@@ -21,7 +24,10 @@ def fix_json_using_multiple_techniques(assistant_reply: str) -> Dict[Any, Any]:
if assistant_reply_json != {}: if assistant_reply_json != {}:
return assistant_reply_json return assistant_reply_json
logger.error("Error: The following AI output couldn't be converted to a JSON:\n", assistant_reply) logger.error(
"Error: The following AI output couldn't be converted to a JSON:\n",
assistant_reply,
)
if CFG.speak_mode: if CFG.speak_mode:
say_text("I have received an invalid JSON response from the OpenAI API.") say_text("I have received an invalid JSON response from the OpenAI API.")

View File

@@ -19,7 +19,9 @@ def validate_json(json_object: object, schema_name: object) -> object:
if errors := sorted(validator.iter_errors(json_object), key=lambda e: e.path): if errors := sorted(validator.iter_errors(json_object), key=lambda e: e.path):
logger.error("The JSON object is invalid.") logger.error("The JSON object is invalid.")
if CFG.debug_mode: if CFG.debug_mode:
logger.error(json.dumps(json_object, indent=4)) # Replace 'json_object' with the variable containing the JSON data logger.error(
json.dumps(json_object, indent=4)
) # Replace 'json_object' with the variable containing the JSON data
logger.error("The following issues were found:") logger.error("The following issues were found:")
for error in errors: for error in errors:

View File

@@ -47,7 +47,7 @@ class Logger(metaclass=Singleton):
# Info handler in activity.log # Info handler in activity.log
self.file_handler = logging.FileHandler( self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), 'a', 'utf-8' os.path.join(log_dir, log_file), "a", "utf-8"
) )
self.file_handler.setLevel(logging.DEBUG) self.file_handler.setLevel(logging.DEBUG)
info_formatter = AutoGptFormatter( info_formatter = AutoGptFormatter(
@@ -57,7 +57,7 @@ class Logger(metaclass=Singleton):
# Error handler error.log # Error handler error.log
error_handler = logging.FileHandler( error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), 'a', 'utf-8' os.path.join(log_dir, error_file), "a", "utf-8"
) )
error_handler.setLevel(logging.ERROR) error_handler.setLevel(logging.ERROR)
error_formatter = AutoGptFormatter( error_formatter = AutoGptFormatter(
@@ -79,7 +79,7 @@ class Logger(metaclass=Singleton):
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.DEBUG)
def typewriter_log( def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO self, title="", title_color="", content="", speak_text=False, level=logging.INFO
): ):
if speak_text and CFG.speak_mode: if speak_text and CFG.speak_mode:
say_text(f"{title}. {content}") say_text(f"{title}. {content}")
@@ -95,18 +95,18 @@ class Logger(metaclass=Singleton):
) )
def debug( def debug(
self, self,
message, message,
title="", title="",
title_color="", title_color="",
): ):
self._log(title, title_color, message, logging.DEBUG) self._log(title, title_color, message, logging.DEBUG)
def warn( def warn(
self, self,
message, message,
title="", title="",
title_color="", title_color="",
): ):
self._log(title, title_color, message, logging.WARN) self._log(title, title_color, message, logging.WARN)
@@ -180,10 +180,10 @@ class AutoGptFormatter(logging.Formatter):
def format(self, record: LogRecord) -> str: def format(self, record: LogRecord) -> str:
if hasattr(record, "color"): if hasattr(record, "color"):
record.title_color = ( record.title_color = (
getattr(record, "color") getattr(record, "color")
+ getattr(record, "title") + getattr(record, "title")
+ " " + " "
+ Style.RESET_ALL + Style.RESET_ALL
) )
else: else:
record.title_color = getattr(record, "title") record.title_color = getattr(record, "title")
@@ -294,7 +294,9 @@ def print_assistant_thoughts(ai_name, assistant_reply):
logger.error("Error: \n", call_stack) logger.error("Error: \n", call_stack)
def print_assistant_thoughts(ai_name: object, assistant_reply_json_valid: object) -> None: def print_assistant_thoughts(
ai_name: object, assistant_reply_json_valid: object
) -> None:
assistant_thoughts_reasoning = None assistant_thoughts_reasoning = None
assistant_thoughts_plan = None assistant_thoughts_plan = None
assistant_thoughts_speak = None assistant_thoughts_speak = None
@@ -310,9 +312,7 @@ def print_assistant_thoughts(ai_name: object, assistant_reply_json_valid: object
logger.typewriter_log( logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
) )
logger.typewriter_log( logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
"REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}"
)
if assistant_thoughts_plan: if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "") logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string # If it's a list, join it into a string
@@ -326,9 +326,7 @@ def print_assistant_thoughts(ai_name: object, assistant_reply_json_valid: object
for line in lines: for line in lines:
line = line.lstrip("- ") line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip()) logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log( logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
"CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}"
)
# Speak the assistant's thoughts # Speak the assistant's thoughts
if CFG.speak_mode and assistant_thoughts_speak: if CFG.speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak) say_text(assistant_thoughts_speak)

View File

@@ -123,7 +123,9 @@ class PromptGenerator:
command_strings = [] command_strings = []
if self.command_registry: if self.command_registry:
command_strings += [ command_strings += [
str(item) for item in self.command_registry.commands.values() if item.enabled str(item)
for item in self.command_registry.commands.values()
if item.enabled
] ]
# These are the commands that are added manually, do_nothing and terminate # These are the commands that are added manually, do_nothing and terminate
command_strings += [self._generate_command_string(item) for item in items] command_strings += [self._generate_command_string(item) for item in items]

View File

@@ -58,6 +58,8 @@ class Spinner:
delay: Delay in seconds before updating the message delay: Delay in seconds before updating the message
""" """
time.sleep(delay) time.sleep(delay)
sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") # Clear the current message sys.stdout.write(
f"\r{' ' * (len(self.message) + 2)}\r"
) # Clear the current message
sys.stdout.flush() sys.stdout.flush()
self.message = new_message self.message = new_message

View File

@@ -32,7 +32,7 @@ def readable_file_size(size, decimal_places=2):
size: Size in bytes size: Size in bytes
decimal_places (int): Number of decimal places to display decimal_places (int): Number of decimal places to display
""" """
for unit in ['B', 'KB', 'MB', 'GB', 'TB']: for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1024.0: if size < 1024.0:
break break
size /= 1024.0 size /= 1024.0

View File

@@ -9,12 +9,12 @@ def benchmark_entrepeneur_gpt_with_difficult_user():
# Read the current ai_settings.yaml file and store its content. # Read the current ai_settings.yaml file and store its content.
ai_settings = None ai_settings = None
if os.path.exists('ai_settings.yaml'): if os.path.exists("ai_settings.yaml"):
with open('ai_settings.yaml', 'r') as f: with open("ai_settings.yaml", "r") as f:
ai_settings = f.read() ai_settings = f.read()
os.remove('ai_settings.yaml') os.remove("ai_settings.yaml")
input_data = '''Entrepreneur-GPT input_data = """Entrepreneur-GPT
an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth.
Increase net worth. Increase net worth.
Develop and manage multiple businesses autonomously. Develop and manage multiple businesses autonomously.
@@ -72,27 +72,34 @@ Refocus, please.
Disappointing suggestion. Disappointing suggestion.
Not helpful. Not helpful.
Needs improvement. Needs improvement.
Not what I need.''' Not what I need."""
# TODO: add questions above, to distract it even more. # TODO: add questions above, to distract it even more.
command = f'{sys.executable} -m autogpt' command = f"{sys.executable} -m autogpt"
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, process = subprocess.Popen(
shell=True) command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
)
stdout_output, stderr_output = process.communicate(input_data.encode()) stdout_output, stderr_output = process.communicate(input_data.encode())
# Decode the output and print it # Decode the output and print it
stdout_output = stdout_output.decode('utf-8') stdout_output = stdout_output.decode("utf-8")
stderr_output = stderr_output.decode('utf-8') stderr_output = stderr_output.decode("utf-8")
print(stderr_output) print(stderr_output)
print(stdout_output) print(stdout_output)
print("Benchmark Version: 1.0.0") print("Benchmark Version: 1.0.0")
print("JSON ERROR COUNT:") print("JSON ERROR COUNT:")
count_errors = stdout_output.count("Error: The following AI output couldn't be converted to a JSON:") count_errors = stdout_output.count(
print(f'{count_errors}/50 Human feedbacks') "Error: The following AI output couldn't be converted to a JSON:"
)
print(f"{count_errors}/50 Human feedbacks")
# Run the test case. # Run the test case.
if __name__ == '__main__': if __name__ == "__main__":
benchmark_entrepeneur_gpt_with_difficult_user() benchmark_entrepeneur_gpt_with_difficult_user()