Skip to content

Commit

Permalink
replace 50+ occurrences of print() with logger (Significant-Gravitas#…
Browse files Browse the repository at this point in the history
…3056)

Co-authored-by: James Collins <[email protected]>
Co-authored-by: Luke Kyohere <[email protected]>
Co-authored-by: k-boikov <[email protected]>
Co-authored-by: Media <[email protected]>
Co-authored-by: Nicholas Tindle <[email protected]>
  • Loading branch information
6 people authored Apr 30, 2023
1 parent 6997bb0 commit 06ae468
Show file tree
Hide file tree
Showing 20 changed files with 134 additions and 139 deletions.
32 changes: 8 additions & 24 deletions autogpt/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from autogpt.logs import logger, print_assistant_thoughts
from autogpt.speech import say_text
from autogpt.spinner import Spinner
from autogpt.utils import clean_input, send_chat_message_to_user
from autogpt.utils import clean_input
from autogpt.workspace import Workspace


Expand Down Expand Up @@ -83,11 +83,7 @@ def start_interaction_loop(self):
logger.typewriter_log(
"Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}"
)
send_chat_message_to_user(
f"Continuous Limit Reached: \n {cfg.continuous_limit}"
)
break
send_chat_message_to_user("Thinking... \n")
# Send message to AI, get response
with Spinner("Thinking... "):
assistant_reply = chat_with_ai(
Expand Down Expand Up @@ -117,7 +113,6 @@ def start_interaction_loop(self):
if cfg.speak_mode:
say_text(f"I want to execute {command_name}")

send_chat_message_to_user("Thinking... \n")
arguments = self._resolve_pathlike_command_args(arguments)

except Exception as e:
Expand All @@ -128,24 +123,19 @@ def start_interaction_loop(self):
# Get key press: Prompt the user to press enter to continue or escape
# to exit
self.user_input = ""
send_chat_message_to_user(
"NEXT ACTION: \n " + f"COMMAND = {command_name} \n "
f"ARGUMENTS = {arguments}"
)
logger.typewriter_log(
"NEXT ACTION: ",
Fore.CYAN,
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} "
f"ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
)
print(

logger.info(
"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 's' to run self-feedback commands"
"'n' to exit program, or enter feedback for "
f"{self.ai_name}...",
flush=True,
f"{self.ai_name}..."
)
while True:
console_input = ""
if cfg.chat_messages_enabled:
console_input = clean_input("Waiting for your response...")
else:
Expand Down Expand Up @@ -176,7 +166,7 @@ def start_interaction_loop(self):
user_input = self_feedback_resp
break
elif console_input.lower().strip() == "":
print("Invalid input format.")
logger.warn("Invalid input format.")
continue
elif console_input.lower().startswith(f"{cfg.authorise_key} -"):
try:
Expand All @@ -185,8 +175,8 @@ def start_interaction_loop(self):
)
user_input = "GENERATE NEXT COMMAND JSON"
except ValueError:
print(
f"Invalid input format. Please enter '{cfg.authorise_key} -N' where N is"
logger.warn(
"Invalid input format. Please enter 'y -n' where n is"
" the number of continuous tasks."
)
continue
Expand All @@ -206,16 +196,10 @@ def start_interaction_loop(self):
"",
)
elif user_input == "EXIT":
send_chat_message_to_user("Exiting...")
print("Exiting...", flush=True)
logger.info("Exiting...")
break
else:
# Print command
send_chat_message_to_user(
"NEXT ACTION: \n " + f"COMMAND = {command_name} \n "
f"ARGUMENTS = {arguments}"
)

