π The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
serdeser rebase from main
better629dd640991b719
diff --cc metagpt/actions/action.pyindex 8b28ffd8e,692a2a6e5..c941d44b6--- a/metagpt/actions/action.py+++ b/metagpt/actions/action.py@@@ -64,11 -62,10 +64,10 @@@ class Action(BaseModel)"""Set prefix for later usage"""self.prefix = prefixself.profile = profile- return self-+def __str__(self):return self.__class__.__name__-+def __repr__(self):return self.__str__()diff --cc metagpt/actions/design_api.pyindex 504328582,015678baa..a13c5873a--- a/metagpt/actions/design_api.py+++ b/metagpt/actions/design_api.py@@@ -4,18 -4,14 +4,23 @@@@Time : 2023/5/11 19:26@Author : alexanderwu@File : design_api.py+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.3 of RFC 135, add incremental iteration functionality.+@Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD."""-import shutil+import jsonfrom pathlib import Path+from typing import Optional+from pydantic import Field++from metagpt.actions import Action, ActionOutput+from metagpt.actions.design_api_an import DESIGN_API_NODE+ from typing import List, Optional, Any++ from pydantic import Field++ from metagpt.actions import Action, ActionOutputfrom metagpt.llm import LLMfrom metagpt.provider.base_gpt_api import BaseGPTAPIfrom metagpt.config import CONFIGdiff --cc metagpt/actions/write_code_review.pyindex 83225060a,79e462f76..636f3f12a--- a/metagpt/actions/write_code_review.py+++ b/metagpt/actions/write_code_review.py@@@ -4,20 -4,14 +4,23 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : write_code_review.py+@Modified By: mashenquan, 2023/11/27. Following the think-act principle, solidify the task parameters when creating the+ WriteCode object, rather than passing them in when calling the run function."""+ from typing import List, Optional, Any+ from pydantic import Field+ from tenacity import retry, stop_after_attempt, wait_fixed+from typing import List, Optional, Any+from pydantic import Field+from tenacity import retry, stop_after_attempt, wait_random_exponential++from metagpt.actions import WriteCodefrom metagpt.llm import LLMfrom metagpt.actions.action import Action+from metagpt.config import CONFIGfrom metagpt.logs import logger+from metagpt.schema import CodingContextfrom metagpt.provider.base_gpt_api import BaseGPTAPIfrom metagpt.utils.common import CodeParserdiff --cc metagpt/const.pyindex 9cf9726fc,4b063a3dd..3b4f2ae4b--- a/metagpt/const.py+++ b/metagpt/const.py@@@ -55,49 -42,8 +55,50 @@@ DATA_PATH = METAGPT_ROOT / "dataRESEARCH_PATH = DATA_PATH / "research"TUTORIAL_PATH = DATA_PATH / "tutorial_docx"INVOICE_OCR_TABLE_PATH = DATA_PATH / "invoice_table"-SERDESER_PATH = WORKSPACE_ROOT / "storage" # TODO to store `storage` under the individual generated project+-SKILL_DIRECTORY = PROJECT_ROOT / "metagpt/skills"+UT_PATH = DATA_PATH / "ut"+SWAGGER_PATH = UT_PATH / "files/api/"+UT_PY_PATH = UT_PATH / "files/ut/"+API_QUESTIONS_PATH = UT_PATH / "files/question/"++SERDESER_PATH = DEFAULT_WORKSPACE_ROOT / "storage" # TODO to store `storage` under the individual generated project++TMP = METAGPT_ROOT / "tmp"++SOURCE_ROOT = METAGPT_ROOT / "metagpt"+PROMPT_PATH = SOURCE_ROOT / "prompts"+SKILL_DIRECTORY = SOURCE_ROOT / "skills"+++# REAL CONSTSMEM_TTL = 24 * 30 * 3600+++MESSAGE_ROUTE_FROM = "sent_from"+MESSAGE_ROUTE_TO = "send_to"+MESSAGE_ROUTE_CAUSE_BY = "cause_by"+MESSAGE_META_ROLE = "role"+MESSAGE_ROUTE_TO_ALL = "<all>"+MESSAGE_ROUTE_TO_NONE = "<none>"++REQUIREMENT_FILENAME = "requirement.txt"+BUGFIX_FILENAME = "bugfix.txt"+PACKAGE_REQUIREMENTS_FILENAME = "requirements.txt"++DOCS_FILE_REPO = "docs"+PRDS_FILE_REPO = "docs/prds"+SYSTEM_DESIGN_FILE_REPO = "docs/system_design"+TASK_FILE_REPO = "docs/tasks"+COMPETITIVE_ANALYSIS_FILE_REPO = "resources/competitive_analysis"+DATA_API_DESIGN_FILE_REPO = "resources/data_api_design"+SEQ_FLOW_FILE_REPO = "resources/seq_flow"+SYSTEM_DESIGN_PDF_FILE_REPO = "resources/system_design"+PRD_PDF_FILE_REPO = "resources/prd"+TASK_PDF_FILE_REPO = "resources/api_spec_and_tasks"+TEST_CODES_FILE_REPO = "tests"+TEST_OUTPUTS_FILE_REPO = "test_outputs"+CODE_SUMMARIES_FILE_REPO = "docs/code_summaries"+CODE_SUMMARIES_PDF_FILE_REPO = "resources/code_summaries"++YAPI_URL = "http://yapi.deepwisdomai.com/"diff --cc metagpt/memory/longterm_memory.pyindex e8a5be395,5d149ee7a..d36188f0c--- a/metagpt/memory/longterm_memory.py+++ b/metagpt/memory/longterm_memory.py@@@ -1,12 -1,10 +1,15 @@@#!/usr/bin/env python# -*- coding: utf-8 -*--# @Desc : the implement of Long-term memory+"""+@Desc : the implement of Long-term memory+"""++from typing import Optional+from pydantic import Field+ from typing import Optional+ from pydantic import Field+from metagpt.logs import loggerfrom metagpt.memory import Memoryfrom metagpt.memory.memory_storage import MemoryStoragediff --cc metagpt/memory/memory.pyindex adef0d283,ed30cde18..b647198e3--- a/metagpt/memory/memory.py+++ b/metagpt/memory/memory.py@@@ -8,7 -7,7 +8,8 @@@"""import copyfrom collections import defaultdict-from typing import Iterable, Type, Union, Optional+++from typing import Iterable, Type, Union, Optional, Setfrom pathlib import Pathfrom pydantic import BaseModel, Fieldimport jsondiff --cc metagpt/roles/architect.pyindex 377531c8d,09d52edbe..266ffc256--- a/metagpt/roles/architect.py+++ b/metagpt/roles/architect.py@@@ -22,13 -22,15 +22,14 @@@ class Architect(Role)goal (str): Primary goal or responsibility of the architect.constraints (str): Constraints or guidelines for the architect."""- name: str = Field(default="Bob")- profile: str = Field(default="Architect")- goal: str = "Design a concise, usable, complete python system"- constraints: str = "Try to specify good open source tools as much as possible"+- def __init__(- self,- **kwargs- ) -> None:+ name: str = "Bob"+ profile: str = Field(default="Architect", alias='profile')+ goal: str = "design a concise, usable, complete software system"+ constraints: str = "make sure the architecture is simple enough and use appropriate open source libraries." \+ "Use same language as user requirement"++ def __init__(self, **kwargs) -> None:super().__init__(**kwargs)# Initialize actions specific to the Architect roleself._init_actions([WriteDesign])diff --cc metagpt/roles/engineer.pyindex 59ca18a17,e90f586f0..ad3d0f66a--- a/metagpt/roles/engineer.py+++ b/metagpt/roles/engineer.py@@@ -4,57 -4,47 +4,56 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : engineer.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.2.1 and 2.2.2 of RFC 116:+ 1. Modify the data type of the `cause_by` value in the `Message` to a string, and utilize the new message+ distribution feature for message filtering.+ 2. Consolidate message reception and processing logic within `_observe`.+ 3. Fix bug: Add logic for handling asynchronous message processing when messages are not ready.+ 4. Supplemented the external transmission of internal messages.+@Modified By: mashenquan, 2023-11-27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.5 of RFC 135, add incremental iteration functionality.+@Modified By: mashenquan, 2023-12-5. Enhance the workflow to navigate to WriteCode or QaEngineer based on the results+ of SummarizeCode."""-import asyncio-import shutil-from collections import OrderedDict-from pathlib import Path++from __future__ import annotationsfrom pydantic import Field+import json+from collections import defaultdict+from pathlib import Path+from typing import Set-from metagpt.actions import WriteCode, WriteCodeReview, WriteDesign, WriteTasks-from metagpt.const import WORKSPACE_ROOT+from metagpt.actions import Action, WriteCode, WriteCodeReview, WriteTasks+from metagpt.actions.fix_bug import FixBug+from metagpt.actions.summarize_code import SummarizeCode+from metagpt.config import CONFIG+from metagpt.const import (+ CODE_SUMMARIES_FILE_REPO,+ CODE_SUMMARIES_PDF_FILE_REPO,+ SYSTEM_DESIGN_FILE_REPO,+ TASK_FILE_REPO,+)from metagpt.logs import logger-from metagpt.roles.role import Role-from metagpt.schema import Message-from metagpt.utils.common import CodeParser-from metagpt.utils.special_tokens import FILENAME_CODE_SEP, MSG_SEP+from metagpt.roles import Role+from metagpt.schema import (+ CodeSummarizeContext,+ CodingContext,+ Document,+ Documents,+ Message,+)+from metagpt.utils.common import any_to_str, any_to_str_set-async def gather_ordered_k(coros, k) -> list:- tasks = OrderedDict()- results = [None] * len(coros)- done_queue = asyncio.Queue()-- for i, coro in enumerate(coros):- if len(tasks) >= k:- done, _ = await asyncio.wait(tasks.keys(), return_when=asyncio.FIRST_COMPLETED)- for task in done:- index = tasks.pop(task)- await done_queue.put((index, task.result()))- task = asyncio.create_task(coro)- tasks[task] = i-- if tasks:- done, _ = await asyncio.wait(tasks.keys())- for task in done:- index = tasks[task]- await done_queue.put((index, task.result()))-- while not done_queue.empty():- index, result = await done_queue.get()- results[index] = result-- return results+IS_PASS_PROMPT = """+{context}+- <<<<<<< HEAD+----+Does the above log indicate anything that needs to be done?+If there are any tasks to be completed, please answer 'NO' along with the to-do list in JSON format;+otherwise, answer 'YES' in JSON format.+"""class Engineer(Role):diff --cc metagpt/roles/project_manager.pyindex b7ee1ed53,c8e785d85..d885f2ee6--- a/metagpt/roles/project_manager.py+++ b/metagpt/roles/project_manager.py@@@ -25,11 -25,13 +25,12 @@@ class ProjectManager(Role)name: str = Field(default="Eve")profile: str = Field(default="Project Manager")- goal: str = "Improve team efficiency and deliver with quality and quantity"- constraints: str = ""+- def __init__(- self,- **kwargs- ) -> None:+ goal: str = "reak down tasks according to PRD/technical design, generate a task list, and analyze task " \+ "dependencies to start with the prerequisite modules"+ constraints: str = "use same language as user requirement"++ def __init__(self, **kwargs) -> None:super().__init__(**kwargs)self._init_actions([WriteTasks])self._watch([WriteDesign])diff --cc metagpt/roles/role.pyindex e63404939,5b998bf9a..bed5a38e7--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -175,7 -138,7 +175,7 @@@ class _RoleInjector(type)role_subclass_registry = {}--class Role(BaseModel):++class Role(BaseModel, metaclass=_RoleInjector):"""Role/Agent"""name: str = ""profile: str = ""@@@ -189,65 -152,63 +189,121 @@@_states: list[str] = Field(default=[])_actions: list[Action] = Field(default=[])_rc: RoleContext = Field(default=RoleContext)+ _subscription: tuple = set()++ # builtin variables+ recovered: bool = False # to tag if a recovered role+ builtin_class_name: str = ""++ _private_attributes = {+ "_llm": LLM() if not is_human else HumanProvider(),+ "_role_id": _role_id,+ "_states": [],+ "_actions": [],+ "_rc": RoleContext()+ }++ class Config:+ arbitrary_types_allowed = True+ exclude = ["_llm"]++ def __init__(self, **kwargs: Any):+ for index in range(len(kwargs.get("_actions", []))):+ current_action = kwargs["_actions"][index]+ if isinstance(current_action, dict):+ item_class_name = current_action.get("builtin_class_name", None)+ for name, subclass in action_subclass_registry.items():+ registery_class_name = subclass.__fields__["builtin_class_name"].default+ if item_class_name == registery_class_name:+ current_action = subclass(**current_action)+ break+ kwargs["_actions"][index] = current_action++ super().__init__(**kwargs)++ # ε ³δΊη§ζειηεε§ε https://github.com/pydantic/pydantic/issues/655+ self._private_attributes["_llm"] = LLM() if not self.is_human else HumanProvider()+ self._private_attributes["_role_id"] = str(self._setting)+ self._subscription = {any_to_str(self), name} if name else {any_to_str(self)}++ for key in self._private_attributes.keys():+ if key in kwargs:+ object.__setattr__(self, key, kwargs[key])+ if key == "_rc":+ _rc = RoleContext(**kwargs["_rc"])+ object.__setattr__(self, "_rc", _rc)+ else:+ if key == "_rc":+ # # Warning, if use self._private_attributes["_rc"],+ # # self._rc will be a shared object between roles, so init one or reset it inside `_reset`+ object.__setattr__(self, key, RoleContext())+ else:+ object.__setattr__(self, key, self._private_attributes[key])++ # deserialize child classes dynamically for inherited `role`+ object.__setattr__(self, "builtin_class_name", self.__class__.__name__)+ self.__fields__["builtin_class_name"].default = self.__class__.__name__++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ role_subclass_registry[cls.__name__] = cls+ # builtin variables+ recovered: bool = False # to tag if a recovered role+ builtin_class_name: str = ""++ _private_attributes = {+ "_llm": LLM() if not is_human else HumanProvider(),+ "_role_id": _role_id,+ "_states": [],+ "_actions": [],+ "_rc": RoleContext()+ }++ class Config:+ arbitrary_types_allowed = True+ exclude = ["_llm"]++ def __init__(self, **kwargs: Any):+ for index in range(len(kwargs.get("_actions", []))):+ current_action = kwargs["_actions"][index]+ if isinstance(current_action, dict):+ item_class_name = current_action.get("builtin_class_name", None)+ for name, subclass in action_subclass_registry.items():+ registery_class_name = subclass.__fields__["builtin_class_name"].default+ if item_class_name == registery_class_name:+ current_action = subclass(**current_action)+ break+ kwargs["_actions"][index] = current_action++ super().__init__(**kwargs)++ # ε ³δΊη§ζειηεε§ε https://github.com/pydantic/pydantic/issues/655+ self._private_attributes["_llm"] = LLM() if not self.is_human else HumanProvider()+ self._private_attributes["_role_id"] = str(self._setting)++ for key in self._private_attributes.keys():+ if key in kwargs:+ object.__setattr__(self, key, kwargs[key])+ if key == "_rc":+ _rc = RoleContext(**kwargs["_rc"])+ object.__setattr__(self, "_rc", _rc)+ else:+ if key == "_rc":+ # # Warning, if use self._private_attributes["_rc"],+ # # self._rc will be a shared object between roles, so init one or reset it inside `_reset`+ object.__setattr__(self, key, RoleContext())+ else:+ object.__setattr__(self, key, self._private_attributes[key])++ # deserialize child classes dynamically for inherited `role`+ object.__setattr__(self, "builtin_class_name", self.__class__.__name__)+ self.__fields__["builtin_class_name"].default = self.__class__.__name__++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ role_subclass_registry[cls.__name__] = cls+def _reset(self):object.__setattr__(self, "_states", [])object.__setattr__(self, "_actions", [])@@@ -574,16 -471,8 +630,16 @@@# If there is no new information, suspend and waitlogger.debug(f"{self._setting}: no news. waiting.")return-+rsp = await self.react()- # Publish the reply to the environment, waiting for the next subscriber to process- self._publish_message(rsp)++ # Reset the next action to be taken.+ self._rc.todo = None+ # Send the response message to the Environment object to have it relay the message to the subscribers.+ self.publish_message(rsp)return rsp++ @property+ def is_idle(self) -> bool:+ """If true, all actions have been executed."""+ return not self._rc.news and not self._rc.todo and self._rc.msg_buffer.empty()diff --cc metagpt/schema.pyindex 15dfb579c,3a5bea7e9..962850547--- a/metagpt/schema.py+++ b/metagpt/schema.py@@@ -29,90 -12,25 +29,94 @@@ from typing import Type, TypedDict, Unifrom pydantic import BaseModel, Fieldfrom pydantic.main import ModelMetaclass+from metagpt.config import CONFIG+from metagpt.const import (+ MESSAGE_ROUTE_CAUSE_BY,+ MESSAGE_ROUTE_FROM,+ MESSAGE_ROUTE_TO,+ MESSAGE_ROUTE_TO_ALL,+ SYSTEM_DESIGN_FILE_REPO,+ TASK_FILE_REPO,+)from metagpt.logs import logger+ from metagpt.utils.serialize import actionoutout_schema_to_mapping, actionoutput_mapping_to_str, \+ actionoutput_str_to_mapping+ from metagpt.utils.utils import import_class+from metagpt.utils.common import any_to_str, any_to_str_set+# from metagpt.utils.serialize import actionoutout_schema_to_mapping+# from metagpt.actions.action_output import ActionOutput+# from metagpt.actions.action import Action++from metagpt.utils.serialize import actionoutout_schema_to_mapping, actionoutput_mapping_to_str, \+ actionoutput_str_to_mapping+from metagpt.utils.utils import import_class+class RawMessage(TypedDict):content: strrole: str-class Message(BaseModel):+++class Document(BaseModel):+ """+ Represents a document.+ """++ root_path: str = ""+ filename: str = ""content: str = ""++ def get_meta(self) -> "Document":+ """Get metadata of the document.++ :return: A new Document instance with the same root path and filename.+ """++ return Document(root_path=self.root_path, filename=self.filename)++ @property+ def root_relative_path(self):+ """Get relative path from root of git repository.++ :return: relative path from root of git repository.+ """+ return os.path.join(self.root_path, self.filename)++ @property+ def full_path(self):+ if not CONFIG.git_repo:+ return None+ return str(CONFIG.git_repo.workdir / self.root_path / self.filename)++ def __str__(self):+ return self.content++ def __repr__(self):+ return self.content+++class Documents(BaseModel):+ """A class representing a collection of documents.++ Attributes:+ docs (Dict[str, Document]): A dictionary mapping document names to Document instances.+ """++ docs: Dict[str, Document] = Field(default_factory=dict)+++class Message(BaseModel):+ """list[<role>: <content>]"""++ id: str # According to Section 2.2.3.1.1 of RFC 135+ content: strinstruct_content: BaseModel = Field(default=None)role: str = "user" # system / user / assistant- cause_by: Type["Action"] = Field(default=None)+ cause_by: str = ""sent_from: str = ""- send_to: str = ""- restricted_to: str = ""+ send_to: Set = Field(default_factory={MESSAGE_ROUTE_TO_ALL})def __init__(self, **kwargs):instruct_content = kwargs.get("instruct_content", None)diff --cc metagpt/team.pyindex 87a6766f6,795019b92..bd02508c4--- a/metagpt/team.py+++ b/metagpt/team.py@@@ -97,9 -89,7 +97,10 @@@ class Team(BaseModel)while n_round > 0:# self._save()n_round -= 1- logger.debug(f"{n_round=}")+ logger.debug(f"max {n_round=} left.")self._check_balance()- await self.environment.run()- return self.environment.history+++ await self.env.run()+ if CONFIG.git_repo:+ CONFIG.git_repo.archive()+ return self.env.historydiff --cc metagpt/utils/utils.pyindex 33ca16944,c1416c352..35df654d7--- a/metagpt/utils/utils.py+++ b/metagpt/utils/utils.py@@@ -7,24 -6,11 +7,27 @@@ from typing import Animport jsonfrom pathlib import Pathimport importlib+from tenacity import _utils+ import traceback++ from metagpt.logs import logger+def general_after_log(logger: "loguru.Logger", sec_format: str = "%0.3f") -> typing.Callable[["RetryCallState"], None]:+ def log_it(retry_state: "RetryCallState") -> None:+ if retry_state.fn is None:+ fn_name = "<unknown>"+ else:+ fn_name = _utils.get_callback_name(retry_state.fn)+ logger.error(+ f"Finished call to '{fn_name}' after {sec_format % retry_state.seconds_since_start}(s), "+ f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it. "+ f"exp: {retry_state.outcome.exception()}"+ )++ return log_it++def read_json_file(json_file: str, encoding=None) -> list[Any]:if not Path(json_file).exists():raise FileNotFoundError(f"json_file: {json_file} not exist, return []")diff --cc tests/metagpt/test_environment.pyindex 8aacdd77b,9f69e6189..ee322368e--- a/tests/metagpt/test_environment.py+++ b/tests/metagpt/test_environment.py@@@ -61,8 -60,7 +61,9 @@@ async def test_publish_and_process_messconstraints="θ΅ζΊζιοΌιθ¦θηζζ¬")env.add_roles([product_manager, architect])- env.publish_message(Message(role="BOSS", content="ιθ¦δΈδΈͺεΊδΊLLMεζ»η»ηζη΄’εΌζ", cause_by=BossRequirement))+++ env.set_manager(Manager())+ env.publish_message(Message(role="User", content="ιθ¦δΈδΈͺεΊδΊLLMεζ»η»ηζη΄’εΌζ", cause_by=UserRequirement))await env.run(k=2)logger.info(f"{env.history=}")diff --cc tests/metagpt/test_schema.pyindex 5eea789ea,c70c93cfc..ca8b9043f--- a/tests/metagpt/test_schema.py+++ b/tests/metagpt/test_schema.py@@@ -4,25 -4,16 +4,31 @@@@Time : 2023/5/20 10:40@Author : alexanderwu@File : test_schema.py+@Modified By: mashenquan, 2023-11-1. In line with Chapter 2.2.1 and 2.2.2 of RFC 116, introduce unit tests for+ the utilization of the new feature of `Message` class."""++<<<<<<< HEAD+import json++import pytest++from metagpt.actions import Action++=======++>>>>>>> a69be36abf7beef1a989a707d1aa027948c07feefrom metagpt.schema import AIMessage, Message, SystemMessage, UserMessagefrom metagpt.actions.action_output import ActionOutputfrom metagpt.actions.write_code import WriteCodefrom metagpt.utils.serialize import serialize_general_message, deserialize_general_message++<<<<<<< HEAD+from metagpt.utils.common import get_class_name++=======++>>>>>>> a69be36abf7beef1a989a707d1aa027948c07feedef test_messages():- test_content = 'test_message'+ test_content = "test_message"msgs = [UserMessage(test_content),SystemMessage(test_content),