Agent Zero AI framework
console print edits for docker
frdel884007cdb006
diff --git a/initialize.py b/initialize.pyindex 127e9f130..ed4397bff 100644--- a/initialize.py+++ b/initialize.py@@ -84,16 +84,12 @@ def args_override(config):# conversion based on type of config[key]if isinstance(getattr(config, key), bool):value = value.lower().strip() == "true"- print("bool", value)elif isinstance(getattr(config, key), int):value = int(value)- print("int", value)elif isinstance(getattr(config, key), float):value = float(value)- print("float", value)elif isinstance(getattr(config, key), str):value = str(value)- print("str", value)else:raise Exception(f"Unsupported argument type of '{key}': {type(getattr(config, key))}"diff --git a/preload.py b/preload.pyindex f5c77fc97..2cf59171d 100644--- a/preload.py+++ b/preload.py@@ -1,7 +1,8 @@import asynciofrom python.helpers import runtime, whisper, settings+from python.helpers.print_style import PrintStyle-print("Running preload...")+PrintStyle().print("Running preload...")runtime.initialize()@@ -14,7 +15,7 @@ async def preload():return asyncio.gather(*tasks, return_exceptions=True)except Exception as e:- print(f"Error in preload: {e}")+ PrintStyle().print(f"Error in preload: {e}")# preload transcription modeldiff --git a/prepare.py b/prepare.pyindex 1853ca16e..a13d95f82 100644--- a/prepare.py+++ b/prepare.py@@ -1,8 +1,10 @@from python.helpers import dotenv, runtime, settingsimport stringimport random+from python.helpers.print_style import PrintStyle-print("Preparing environment...")++PrintStyle.standard("Preparing environment...")try:@@ -12,8 +14,8 @@ try:root_pass = dotenv.get_dotenv_value(dotenv.KEY_ROOT_PASSWORD)if not root_pass:root_pass = "".join(random.choices(string.ascii_letters + string.digits, k=32))- print("Changing root password...")+ PrintStyle.standard("Changing root password...")settings.set_root_password(root_pass)except Exception as e:- print(f"Error in preload: {e}")+ PrintStyle.error(f"Error in preload: {e}")diff --git a/python/helpers/attachment_manager.py b/python/helpers/attachment_manager.pyindex 039076ebd..aad7c1375 100644--- a/python/helpers/attachment_manager.py+++ b/python/helpers/attachment_manager.py@@ -5,6 +5,8 @@ from PIL import Imagefrom typing import Dict, List, Optional, Tuplefrom werkzeug.utils import secure_filename+from python.helpers.print_style import PrintStyle+class AttachmentManager:ALLOWED_EXTENSIONS = {'image': {'jpg', 'jpeg', 'png', 'bmp'},@@ -66,7 +68,7 @@ class AttachmentManager:return file_path, metadataexcept Exception as e:- print(f"Error saving file {filename}: {e}")+ PrintStyle.error(f"Error saving file {filename}: {e}")return None, {} # type: ignoredef generate_image_preview(self, image_path: str, max_size: int = 800) -> Optional[str]:@@ -86,6 +88,6 @@ class AttachmentManager:# Convert to base64return base64.b64encode(buffer.getvalue()).decode('utf-8')except Exception as e:- print(f"Error generating preview for {image_path}: {e}")+ PrintStyle.error(f"Error generating preview for {image_path}: {e}")return None\ No newline at end of filediff --git a/python/helpers/cloudflare_tunnel.py b/python/helpers/cloudflare_tunnel.pyindex eb90555bb..ebd1f50e8 100644--- a/python/helpers/cloudflare_tunnel.py+++ b/python/helpers/cloudflare_tunnel.py@@ -4,6 +4,7 @@ import requestsimport subprocessimport threadingfrom python.helpers import files+from python.helpers.print_style import PrintStyleclass CloudflareTunnel:def __init__(self, port: int):@@ -41,7 +42,7 @@ class CloudflareTunnel:download_url = f"{base_url}{download_file}"download_path = files.get_abs_path(self.bin_dir, download_file)- print(f"\nDownloading cloudflared from: {download_url}")+ PrintStyle().print(f"\nDownloading cloudflared from: {download_url}")response = requests.get(download_url, stream=True)if response.status_code != 200:raise RuntimeError(f"Failed to download cloudflared: {response.status_code}")@@ -77,7 +78,7 @@ class CloudflareTunnel:download_url = f"{base_url}{download_file}"download_path = files.get_abs_path(self.bin_dir, download_file)- print(f"\nDownloading cloudflared from: {download_url}")+ PrintStyle().print(f"\nDownloading cloudflared from: {download_url}")response = requests.get(download_url, stream=True)if response.status_code != 200:raise RuntimeError(f"Failed to download cloudflared: {response.status_code}")@@ -113,9 +114,9 @@ class CloudflareTunnel:start = line.find("https://")end = line.find("trycloudflare.com") + len("trycloudflare.com")self.tunnel_url = line[start:end].strip()- print("\n=== Cloudflare Tunnel URL ===")- print(f"URL: {self.tunnel_url}")- print("============================\n")+ PrintStyle().print("\n=== Cloudflare Tunnel URL ===")+ PrintStyle().print(f"URL: {self.tunnel_url}")+ PrintStyle().print("============================\n")returndef start(self):@@ -123,7 +124,7 @@ class CloudflareTunnel:if not self.cloudflared_path:self.download_cloudflared()- print("\nStarting Cloudflare tunnel...")+ PrintStyle().print("\nStarting Cloudflare tunnel...")# Start tunnel processself.tunnel_process = subprocess.Popen([@@ -149,7 +150,7 @@ class CloudflareTunnel:"""Stops the cloudflare tunnel"""self._stop_event.set()if self.tunnel_process:- print("\nStopping Cloudflare tunnel...")+ PrintStyle().print("\nStopping Cloudflare tunnel...")self.tunnel_process.terminate()self.tunnel_process.wait()self.tunnel_process = Nonediff --git a/python/helpers/docker.py b/python/helpers/docker.pyindex fc4b9661b..b71651954 100644--- a/python/helpers/docker.py+++ b/python/helpers/docker.py@@ -38,10 +38,10 @@ class DockerContainerManager:try:self.container.stop()self.container.remove()- print(f"Stopped and removed the container: {self.container.id}")+ PrintStyle.standard(f"Stopped and removed the container: {self.container.id}")if self.logger: self.logger.log(type="info", content=f"Stopped and removed the container: {self.container.id}")except Exception as e:- print(f"Failed to stop and remove the container: {e}")+ PrintStyle.error(f"Failed to stop and remove the container: {e}")if self.logger: self.logger.log(type="error", content=f"Failed to stop and remove the container: {e}")def get_image_containers(self):@@ -72,7 +72,7 @@ class DockerContainerManager:if existing_container:if existing_container.status != 'running':- print(f"Starting existing container: {self.name} for safe code execution...")+ PrintStyle.standard(f"Starting existing container: {self.name} for safe code execution...")if self.logger: self.logger.log(type="info", content=f"Starting existing container: {self.name} for safe code execution...", temp=True)existing_container.start()@@ -81,9 +81,9 @@ class DockerContainerManager:else:self.container = existing_container- # print(f"Container with name '{self.name}' is already running with ID: {existing_container.id}")+ # PrintStyle.standard(f"Container with name '{self.name}' is already running with ID: {existing_container.id}")else:- print(f"Initializing docker container {self.name} for safe code execution...")+ PrintStyle.standard(f"Initializing docker container {self.name} for safe code execution...")if self.logger: self.logger.log(type="info", content=f"Initializing docker container {self.name} for safe code execution...", temp=True)self.container = self.client.containers.run(@@ -94,6 +94,6 @@ class DockerContainerManager:volumes=self.volumes, # type: ignore)# atexit.register(self.cleanup_container)- print(f"Started container with ID: {self.container.id}")+ PrintStyle.standard(f"Started container with ID: {self.container.id}")if self.logger: self.logger.log(type="info", content=f"Started container with ID: {self.container.id}")time.sleep(5) # this helps to get SSH readydiff --git a/python/helpers/dotenv.py b/python/helpers/dotenv.pyindex be9e01cbc..07ef0942b 100644--- a/python/helpers/dotenv.py+++ b/python/helpers/dotenv.py@@ -1,5 +1,6 @@import osimport re+from typing import Anyfrom .files import get_abs_pathfrom dotenv import load_dotenv as _load_dotenv@@ -16,9 +17,9 @@ def load_dotenv():def get_dotenv_file_path():return get_abs_path(".env")-def get_dotenv_value(key: str):+def get_dotenv_value(key: str, default: Any = None):# load_dotenv()- return os.getenv(key)+ return os.getenv(key, default)def save_dotenv_value(key: str, value: str):if value is None:diff --git a/python/helpers/file_browser.py b/python/helpers/file_browser.pyindex 28194ea7e..41fdd5bed 100644--- a/python/helpers/file_browser.py+++ b/python/helpers/file_browser.py@@ -8,6 +8,7 @@ from werkzeug.utils import secure_filenamefrom datetime import datetimefrom python.helpers import files, runtime+from python.helpers.print_style import PrintStyleclass FileBrowser:ALLOWED_EXTENSIONS = {@@ -58,13 +59,13 @@ class FileBrowser:else:failed.append(file.filename)except Exception as e:- print(f"Error saving file {file.filename}: {e}")+ PrintStyle.error(f"Error saving file {file.filename}: {e}")failed.append(file.filename)return successful, failedexcept Exception as e:- print(f"Error in save_files: {e}")+ PrintStyle.error(f"Error in save_files: {e}")return successful, faileddef delete_file(self, file_path: str) -> bool:@@ -85,7 +86,7 @@ class FileBrowser:return Falseexcept Exception as e:- print(f"Error deleting {file_path}: {e}")+ PrintStyle.error(f"Error deleting {file_path}: {e}")return Falsedef _is_allowed_file(self, filename: str, file) -> bool:@@ -160,7 +161,7 @@ class FileBrowser:}except Exception as e:- print(f"Error reading directory: {e}")+ PrintStyle.error(f"Error reading directory: {e}")return {"entries": [], "current_path": "", "parent_path": ""}def get_full_path(self, file_path: str, allow_dir: bool = False) -> str:diff --git a/python/helpers/knowledge_import.py b/python/helpers/knowledge_import.pyindex 8306cd55b..64af5e190 100644--- a/python/helpers/knowledge_import.py+++ b/python/helpers/knowledge_import.py@@ -13,6 +13,7 @@ from langchain_community.document_loaders import ()from python.helpers import filesfrom python.helpers.log import LogItem+from python.helpers.print_style import PrintStyletext_loader_kwargs = {"autodetect_encoding": True}@@ -70,7 +71,7 @@ def load_knowledge(kn_files = [f for f in kn_files if os.path.isfile(f)]if kn_files:- print(+ PrintStyle.standard(f"Found {len(kn_files)} knowledge files in {knowledge_dir}, processing...")if log_item:@@ -108,7 +109,7 @@ def load_knowledge(doc.metadata = {**doc.metadata, **metadata}cnt_files += 1cnt_docs += len(file_data["documents"])- # print(f"Imported {len(file_data['documents'])} documents from {file_path}")+ # PrintStyle.standard(f"Imported {len(file_data['documents'])} documents from {file_path}")# Update the indexindex[file_key] = file_data # type: ignore@@ -118,7 +119,7 @@ def load_knowledge(if not file_data.get("state", ""):index[file_key]["state"] = "removed"- print(f"Processed {cnt_docs} documents from {cnt_files} files.")+ PrintStyle.standard(f"Processed {cnt_docs} documents from {cnt_files} files.")if log_item:log_item.stream(progress=f"\nProcessed {cnt_docs} documents from {cnt_files} files."diff --git a/python/helpers/memory.py b/python/helpers/memory.pyindex 0a7e24fd9..1815c8583 100644--- a/python/helpers/memory.py+++ b/python/helpers/memory.py@@ -13,6 +13,8 @@ from langchain_community.vectorstores.utils import (import os, jsonimport numpy as np++from python.helpers.print_style import PrintStylefrom . import filesfrom langchain_core.documents import Documentimport uuid@@ -78,7 +80,7 @@ class Memory:in_memory=False,) -> MyFaiss:- print("Initializing VectorDB...")+ PrintStyle.standard("Initializing VectorDB...")if log_item:log_item.stream(progress="\nInitializing VectorDB")@@ -312,7 +314,7 @@ class Memory:try:return eval(condition, {}, data)except Exception as e:- # print(f"Error evaluating condition: {e}")+ # PrintStyle.error(f"Error evaluating condition: {e}")return Falsereturn comparatordiff --git a/python/helpers/print_style.py b/python/helpers/print_style.pyindex e54f4fe08..083326662 100644--- a/python/helpers/print_style.py+++ b/python/helpers/print_style.py@@ -117,6 +117,10 @@ class PrintStyle:lines = sys.stdin.readlines()return bool(lines) and not lines[-1].strip()+ @staticmethod+ def standard(text:str):+ PrintStyle().print(text)+@staticmethoddef hint(text:str):PrintStyle(font_color="#6C3483", padding=True).print("Hint: "+text)diff --git a/python/helpers/process.py b/python/helpers/process.pyindex e30662d3b..59c994d32 100644--- a/python/helpers/process.py+++ b/python/helpers/process.py@@ -1,6 +1,7 @@import osimport sysfrom python.helpers import runtime+from python.helpers.print_style import PrintStyle_server = None@@ -26,10 +27,10 @@ def reload():restart_process()def restart_process():- print("Restarting process...")+ PrintStyle.standard("Restarting process...")python = sys.executableos.execv(python, [python] + sys.argv)def exit_process():- print("Exiting process...")+ PrintStyle.standard("Exiting process...")sys.exit(0)\ No newline at end of filediff --git a/python/helpers/shell_ssh.py b/python/helpers/shell_ssh.pyindex 7aa6d52f0..ec4869b9a 100644--- a/python/helpers/shell_ssh.py+++ b/python/helpers/shell_ssh.py@@ -4,6 +4,7 @@ import timeimport refrom typing import Tuplefrom python.helpers.log import Log+from python.helpers.print_style import PrintStylefrom python.helpers.strings import calculate_valid_match_lengths@@ -51,7 +52,7 @@ class SSHInteractiveSession:except Exception as e:errors += 1if errors < 3:- print(f"SSH Connection attempt {errors}...")+ PrintStyle.standard(f"SSH Connection attempt {errors}...")self.logger.log(type="info",content=f"SSH Connection attempt {errors}...",diff --git a/python/helpers/whisper.py b/python/helpers/whisper.pyindex acfb819db..f92e4c8b5 100644--- a/python/helpers/whisper.py+++ b/python/helpers/whisper.py@@ -4,6 +4,7 @@ import whisperimport tempfileimport asynciofrom python.helpers import runtime, rfc, settings+from python.helpers.print_style import PrintStyle# Suppress FutureWarning from torch.loadwarnings.filterwarnings("ignore", category=FutureWarning)@@ -28,7 +29,7 @@ async def _preload(model_name:str):try:is_updating_model = Trueif not _model or _model_name != model_name:- print(f"Loading Whisper model: {model_name}")+ PrintStyle.standard(f"Loading Whisper model: {model_name}")_model = whisper.load_model(model_name)_model_name = model_namefinally:diff --git a/run_cli.py b/run_cli.pyindex 4045ebec3..4afdb1fc1 100644--- a/run_cli.py+++ b/run_cli.py@@ -96,7 +96,7 @@ def timeout_input(prompt, timeout=10):def run():global context- print("Initializing framework...")+ PrintStyle.standard("Initializing framework...")#load env varsload_dotenv()@@ -112,5 +112,5 @@ def run():asyncio.run(chat(context))if __name__ == "__main__":- print("\n\n!!! run_cli.py is now discontinued. run_ui.py serves as both UI and API endpoint !!!\n\n")+ PrintStyle.standard("\n\n!!! run_cli.py is now discontinued. run_ui.py serves as both UI and API endpoint !!!\n\n")run()\ No newline at end of filediff --git a/run_ui.py b/run_ui.pyindex c9d2cbbcb..abf01d0d4 100644--- a/run_ui.py+++ b/run_ui.py@@ -3,12 +3,13 @@ import osimport threadingfrom flask import Flask, request, Responsefrom flask_basicauth import BasicAuth-from python.helpers import files, git+from python.helpers import errors, files, gitfrom python.helpers.files import get_abs_pathfrom python.helpers import persist_chat, runtime, dotenv, processfrom python.helpers.cloudflare_tunnel import CloudflareTunnelfrom python.helpers.extract_tools import load_classes_from_folderfrom python.helpers.api import ApiHandler+from python.helpers.print_style import PrintStyle# initialize the internal Flask server@@ -54,7 +55,7 @@ async def serve_index():def run():- print("Initializing framework...")+ PrintStyle().print("Initializing framework...")# Suppress only request logs but keep the startup messagesfrom werkzeug.serving import WSGIRequestHandler@@ -65,25 +66,29 @@ def run():pass # Override to suppress request logging# Get configuration from environment- port = runtime.get_arg("port") or int(os.environ.get("WEB_UI_PORT", 0)) or 5000- host = runtime.get_arg("host") or os.environ.get("WEB_UI_HOST") or "localhost"- use_cloudflare = (- runtime.get_arg("cloudflare_tunnel")- or os.environ.get("USE_CLOUDFLARE", "false").lower() == "true"- )+ port = runtime.get_arg("port") or int(dotenv.get_dotenv_value("WEB_UI_PORT", 0)) or 5000+ host = runtime.get_arg("host") or dotenv.get_dotenv_value("WEB_UI_HOST") or "localhost"+ use_cloudflare = (runtime.get_arg("cloudflare_tunnel")+ or dotenv.get_dotenv_value("USE_CLOUDFLARE", "false").lower()) == "true"+- # Initialize and start Cloudflare tunnel if enabledtunnel = None- if use_cloudflare and port:- try:- tunnel = CloudflareTunnel(port)- tunnel.start()- except Exception as e:- print(f"Failed to start Cloudflare tunnel: {e}")- print("Continuing without tunnel...")- # initialize contexts from persisted chats- persist_chat.load_tmp_chats()+ try:+ # Initialize and start Cloudflare tunnel if enabled+ if use_cloudflare and port:+ try:+ tunnel = CloudflareTunnel(port)+ tunnel.start()+ except Exception as e:+ PrintStyle().error(f"Failed to start Cloudflare tunnel: {e}")+ PrintStyle().print("Continuing without tunnel...")++ # initialize contexts from persisted chats+ persist_chat.load_tmp_chats()++ except Exception as e:+ PrintStyle().error(errors.format_error(e))server = None@@ -123,4 +128,5 @@ def run():# run the internal serverif __name__ == "__main__":runtime.initialize()+ dotenv.load_dotenv()run()