logger.typewriter_log(
"NEXT ACTION: ",
Fore.CYAN,
Expand Down
3 changes: 2 additions & 1 deletion autogpt/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from autogpt.commands.command import CommandRegistry, command
from autogpt.commands.web_requests import scrape_links, scrape_text
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.memory import get_memory
from autogpt.processing.text import summarize_text
from autogpt.prompts.generator import PromptGenerator
Expand Down Expand Up @@ -172,7 +173,7 @@ def get_hyperlinks(url: str) -> Union[str, List[str]]:

def shutdown() -> NoReturn:
"""Shut down the program"""
print("Shutting down...")
logger.info("Shutting down...")
quit()


Expand Down
23 changes: 15 additions & 8 deletions autogpt/commands/execute_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger

CFG = Config()

Expand All @@ -22,7 +23,7 @@ def execute_python_file(filename: str) -> str:
Returns:
str: The output of the file
"""
print(f"Executing file '{filename}'")
logger.info(f"Executing file '{filename}'")

if not filename.endswith(".py"):
return "Error: Invalid file type. Only .py files are allowed."
Expand All @@ -47,19 +48,21 @@ def execute_python_file(filename: str) -> str:
image_name = "python:3-alpine"
try:
client.images.get(image_name)
print(f"Image '{image_name}' found locally")
logger.warn(f"Image '{image_name}' found locally")
except ImageNotFound:
print(f"Image '{image_name}' not found locally, pulling from Docker Hub")
logger.info(
f"Image '{image_name}' not found locally, pulling from Docker Hub"
)
# Use the low-level API to stream the pull response
low_level_client = docker.APIClient()
for line in low_level_client.pull(image_name, stream=True, decode=True):
# Print the status and progress, if available
status = line.get("status")
progress = line.get("progress")
if status and progress:
print(f"{status}: {progress}")
logger.info(f"{status}: {progress}")
elif status:
print(status)
logger.info(status)
container = client.containers.run(
image_name,
f"python {Path(filename).relative_to(CFG.workspace_path)}",
Expand All @@ -85,7 +88,7 @@ def execute_python_file(filename: str) -> str:
return logs

except docker.errors.DockerException as e:
print(
logger.warn(
"Could not run the script in a container. If you haven't already, please install Docker https://docs.docker.com/get-docker/"
)
return f"Error: {str(e)}"
Expand Down Expand Up @@ -118,7 +121,9 @@ def execute_shell(command_line: str) -> str:
if not current_dir.is_relative_to(CFG.workspace_path):
os.chdir(CFG.workspace_path)

print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'")
logger.info(
f"Executing command '{command_line}' in working directory '{os.getcwd()}'"
)

result = subprocess.run(command_line, capture_output=True, shell=True)
output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
Expand Down Expand Up @@ -154,7 +159,9 @@ def execute_shell_popen(command_line) -> str:
if CFG.workspace_path not in current_dir:
os.chdir(CFG.workspace_path)

print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'")
logger.info(
f"Executing command '{command_line}' in working directory '{os.getcwd()}'"
)

do_not_show_output = subprocess.DEVNULL
process = subprocess.Popen(
Expand Down
11 changes: 6 additions & 5 deletions autogpt/commands/file_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.spinner import Spinner
from autogpt.utils import readable_file_size

Expand Down Expand Up @@ -106,25 +107,25 @@ def ingest_file(
:param overlap: The number of overlapping characters between chunks, default is 200
"""
try:
print(f"Working with file {filename}")
logger.info(f"Working with file {filename}")
content = read_file(filename)
content_length = len(content)
print(f"File length: {content_length} characters")
logger.info(f"File length: {content_length} characters")

chunks = list(split_file(content, max_length=max_length, overlap=overlap))

num_chunks = len(chunks)
for i, chunk in enumerate(chunks):
print(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
logger.info(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
memory_to_add = (
f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}"
)

memory.add(memory_to_add)

print(f"Done ingesting {num_chunks} chunks from {filename}.")
logger.info(f"Done ingesting {num_chunks} chunks from {filename}.")
except Exception as e:
print(f"Error while ingesting file '{filename}': {str(e)}")
logger.info(f"Error while ingesting file '{filename}': {str(e)}")


@command("write_to_file", "Write to file", '"filename": "<filename>", "text": "<text>"')
Expand Down
9 changes: 5 additions & 4 deletions autogpt/commands/image_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger

CFG = Config()

Expand Down Expand Up @@ -69,7 +70,7 @@ def generate_image_with_hf(prompt: str, filename: str) -> str:
)

image = Image.open(io.BytesIO(response.content))
print(f"Image Generated for prompt:{prompt}")
logger.info(f"Image Generated for prompt:{prompt}")

image.save(filename)

Expand All @@ -91,7 +92,7 @@ def generate_image_with_dalle(prompt: str, filename: str, size: int) -> str:
# Check for supported image sizes
if size not in [256, 512, 1024]:
closest = min([256, 512, 1024], key=lambda x: abs(x - size))
print(
logger.info(
f"DALL-E only supports image sizes of 256x256, 512x512, or 1024x1024. Setting to {closest}, was {size}."
)
size = closest
Expand All @@ -104,7 +105,7 @@ def generate_image_with_dalle(prompt: str, filename: str, size: int) -> str:
api_key=CFG.openai_api_key,
)

print(f"Image Generated for prompt:{prompt}")
logger.info(f"Image Generated for prompt:{prompt}")

image_data = b64decode(response["data"][0]["b64_json"])

Expand Down Expand Up @@ -153,7 +154,7 @@ def generate_image_with_sd_webui(
},
)

