Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated team.py code file. #1485

Open
wants to merge 3 commits into
base: v0.8-release
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions metagpt/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
import sys
from datetime import datetime
from functools import partial
from typing import Callable, Optional

from loguru import logger as _logger

from metagpt.const import METAGPT_ROOT


def define_log_level(print_level="INFO", logfile_level="DEBUG", name: str = None):
"""Adjust the log level to above level"""
def define_log_level(print_level: str = "INFO", logfile_level: str = "DEBUG", name: Optional[str] = None) -> _logger:
"""Adjust the log level to the specified levels."""
current_date = datetime.now()
formatted_date = current_date.strftime("%Y%m%d")
log_name = f"{name}_{formatted_date}" if name else formatted_date # name a log with prefix name
Expand All @@ -30,13 +31,15 @@ def define_log_level(print_level="INFO", logfile_level="DEBUG", name: str = None
logger = define_log_level()


def log_llm_stream(msg):
def log_llm_stream(msg: str) -> None:
"""Log LLM stream messages."""
_llm_stream_log(msg)


def set_llm_stream_logfunc(func):
def set_llm_stream_logfunc(func: Callable[[str], None]) -> None:
"""Set the function to be used for logging LLM streams."""
global _llm_stream_log
_llm_stream_log = func


_llm_stream_log = partial(print, end="")
_llm_stream_log: Callable[[str], None] = partial(print, end="")
8 changes: 4 additions & 4 deletions metagpt/software_company.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def startup(
run_tests: bool = typer.Option(default=False, help="Whether to enable QA for adding & running tests."),
implement: bool = typer.Option(default=True, help="Enable or disable code implementation."),
project_name: str = typer.Option(default="", help="Unique project name, such as 'game_2048'."),
inc: bool = typer.Option(default=False, help="Incremental mode. Use it to coop with existing repo."),
inc: bool = typer.Option(default=False, help="Incremental mode. Use it to cope with existing repo."),
project_path: str = typer.Option(
default="",
help="Specify the directory path of the old version project to fulfill the incremental requirements.",
Expand Down Expand Up @@ -135,16 +135,16 @@ def copy_config_to():
"""Initialize the configuration file for MetaGPT."""
target_path = CONFIG_ROOT / "config2.yaml"

# 创建目标目录(如果不存在)
# 创建目标目录(如果不存在)/ Create the target directory if it does not exist
target_path.parent.mkdir(parents=True, exist_ok=True)

# 如果目标文件已经存在,则重命名为 .bak
# 如果目标文件已经存在,则重命名为 .bak / If the target file already exists, rename it to .bak
if target_path.exists():
backup_path = target_path.with_suffix(".bak")
target_path.rename(backup_path)
print(f"Existing configuration file backed up at {backup_path}")

# 复制文件
# 复制文件 / Copy files
target_path.write_text(DEFAULT_CONFIG, encoding="utf-8")
print(f"Configuration file initialized at {target_path}")

Expand Down
21 changes: 14 additions & 7 deletions metagpt/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ def __init__(self, context: Context = None, **data: Any):
def serialize(self, stg_path: Path = None):
stg_path = SERDESER_PATH.joinpath("team") if stg_path is None else stg_path
team_info_path = stg_path.joinpath("team.json")
serialized_data = self.model_dump()
serialized_data["context"] = self.env.context.serialize()

write_json_file(team_info_path, self.model_dump())
write_json_file(team_info_path, serialized_data)

@classmethod
def deserialize(cls, stg_path: Path, context: Context = None) -> "Team":
Expand All @@ -71,6 +73,7 @@ def deserialize(cls, stg_path: Path, context: Context = None) -> "Team":

team_info: dict = read_json_file(team_info_path)
ctx = context or Context()
ctx.deserialize(team_info.pop("context", None))
team = Team(**team_info, context=ctx)
return team

Expand Down Expand Up @@ -116,21 +119,25 @@ def start_project(self, idea, send_to: str = ""):
)
return self.run_project(idea=idea, send_to=send_to)

def _save(self):
logger.info(self.model_dump_json())

@serialize_decorator
async def run(self, n_round=3, idea="", send_to="", auto_archive=True):
"""Run company until target round or no money"""
if idea:
self.run_project(idea=idea, send_to=send_to)

while n_round > 0:
# self._save()
if self.env.is_idle:
logger.debug("All roles are idle.")
break
n_round -= 1
logger.debug(f"max {n_round=} left.")
self._check_balance()
try:
self._check_balance()
except NoMoneyException as e:
logger.error(f"Project stopped due to insufficient funds: {e}")
break

await self.env.run()

logger.debug(f"max {n_round=} left.")
self.env.archive(auto_archive)
return self.env.history
Loading