Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Merge branch 'feature/global-logging' of github.com:agiletechnologist/MemGPT into feature/global-logging
Max Blackmer72d184a5e33d
diff --cc memgpt/cli/cli_config.pyindex 8203a5e59,0b4807122..2577a6c24--- a/memgpt/cli/cli_config.py+++ b/memgpt/cli/cli_config.py@@@ -4,10 -4,9 +4,12 @@@ from prettytable import PrettyTablimport typerimport osimport shutil+ from typing import Annotated+ from enum import Enum+# from global logging configuration+from memgpt.log import logger+# from memgpt.cli import appfrom memgpt import utilsdiff --cc memgpt/config.pyindex f6d7aa8f6,65da99c5e..5d61c72ea--- a/memgpt/config.py+++ b/memgpt/config.py@@@ -1,6 -1,3 +1,4 @@@- import logging- import logging.config- from memgpt.log import logger, reload_logger, fix_file_path++from log import loggerimport inspectimport jsonimport os@@@ -10,7 -7,9 +8,10 @@@ import configparseimport memgptimport memgpt.utils as utils- from memgpt.constants import MEMGPT_DIR, LLM_MAX_TOKENS, DEFAULT_HUMAN, DEFAULT_PERSONA, LOGGER_NAME+ from memgpt.utils import printd, get_schema_diff+ from memgpt.functions.functions import load_all_function_sets+ from memgpt.constants import MEMGPT_DIR, LLM_MAX_TOKENS, DEFAULT_HUMAN, DEFAULT_PERSONA++from memgpt.presets.presets import DEFAULT_PRESET@@@ -150,49 -150,14 +154,16 @@@ class MemGPTConfig"anon_clientid": get_field(config, "client", "anon_clientid"),"config_path": config_path,"memgpt_version": get_field(config, "version", "memgpt_version"),- "logging_level": get_field(config, "logger_MemGPT", "level"),- "logging_enable_logfile": True- if "consoleHandler,logfileHandler" == get_field(config, "logger_MemGPT", "handlers")- else False,- "logging_backup_count": get_field(config, "handler_logfileHandler", "backupcount"),- "logging_max_file_bytes": get_field(config, "handler_logfileHandler", "maxBytes"),- "logging_logdir": get_field(config, "logging_paths", "logdir"),- "logging_logpathname": get_field(config, "logging_paths", "logpathname"),}- # ensure logging is config is set correctly support for upgrades- force_save = False- if (- config_dict["logging_level"] is None- or config_dict["logging_backup_count"] is None- or config_dict["logging_max_file_bytes"] is None- or config_dict["logging_logdir"] is None- or config_dict["logging_logpathname"] is None- ):- # load loggind defaults if none- config_dict["logging_enable_logfile"] = MemGPTConfig.logging_enable_logfile- config_dict["logging_level"] = MemGPTConfig.logging_level- config_dict["logging_backup_count"] = MemGPTConfig.logging_backup_count- config_dict["logging_max_file_bytes"] = MemGPTConfig.logging_max_file_bytes- config_dict["logging_logdir"] = MemGPTConfig.logging_logdir- config_dict["logging_logpathname"] = MemGPTConfig.logging_logpathname- force_save = Trueconfig_dict = {k: v for k, v in config_dict.items() if v is not None}+- if force_save:- temp_config = cls(**config_dict)- temp_config.save()- logger = logging.getLogger(LOGGER_NAME)- logger.debug(f"Updated Missing Logging Configuration: {config_path}")-return cls(**config_dict)# create new configanon_clientid = MemGPTConfig.generate_uuid()config = cls(anon_clientid=anon_clientid, config_path=config_path)+ config.create_config_dir() # create dirsconfig.save() # save updated config- logger = logging.getLogger(LOGGER_NAME)- logger.debug(f"Created New Configuration: {config_path}")return configdef save(self):@@@ -243,57 -218,10 +224,12 @@@self.anon_clientid = self.generate_uuid()set_field(config, "client", "anon_clientid", self.anon_clientid)- # logging- set_field(config, "loggers", "keys", "root,MemGPT")- set_field(config, "handlers", "keys", "consoleHandler,logfileHandler")- set_field(config, "formatters", "keys", "consoleFormatter,logfileFormatter")- # logging root possibly used by other modules not using MemGPT logger- set_field(config, "logger_root", "level", "CRITICAL")- set_field(config, "logger_root", "handlers", "consoleHandler")- # logging MemGPT- set_field(config, "logger_MemGPT", "level", self.logging_level)- if self.logging_enable_logfile:- # this will enable logging to file- set_field(config, "logger_MemGPT", "handlers", "consoleHandler,logfileHandler")- else:- # this removes file logging if not enabled- set_field(config, "logger_MemGPT", "handlers", "consoleHandler")- set_field(config, "logger_MemGPT", "qualname", "MemGPT")- set_field(config, "logger_MemGPT", "propagate", "0") # do not propigate to root- # console logging handler- set_field(config, "handler_consoleHandler", "class", "StreamHandler")- set_field(config, "handler_consoleHandler", "level", self.logging_level)- set_field(config, "handler_consoleHandler", "formatter", "consoleFormatter")- set_field(config, "handler_consoleHandler", "args", "(sys.stdout,)")- # console logging formatter- set_field(config, "formatter_consoleFormatter", "format", "%(name)s - %(levelname)s - %(message)s")- if self.logging_enable_logfile:- set_field(config, "formatter_logfileFormatter", "format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")- # logfile logging handler Rotating File Handler- set_field(config, "handler_logfileHandler", "class", "handlers.RotatingFileHandler")- set_field(config, "handler_logfileHandler", "level", self.logging_level)- fixed_logpathname = fix_file_path(self.logging_logpathname)- set_field(- config,- "handler_logfileHandler",- "args",- f"('{fixed_logpathname}', {self.logging_max_file_bytes}, {self.logging_backup_count})",- )- set_field(config, "handler_logfileHandler", "formatter", "logfileFormatter")- # logging paths- set_field(config, "logging_paths", "logdir", self.logging_logdir)- set_field(config, "logging_paths", "logpathname", self.logging_logpathname)-- if not os.path.exists(MEMGPT_DIR):- os.makedirs(MEMGPT_DIR, exist_ok=True)+ # always make sure all directories are present+ self.create_config_dir()+with open(self.config_path, "w") as f:config.write(f)- # reload logging config after write.- logging.config.fileConfig(self.config_path, disable_existing_loggers=False)- # reset the logger (global) logger is defined as global- reload_logger()+ logger.debug(f"Saved Config: {self.config_path}")@staticmethoddef exists():@@@ -311,8 -239,7 +247,8 @@@if not os.path.exists(MEMGPT_DIR):os.makedirs(MEMGPT_DIR, exist_ok=True)- folders = ["personas", "humans", "archival", "agents", "functions", "system_prompts", "presets", "settings", "logs"]+ folders = ["personas", "humans", "archival", "agents", "functions", "system_prompts", "presets", "settings"]+for folder in folders:if not os.path.exists(os.path.join(MEMGPT_DIR, folder)):os.makedirs(os.path.join(MEMGPT_DIR, folder))diff --cc memgpt/constants.pyindex b96362ce6,9710e8d73..d0f50a7f5--- a/memgpt/constants.py+++ b/memgpt/constants.py@@@ -1,4 -1,4 +1,5 @@@import os++from logging import CRITICAL, ERROR, WARN, WARNING, INFO, DEBUG, NOTSETMEMGPT_DIR = os.path.join(os.path.expanduser("~"), ".memgpt")@@@ -6,8 -6,6 +7,20 @@@ DEFAULT_MEMGPT_MODEL = "gpt-4DEFAULT_PERSONA = "sam_pov"DEFAULT_HUMAN = "basic"++# Used to isolate MemGPT logger instance from Dependant Libraries logging+LOGGER_NAME = "MemGPT"++LOGGER_DEFAULT_LEVEL = CRITICAL++# Where to store the logs++LOGGER_DIR = os.path.join(MEMGPT_DIR, "logs")++# filename of the log++LOGGER_FILENAME = "MemGPT.log"++# Number of log files to rotate++LOGGER_FILE_BACKUP_COUNT = 3++# Max Log file size in bytes++LOGGER_MAX_FILE_SIZE = 10485760++# LOGGER_LOG_LEVEL is use to convert Text to Logging level value for logging mostly for Cli input to setting level++LOGGER_LOG_LEVELS = {"CRITICAL": CRITICAL, "ERROR": ERROR, "WARN": WARN, "WARNING": WARNING, "INFO": INFO, "DEBUG": DEBUG, "NOTSET": NOTSET}+FIRST_MESSAGE_ATTEMPTS = 10INITIAL_BOOT_MESSAGE = "Boot sequence complete. Persona activated."diff --cc memgpt/log.pyindex 8151cd990,000000000..24fef9d39mode 100644,000000..100644--- a/memgpt/log.py+++ b/memgpt/log.py@@@ -1,20 -1,0 +1,42 @@@++import os+import os.path+import logging- from memgpt.constants import LOGGER_NAME++from logging.handlers import RotatingFileHandler++from memgpt.constants import (++ LOGGER_NAME,++ LOGGER_DEFAULT_LEVEL,++ LOGGER_DIR,++ LOGGER_FILENAME,++ LOGGER_FILE_BACKUP_COUNT,++ LOGGER_MAX_FILE_SIZE,++)+- # load the logger for global use++# Checking if log directory exists++if not os.path.exists(LOGGER_DIR):++ os.makedirs(LOGGER_DIR, exist_ok=True)++++# Create logger for MemGPT+logger = logging.getLogger(LOGGER_NAME)++logger.setLevel(LOGGER_DEFAULT_LEVEL)++++# create console handler and set level to debug++console_handler = logging.StreamHandler()++++# create rotatating file handler++file_handler = RotatingFileHandler(++ os.path.join(LOGGER_DIR, LOGGER_FILENAME), maxBytes=LOGGER_MAX_FILE_SIZE, backupCount=LOGGER_FILE_BACKUP_COUNT++)+++# create formatters++console_formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s") # not datetime++file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")+- def reload_logger():- global logger # This is required to modify the global 'logger'- # Reconfigure logger- logger = logging.getLogger(LOGGER_NAME)++# add formatter to console handler++console_handler.setFormatter(console_formatter)+++# add formatter for file handler++file_handler.setFormatter(file_formatter)+- def fix_file_path(path):- """- Converts backslashes to forward slashes in a file path.- This is useful for ensuring compatibility in file paths across different systems.- """- return path.replace("\\", "/")++# add ch to logger++logger.addHandler(console_handler)++logger.addHandler(file_handler)