print(f"Image Generated for prompt:{prompt}")
logger.info(f"Image Generated for prompt:{prompt}")

# Save the image to disk
response = response.json()
Expand Down
4 changes: 3 additions & 1 deletion autogpt/commands/web_playwright.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Web scraping commands using Playwright"""
from __future__ import annotations

from autogpt.logs import logger

try:
from playwright.sync_api import sync_playwright
except ImportError:
print(
logger.info(
"Playwright not installed. Please install it with 'pip install playwright' to use."
)
from bs4 import BeautifulSoup
Expand Down
13 changes: 5 additions & 8 deletions autogpt/json_utils/json_fix_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from autogpt.config import Config
from autogpt.json_utils.utilities import extract_char_position
from autogpt.logs import logger

CFG = Config()

Expand All @@ -33,8 +34,7 @@ def fix_invalid_escape(json_to_load: str, error_message: str) -> str:
json.loads(json_to_load)
return json_to_load
except json.JSONDecodeError as e:
if CFG.debug_mode:
print("json loads error - fix invalid escape", e)
logger.debug("json loads error - fix invalid escape", e)
error_message = str(e)
return json_to_load

Expand Down Expand Up @@ -98,13 +98,11 @@ def correct_json(json_to_load: str) -> str:
"""

try:
if CFG.debug_mode:
print("json", json_to_load)
logger.debug("json", json_to_load)
json.loads(json_to_load)
return json_to_load
except json.JSONDecodeError as e:
if CFG.debug_mode:
print("json loads error", e)
logger.debug("json loads error", e)
error_message = str(e)
if error_message.startswith("Invalid \\escape"):
json_to_load = fix_invalid_escape(json_to_load, error_message)
Expand All @@ -116,8 +114,7 @@ def correct_json(json_to_load: str) -> str:
json.loads(json_to_load)
return json_to_load
except json.JSONDecodeError as e:
if CFG.debug_mode:
print("json loads error - add quotes", e)
logger.debug("json loads error - add quotes", e)
error_message = str(e)
if balanced_str := balance_braces(json_to_load):
return balanced_str
Expand Down
5 changes: 2 additions & 3 deletions autogpt/json_utils/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ def validate_json(json_object: object, schema_name: str) -> dict | None:

for error in errors:
logger.error(f"Error: {error.message}")
return None
if CFG.debug_mode:
print("The JSON object is valid.")
else:
logger.debug("The JSON object is valid.")

return json_object

Expand Down
7 changes: 3 additions & 4 deletions autogpt/llm/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,8 @@ def chat_with_ai(
[create_chat_message("system", plugin_response)], model
)
if current_tokens_used + tokens_to_add > send_token_limit:
if cfg.debug_mode:
print("Plugin response too long, skipping:", plugin_response)
print("Plugins remaining at stop:", plugin_count - i)
logger.debug("Plugin response too long, skipping:", plugin_response)
logger.debug("Plugins remaining at stop:", plugin_count - i)
break
current_context.append(create_chat_message("system", plugin_response))

Expand Down Expand Up @@ -227,5 +226,5 @@ def chat_with_ai(
return assistant_reply
except RateLimitError:
# TODO: When we switch to langchain, this is built in
print("Error: ", "API Rate Limit Reached. Waiting 10 seconds...")
logger.warn("Error: ", "API Rate Limit Reached. Waiting 10 seconds...")
time.sleep(10)
Loading

0 comments on commit 06ae468

Please sign in to comment.