🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge geekan:cli-etc
莘权 马78548c2ddcae
diff --cc examples/agent_creator.pyindex 3618c0608,bcb9c0c1d..e724105a3--- a/examples/agent_creator.py+++ b/examples/agent_creator.py@@@ -2,16 -2,17 +2,17 @@@Filename: MetaGPT/examples/agent_creator.pyCreated Date: Tuesday, September 12th 2023, 3:28:37 pmAuthor: garylin2099-'''+"""import re-from metagpt.const import METAGPT_ROOT-from metagpt.config import CONFIGfrom metagpt.actions import Action- from metagpt.const import PROJECT_ROOT, WORKSPACE_ROOT++from metagpt.config import CONFIG++from metagpt.const import METAGPT_ROOT+from metagpt.logs import loggerfrom metagpt.roles import Rolefrom metagpt.schema import Message-from metagpt.logs import logger- with open(PROJECT_ROOT / "examples/build_customized_agent.py", "r") as f:+ with open(METAGPT_ROOT / "examples/build_customized_agent.py", "r") as f:# use official example script to guide AgentCreatorMULTI_ACTION_AGENT_CODE_EXAMPLE = f.read()@@@ -45,10 -47,10 +46,10 @@@ class CreateAgent(Action)@staticmethoddef parse_code(rsp):- pattern = r'```python(.*)```'+ pattern = r"```python(.*)```"match = re.search(pattern, rsp, re.DOTALL)code_text = match.group(1) if match else ""- with open(WORKSPACE_ROOT / "agent_created_agent.py", "w") as f:+ with open(CONFIG.workspace_path / "agent_created_agent.py", "w") as f:f.write(code_text)return code_textdiff --cc examples/build_customized_agent.pyindex ef274be8b,be34e5e5e..6805fd460--- a/examples/build_customized_agent.py+++ b/examples/build_customized_agent.py@@@ -9,13 -8,15 +9,14 @@@ import subprocesimport fire-from metagpt.llm import LLMfrom metagpt.actions import Action++from metagpt.llm import LLM+from metagpt.logs import loggerfrom metagpt.roles import Rolefrom metagpt.schema import Message-from metagpt.logs import logger-class SimpleWriteCode(Action):+class SimpleWriteCode(Action):PROMPT_TEMPLATE = """Write a python function that can {instruction} and provide two runnnable test cases.Return ```python your_code_here ``` with NO other texts,@@@ -74,13 -67,12 +66,11 @@@ class SimpleCoder(Role)async def _act(self) -> Message:logger.info(f"{self._setting}: ready to {self._rc.todo}")- todo = self._rc.todo- todo = self._rc.todo # todo will be SimpleWriteCode()--- msg = self._rc.memory.get()[-1] # retrieve the latest memory- instruction = msg.content- msg = self.get_memories(k=1)[0] # find the most recent messages++ todo = self._rc.todo # todo will be SimpleWriteCode()- code_text = await SimpleWriteCode().run(instruction)- msg = Message(content=code_text, role=self.profile, cause_by=todo)++ msg = self.get_memories(k=1)[0] # find the most recent messages+ code_text = await todo.run(msg.content)+ msg = Message(content=code_text, role=self.profile, cause_by=type(todo))return msg@@@ -107,18 -90,14 +88,14 @@@ class RunnableCoder(Role)async def _act(self) -> Message:logger.info(f"{self._setting}: ready to {self._rc.todo}")+ # By choosing the Action by order under the hood+ # todo will be first SimpleWriteCode() then SimpleRunCode()todo = self._rc.todo- msg = self._rc.memory.get()[-1]-- if isinstance(todo, SimpleWriteCode):- instruction = msg.content- result = await SimpleWriteCode().run(instruction)- elif isinstance(todo, SimpleRunCode):- code_text = msg.content- result = await SimpleRunCode().run(code_text)- msg = self.get_memories(k=1)[0] # find the most k recent messages++ msg = self.get_memories(k=1)[0] # find the most k recent messages+ result = await todo.run(msg.content)- msg = Message(content=result, role=self.profile, cause_by=todo)+ msg = Message(content=result, role=self.profile, cause_by=type(todo))self._rc.memory.add(msg)return msgdiff --cc examples/build_customized_multi_agents.pyindex 000000000,0df927e32..030a4b339mode 000000,100644..100644--- a/examples/build_customized_multi_agents.py+++ b/examples/build_customized_multi_agents.py@@@ -1,0 -1,158 +1,155 @@@-'''++"""+ Filename: MetaGPT/examples/build_customized_multi_agents.py+ Created Date: Wednesday, November 15th 2023, 7:12:39 pm+ Author: garylin2099-'''++"""+ import re-import asyncio+++ import fire+++from metagpt.actions import Action, UserRequirement+ from metagpt.llm import LLM-from metagpt.actions import Action, BossRequirement++from metagpt.logs import logger+ from metagpt.roles import Role-from metagpt.team import Team+ from metagpt.schema import Message-from metagpt.logs import logger++from metagpt.team import Team++++ def parse_code(rsp):- pattern = r'```python(.*)```'++ pattern = r"```python(.*)```"+ match = re.search(pattern, rsp, re.DOTALL)+ code_text = match.group(1) if match else rsp+ return code_text+-class SimpleWriteCode(Action):+++class SimpleWriteCode(Action):+ PROMPT_TEMPLATE = """+ Write a python function that can {instruction}.+ Return ```python your_code_here ``` with NO other texts,+ your code:+ """++ def __init__(self, name: str = "SimpleWriteCode", context=None, llm: LLM = None):+ super().__init__(name, context, llm)++ async def run(self, instruction: str):-+ prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)++ rsp = await self._aask(prompt)++ code_text = parse_code(rsp)++ return code_text+++ class SimpleCoder(Role):+ def __init__(+ self,+ name: str = "Alice",+ profile: str = "SimpleCoder",+ **kwargs,+ ):+ super().__init__(name, profile, **kwargs)- self._watch([BossRequirement])++ self._watch([UserRequirement])+ self._init_actions([SimpleWriteCode])+++ class SimpleWriteTest(Action):-+ PROMPT_TEMPLATE = """+ Context: {context}+ Write {k} unit tests using pytest for the given function, assuming you have imported it.+ Return ```python your_code_here ``` with NO other texts,+ your code:+ """++ def __init__(self, name: str = "SimpleWriteTest", context=None, llm: LLM = None):+ super().__init__(name, context, llm)++ async def run(self, context: str, k: int = 3):-+ prompt = self.PROMPT_TEMPLATE.format(context=context, k=k)++ rsp = await self._aask(prompt)++ code_text = parse_code(rsp)++ return code_text+++ class SimpleTester(Role):+ def __init__(+ self,+ name: str = "Bob",+ profile: str = "SimpleTester",+ **kwargs,+ ):+ super().__init__(name, profile, **kwargs)+ self._init_actions([SimpleWriteTest])+ # self._watch([SimpleWriteCode])- self._watch([SimpleWriteCode, SimpleWriteReview]) # feel free to try this too++ self._watch([SimpleWriteCode, SimpleWriteReview]) # feel free to try this too++ async def _act(self) -> Message:+ logger.info(f"{self._setting}: ready to {self._rc.todo}")+ todo = self._rc.todo++ # context = self.get_memories(k=1)[0].content # use the most recent memory as context- context = self.get_memories() # use all memories as context++ context = self.get_memories() # use all memories as context+- code_text = await todo.run(context, k=5) # specify arguments++ code_text = await todo.run(context, k=5) # specify arguments+ msg = Message(content=code_text, role=self.profile, cause_by=type(todo))++ return msg+++ class SimpleWriteReview(Action):-+ PROMPT_TEMPLATE = """+ Context: {context}+ Review the test cases and provide one critical comments:+ """++ def __init__(self, name: str = "SimpleWriteReview", context=None, llm: LLM = None):+ super().__init__(name, context, llm)++ async def run(self, context: str):-+ prompt = self.PROMPT_TEMPLATE.format(context=context)++ rsp = await self._aask(prompt)++ return rsp+++ class SimpleReviewer(Role):+ def __init__(+ self,+ name: str = "Charlie",+ profile: str = "SimpleReviewer",+ **kwargs,+ ):+ super().__init__(name, profile, **kwargs)+ self._init_actions([SimpleWriteReview])+ self._watch([SimpleWriteTest])+++ async def main(+ idea: str = "write a function that calculates the product of a list",+ investment: float = 3.0,+ n_round: int = 5,+ add_human: bool = False,+ ):+ logger.info(idea)++ team = Team()+ team.hire(+ [+ SimpleCoder(),+ SimpleTester(),+ SimpleReviewer(is_human=add_human),+ ]+ )++ team.invest(investment=investment)+ team.start_project(idea)+ await team.run(n_round=n_round)+-if __name__ == '__main__':++++if __name__ == "__main__":+ fire.Fire(main)diff --cc examples/debate.pyindex 597b44e8d,e62a5aaa1..52f49e00e--- a/examples/debate.py+++ b/examples/debate.py@@@ -2,24 -2,19 +2,23 @@@Filename: MetaGPT/examples/debate.pyCreated Date: Tuesday, September 19th 2023, 6:52:25 pmAuthor: garylin2099-'''+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.1.3 of RFC 116, modify the data type of the `send_to`+ value of the `Message` object; modify the argument type of `get_by_actions`.+"""import asyncioimport platform+import fire- from metagpt.actions import Action, BossRequirement-from metagpt.team import Team+ from metagpt.actions import Action, UserRequirement+from metagpt.logs import loggerfrom metagpt.roles import Rolefrom metagpt.schema import Message- from metagpt.software_company import SoftwareCompany- from metagpt.utils.common import any_to_str-from metagpt.logs import logger++from metagpt.team import Team+- class ShoutOut(Action):- """Action: Shout out loudly in a debate (quarrel)"""+ class SpeakAloud(Action):+ """Action: Speak out aloud in a debate (quarrel)"""PROMPT_TEMPLATE = """## BACKGROUND@@@ -43,19 -39,19 +42,19 @@@return rsp+- class Trump(Role):+ class Debator(Role):def __init__(self,- name: str = "Trump",- profile: str = "Republican",+ name: str,+ profile: str,+ opponent_name: str,**kwargs,):super().__init__(name, profile, **kwargs)- self._init_actions([ShoutOut])- self._watch([ShoutOut])- self.name = "Trump"- self.opponent_name = "Biden"+ self._init_actions([SpeakAloud])+ self._watch([UserRequirement, SpeakAloud])- self.name = name+ self.opponent_name = opponent_nameasync def _observe(self) -> int:await super()._observe()@@@ -65,14 -61,13 +64,13 @@@async def _act(self) -> Message:logger.info(f"{self._setting}: ready to {self._rc.todo}")- todo = self._rc.todo # An instance of SpeakAloud++ todo = self._rc.todo # An instance of SpeakAloud- msg_history = self._rc.memory.get_by_actions([ShoutOut])- context = []- for m in msg_history:- context.append(str(m))- context = "\n".join(context)+ memories = self.get_memories()+ context = "\n".join(f"{msg.sent_from}: {msg.content}" for msg in memories)+ # print(context)- rsp = await ShoutOut().run(context=context, name=self.name, opponent_name=self.opponent_name)+ rsp = await todo.run(context=context, name=self.name, opponent_name=self.opponent_name)msg = Message(content=rsp,@@@ -81,64 -76,20 +79,20 @@@sent_from=self.name,send_to=self.opponent_name,)-+ self._rc.memory.add(msg)return msg+- class Biden(Role):- def __init__(- self,- name: str = "Biden",- profile: str = "Democrat",- **kwargs,- ):- super().__init__(name, profile, **kwargs)- self._init_actions([ShoutOut])- self._watch([BossRequirement, ShoutOut])- self.name = "Biden"- self.opponent_name = "Trump"-- async def _observe(self) -> int:- await super()._observe()- # accept the very first human instruction (the debate topic) or messages sent (from opponent) to self,- # disregard own messages from the last round- self._rc.news = [- msg for msg in self._rc.news if msg.cause_by == any_to_str(BossRequirement) or msg.send_to == {self.name}- ]- return len(self._rc.news)-- async def _act(self) -> Message:- logger.info(f"{self._setting}: ready to {self._rc.todo}")-- msg_history = self._rc.memory.get_by_actions([BossRequirement, ShoutOut])- context = []- for m in msg_history:- context.append(str(m))- context = "\n".join(context)-- rsp = await ShoutOut().run(context=context, name=self.name, opponent_name=self.opponent_name)-- msg = Message(- content=rsp,- role=self.profile,- cause_by=ShoutOut,- sent_from=self.name,- send_to=self.opponent_name,- )-- return msg--- async def startup(- idea: str, investment: float = 3.0, n_round: int = 5, code_review: bool = False, run_tests: bool = False- ):- """We reuse the startup paradigm for roles to interact with each other.- Now we run a startup of presidents and watch they quarrel. :)"""- company = SoftwareCompany()- company.hire([Biden(), Trump()])- company.invest(investment)- company.start_project(idea)- await company.run(n_round=n_round)+ async def debate(idea: str, investment: float = 3.0, n_round: int = 5):- """Run a team of presidents and watch they quarrel. :) """++ """Run a team of presidents and watch they quarrel. :)"""+ Biden = Debator(name="Biden", profile="Democrat", opponent_name="Trump")+ Trump = Debator(name="Trump", profile="Republican", opponent_name="Biden")+ team = Team()+ team.hire([Biden, Trump])+ team.invest(investment)- team.run_project(idea, send_to="Biden") # send debate topic to Biden and let him speak first++ team.run_project(idea, send_to="Biden") # send debate topic to Biden and let him speak first+ await team.run(n_round=n_round)def main(idea: str, investment: float = 3.0, n_round: int = 10):@@@ -151,8 -102,8 +105,8 @@@"""if platform.system() == "Windows":asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())- asyncio.run(startup(idea, investment, n_round))+ asyncio.run(debate(idea, investment, n_round))-if __name__ == '__main__':+if __name__ == "__main__":fire.Fire(main)diff --cc metagpt/actions/add_requirement.pyindex 16e14b3a4,8e2c56a62..d77d423ba--- a/metagpt/actions/add_requirement.py+++ b/metagpt/actions/add_requirement.py@@@ -8,8 -8,7 +8,8 @@@from metagpt.actions import Action- class BossRequirement(Action):- """Boss Requirement without any implementation details"""+ class UserRequirement(Action):+ """User Requirement without any implementation details"""+async def run(self, *args, **kwargs):raise NotImplementedErrordiff --cc metagpt/actions/debug_error.pyindex dd1527154,d69a22dba..e66eadeaa--- a/metagpt/actions/debug_error.py+++ b/metagpt/actions/debug_error.py@@@ -50,26 -28,24 +50,32 @@@ class DebugError(Action)def __init__(self, name="DebugError", context=None, llm=None):super().__init__(name, context, llm)- # async def run(self, code, error):- # prompt = f"Here is a piece of Python code:\n\n{code}\n\nThe following error occurred during execution:" \- # f"\n\n{error}\n\nPlease try to fix the error in this code."- # fixed_code = await self._aask(prompt)- # return fixed_code-- async def run(self, context):- if "PASS" in context:- return "", "the original code works fine, no need to debug"-- file_name = re.search("## File To Rewrite:\s*(.+\\.py)", context).group(1)-- logger.info(f"Debug and rewrite {file_name}")-- prompt = PROMPT_TEMPLATE.format(context=context)-- rsp = await self._aask(prompt)+ async def run(self, *args, **kwargs) -> str:- output_doc = await FileRepository.get_file(filename=self.context.output_filename, relative_path=TEST_OUTPUTS_FILE_REPO)++ output_doc = await FileRepository.get_file(++ filename=self.context.output_filename, relative_path=TEST_OUTPUTS_FILE_REPO++ )+ if not output_doc:+ return ""+ output_detail = RunCodeResult.loads(output_doc.content)+ pattern = r"Ran (\d+) tests in ([\d.]+)s\n\nOK"+ matches = re.search(pattern, output_detail.stderr)+ if matches:+ return ""+ logger.info(f"Debug and rewrite {self.context.code_filename}")- code_doc = await FileRepository.get_file(filename=self.context.code_filename, relative_path=CONFIG.src_workspace)++ code_doc = await FileRepository.get_file(++ filename=self.context.code_filename, relative_path=CONFIG.src_workspace++ )+ if not code_doc:+ return ""- test_doc = await FileRepository.get_file(filename=self.context.test_filename, relative_path=TEST_CODES_FILE_REPO)++ test_doc = await FileRepository.get_file(++ filename=self.context.test_filename, relative_path=TEST_CODES_FILE_REPO++ )+ if not test_doc:+ return ""+ prompt = PROMPT_TEMPLATE.format(code=code_doc.content, test_code=test_doc.content, logs=output_detail.stderr)++ rsp = await self._aask(prompt)code = CodeParser.parse_code(block="", text=rsp)- return file_name, code+ return codediff --cc metagpt/actions/design_api.pyindex f987c6042,9e2bfc12c..431879c25--- a/metagpt/actions/design_api.py+++ b/metagpt/actions/design_api.py@@@ -196,118 -156,60 +196,177 @@@ class WriteDesign(Action)"clearly and in detail.")- def recreate_workspace(self, workspace: Path):- try:- shutil.rmtree(workspace)- except FileNotFoundError:- pass # Folder does not exist, but we don't care- workspace.mkdir(parents=True, exist_ok=True)-- async def _save_prd(self, docs_path, resources_path, context):- prd_file = docs_path / "prd.md"- if context[-1].instruct_content and context[-1].instruct_content.dict()["Competitive Quadrant Chart"]:- quadrant_chart = context[-1].instruct_content.dict()["Competitive Quadrant Chart"]- await mermaid_to_file(quadrant_chart, resources_path / "competitive_analysis")-- if context[-1].instruct_content:- logger.info(f"Saving PRD to {prd_file}")- prd_file.write_text(context[-1].instruct_content.json(ensure_ascii=False), encoding='utf-8')-- async def _save_system_design(self, docs_path, resources_path, system_design):- data_api_design = system_design.instruct_content.dict()[- "Data structures and interfaces"- ] # CodeParser.parse_code(block="Data structures and interfaces", text=content)- seq_flow = system_design.instruct_content.dict()[- "Program call flow"- ] # CodeParser.parse_code(block="Program call flow", text=content)- await mermaid_to_file(data_api_design, resources_path / "data_api_design")- await mermaid_to_file(seq_flow, resources_path / "seq_flow")- system_design_file = docs_path / "system_design.md"- logger.info(f"Saving System Designs to {system_design_file}")- system_design_file.write_text(system_design.instruct_content.json(ensure_ascii=False), encoding='utf-8')-- async def _save(self, context, system_design):- if isinstance(system_design, ActionOutput):- project_name = system_design.instruct_content.dict()["project_name"]- else:- project_name = CodeParser.parse_str(block="project_name", text=system_design)- workspace = CONFIG.workspace_path / project_name- self.recreate_workspace(workspace)- docs_path = workspace / "docs"- resources_path = workspace / "resources"- docs_path.mkdir(parents=True, exist_ok=True)- resources_path.mkdir(parents=True, exist_ok=True)- await self._save_prd(docs_path, resources_path, context)- await self._save_system_design(docs_path, resources_path, system_design)-- async def run(self, context, format=CONFIG.prompt_format):+ async def run(self, with_messages, format=CONFIG.prompt_format):+ # Use `git diff` to identify which PRD documents have been modified in the `docs/prds` directory.+ prds_file_repo = CONFIG.git_repo.new_file_repository(PRDS_FILE_REPO)+ changed_prds = prds_file_repo.changed_files+ # Use `git diff` to identify which design documents in the `docs/system_designs` directory have undergone+ # changes.+ system_design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)+ changed_system_designs = system_design_file_repo.changed_files++ # For those PRDs and design documents that have undergone changes, regenerate the design content.+ changed_files = Documents()+ for filename in changed_prds.keys():+ doc = await self._update_system_design(+ filename=filename, prds_file_repo=prds_file_repo, system_design_file_repo=system_design_file_repo+ )+ changed_files.docs[filename] = doc++ for filename in changed_system_designs.keys():+ if filename in changed_files.docs:+ continue+ doc = await self._update_system_design(+ filename=filename, prds_file_repo=prds_file_repo, system_design_file_repo=system_design_file_repo+ )+ changed_files.docs[filename] = doc+ if not changed_files.docs:+ logger.info("Nothing has changed.")+ # Wait until all files under `docs/system_designs/` are processed before sending the publish message,+ # leaving room for global optimization in subsequent steps.+ return ActionOutput(content=changed_files.json(), instruct_content=changed_files)+++ # =======++ # def recreate_workspace(self, workspace: Path):++ # try:++ # shutil.rmtree(workspace)++ # except FileNotFoundError:++ # pass # Folder does not exist, but we don't care++ # workspace.mkdir(parents=True, exist_ok=True)++++ # async def _save_prd(self, docs_path, resources_path, context):++ # prd_file = docs_path / "prd.md"++ # if context[-1].instruct_content and context[-1].instruct_content.dict()["Competitive Quadrant Chart"]:++ # quadrant_chart = context[-1].instruct_content.dict()["Competitive Quadrant Chart"]++ # await mermaid_to_file(quadrant_chart, resources_path / "competitive_analysis")++ #++ # if context[-1].instruct_content:++ # logger.info(f"Saving PRD to {prd_file}")++ # prd_file.write_text(context[-1].instruct_content.json(ensure_ascii=False), encoding='utf-8')++++ # async def _save_system_design(self, docs_path, resources_path, system_design):++ # data_api_design = system_design.instruct_content.dict()[++ # "Data structures and interfaces"++ # ] # CodeParser.parse_code(block="Data structures and interfaces", text=content)++ # seq_flow = system_design.instruct_content.dict()[++ # "Program call flow"++ # ] # CodeParser.parse_code(block="Program call flow", text=content)++ # await mermaid_to_file(data_api_design, resources_path / "data_api_design")++ # await mermaid_to_file(seq_flow, resources_path / "seq_flow")++ # system_design_file = docs_path / "system_design.md"++ # logger.info(f"Saving System Designs to {system_design_file}")++ # system_design_file.write_text(system_design.instruct_content.json(ensure_ascii=False), encoding='utf-8')++++ # async def _save(self, context, system_design):++ # if isinstance(system_design, ActionOutput):++ # project_name = system_design.instruct_content.dict()["project_name"]++ # else:++ # project_name = CodeParser.parse_str(block="project_name", text=system_design)++ # workspace = CONFIG.workspace_path / project_name++ # self.recreate_workspace(workspace)++ # docs_path = workspace / "docs"++ # resources_path = workspace / "resources"++ # docs_path.mkdir(parents=True, exist_ok=True)++ # resources_path.mkdir(parents=True, exist_ok=True)++ # await self._save_prd(docs_path, resources_path, context)++ # await self._save_system_design(docs_path, resources_path, system_design)++++ # async def run(self, context, format=CONFIG.prompt_format):+++ async def _new_system_design(self, context, format=CONFIG.prompt_format):prompt_template, format_example = get_template(templates, format)prompt = prompt_template.format(context=context, format_example=format_example)# system_design = await self._aask(prompt)system_design = await self._aask_v1(prompt, "system_design", OUTPUT_MAPPING, format=format)- # fix Python package name, we can't system_design.instruct_content.python_package_name = "xxx" since "Python- # package name" contain space, have to use setattr- # fix project_name, we can't system_design.instruct_content.python_package_name = "xxx" since "project_name" contain space, have to use setattr- # setattr(- # system_design.instruct_content,- # "project_name",- # system_design.instruct_content.dict()["project_name"].strip().strip("'").strip('"'),- # )- await self._save(context, system_design)++++ # fix project_name, we can't system_design.instruct_content.python_package_name = "xxx" since "project_name"++ # contain space, have to use setattr+ setattr(+ system_design.instruct_content,- "Python package name",- system_design.instruct_content.dict()["Python package name"].strip().strip("'").strip('"'),++ "project_name",++ system_design.instruct_content.dict()["project_name"].strip().strip("'").strip('"'),+ )+ await self._rename_workspace(system_design)++ # =======++ # # fix project_name, we can't system_design.instruct_content.python_package_name = "xxx" since "project_name" contain space, have to use setattr++ # # setattr(++ # # system_design.instruct_content,++ # # "project_name",++ # # system_design.instruct_content.dict()["project_name"].strip().strip("'").strip('"'),++ # # )++ # await self._save(context, system_design)++ # >>>>>>> feature/geekan_cli_etcreturn system_design++ async def _merge(self, prd_doc, system_design_doc, format=CONFIG.prompt_format):+ prompt = MERGE_PROMPT.format(old_design=system_design_doc.content, context=prd_doc.content)+ system_design = await self._aask_v1(prompt, "system_design", OUTPUT_MAPPING, format=format)+ # fix Python package name, we can't system_design.instruct_content.python_package_name = "xxx" since "Python+ # package name" contain space, have to use setattr+ setattr(+ system_design.instruct_content,- "Python package name",- system_design.instruct_content.dict()["Python package name"].strip().strip("'").strip('"'),++ "project_name",++ system_design.instruct_content.dict()["project_name"].strip().strip("'").strip('"'),+ )- system_design_doc.content = system_design.instruct_content.json()++ system_design_doc.content = system_design.instruct_content.json(ensure_ascii=False)+ return system_design_doc++ @staticmethod+ async def _rename_workspace(system_design):+ if CONFIG.WORKDIR: # Updating on the old version has already been specified if it's valid.+ return++ if isinstance(system_design, ActionOutput):- ws_name = system_design.instruct_content.dict()["Python package name"]++ ws_name = system_design.instruct_content.dict()["project_name"]+ else:- ws_name = CodeParser.parse_str(block="Python package name", text=system_design)++ ws_name = CodeParser.parse_str(block="project_name", text=system_design)+ CONFIG.git_repo.rename_root(ws_name)++ async def _update_system_design(self, filename, prds_file_repo, system_design_file_repo) -> Document:+ prd = await prds_file_repo.get(filename)+ old_system_design_doc = await system_design_file_repo.get(filename)+ if not old_system_design_doc:+ system_design = await self._new_system_design(context=prd.content)+ doc = Document(- root_path=SYSTEM_DESIGN_FILE_REPO, filename=filename, content=system_design.instruct_content.json()++ root_path=SYSTEM_DESIGN_FILE_REPO,++ filename=filename,++ content=system_design.instruct_content.json(ensure_ascii=False),+ )+ else:+ doc = await self._merge(prd_doc=prd, system_design_doc=old_system_design_doc)+ await system_design_file_repo.save(+ filename=filename, content=doc.content, dependencies={prd.root_relative_path}+ )+ await self._save_data_api_design(doc)+ await self._save_seq_flow(doc)+ await self._save_pdf(doc)+ return doc++ @staticmethod+ async def _save_data_api_design(design_doc):+ m = json.loads(design_doc.content)+ data_api_design = m.get("Data structures and interface definitions")+ if not data_api_design:+ return+ pathname = CONFIG.git_repo.workdir / Path(DATA_API_DESIGN_FILE_REPO) / Path(design_doc.filename).with_suffix("")+ await WriteDesign._save_mermaid_file(data_api_design, pathname)+ logger.info(f"Save class view to {str(pathname)}")++ @staticmethod+ async def _save_seq_flow(design_doc):+ m = json.loads(design_doc.content)+ seq_flow = m.get("Program call flow")+ if not seq_flow:+ return+ pathname = CONFIG.git_repo.workdir / Path(SEQ_FLOW_FILE_REPO) / Path(design_doc.filename).with_suffix("")+ await WriteDesign._save_mermaid_file(seq_flow, pathname)+ logger.info(f"Saving sequence flow to {str(pathname)}")++ @staticmethod+ async def _save_pdf(design_doc):+ await FileRepository.save_as(doc=design_doc, with_suffix=".md", relative_path=SYSTEM_DESIGN_PDF_FILE_REPO)++ @staticmethod+ async def _save_mermaid_file(data: str, pathname: Path):+ pathname.parent.mkdir(parents=True, exist_ok=True)+ await mermaid_to_file(data, pathname)diff --cc metagpt/actions/project_management.pyindex 7205d11e7,805226a25..db856e55b--- a/metagpt/actions/project_management.py+++ b/metagpt/actions/project_management.py@@@ -4,21 -4,12 +4,26 @@@@Time : 2023/5/11 19:12@Author : alexanderwu@File : project_management.py+@Modified By: mashenquan, 2023/11/27.+ 1. Divide the context into three components: legacy code, unit test code, and console log.+ 2. Move the document storage operations related to WritePRD from the save operation of WriteDesign.+ 3. According to the design in Section 2.2.3.5.4 of RFC 135, add incremental iteration functionality."""+import jsonfrom typing import List+from metagpt.actions import ActionOutputfrom metagpt.actions.action import Actionfrom metagpt.config import CONFIG- from metagpt.const import SYSTEM_DESIGN_FILE_REPO, TASK_FILE_REPO, TASK_PDF_FILE_REPO, PACKAGE_REQUIREMENTS_FILENAME-from metagpt.utils.common import CodeParser++from metagpt.const import (++ PACKAGE_REQUIREMENTS_FILENAME,++ SYSTEM_DESIGN_FILE_REPO,++ TASK_FILE_REPO,++ TASK_PDF_FILE_REPO,++)+from metagpt.logs import logger+from metagpt.schema import Document, Documents+from metagpt.utils.file_repository import FileRepositoryfrom metagpt.utils.get_template import get_templatetemplates = {@@@ -202,82 -167,25 +210,99 @@@ class WriteTasks(Action)def __init__(self, name="CreateTasks", context=None, llm=None):super().__init__(name, context, llm)- def _save(self, context, rsp):- if context[-1].instruct_content:- ws_name = context[-1].instruct_content.dict()["project_name"]+ async def run(self, with_messages, format=CONFIG.prompt_format):+ system_design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)+ changed_system_designs = system_design_file_repo.changed_files++ tasks_file_repo = CONFIG.git_repo.new_file_repository(TASK_FILE_REPO)+ changed_tasks = tasks_file_repo.changed_files+ change_files = Documents()+ # Rewrite the system designs that have undergone changes based on the git head diff under+ # `docs/system_designs/`.+ for filename in changed_system_designs:+ task_doc = await self._update_tasks(+ filename=filename, system_design_file_repo=system_design_file_repo, tasks_file_repo=tasks_file_repo+ )+ change_files.docs[filename] = task_doc++ # Rewrite the task files that have undergone changes based on the git head diff under `docs/tasks/`.+ for filename in changed_tasks:+ if filename in change_files.docs:+ continue+ task_doc = await self._update_tasks(+ filename=filename, system_design_file_repo=system_design_file_repo, tasks_file_repo=tasks_file_repo+ )+ change_files.docs[filename] = task_doc++ if not change_files.docs:+ logger.info("Nothing has changed.")+ # Wait until all files under `docs/tasks/` are processed before sending the publish_message, leaving room for+ # global optimization in subsequent steps.+ return ActionOutput(content=change_files.json(), instruct_content=change_files)++ async def _update_tasks(self, filename, system_design_file_repo, tasks_file_repo):+ system_design_doc = await system_design_file_repo.get(filename)+ task_doc = await tasks_file_repo.get(filename)+ if task_doc:+ task_doc = await self._merge(system_design_doc=system_design_doc, task_doc=task_doc)else:- ws_name = CodeParser.parse_str(block="project_name", text=context[-1].content)- file_path = CONFIG.workspace_path / ws_name / "docs/api_spec_and_tasks.md"- file_path.write_text(rsp.instruct_content.json(ensure_ascii=False))-- # Write requirements.txt- requirements_path = CONFIG.workspace_path / ws_name / "requirements.txt"- requirements_path.write_text("\n".join(rsp.instruct_content.dict().get("Required Python third-party packages")))-- async def run(self, context, format=CONFIG.prompt_format):+ rsp = await self._run_new_tasks(context=system_design_doc.content)- task_doc = Document(root_path=TASK_FILE_REPO, filename=filename, content=rsp.instruct_content.json())++ task_doc = Document(++ root_path=TASK_FILE_REPO, filename=filename, content=rsp.instruct_content.json(ensure_ascii=False)++ )+ await tasks_file_repo.save(+ filename=filename, content=task_doc.content, dependencies={system_design_doc.root_relative_path}+ )+ await self._update_requirements(task_doc)+ await self._save_pdf(task_doc=task_doc)+ return task_doc++ async def _run_new_tasks(self, context, format=CONFIG.prompt_format):++ # =======++ # def _save(self, context, rsp):++ # if context[-1].instruct_content:++ # ws_name = context[-1].instruct_content.dict()["project_name"]++ # else:++ # ws_name = CodeParser.parse_str(block="project_name", text=context[-1].content)++ # file_path = CONFIG.workspace_path / ws_name / "docs/api_spec_and_tasks.md"++ # file_path.write_text(rsp.instruct_content.json(ensure_ascii=False))++ #++ # # Write requirements.txt++ # requirements_path = CONFIG.workspace_path / ws_name / "requirements.txt"++ # requirements_path.write_text("\n".join(rsp.instruct_content.dict().get("Required Python third-party packages")))++ #++ # async def run(self, context, format=CONFIG.prompt_format):++ # >>>>>>> feature/geekan_cli_etcprompt_template, format_example = get_template(templates, format)prompt = prompt_template.format(context=context, format_example=format_example)rsp = await self._aask_v1(prompt, "task", OUTPUT_MAPPING, format=format)- self._save(context, rsp)return rsp+ async def _merge(self, system_design_doc, task_doc, format=CONFIG.prompt_format) -> Document:+ prompt = MERGE_PROMPT.format(context=system_design_doc.content, old_tasks=task_doc.content)+ rsp = await self._aask_v1(prompt, "task", OUTPUT_MAPPING, format=format)- task_doc.content = rsp.instruct_content.json()++ task_doc.content = rsp.instruct_content.json(ensure_ascii=False)+ return task_doc++ @staticmethod+ async def _update_requirements(doc):+ m = json.loads(doc.content)+ packages = set(m.get("Required Python third-party packages", set()))+ file_repo = CONFIG.git_repo.new_file_repository()+ requirement_doc = await file_repo.get(filename=PACKAGE_REQUIREMENTS_FILENAME)+ if not requirement_doc:+ requirement_doc = Document(filename=PACKAGE_REQUIREMENTS_FILENAME, root_path=".", content="")+ lines = requirement_doc.content.splitlines()+ for pkg in lines:+ if pkg == "":+ continue+ packages.add(pkg)+ await file_repo.save(PACKAGE_REQUIREMENTS_FILENAME, content="\n".join(packages))++ @staticmethod+ async def _save_pdf(task_doc):+ await FileRepository.save_as(doc=task_doc, with_suffix=".md", relative_path=TASK_PDF_FILE_REPO)+class AssignTasks(Action):async def run(self, *args, **kwargs):diff --cc metagpt/actions/summarize_code.pyindex 000000000,a85d3cdeb..88a37536bmode 000000,100644..100644--- a/metagpt/actions/summarize_code.py+++ b/metagpt/actions/summarize_code.py@@@ -1,0 -1,92 +1,115 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ """+ @Author : alexanderwu+ @File : summarize_code.py+ """++ from tenacity import retry, stop_after_attempt, wait_fixed+++ from metagpt.actions.action import Action++from metagpt.config import CONFIG+ from metagpt.logs import logger-from metagpt.schema import Message++from metagpt.utils.file_repository import FileRepository++ PROMPT_TEMPLATE = """+ NOTICE+ Role: You are a professional software engineer, and your main task is to review the code.+ Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese.+ ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example".++ ------# Context-{context}++# System Design++```text++{system_design}++```++-----++# Tasks++```text++{tasks}++```+ -----++{code_blocks}++ ## Code Review All: 请你对历史所有文件进行阅读,在文件中找到可能的bug,如函数未实现、调用错误、未引用等++ ## Call flow: mermaid代码,根据实现的函数,使用mermaid绘制完整的调用链++ ## Summary: 根据历史文件的实现情况进行总结++ ## TODOs: Python dict[str, str],这里写出需要修改的文件列表与理由,我们会在之后进行修改++ """++ FORMAT_EXAMPLE = """++ ## Code Review All++ ### a.py+ - 它少实现了xxx需求...+ - 字段yyy没有给出...+ - ...++ ### b.py+ ...++ ### c.py+ ...++ ## Call flow+ ```mermaid+ flowchart TB+ c1-->a2+ subgraph one+ a1-->a2+ end+ subgraph two+ b1-->b2+ end+ subgraph three+ c1-->c2+ end+ ```++ ## Summary+ - a.py:...+ - b.py:...+ - c.py:...+ - ...++ ## TODOs+ {+ "a.py": "implement requirement xxx...",+ }++ """+++ class SummarizeCode(Action):- def __init__(self, name="SummarizeCode", context: list[Message] = None, llm=None):++ def __init__(self, name="SummarizeCode", context=None, llm=None):+ super().__init__(name, context, llm)++ @retry(stop=stop_after_attempt(2), wait=wait_fixed(1))+ async def summarize_code(self, prompt):+ code_rsp = await self._aask(prompt)+ return code_rsp+- async def run(self, context):++ async def run(self):++ design_doc = await FileRepository.get_file(self.context.design_filename)++ task_doc = await FileRepository.get_file(self.context.task_filename)++ src_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)++ code_blocks = []++ for filename in self.context.codes_filenames:++ code_doc = await src_file_repo.get(filename)++ code_block = f"```python\n{code_doc.content}\n```\n-----"++ code_blocks.append(code_block)+ format_example = FORMAT_EXAMPLE- prompt = PROMPT_TEMPLATE.format(context=context, format_example=format_example)++ prompt = PROMPT_TEMPLATE.format(++ system_design=design_doc.content,++ tasks=task_doc.content,++ code_blocks="\n".join(code_blocks),++ format_example=format_example,++ )+ logger.info("Summarize code..")+ rsp = await self.summarize_code(prompt)+ return rspdiff --cc metagpt/actions/write_code.pyindex 3a4ca7768,2631ec138..e373b1127--- a/metagpt/actions/write_code.py+++ b/metagpt/actions/write_code.py@@@ -4,26 -4,14 +4,26 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : write_code.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.1.3 of RFC 116, modify the data type of the `cause_by`+ value of the `Message` object.+@Modified By: mashenquan, 2023-11-27.+ 1. Mark the location of Design, Tasks, Legacy Code and Debug logs in the PROMPT_TEMPLATE with markdown+ code-block formatting to enhance the understanding for the LLM.+ 2. Following the think-act principle, solidify the task parameters when creating the WriteCode object, rather+ than passing them in when calling the run function.+ 3. Encapsulate the input of RunCode into RunCodeContext and encapsulate the output of RunCode into+ RunCodeResult to standardize and unify parameter passing between WriteCode, RunCode, and DebugError."""+++from tenacity import retry, stop_after_attempt, wait_fixed-from metagpt.actions import WriteDesign+from metagpt.actions.action import Action--from metagpt.config import CONFIG+from metagpt.const import TEST_OUTPUTS_FILE_REPOfrom metagpt.logs import logger-from metagpt.schema import Message+from metagpt.schema import CodingContext, RunCodeResultfrom metagpt.utils.common import CodeParser+from metagpt.utils.file_repository import FileRepositoryPROMPT_TEMPLATE = """NOTICE@@@ -38,28 -32,9 +44,30 @@@ ATTENTION: Use '##' to SPLIT SECTIONS,5. Think before writing: What should be implemented and provided in this document?6. CAREFULLY CHECK THAT YOU DONT MISS ANY NECESSARY CLASS/FUNCTION IN THIS FILE.7. Do not use public member functions that do not exist in your design.+ 8. Before using a variable, make sure you reference it first+ 9. Write out EVERY DETAIL, DON'T LEAVE TODO.+-----+# Design+```json+{design}+```+-----+# Tasks+```json+{tasks}+```+-----+# Legacy Code+```python+{code}+```+-----+# Debug logs+```text+{logs}+```+-----## Format example-----## Code: {filename}@@@ -72,31 -47,40 +80,55 @@@class WriteCode(Action):- def __init__(self, name="WriteCode", context: list[Message] = None, llm=None):+ def __init__(self, name="WriteCode", context=None, llm=None):super().__init__(name, context, llm)- def _is_invalid(self, filename):- return any(i in filename for i in ["mp3", "wav"])-- def _save(self, context, filename, code):- # logger.info(filename)- # logger.info(code_rsp)- if self._is_invalid(filename):- return-- design = [i for i in context if i.cause_by == WriteDesign][0]-- ws_name = CodeParser.parse_str(block="project_name", text=design.content)- ws_path = CONFIG.workspace_path / ws_name- if f"{ws_name}/" not in filename and all(i not in filename for i in ["requirements.txt", ".md"]):- ws_path = ws_path / ws_name- code_path = ws_path / filename- code_path.parent.mkdir(parents=True, exist_ok=True)- code_path.write_text(code)- logger.info(f"Saving Code to {code_path}")-++ # <<<<<<< HEAD++ # =======++ # def _is_invalid(self, filename):++ # return any(i in filename for i in ["mp3", "wav"])++ #++ # def _save(self, context, filename, code):++ # # logger.info(filename)++ # # logger.info(code_rsp)++ # if self._is_invalid(filename):++ # return++ #++ # design = [i for i in context if i.cause_by == WriteDesign][0]++ #++ # ws_name = CodeParser.parse_str(block="project_name", text=design.content)++ # ws_path = CONFIG.workspace_path / ws_name++ # if f"{ws_name}/" not in filename and all(i not in filename for i in ["requirements.txt", ".md"]):++ # ws_path = ws_path / ws_name++ # code_path = ws_path / filename++ # code_path.parent.mkdir(parents=True, exist_ok=True)++ # code_path.write_text(code)++ # logger.info(f"Saving Code to {code_path}")++ #++ # >>>>>>> feature/geekan_cli_etc@retry(stop=stop_after_attempt(2), wait=wait_fixed(1))- async def write_code(self, prompt):+ async def write_code(self, prompt) -> str:code_rsp = await self._aask(prompt)code = CodeParser.parse_code(block="", text=code_rsp)return code- async def run(self, context, filename):- prompt = PROMPT_TEMPLATE.format(context=context, filename=filename)- logger.info(f'Writing {filename}..')+ async def run(self, *args, **kwargs) -> CodingContext:+ coding_context = CodingContext.loads(self.context.content)- test_doc = await FileRepository.get_file(filename="test_" + coding_context.filename + ".json",- relative_path=TEST_OUTPUTS_FILE_REPO)++ test_doc = await FileRepository.get_file(++ filename="test_" + coding_context.filename + ".json", relative_path=TEST_OUTPUTS_FILE_REPO++ )+ logs = ""+ if test_doc:+ test_detail = RunCodeResult.loads(test_doc.content)+ logs = test_detail.stderr+ prompt = PROMPT_TEMPLATE.format(+ design=coding_context.design_doc.content,+ tasks=coding_context.task_doc.content,+ code=coding_context.code_doc.content,+ logs=logs,+ filename=self.context.filename,+ )+ logger.info(f"Writing {coding_context.filename}..")code = await self.write_code(prompt)- # code_rsp = await self._aask_v1(prompt, "code_rsp", OUTPUT_MAPPING)- # self._save(context, filename, code)- return code-+ coding_context.code_doc.content = code+ return coding_contextdiff --cc metagpt/actions/write_code_review.pyindex dae1c965f,aebe3f4fa..6d405029a--- a/metagpt/actions/write_code_review.py+++ b/metagpt/actions/write_code_review.py@@@ -9,11 -7,11 +9,12 @@@"""from tenacity import retry, stop_after_attempt, wait_fixed+from metagpt.actions.action import Action++from metagpt.config import CONFIGfrom metagpt.logs import logger-from metagpt.schema import Message+from metagpt.schema import CodingContextfrom metagpt.utils.common import CodeParser-from metagpt.config import CONFIGPROMPT_TEMPLATE = """NOTICE@@@ -69,23 -92,27 +95,60 @@@ class WriteCodeReview(Action)super().__init__(name, context, llm)@retry(stop=stop_after_attempt(2), wait=wait_fixed(1))- async def write_code(self, prompt):+ async def write_code_review_and_rewrite(self, prompt):code_rsp = await self._aask(prompt)+ result = CodeParser.parse_block("Code Review Result", code_rsp)+ if "LGTM" in result:+ return result, Nonecode = CodeParser.parse_code(block="", text=code_rsp)- return code+ return result, code- async def run(self, context, code, filename):- iterative_code = code- k = CONFIG.code_review_k_times++ # <<<<<<< HEAD++ # async def run(self, *args, **kwargs) -> CodingContext:++ # format_example = FORMAT_EXAMPLE.format(filename=self.context.code_doc.filename)++ # context = "\n----------\n".join(++ # [self.context.design_doc.content, self.context.task_doc.content, self.context.code_doc.content]++ # )++ # prompt = PROMPT_TEMPLATE.format(++ # context=context,++ # code=self.context.code_doc.content,++ # filename=self.context.code_doc.filename,++ # format_example=format_example,++ # )++ # logger.info(f"Code review {self.context.code_doc.filename}..")++ # code = await self.write_code(prompt)++ # self.context.code_doc.content = code++ # return self.context++ # =======+ async def run(self, *args, **kwargs) -> CodingContext:- format_example = FORMAT_EXAMPLE.format(filename=self.context.code_doc.filename)- context = "\n".join(- [self.context.design_doc.content, self.context.task_doc.content, self.context.code_doc.content]- )- prompt = PROMPT_TEMPLATE.format(- context=context,- code=self.context.code_doc.content,- filename=self.context.code_doc.filename,- format_example=format_example,- )- logger.info(f"Code review {self.context.code_doc.filename}..")- code = await self.write_code(prompt)- self.context.code_doc.content = code++ iterative_code = self.context.code_doc.content++ k = CONFIG.code_review_k_times or 1+ for i in range(k):- format_example = FORMAT_EXAMPLE.format(filename=filename)- prompt = PROMPT_TEMPLATE.format(context=context, code=iterative_code, filename=filename, format_example=format_example)- logger.info(f'Code review and rewrite {filename}: {i+1}/{k} | {len(iterative_code)=}, {len(code)=}')++ format_example = FORMAT_EXAMPLE.format(filename=self.context.code_doc.filename)++ context = "\n----------\n".join(++ [++ "```text\n" + self.context.design_doc.content + "```\n",++ "```text\n" + self.context.task_doc.content + "```\n",++ "```python\n" + self.context.code_doc.content + "```\n",++ ]++ )++ prompt = PROMPT_TEMPLATE.format(++ context=context,++ code=iterative_code,++ filename=self.context.code_doc.filename,++ format_example=format_example,++ )++ logger.info(++ f"Code review and rewrite {self.context.code_doc.filename,}: {i+1}/{k} | {len(iterative_code)=}, {len(self.context.code_doc.content)=}"++ )+ result, rewrited_code = await self.write_code_review_and_rewrite(prompt)+ if "LBTM" in result:+ iterative_code = rewrited_code+ elif "LGTM" in result:- return iterative_code++ self.context.code_doc.content = iterative_code++ return self.context+ # code_rsp = await self._aask_v1(prompt, "code_rsp", OUTPUT_MAPPING)+ # self._save(context, filename, code)+ # 如果rewrited_code是None(原code perfect),那么直接返回code- return iterative_code++ self.context.code_doc.content = iterative_code+ return self.contextdiff --cc metagpt/actions/write_prd.pyindex c1653a850,4780762ca..ab216b7a0--- a/metagpt/actions/write_prd.py+++ b/metagpt/actions/write_prd.py@@@ -223,8 -206,8 +224,9 @@@ There are no unclear points},}+OUTPUT_MAPPING = {+ "Language": (str, ...),"Original Requirements": (str, ...),"Product Goals": (List[str], ...),"User Stories": (List[str], ...),@@@ -330,55 -244,3 +335,55 @@@ class WritePRD(Action)# prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING)prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING, format=format)return prd++ async def _is_relative_to(self, new_requirement_doc, old_prd_doc) -> bool:+ m = json.loads(old_prd_doc.content)+ if m.get("Original Requirements") == new_requirement_doc.content:+ # There have been no changes in the requirements, so they are considered unrelated.+ return False+ prompt = IS_RELATIVE_PROMPT.format(old_prd=old_prd_doc.content, requirements=new_requirement_doc.content)+ res = await self._aask(prompt=prompt)+ logger.info(f"[{new_requirement_doc.root_relative_path}, {old_prd_doc.root_relative_path}]: {res}")+ if "YES" in res:+ return True+ return False++ async def _merge(self, new_requirement_doc, prd_doc, format=CONFIG.prompt_format) -> Document:+ prompt = MERGE_PROMPT.format(requirements=new_requirement_doc.content, old_prd=prd_doc.content)+ prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING, format=format)- prd_doc.content = prd.instruct_content.json()++ prd_doc.content = prd.instruct_content.json(ensure_ascii=False)+ return prd_doc++ async def _update_prd(self, requirement_doc, prd_doc, prds_file_repo, *args, **kwargs) -> Document | None:+ if not prd_doc:+ prd = await self._run_new_requirement(requirements=[requirement_doc.content], *args, **kwargs)+ new_prd_doc = Document(+ root_path=PRDS_FILE_REPO,+ filename=FileRepository.new_filename() + ".json",- content=prd.instruct_content.json(),++ content=prd.instruct_content.json(ensure_ascii=False),+ )+ elif await self._is_relative_to(requirement_doc, prd_doc):+ new_prd_doc = await self._merge(requirement_doc, prd_doc)+ else:+ return None+ await prds_file_repo.save(filename=new_prd_doc.filename, content=new_prd_doc.content)+ await self._save_competitive_analysis(new_prd_doc)+ await self._save_pdf(new_prd_doc)+ return new_prd_doc++ @staticmethod+ async def _save_competitive_analysis(prd_doc):+ m = json.loads(prd_doc.content)+ quadrant_chart = m.get("Competitive Quadrant Chart")+ if not quadrant_chart:+ return+ pathname = (+ CONFIG.git_repo.workdir / Path(COMPETITIVE_ANALYSIS_FILE_REPO) / Path(prd_doc.filename).with_suffix("")+ )+ if not pathname.parent.exists():+ pathname.parent.mkdir(parents=True, exist_ok=True)+ await mermaid_to_file(quadrant_chart, pathname)++ @staticmethod+ async def _save_pdf(prd_doc):+ await FileRepository.save_as(doc=prd_doc, with_suffix=".md", relative_path=PRD_PDF_FILE_REPO)diff --cc metagpt/actions/write_test.pyindex e980e0831,9988fda16..7cbb42e1d--- a/metagpt/actions/write_test.py+++ b/metagpt/actions/write_test.py@@@ -3,14 -3,10 +3,14 @@@"""@Time : 2023/5/11 22:12@Author : alexanderwu- @File : environment.py+ @File : write_test.py+@Modified By: mashenquan, 2023-11-27. Following the think-act principle, solidify the task parameters when creating the+ WriteTest object, rather than passing them in when calling the run function."""from metagpt.actions.action import Action+from metagpt.config import CONFIGfrom metagpt.logs import logger+from metagpt.schema import TestingContextfrom metagpt.utils.common import CodeParserPROMPT_TEMPLATE = """diff --cc metagpt/config.pyindex 1b70d5fa6,d30a337e3..d04ae7291--- a/metagpt/config.py+++ b/metagpt/config.py@@@ -2,18 -2,15 +2,18 @@@# -*- coding: utf-8 -*-"""Provide configuration, singleton+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.11 of RFC 135, add git repository support.+ 2. Add the parameter `src_workspace` for the old version project path."""import os+from copy import deepcopy++from pathlib import Path+from typing import Any--import openaiimport yaml- from metagpt.const import OPTIONS, PROJECT_ROOT-from pathlib import Path--from metagpt.const import METAGPT_ROOT, DEFAULT_WORKSPACE_ROOT++from metagpt.const import DEFAULT_WORKSPACE_ROOT, METAGPT_ROOT, OPTIONSfrom metagpt.logs import loggerfrom metagpt.tools import SearchEngineType, WebBrowserEngineTypefrom metagpt.utils.singleton import Singleton@@@ -40,27 -37,24 +40,29 @@@ class Config(metaclass=Singleton)"""_instance = None- key_yaml_file = PROJECT_ROOT / "config/key.yaml"- default_yaml_file = PROJECT_ROOT / "config/config.yaml"+ home_yaml_file = Path.home() / ".metagpt/config.yaml"+ key_yaml_file = METAGPT_ROOT / "config/key.yaml"+ default_yaml_file = METAGPT_ROOT / "config/config.yaml"def __init__(self, yaml_file=default_yaml_file):- self._configs = {}- self._init_with_config_files_and_env(self._configs, yaml_file)+ self._init_with_config_files_and_env(yaml_file)+ logger.info("Config loading done.")+ self._update()++ def _update(self):+ # logger.info("Config loading done.")self.global_proxy = self._get("GLOBAL_PROXY")self.openai_api_key = self._get("OPENAI_API_KEY")self.anthropic_api_key = self._get("Anthropic_API_KEY")- if (not self.openai_api_key or "YOUR_API_KEY" == self.openai_api_key) and (- not self.anthropic_api_key or "YOUR_API_KEY" == self.anthropic_api_key+ self.zhipuai_api_key = self._get("ZHIPUAI_API_KEY")- if (not self.openai_api_key or "YOUR_API_KEY" == self.openai_api_key) and \- (not self.anthropic_api_key or "YOUR_API_KEY" == self.anthropic_api_key) and \- (not self.zhipuai_api_key or "YOUR_API_KEY" == self.zhipuai_api_key):++ if (++ (not self.openai_api_key or "YOUR_API_KEY" == self.openai_api_key)++ and (not self.anthropic_api_key or "YOUR_API_KEY" == self.anthropic_api_key)++ and (not self.zhipuai_api_key or "YOUR_API_KEY" == self.zhipuai_api_key)+ ):- raise NotConfiguredException("Set OPENAI_API_KEY or Anthropic_API_KEY first")+ raise NotConfiguredException("Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first")self.openai_api_base = self._get("OPENAI_API_BASE")- openai_proxy = self._get("OPENAI_PROXY") or self.global_proxy- if openai_proxy:- openai.proxy = openai_proxy- openai.api_base = self.openai_api_base+ self.openai_proxy = self._get("OPENAI_PROXY") or self.global_proxyself.openai_api_type = self._get("OPENAI_API_TYPE")self.openai_api_version = self._get("OPENAI_API_VERSION")self.openai_api_rpm = self._get("RPM", 3)@@@ -100,12 -95,18 +103,18 @@@self.pyppeteer_executable_path = self._get("PYPPETEER_EXECUTABLE_PATH", "")self.prompt_format = self._get("PROMPT_FORMAT", "markdown")+ self.workspace_path = Path(self._get("WORKSPACE_PATH", DEFAULT_WORKSPACE_ROOT))+ self._ensure_workspace_exists()++ def _ensure_workspace_exists(self):+ self.workspace_path.mkdir(parents=True, exist_ok=True)+ logger.info(f"WORKSPACE_PATH set to {self.workspace_path}")- def _init_with_config_files_and_env(self, configs: dict, yaml_file):+ def _init_with_config_files_and_env(self, yaml_file):"""Load from config/key.yaml, config/config.yaml, and env in decreasing order of priority"""- configs.update(os.environ)+ configs = dict(os.environ)- for _yaml_file in [yaml_file, self.key_yaml_file]:+ for _yaml_file in [yaml_file, self.key_yaml_file, self.home_yaml_file]:if not _yaml_file.exists():continuediff --cc metagpt/const.pyindex 9278a5d0e,14e692487..6e616e820--- a/metagpt/const.py+++ b/metagpt/const.py@@@ -4,69 -4,55 +4,116 @@@@Time : 2023/5/1 11:59@Author : alexanderwu@File : const.py+@Modified By: mashenquan, 2023-11-1. According to Section 2.2.1 and 2.2.2 of RFC 116, added key definitions for+ common properties in the Message.+@Modified By: mashenquan, 2023-11-27. Defines file repository paths according to Section 2.2.3.4 of RFC 135."""+import contextvars+ import osfrom pathlib import Path++ from loguru import logger+- def get_project_root():- """Search upwards to find the project root directory."""- current_path = Path.cwd()- while True:- if (- (current_path / ".git").exists()- or (current_path / ".project_root").exists()- or (current_path / ".gitignore").exists()- ):- return current_path- parent_path = current_path.parent- if parent_path == current_path:- raise Exception("Project root not found.")- current_path = parent_path-+ import metagpt+OPTIONS = contextvars.ContextVar("OPTIONS")- PROJECT_ROOT = get_project_root()- DATA_PATH = PROJECT_ROOT / "data"- WORKSPACE_ROOT = PROJECT_ROOT / "workspace"- PROMPT_PATH = PROJECT_ROOT / "metagpt/prompts"- UT_PATH = PROJECT_ROOT / "data/ut"- SWAGGER_PATH = UT_PATH / "files/api/"- UT_PY_PATH = UT_PATH / "files/ut/"- API_QUESTIONS_PATH = UT_PATH / "files/question/"- YAPI_URL = "http://yapi.deepwisdomai.com/"- TMP = PROJECT_ROOT / "tmp"++++# <<<<<<< HEAD++# def get_project_root():++# """Search upwards to find the project root directory."""++# current_path = Path.cwd()++# while True:++# if (++# (current_path / ".git").exists()++# or (current_path / ".project_root").exists()++# or (current_path / ".gitignore").exists()++# ):++# return current_path++# parent_path = current_path.parent++# if parent_path == current_path:++# raise Exception("Project root not found.")++# current_path = parent_path++#++#++# PROJECT_ROOT = get_project_root()++# DATA_PATH = PROJECT_ROOT / "data"++# WORKSPACE_ROOT = PROJECT_ROOT / "workspace"++# PROMPT_PATH = PROJECT_ROOT / "metagpt/prompts"++# UT_PATH = PROJECT_ROOT / "data/ut"++# SWAGGER_PATH = UT_PATH / "files/api/"++# UT_PY_PATH = UT_PATH / "files/ut/"++# API_QUESTIONS_PATH = UT_PATH / "files/question/"++# YAPI_URL = "http://yapi.deepwisdomai.com/"++# TMP = PROJECT_ROOT / "tmp"++# =======+ def get_metagpt_package_root():+ """Get the root directory of the installed package."""+ package_root = Path(metagpt.__file__).parent.parent+ logger.info(f"Package root set to {str(package_root)}")+ return package_root+++ def get_metagpt_root():+ """Get the project root directory."""+ # Check if a project root is specified in the environment variable- project_root_env = os.getenv('METAGPT_PROJECT_ROOT')++ project_root_env = os.getenv("METAGPT_PROJECT_ROOT")+ if project_root_env:+ project_root = Path(project_root_env)+ logger.info(f"PROJECT_ROOT set from environment variable to {str(project_root)}")+ else:+ # Fallback to package root if no environment variable is set+ project_root = get_metagpt_package_root()+ return project_root+++ # METAGPT PROJECT ROOT AND VARS++ METAGPT_ROOT = get_metagpt_root()+ DEFAULT_WORKSPACE_ROOT = METAGPT_ROOT / "workspace"++ DATA_PATH = METAGPT_ROOT / "data"RESEARCH_PATH = DATA_PATH / "research"TUTORIAL_PATH = DATA_PATH / "tutorial_docx"INVOICE_OCR_TABLE_PATH = DATA_PATH / "invoice_table"+ 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/"++ TMP = METAGPT_ROOT / "tmp"- SKILL_DIRECTORY = PROJECT_ROOT / "metagpt/skills"+ 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"+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"+++ YAPI_URL = "http://yapi.deepwisdomai.com/"diff --cc metagpt/document.pyindex 000000000,cf0821421..6ac4834aamode 000000,100644..100644--- a/metagpt/document.py+++ b/metagpt/document.py@@@ -1,0 -1,253 +1,255 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ """+ @Time : 2023/6/8 14:03+ @Author : alexanderwu+ @File : document.py+ """+ from enum import Enum-from typing import Union, Optional+ from pathlib import Path-from pydantic import BaseModel, Field++from typing import Optional, Union+++ import pandas as pd+ from langchain.document_loaders import (+ TextLoader,+ UnstructuredPDFLoader,+ UnstructuredWordDocumentLoader,+ )+ from langchain.text_splitter import CharacterTextSplitter++from pydantic import BaseModel, Field+ from tqdm import tqdm++ from metagpt.config import CONFIG+ from metagpt.logs import logger+ from metagpt.repo_parser import RepoParser+++ def validate_cols(content_col: str, df: pd.DataFrame):+ if content_col not in df.columns:+ raise ValueError("Content column not found in DataFrame.")+++ def read_data(data_path: Path):+ suffix = data_path.suffix- if '.xlsx' == suffix:++ if ".xlsx" == suffix:+ data = pd.read_excel(data_path)- elif '.csv' == suffix:++ elif ".csv" == suffix:+ data = pd.read_csv(data_path)- elif '.json' == suffix:++ elif ".json" == suffix:+ data = pd.read_json(data_path)- elif suffix in ('.docx', '.doc'):- data = UnstructuredWordDocumentLoader(str(data_path), mode='elements').load()- elif '.txt' == suffix:++ elif suffix in (".docx", ".doc"):++ data = UnstructuredWordDocumentLoader(str(data_path), mode="elements").load()++ elif ".txt" == suffix:+ data = TextLoader(str(data_path)).load()- text_splitter = CharacterTextSplitter(separator='\n', chunk_size=256, chunk_overlap=0)++ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=256, chunk_overlap=0)+ texts = text_splitter.split_documents(data)+ data = texts- elif '.pdf' == suffix:++ elif ".pdf" == suffix:+ data = UnstructuredPDFLoader(str(data_path), mode="elements").load()+ else:+ raise NotImplementedError("File format not supported.")+ return data+++ class DocumentStatus(Enum):+ """Indicates document status, a mechanism similar to RFC/PEP"""+++ DRAFT = "draft"+ UNDERREVIEW = "underreview"+ APPROVED = "approved"+ DONE = "done"+++ class Document(BaseModel):+ """+ Document: Handles operations related to document files.+ """+++ path: Path = Field(default=None)+ name: str = Field(default="")+ content: str = Field(default="")++ # metadata? in content perhaps.+ author: str = Field(default="")+ status: DocumentStatus = Field(default=DocumentStatus.DRAFT)+ reviews: list = Field(default_factory=list)++ @classmethod+ def from_path(cls, path: Path):+ """+ Create a Document instance from a file path.+ """+ if not path.exists():+ raise FileNotFoundError(f"File {path} not found.")+ content = path.read_text()+ return cls(content=content, path=path)++ @classmethod+ def from_text(cls, text: str, path: Optional[Path] = None):+ """+ Create a Document from a text string.+ """+ return cls(content=text, path=path)++ def to_path(self, path: Optional[Path] = None):+ """+ Save content to the specified file path.+ """+ if path is not None:+ self.path = path++ if self.path is None:+ raise ValueError("File path is not set.")++ self.path.parent.mkdir(parents=True, exist_ok=True)+ self.path.write_text(self.content, encoding="utf-8")++ def persist(self):+ """+ Persist document to disk.+ """+ return self.to_path()+++ class IndexableDocument(Document):+ """+ Advanced document handling: For vector databases or search engines.+ """+++ data: Union[pd.DataFrame, list]- content_col: Optional[str] = Field(default='')- meta_col: Optional[str] = Field(default='')++ content_col: Optional[str] = Field(default="")++ meta_col: Optional[str] = Field(default="")++ class Config:+ arbitrary_types_allowed = True++ @classmethod- def from_path(cls, data_path: Path, content_col='content', meta_col='metadata'):++ def from_path(cls, data_path: Path, content_col="content", meta_col="metadata"):+ if not data_path.exists():+ raise FileNotFoundError(f"File {data_path} not found.")+ data = read_data(data_path)+ content = data_path.read_text()+ if isinstance(data, pd.DataFrame):+ validate_cols(content_col, data)+ return cls(data=data, content=content, content_col=content_col, meta_col=meta_col)++ def _get_docs_and_metadatas_by_df(self) -> (list, list):+ df = self.data+ docs = []+ metadatas = []+ for i in tqdm(range(len(df))):+ docs.append(df[self.content_col].iloc[i])+ if self.meta_col:+ metadatas.append({self.meta_col: df[self.meta_col].iloc[i]})+ else:+ metadatas.append({})+ return docs, metadatas++ def _get_docs_and_metadatas_by_langchain(self) -> (list, list):+ data = self.data+ docs = [i.page_content for i in data]+ metadatas = [i.metadata for i in data]+ return docs, metadatas++ def get_docs_and_metadatas(self) -> (list, list):+ if isinstance(self.data, pd.DataFrame):+ return self._get_docs_and_metadatas_by_df()+ elif isinstance(self.data, list):+ return self._get_docs_and_metadatas_by_langchain()+ else:+ raise NotImplementedError("Data type not supported for metadata extraction.")+++ class RepoMetadata(BaseModel):-+ name: str = Field(default="")+ n_docs: int = Field(default=0)+ n_chars: int = Field(default=0)+ symbols: list = Field(default_factory=list)+++ class Repo(BaseModel):-+ # Name of this repo.+ name: str = Field(default="")+ # metadata: RepoMetadata = Field(default=RepoMetadata)+ docs: dict[Path, Document] = Field(default_factory=dict)+ codes: dict[Path, Document] = Field(default_factory=dict)+ assets: dict[Path, Document] = Field(default_factory=dict)+ path: Path = Field(default=None)++ def _path(self, filename):+ return self.path / filename++ @classmethod+ def from_path(cls, path: Path):+ """Load documents, code, and assets from a repository path."""+ path.mkdir(parents=True, exist_ok=True)+ repo = Repo(path=path, name=path.name)- for file_path in path.rglob('*'):++ for file_path in path.rglob("*"):+ # FIXME: These judgments are difficult to support multiple programming languages and need to be more general+ if file_path.is_file() and file_path.suffix in [".json", ".txt", ".md", ".py", ".js", ".css", ".html"]:+ repo._set(file_path.read_text(), file_path)+ return repo++ def to_path(self):+ """Persist all documents, code, and assets to the given repository path."""+ for doc in self.docs.values():+ doc.to_path()+ for code in self.codes.values():+ code.to_path()+ for asset in self.assets.values():+ asset.to_path()++ def _set(self, content: str, path: Path):+ """Add a document to the appropriate category based on its file extension."""+ suffix = path.suffix+ doc = Document(content=content, path=path, name=str(path.relative_to(self.path)))++ # FIXME: These judgments are difficult to support multiple programming languages and need to be more general- if suffix.lower() == '.md':++ if suffix.lower() == ".md":+ self.docs[path] = doc- elif suffix.lower() in ['.py', '.js', '.css', '.html']:++ elif suffix.lower() in [".py", ".js", ".css", ".html"]:+ self.codes[path] = doc+ else:+ self.assets[path] = doc+ return doc++ def set(self, content: str, filename: str):+ """Set a document and persist it to disk."""+ path = self._path(filename)+ doc = self._set(content, path)+ doc.to_path()++ def get(self, filename: str) -> Optional[Document]:+ """Get a document by its filename."""+ path = self._path(filename)+ return self.docs.get(path) or self.codes.get(path) or self.assets.get(path)++ def get_text_documents(self) -> list[Document]:+ return list(self.docs.values()) + list(self.codes.values())++ def eda(self) -> RepoMetadata:+ n_docs = sum(len(i) for i in [self.docs, self.codes, self.assets])+ n_chars = sum(sum(len(j.content) for j in i.values()) for i in [self.docs, self.codes, self.assets])+ symbols = RepoParser(base_directory=self.path).generate_symbols()+ return RepoMetadata(name=self.name, n_docs=n_docs, n_chars=n_chars, symbols=symbols)+++ def set_existing_repo(path=CONFIG.workspace_path / "t1"):+ repo1 = Repo.from_path(path)+ repo1.set("wtf content", "doc/wtf_file.md")+ repo1.set("wtf code", "code/wtf_file.py")+ logger.info(repo1) # check doc+++ def load_existing_repo(path=CONFIG.workspace_path / "web_tetris"):+ repo = Repo.from_path(path)+ logger.info(repo)+ logger.info(repo.eda())+++ def main():+ load_existing_repo()++-if __name__ == '__main__':++if __name__ == "__main__":+ main()diff --cc metagpt/document_store/base_store.pyindex 7d102e00b,84b47a98c..5de377d21--- a/metagpt/document_store/base_store.py+++ b/metagpt/document_store/base_store.py@@@ -41,7 -41,7 +41,7 @@@ class LocalStore(BaseStore, ABC)self.store = self.write()def _get_index_and_store_fname(self):- fname = self.raw_data.name.split(".")[0]- fname = self.raw_data_path.name.split('.')[0]++ fname = self.raw_data_path.name.split(".")[0]index_file = self.cache_dir / f"{fname}.index"store_file = self.cache_dir / f"{fname}.pkl"return index_file, store_filediff --cc metagpt/document_store/faiss_store.pyindex 8ff904cdd,885ad3e15..53725c3f9--- a/metagpt/document_store/faiss_store.py+++ b/metagpt/document_store/faiss_store.py@@@ -14,16 -14,16 +14,16 @@@ from langchain.embeddings import OpenAIfrom langchain.vectorstores import FAISSfrom metagpt.const import DATA_PATH-from metagpt.document_store.base_store import LocalStore+ from metagpt.document import IndexableDocument+from metagpt.document_store.base_store import LocalStore- from metagpt.document_store.document import Documentfrom metagpt.logs import loggerclass FaissStore(LocalStore):- def __init__(self, raw_data: Path, cache_dir=None, meta_col="source", content_col="output"):- def __init__(self, raw_data_path: Path, cache_dir=None, meta_col='source', content_col='output'):++ def __init__(self, raw_data_path: Path, cache_dir=None, meta_col="source", content_col="output"):self.meta_col = meta_colself.content_col = content_col- super().__init__(raw_data, cache_dir)+ super().__init__(raw_data_path, cache_dir)def _load(self) -> Optional["FaissStore"]:index_file, store_file = self._get_index_and_store_fname()diff --cc metagpt/environment.pyindex 02eb3d340,44c9b1c67..e8bdd25c7--- a/metagpt/environment.py+++ b/metagpt/environment.py@@@ -23,14 -20,15 +23,26 @@@ from metagpt.utils.common import is_subclass Environment(BaseModel):- """++ # <<<<<<< HEAD+ """环境,承载一批角色,角色可以向环境发布消息,可以被其他角色观察到Environment, hosting a batch of roles, roles can publish messages to the environment, and can be observed by other roles+"""roles: dict[str, Role] = Field(default_factory=dict)- memory: Memory = Field(default_factory=Memory)- history: str = Field(default='')- repo: Repo = Field(default_factory=Repo)- kv: dict = Field(default_factory=dict)+ members: dict[Role, Set] = Field(default_factory=dict)+ history: str = Field(default="") # For debug++ # =======++ # """++ # Environment, hosting a batch of roles, roles can publish messages to the environment, and can be observed by other roles++ # """++ #++ # roles: dict[str, Role] = Field(default_factory=dict)++ # memory: Memory = Field(default_factory=Memory) # 已经私有化++ # history: str = Field(default='')++ # repo: Repo = Field(default_factory=Repo) # 在CONFIG里++ # kv: dict = Field(default_factory=dict) # 在CONFIG里++ # >>>>>>> feature/geekan_cli_etcclass Config:arbitrary_types_allowed = True@@@ -49,28 -47,41 +61,60 @@@for role in roles:self.add_role(role)- def publish_message(self, message: Message):- """向当前环境发布信息- Post information to the current environment+ def publish_message(self, message: Message) -> bool:"""- # self.message_queue.put(message)- self.memory.add(message)- self.history += f"\n{message}"-- def set_doc(self, content: str, filename: str):- """向当前环境发布文档(包括代码)"""- return self.repo.set(content, filename)-- def get_doc(self, filename: str):- return self.repo.get(filename)-- def set(self, k: str, v: str):- self.kv[k] = v-- def get(self, k: str):- return self.kv.get(k, None)-- def load_existing_repo(self, path: Path, inc: bool):- self.repo = Repo.from_path(path)- logger.info(self.repo.eda())-- # Incremental mode: publish all docs to messages. Then roles can read the docs.- if inc:- docs = self.repo.get_text_documents()- for doc in docs:- msg = Message(content=doc.content)- self.publish_message(msg)- logger.info(f"Message from existing doc {doc.path}: {msg}")- logger.info(f"Load {len(docs)} docs from existing repo.")- raise NotImplementedError+ Distribute the message to the recipients.+ In accordance with the Message routing structure design in Chapter 2.2.1 of RFC 116, as already planned+ in RFC 113 for the entire system, the routing information in the Message is only responsible for+ specifying the message recipient, without concern for where the message recipient is located. How to+ route the message to the message recipient is a problem addressed by the transport framework designed+ in RFC 113.+ """+ logger.info(f"publish_message: {message.dump()}")+ found = False+ # According to the routing feature plan in Chapter 2.2.3.2 of RFC 113+ for role, subscription in self.members.items():+ if is_subscribed(message, subscription):+ role.put_message(message)+ found = True+ if not found:+ logger.warning(f"Message no recipients: {message.dump()}")+ self.history += f"\n{message}" # For debug++ return True+++ # # Replaced by FileRepository.set_file++ # def set_doc(self, content: str, filename: str):++ # """向当前环境发布文档(包括代码)"""++ # return self.repo.set(content, filename)++ #++ # # Replaced by FileRepository.get_file++ # def get_doc(self, filename: str):++ # return self.repo.get(filename)++ #++ # # Replaced by CONFIG.xx++ # def set(self, k: str, v: str):++ # self.kv[k] = v++ #++ # # Replaced by CONFIG.xx++ # def get(self, k: str):++ # return self.kv.get(k, None)++++ # Replaced By 增量变更流程++ # def load_existing_repo(self, path: Path, inc: bool):++ # self.repo = Repo.from_path(path)++ # logger.info(self.repo.eda())++ #++ # # Incremental mode: publish all docs to messages. Then roles can read the docs.++ # if inc:++ # docs = self.repo.get_text_documents()++ # for doc in docs:++ # msg = Message(content=doc.content)++ # self.publish_message(msg)++ # logger.info(f"Message from existing doc {doc.path}: {msg}")++ # logger.info(f"Load {len(docs)} docs from existing repo.")++ # raise NotImplementedError+async def run(self, k=1):"""处理一次所有信息的运行Process all Role runs at oncediff --cc metagpt/llm.pyindex 410f3dcb5,4edcd7a83..14bbad1b4--- a/metagpt/llm.py+++ b/metagpt/llm.py@@@ -6,15 -6,27 +6,25 @@@@File : llm.py"""-from metagpt.logs import logger+ from metagpt.config import CONFIGfrom metagpt.provider.anthropic_api import Claude2 as Claude- from metagpt.provider.openai_api import OpenAIGPTAPI as LLM+ from metagpt.provider.openai_api import OpenAIGPTAPI-from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI+ from metagpt.provider.spark_api import SparkAPI-from metagpt.provider.human_provider import HumanProvider++from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI- DEFAULT_LLM = LLM()- CLAUDE_LLM = Claude()+ def LLM() -> "BaseGPTAPI":- """ initialize different LLM instance according to the key field existence"""++ """initialize different LLM instance according to the key field existence"""+ # TODO a little trick, can use registry to initialize LLM instance further+ if CONFIG.openai_api_key:+ llm = OpenAIGPTAPI()+ elif CONFIG.claude_api_key:+ llm = Claude()+ elif CONFIG.spark_api_key:+ llm = SparkAPI()+ elif CONFIG.zhipuai_api_key:+ llm = ZhiPuAIGPTAPI()+ else:+ raise RuntimeError("You should config a LLM configuration first")- async def ai_func(prompt):- """使用LLM进行QA- QA with LLMs- """- return await DEFAULT_LLM.aask(prompt)+ return llmdiff --cc metagpt/logs.pyindex 55d85312f,afebbfed9..092b4c476--- a/metagpt/logs.py+++ b/metagpt/logs.py@@@ -14,12 -14,10 +14,10 @@@ from metagpt.const import METAGPT_ROOdef define_log_level(print_level="INFO", logfile_level="DEBUG"):- """调整日志级别到level之上- Adjust the log level to above level- """+ """Adjust the log level to above level"""_logger.remove()_logger.add(sys.stderr, level=print_level)- _logger.add(PROJECT_ROOT / "logs/log.txt", level=logfile_level)- _logger.add(METAGPT_ROOT / 'logs/log.txt', level=logfile_level)++ _logger.add(METAGPT_ROOT / "logs/log.txt", level=logfile_level)return _loggerdiff --cc metagpt/memory/__init__.pyindex 710930626,bd6e72163..3d8f679b2--- a/metagpt/memory/__init__.py+++ b/metagpt/memory/__init__.py@@@ -7,7 -7,7 +7,8 @@@"""from metagpt.memory.memory import Memory- from metagpt.memory.longterm_memory import LongTermMemory+++ # from metagpt.memory.longterm_memory import LongTermMemory__all__ = [diff --cc metagpt/provider/base_chatbot.pyindex 2d4cfe2d9,72e6c94f9..a6950f144--- a/metagpt/provider/base_chatbot.py+++ b/metagpt/provider/base_chatbot.py@@@ -12,8 -12,8 +12,9 @@@ from dataclasses import dataclas@dataclassclass BaseChatbot(ABC):"""Abstract GPT class"""+mode: str = "API"+ use_system_prompt: bool = True@abstractmethoddef ask(self, msg: str) -> str:diff --cc metagpt/provider/base_gpt_api.pyindex adc57c66b,b6b034329..565ae94f7--- a/metagpt/provider/base_gpt_api.py+++ b/metagpt/provider/base_gpt_api.py@@@ -39,9 -40,11 +40,15 @@@ class BaseGPTAPI(BaseChatbot)async def aask(self, msg: str, system_msgs: Optional[list[str]] = None) -> str:if system_msgs:- message = self._system_msgs(system_msgs) + [self._user_msg(msg)]- message = self._system_msgs(system_msgs) + [self._user_msg(msg)] if self.use_system_prompt \++ message = (++ self._system_msgs(system_msgs) + [self._user_msg(msg)]++ if self.use_system_prompt+ else [self._user_msg(msg)]++ )else:- message = [self._default_system_msg(), self._user_msg(msg)]- message = [self._default_system_msg(), self._user_msg(msg)] if self.use_system_prompt \- else [self._user_msg(msg)]++ message = (++ [self._default_system_msg(), self._user_msg(msg)] if self.use_system_prompt else [self._user_msg(msg)]++ )rsp = await self.acompletion_text(message, stream=True)logger.debug(message)# logger.debug(rsp)diff --cc metagpt/provider/general_api_requestor.pyindex 000000000,150f2f1e0..875122e8bmode 000000,100644..100644--- a/metagpt/provider/general_api_requestor.py+++ b/metagpt/provider/general_api_requestor.py@@@ -1,0 -1,62 +1,58 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : General Async API for http-based LLM model+-from typing import AsyncGenerator, Tuple, Union, Optional, Literal-import aiohttp+ import asyncio++from typing import AsyncGenerator, Tuple, Union+++import aiohttp+ from openai.api_requestor import APIRequestor++ from metagpt.logs import logger+++ class GeneralAPIRequestor(APIRequestor):+ """+ usage+ # full_url = "{api_base}{url}"+ requester = GeneralAPIRequestor(api_base=api_base)+ result, _, api_key = await requester.arequest(+ method=method,+ url=url,+ headers=headers,+ stream=stream,+ params=kwargs,+ request_timeout=120+ )+ """+- def _interpret_response_line(- self, rbody: str, rcode: int, rheaders, stream: bool- ) -> str:++ def _interpret_response_line(self, rbody: str, rcode: int, rheaders, stream: bool) -> str:+ # just do nothing to meet the APIRequestor process and return the raw data+ # due to the openai sdk will convert the data into OpenAIResponse which we don't need in general cases.++ return rbody++ async def _interpret_async_response(+ self, result: aiohttp.ClientResponse, stream: bool+ ) -> Tuple[Union[str, AsyncGenerator[str, None]], bool]:+ if stream and "text/event-stream" in result.headers.get("Content-Type", ""):+ return (- self._interpret_response_line(- line, result.status, result.headers, stream=True- )- async for line in result.content- ), True++ self._interpret_response_line(line, result.status, result.headers, stream=True)++ async for line in result.content++ ), True+ else:+ try:+ await result.read()+ except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e:+ raise TimeoutError("Request timed out") from e+ except aiohttp.ClientError as exp:+ logger.warning(f"response: {result.content}, exp: {exp}")+ return (+ self._interpret_response_line(+ await result.read(), # let the caller to decode the msg+ result.status,+ result.headers,+ stream=False,+ ),+ False,+ )diff --cc metagpt/provider/human_provider.pyindex 000000000,1d12f972f..c70a7f1a6mode 000000,100644..100644--- a/metagpt/provider/human_provider.py+++ b/metagpt/provider/human_provider.py@@@ -1,0 -1,35 +1,37 @@@-'''++"""+ Filename: MetaGPT/metagpt/provider/human_provider.py+ Created Date: Wednesday, November 8th 2023, 11:55:46 pm+ Author: garylin2099-'''++"""+ from typing import Optional-from metagpt.provider.base_gpt_api import BaseGPTAPI+++ from metagpt.logs import logger++from metagpt.provider.base_gpt_api import BaseGPTAPI++++ class HumanProvider(BaseGPTAPI):+ """Humans provide themselves as a 'model', which actually takes in human input as its response.+ This enables replacing LLM anywhere in the framework with a human, thus introducing human interaction+ """++ def ask(self, msg: str) -> str:+ logger.info("It's your turn, please type in your response. You may also refer to the context below")+ rsp = input(msg)+ if rsp in ["exit", "quit"]:+ exit()+ return rsp++ async def aask(self, msg: str, system_msgs: Optional[list[str]] = None) -> str:+ return self.ask(msg)++ def completion(self, messages: list[dict]):+ """dummy implementation of abstract method in base"""+ return []++ async def acompletion(self, messages: list[dict]):+ """dummy implementation of abstract method in base"""+ return []++ async def acompletion_text(self, messages: list[dict], stream=False) -> str:+ """dummy implementation of abstract method in base"""+ return []diff --cc metagpt/provider/zhipuai/async_sse_client.pyindex 000000000,b819fdc63..d7168202amode 000000,100644..100644--- a/metagpt/provider/zhipuai/async_sse_client.py+++ b/metagpt/provider/zhipuai/async_sse_client.py@@@ -1,0 -1,78 +1,75 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : async_sse_client to make keep the use of Event to access response+ # refs to `https://github.com/zhipuai/zhipuai-sdk-python/blob/main/zhipuai/utils/sse_client.py`+-from zhipuai.utils.sse_client import SSEClient, Event, _FIELD_SEPARATOR++from zhipuai.utils.sse_client import _FIELD_SEPARATOR, Event, SSEClient+++ class AsyncSSEClient(SSEClient):-+ async def _aread(self):+ data = b""+ async for chunk in self._event_source:+ for line in chunk.splitlines(True):+ data += line+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):+ yield data+ data = b""+ if data:+ yield data++ async def async_events(self):+ async for chunk in self._aread():+ event = Event()+ # Split before decoding so splitlines() only uses \r and \n+ for line in chunk.splitlines():+ # Decode the line.+ line = line.decode(self._char_enc)++ # Lines starting with a separator are comments and are to be+ # ignored.+ if not line.strip() or line.startswith(_FIELD_SEPARATOR):+ continue++ data = line.split(_FIELD_SEPARATOR, 1)+ field = data[0]++ # Ignore unknown fields.+ if field not in event.__dict__:- self._logger.debug(- "Saw invalid field %s while parsing " "Server Side Event", field- )++ self._logger.debug("Saw invalid field %s while parsing " "Server Side Event", field)+ continue++ if len(data) > 1:+ # From the spec:+ # "If value starts with a single U+0020 SPACE character,+ # remove it from value."+ if data[1].startswith(" "):+ value = data[1][1:]+ else:+ value = data[1]+ else:+ # If no value is present after the separator,+ # assume an empty value.+ value = ""++ # The data field may come over multiple lines and their values+ # are concatenated with each other.+ if field == "data":+ event.__dict__[field] += value + "\n"+ else:+ event.__dict__[field] = value++ # Events with no data are not dispatched.+ if not event.data:+ continue++ # If the data field ends with a newline, remove it.+ if event.data.endswith("\n"):+ event.data = event.data[0:-1]++ # Empty event names default to 'message'+ event.event = event.event or "message"++ # Dispatch the event+ self._logger.debug("Dispatching %s...", event)+ yield eventdiff --cc metagpt/provider/zhipuai/zhipu_model_api.pyindex 000000000,618b2e865..23dd7229dmode 000000,100644..100644--- a/metagpt/provider/zhipuai/zhipu_model_api.py+++ b/metagpt/provider/zhipuai/zhipu_model_api.py@@@ -1,0 -1,79 +1,72 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : zhipu model api to support sync & async for invoke & sse_invoke++ import zhipuai-from zhipuai.model_api.api import ModelAPI, InvokeType++from zhipuai.model_api.api import InvokeType, ModelAPI+ from zhipuai.utils.http_client import headers as zhipuai_default_headers+-from metagpt.provider.zhipuai.async_sse_client import AsyncSSEClient+ from metagpt.provider.general_api_requestor import GeneralAPIRequestor++from metagpt.provider.zhipuai.async_sse_client import AsyncSSEClient+++ class ZhiPuModelAPI(ModelAPI):-+ @classmethod+ def get_header(cls) -> dict:+ token = cls._generate_token()+ zhipuai_default_headers.update({"Authorization": token})+ return zhipuai_default_headers++ @classmethod+ def get_sse_header(cls) -> dict:+ token = cls._generate_token()- headers = {- "Authorization": token- }++ headers = {"Authorization": token}+ return headers++ @classmethod+ def split_zhipu_api_url(cls, invoke_type: InvokeType, kwargs):+ # use this method to prevent zhipu api upgrading to different version.+ # and follow the GeneralAPIRequestor implemented based on openai sdk+ zhipu_api_url = cls._build_api_url(kwargs, invoke_type)+ """+ example:+ zhipu_api_url: https://open.bigmodel.cn/api/paas/v3/model-api/{model}/{invoke_method}+ """+ arr = zhipu_api_url.split("/api/")+ # ("https://open.bigmodel.cn/api/" , "/paas/v3/model-api/chatglm_turbo/invoke")+ return f"{arr[0]}/api", f"/{arr[1]}"++ @classmethod+ async def arequest(cls, invoke_type: InvokeType, stream: bool, method: str, headers: dict, kwargs):+ # TODO to make the async request to be more generic for models in http mode.+ assert method in ["post", "get"]++ api_base, url = cls.split_zhipu_api_url(invoke_type, kwargs)+ requester = GeneralAPIRequestor(api_base=api_base)+ result, _, api_key = await requester.arequest(+ method=method,+ url=url,+ headers=headers,+ stream=stream,+ params=kwargs,- request_timeout=zhipuai.api_timeout_seconds++ request_timeout=zhipuai.api_timeout_seconds,+ )++ return result++ @classmethod+ async def ainvoke(cls, **kwargs) -> dict:- """ async invoke different from raw method `async_invoke` which get the final result by task_id"""++ """async invoke different from raw method `async_invoke` which get the final result by task_id"""+ headers = cls.get_header()- resp = await cls.arequest(invoke_type=InvokeType.SYNC,- stream=False,- method="post",- headers=headers,- kwargs=kwargs)++ resp = await cls.arequest(++ invoke_type=InvokeType.SYNC, stream=False, method="post", headers=headers, kwargs=kwargs++ )+ return resp++ @classmethod+ async def asse_invoke(cls, **kwargs) -> AsyncSSEClient:- """ async sse_invoke """++ """async sse_invoke"""+ headers = cls.get_sse_header()- return AsyncSSEClient(await cls.arequest(invoke_type=InvokeType.SSE,- stream=True,- method="post",- headers=headers,- kwargs=kwargs))++ return AsyncSSEClient(++ await cls.arequest(invoke_type=InvokeType.SSE, stream=True, method="post", headers=headers, kwargs=kwargs)++ )diff --cc metagpt/provider/zhipuai_api.pyindex 000000000,3161c0e88..edd9084e3mode 000000,100644..100644--- a/metagpt/provider/zhipuai_api.py+++ b/metagpt/provider/zhipuai_api.py@@@ -1,0 -1,139 +1,135 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : zhipuai LLM from https://open.bigmodel.cn/dev/api#sdk+-from enum import Enum+ import json++from enum import Enum++++import openai++import zhipuai++from requests import ConnectionError+ from tenacity import (+ after_log,+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_fixed,+ )-from requests import ConnectionError--import openai-import zhipuai++ from metagpt.config import CONFIG+ from metagpt.logs import logger+ from metagpt.provider.base_gpt_api import BaseGPTAPI+ from metagpt.provider.openai_api import CostManager, log_and_reraise+ from metagpt.provider.zhipuai.zhipu_model_api import ZhiPuModelAPI+++ class ZhiPuEvent(Enum):+ ADD = "add"+ ERROR = "error"+ INTERRUPTED = "interrupted"+ FINISH = "finish"+++ class ZhiPuAIGPTAPI(BaseGPTAPI):+ """+ Refs to `https://open.bigmodel.cn/dev/api#chatglm_turbo`+ From now, there is only one model named `chatglm_turbo`+ """++ use_system_prompt: bool = False # zhipuai has no system prompt when use api++ def __init__(self):+ self.__init_zhipuai(CONFIG)+ self.llm = ZhiPuModelAPI+ self.model = "chatglm_turbo" # so far only one model, just use it+ self._cost_manager = CostManager()++ def __init_zhipuai(self, config: CONFIG):+ assert config.zhipuai_api_key+ zhipuai.api_key = config.zhipuai_api_key+ openai.api_key = zhipuai.api_key # due to use openai sdk, set the api_key but it will't be used.++ def _const_kwargs(self, messages: list[dict]) -> dict:- kwargs = {- "model": self.model,- "prompt": messages,- "temperature": 0.3- }++ kwargs = {"model": self.model, "prompt": messages, "temperature": 0.3}+ return kwargs++ def _update_costs(self, usage: dict):- """ update each request's token cost """++ """update each request's token cost"""+ if CONFIG.calc_usage:+ try:+ prompt_tokens = int(usage.get("prompt_tokens", 0))+ completion_tokens = int(usage.get("completion_tokens", 0))+ self._cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)+ except Exception as e:+ logger.error("zhipuai updats costs failed!", e)++ def get_choice_text(self, resp: dict) -> str:- """ get the first text of choice from llm response """++ """get the first text of choice from llm response"""+ assist_msg = resp.get("data", {}).get("choices", [{"role": "error"}])[-1]+ assert assist_msg["role"] == "assistant"+ return assist_msg.get("content")++ def completion(self, messages: list[dict]) -> dict:+ resp = self.llm.invoke(**self._const_kwargs(messages))+ usage = resp.get("data").get("usage")+ self._update_costs(usage)+ return resp++ async def _achat_completion(self, messages: list[dict]) -> dict:+ resp = await self.llm.ainvoke(**self._const_kwargs(messages))+ usage = resp.get("data").get("usage")+ self._update_costs(usage)+ return resp++ async def acompletion(self, messages: list[dict]) -> dict:+ return await self._achat_completion(messages)++ async def _achat_completion_stream(self, messages: list[dict]) -> str:+ response = await self.llm.asse_invoke(**self._const_kwargs(messages))+ collected_content = []+ usage = {}+ async for event in response.async_events():+ if event.event == ZhiPuEvent.ADD.value:+ content = event.data+ collected_content.append(content)+ print(content, end="")+ elif event.event == ZhiPuEvent.ERROR.value or event.event == ZhiPuEvent.INTERRUPTED.value:+ content = event.data+ logger.error(f"event error: {content}", end="")+ collected_content.append([content])+ elif event.event == ZhiPuEvent.FINISH.value:+ """+ event.meta+ {+ "task_status":"SUCCESS",+ "usage":{+ "completion_tokens":351,+ "prompt_tokens":595,+ "total_tokens":946+ },+ "task_id":"xx",+ "request_id":"xxx"+ }+ """+ meta = json.loads(event.meta)+ usage = meta.get("usage")+ else:+ print(f"zhipuapi else event: {event.data}", end="")++ self._update_costs(usage)+ full_content = "".join(collected_content)+ return full_content++ @retry(+ stop=stop_after_attempt(3),+ wait=wait_fixed(1),+ after=after_log(logger, logger.level("WARNING").name),+ retry=retry_if_exception_type(ConnectionError),- retry_error_callback=log_and_reraise++ retry_error_callback=log_and_reraise,+ )+ async def acompletion_text(self, messages: list[dict], stream=False) -> str:- """ response in async with stream or non-stream mode """++ """response in async with stream or non-stream mode"""+ if stream:+ return await self._achat_completion_stream(messages)+ resp = await self._achat_completion(messages)+ return self.get_choice_text(resp)diff --cc metagpt/repo_parser.pyindex 000000000,0020d47aa..b84dbab9amode 000000,100644..100644--- a/metagpt/repo_parser.py+++ b/metagpt/repo_parser.py@@@ -1,0 -1,94 +1,94 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ """+ @Time : 2023/11/17 17:58+ @Author : alexanderwu+ @File : repo_parser.py+ """++import ast+ import json+ from pathlib import Path++from pprint import pformat+-import ast+ import pandas as pd+ from pydantic import BaseModel, Field-from pprint import pformat++ from metagpt.config import CONFIG+ from metagpt.logs import logger+++ class RepoParser(BaseModel):+ base_directory: Path = Field(default=None)++ def parse_file(self, file_path):+ """Parse a Python file in the repository."""+ try:+ return ast.parse(file_path.read_text()).body+ except:+ return []++ def extract_class_and_function_info(self, tree, file_path):+ """Extract class, function, and global variable information from the AST."""+ file_info = {+ "file": str(file_path.relative_to(self.base_directory)),+ "classes": [],+ "functions": [],- "globals": []++ "globals": [],+ }++ for node in tree:+ if isinstance(node, ast.ClassDef):+ class_methods = [m.name for m in node.body if is_func(m)]+ file_info["classes"].append({"name": node.name, "methods": class_methods})+ elif is_func(node):+ file_info["functions"].append(node.name)+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):+ for target in node.targets if isinstance(node, ast.Assign) else [node.target]:+ if isinstance(target, ast.Name):+ file_info["globals"].append(target.id)+ return file_info++ def generate_symbols(self):+ files_classes = []+ directory = self.base_directory- for path in directory.rglob('*.py'):++ for path in directory.rglob("*.py"):+ tree = self.parse_file(path)+ file_info = self.extract_class_and_function_info(tree, path)+ files_classes.append(file_info)++ return files_classes++ def generate_json_structure(self, output_path):+ """Generate a JSON file documenting the repository structure."""+ files_classes = self.generate_symbols()+ output_path.write_text(json.dumps(files_classes, indent=4))++ def generate_dataframe_structure(self, output_path):+ """Generate a DataFrame documenting the repository structure and save as CSV."""+ files_classes = self.generate_symbols()+ df = pd.DataFrame(files_classes)+ df.to_csv(output_path, index=False)+- def generate_structure(self, output_path=None, mode='json'):++ def generate_structure(self, output_path=None, mode="json"):+ """Generate the structure of the repository as a specified format."""+ output_file = self.base_directory / f"{self.base_directory.name}-structure.{mode}"+ output_path = Path(output_path) if output_path else output_file+- if mode == 'json':++ if mode == "json":+ self.generate_json_structure(output_path)- elif mode == 'csv':++ elif mode == "csv":+ self.generate_dataframe_structure(output_path)+++ def is_func(node):+ return isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+++ def main():+ repo_parser = RepoParser(base_directory=CONFIG.workspace_path / "web_2048")+ symbols = repo_parser.generate_symbols()+ logger.info(pformat(symbols))++-if __name__ == '__main__':++if __name__ == "__main__":+ main()diff --cc metagpt/roles/engineer.pyindex 3cf1f2125,e3f36b50d..48262989c--- a/metagpt/roles/engineer.py+++ b/metagpt/roles/engineer.py@@@ -4,28 -4,47 +4,35 @@@@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."""-import asyncio-import shutil-from collections import OrderedDict+from __future__ import annotations++import jsonfrom pathlib import Path+from typing import Set-from metagpt.actions import WriteCode, WriteCodeReview, WriteDesign, WriteTasks+from metagpt.actions import Action, WriteCode, WriteCodeReview, WriteTasks+ from metagpt.actions.summarize_code import SummarizeCodefrom metagpt.config import CONFIG- from metagpt.const import SYSTEM_DESIGN_FILE_REPO, TASK_FILE_REPO++from metagpt.const import MESSAGE_ROUTE_TO_NONE, SYSTEM_DESIGN_FILE_REPO, TASK_FILE_REPOfrom metagpt.logs import loggerfrom metagpt.roles import Role- from metagpt.schema import CodingContext, Document, Documents, Message-from metagpt.schema import Message-from metagpt.utils.common import CodeParser-from metagpt.utils.special_tokens import FILENAME_CODE_SEP, MSG_SEP---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++from metagpt.schema import (++ CodeSummarizeContext,++ CodingContext,++ Document,++ Documents,++ Message,++)class Engineer(Role):@@@ -39,7 -58,7 +46,6 @@@constraints (str): Constraints for the engineer.n_borg (int): Number of borgs.use_code_review (bool): Whether to use code review.-- todos (list): List of tasks."""def __init__(@@@ -53,20 -72,105 +59,111 @@@) -> None:"""Initializes the Engineer role with given attributes."""super().__init__(name, profile, goal, constraints)- self._init_actions([WriteCode])self.use_code_review = use_code_review- # if self.use_code_review:- # self._init_actions([WriteCode, WriteCodeReview])self._watch([WriteTasks])-- self.todos = []++ self.code_todos = []++ self.summarize_todos = []self.n_borg = n_borg- @classmethod- def parse_tasks(cls, task_msg: Message) -> list[str]:- if task_msg.instruct_content:- return task_msg.instruct_content.dict().get("Task list")- return CodeParser.parse_file_list(block="Task list", text=task_msg.content)-- @classmethod- def parse_code(cls, code_text: str) -> str:- return CodeParser.parse_code(block="", text=code_text)-- @classmethod- def parse_workspace(cls, system_design_msg: Message) -> str:- if system_design_msg.instruct_content:- return system_design_msg.instruct_content.dict().get("project_name").strip().strip("'").strip('"')- return CodeParser.parse_str(block="project_name", text=system_design_msg.content)-- def get_workspace(self) -> Path:- msg = self._rc.memory.get_by_action(WriteDesign)[-1]- if not msg:- return CONFIG.workspace_path / "src"- workspace = self.parse_workspace(msg)- # Codes are written in workspace/{package_name}/{package_name}- return CONFIG.workspace_path / workspace / workspace-- def recreate_workspace(self):- workspace = self.get_workspace()- try:- shutil.rmtree(workspace)- except FileNotFoundError:- pass # The folder does not exist, but we don't care- workspace.mkdir(parents=True, exist_ok=True)-- def write_file(self, filename: str, code: str):- workspace = self.get_workspace()- filename = filename.replace('"', "").replace("\n", "")- file = workspace / filename- file.parent.mkdir(parents=True, exist_ok=True)- file.write_text(code)- return file-- def recv(self, message: Message) -> None:- self._rc.memory.add(message)- if message in self._rc.important_memory:- self.todos = self.parse_tasks(message)-- async def _act_mp(self) -> Message:- # self.recreate_workspace()- todo_coros = []- for todo in self.todos:- todo_coro = WriteCode().run(- context=self._rc.memory.get_by_actions([WriteTasks, WriteDesign]), filename=todo- )- todo_coros.append(todo_coro)-- rsps = await gather_ordered_k(todo_coros, self.n_borg)- for todo, code_rsp in zip(self.todos, rsps):- _ = self.parse_code(code_rsp)- logger.info(todo)- logger.info(code_rsp)- # self.write_file(todo, code)- msg = Message(content=code_rsp, role=self.profile, cause_by=type(self._rc.todo))- self._rc.memory.add(msg)- del self.todos[0]-- logger.info(f"Done {self.get_workspace()} generating.")- msg = Message(content="all done.", role=self.profile, cause_by=type(self._rc.todo))- return msg-- async def _act_sp(self) -> Message:- code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later- for todo in self.todos:- code = await WriteCode().run(context=self._rc.history, filename=todo)- # logger.info(todo)- # logger.info(code_rsp)- # code = self.parse_code(code_rsp)- file_path = self.write_file(todo, code)- msg = Message(content=code, role=self.profile, cause_by=type(self._rc.todo))- self._rc.memory.add(msg)+ @staticmethod+ def _parse_tasks(task_msg: Document) -> list[str]:+ m = json.loads(task_msg.content)+ return m.get("Task list")- async def _act_sp_precision(self, review=False) -> Set[str]:- code_msg = todo + FILENAME_CODE_SEP + str(file_path)- code_msg_all.append(code_msg)++ # @classmethod++ # def parse_tasks(cls, task_msg: Message) -> list[str]:++ # if task_msg.instruct_content:++ # return task_msg.instruct_content.dict().get("Task list")++ # return CodeParser.parse_file_list(block="Task list", text=task_msg.content)++ #++ # @classmethod++ # def parse_code(cls, code_text: str) -> str:++ # return CodeParser.parse_code(block="", text=code_text)++ #++ # @classmethod++ # def parse_workspace(cls, system_design_msg: Message) -> str:++ # if system_design_msg.instruct_content:++ # return system_design_msg.instruct_content.dict().get("project_name").strip().strip("'").strip('"')++ # return CodeParser.parse_str(block="project_name", text=system_design_msg.content)++ #++ # def get_workspace(self) -> Path:++ # msg = self._rc.memory.get_by_action(WriteDesign)[-1]++ # if not msg:++ # return CONFIG.workspace_path / "src"++ # workspace = self.parse_workspace(msg)++ # # Codes are written in workspace/{package_name}/{package_name}++ # return CONFIG.workspace_path / workspace / workspace++ #++ # def recreate_workspace(self):++ # workspace = self.get_workspace()++ # try:++ # shutil.rmtree(workspace)++ # except FileNotFoundError:++ # pass # The folder does not exist, but we don't care++ # workspace.mkdir(parents=True, exist_ok=True)++ #++ # def write_file(self, filename: str, code: str):++ # workspace = self.get_workspace()++ # filename = filename.replace('"', "").replace("\n", "")++ # file = workspace / filename++ # file.parent.mkdir(parents=True, exist_ok=True)++ # file.write_text(code)++ # return file++ #++ # def recv(self, message: Message) -> None:++ # self._rc.memory.add(message)++ # if message in self._rc.important_memory:++ # self.todos = self.parse_tasks(message)++ #++ # async def _act_mp(self) -> Message:++ # # self.recreate_workspace()++ # todo_coros = []++ # for todo in self.todos:++ # todo_coro = WriteCode().run(++ # context=self._rc.memory.get_by_actions([WriteTasks, WriteDesign]), filename=todo++ # )++ # todo_coros.append(todo_coro)++ #++ # rsps = await gather_ordered_k(todo_coros, self.n_borg)++ # for todo, code_rsp in zip(self.todos, rsps):++ # _ = self.parse_code(code_rsp)++ # logger.info(todo)++ # logger.info(code_rsp)++ # # self.write_file(todo, code)++ # msg = Message(content=code_rsp, role=self.profile, cause_by=type(self._rc.todo))++ # self._rc.memory.add(msg)++ # del self.todos[0]++ #++ # logger.info(f"Done {self.get_workspace()} generating.")++ # msg = Message(content="all done.", role=self.profile, cause_by=type(self._rc.todo))++ # return msg++ #++ # async def _act_sp(self) -> Message:++ # code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later++ # for todo in self.todos:++ # code = await WriteCode().run(context=self._rc.history, filename=todo)++ # # logger.info(todo)++ # # logger.info(code_rsp)++ # # code = self.parse_code(code_rsp)++ # file_path = self.write_file(todo, code)++ # msg = Message(content=code, role=self.profile, cause_by=type(self._rc.todo))++ # self._rc.memory.add(msg)++ #++ # code_msg = todo + FILENAME_CODE_SEP + str(file_path)++ # code_msg_all.append(code_msg)++ #++ # logger.info(f"Done {self.get_workspace()} generating.")++ # msg = Message(++ # content=MSG_SEP.join(code_msg_all), role=self.profile, cause_by=type(self._rc.todo), send_to="QaEngineer"++ # )++ # return msg+- logger.info(f"Done {self.get_workspace()} generating.")- msg = Message(- content=MSG_SEP.join(code_msg_all), role=self.profile, cause_by=type(self._rc.todo), send_to="QaEngineer"- )- return msg-- async def _act_sp_with_cr(self) -> Message:- code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later- for todo in self.todos:++ # async def _act_sp_with_cr(self) -> Message:++ # code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later++ async def _act_sp_with_cr(self, review=False) -> Set[str]:+ changed_files = set()+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)- for todo in self.todos:++ for todo in self.code_todos:"""# Select essential information from the historical data to reduce the length of the prompt (summarized from human experience):1. All from Architect@@@ -74,120 -178,43 +171,180 @@@3. Do we need other codes (currently needed)?TODO: The goal is not to need it. After clear task decomposition, based on the design idea, you should be able to write a single file without needing other codes. If you can't, it means you need a clearer definition. This is the key to writing longer code."""- context = []- msg = self._rc.memory.get_by_actions([WriteDesign, WriteTasks, WriteCode])- for m in msg:- context.append(m.content)- context_str = "\n----------\n".join(context)- # Write code- code = await WriteCode().run(context=context_str, filename=todo)+ coding_context = await todo.run()# Code review- if self.use_code_review:- # try:- rewrite_code = await WriteCodeReview().run(context=context_str, code=code, filename=todo)- code = rewrite_code- # except Exception as e:- # logger.error("code review failed!", e)- file_path = self.write_file(todo, code)- msg = Message(content=code, role=self.profile, cause_by=WriteCode)+ if review:- try:- coding_context = await WriteCodeReview(context=coding_context, llm=self._llm).run()- except Exception as e:- logger.error("code review failed!", e)- pass++ coding_context = await WriteCodeReview(context=coding_context, llm=self._llm).run()+ await src_file_repo.save(+ coding_context.filename,+ dependencies={coding_context.design_doc.root_relative_path, coding_context.task_doc.root_relative_path},+ content=coding_context.code_doc.content,+ )+ msg = Message(+ content=coding_context.json(), instruct_content=coding_context, role=self.profile, cause_by=WriteCode+ )++ # =======++ # context = []++ # msg = self._rc.memory.get_by_actions([WriteDesign, WriteTasks, WriteCode])++ # for m in msg:++ # context.append(m.content)++ # context_str = "\n----------\n".join(context)++ # # Write code++ # code = await WriteCode().run(context=context_str, filename=todo)++ # # Code review++ # if self.use_code_review:++ # # try:++ # rewrite_code = await WriteCodeReview().run(context=context_str, code=code, filename=todo)++ # code = rewrite_code++ # # except Exception as e:++ # # logger.error("code review failed!", e)++ # file_path = self.write_file(todo, code)++ # msg = Message(content=code, role=self.profile, cause_by=WriteCode)++ # >>>>>>> feature/geekan_cli_etcself._rc.memory.add(msg)- code_msg = todo + FILENAME_CODE_SEP + str(file_path)- code_msg_all.append(code_msg)+ changed_files.add(coding_context.code_doc.filename)+ if not changed_files:+ logger.info("Nothing has changed.")+ return changed_files+- async def _act(self) -> Message:++ async def _act(self) -> Message | None:+ """Determines the mode of action based on whether code review is used."""- changed_files = await self._act_sp_precision(review=self.use_code_review)- # Unit tests only.- if CONFIG.REQA_FILENAME and CONFIG.REQA_FILENAME not in changed_files:- changed_files.add(CONFIG.REQA_FILENAME)-- from metagpt.roles import QaEngineer # Avoid circular references.-- msg = Message(- content="\n".join(changed_files),- role=self.profile,- cause_by=WriteCodeReview if self.use_code_review else WriteCode,- send_to=QaEngineer,- )- return msg++ if self._rc.todo is None:++ return None++ if isinstance(self._rc.todo, WriteCode):++ changed_files = await self._act_sp_with_cr(review=self.use_code_review)++ # Unit tests only.++ if CONFIG.REQA_FILENAME and CONFIG.REQA_FILENAME not in changed_files:++ changed_files.add(CONFIG.REQA_FILENAME)++ return Message(++ content="\n".join(changed_files),++ role=self.profile,++ cause_by=WriteCodeReview if self.use_code_review else WriteCode,++ send_to="Edward", # The name of QaEngineer++ )++ if isinstance(self._rc.todo, SummarizeCode):++ summaries = []++ for todo in self.summarize_todos:++ summary = await todo.run()++ summaries.append(summary.json(ensure_ascii=False))++ return Message(++ content="\n".join(summaries),++ role=self.profile,++ cause_by=SummarizeCode,++ send_to=MESSAGE_ROUTE_TO_NONE,++ )++ return None++ async def _think(self) -> Action | None:+ if not CONFIG.src_workspace:+ CONFIG.src_workspace = CONFIG.git_repo.workdir / CONFIG.git_repo.workdir.name++ if not self.code_todos:++ await self._new_code_actions()++ elif not self.summarize_todos:++ await self._new_summarize_actions()++ else:++ return None++ return self._rc.todo # For agent store+- context = []- msg = self._rc.memory.get_by_actions([WriteDesign, WriteTasks, WriteCode])- for m in msg:- context.append(m.content)- context_str = "\n----------\n".join(context)- summary = await SummarizeCode().run(context=context_str)++ @staticmethod++ async def _new_coding_context(++ filename, src_file_repo, task_file_repo, design_file_repo, dependency++ ) -> CodingContext:++ old_code_doc = await src_file_repo.get(filename)++ if not old_code_doc:++ old_code_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content="")++ dependencies = {Path(i) for i in await dependency.get(old_code_doc.root_relative_path)}++ task_doc = None++ design_doc = None++ for i in dependencies:++ if str(i.parent) == TASK_FILE_REPO:++ task_doc = task_file_repo.get(i.filename)++ elif str(i.parent) == SYSTEM_DESIGN_FILE_REPO:++ design_doc = design_file_repo.get(i.filename)++ context = CodingContext(filename=filename, design_doc=design_doc, task_doc=task_doc, code_doc=old_code_doc)++ return context+- logger.info(f"Done {self.get_workspace()} generating.")- msg = Message(- content=MSG_SEP.join(code_msg_all), role=self.profile, cause_by=type(self._rc.todo), send_to="QaEngineer"++ @staticmethod++ async def _new_coding_doc(filename, src_file_repo, task_file_repo, design_file_repo, dependency):++ context = await Engineer._new_coding_context(++ filename, src_file_repo, task_file_repo, design_file_repo, dependency+ )- return msg++ coding_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content=context.json())++ return coding_doc+- async def _act(self) -> Message:- """Determines the mode of action based on whether code review is used."""- logger.info(f"{self._setting}: ready to WriteCode")- if self.use_code_review:- return await self._act_sp_with_cr()- return await self._act_sp()++ # =======++ # async def _act(self) -> Message:++ # """Determines the mode of action based on whether code review is used."""++ # logger.info(f"{self._setting}: ready to WriteCode")++ # if self.use_code_review:++ # return await self._act_sp_with_cr()++ # return await self._act_sp()++ # >>>>>>> feature/geekan_cli_etc++++ async def _new_code_actions(self):+ # Prepare file repos+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ changed_src_files = src_file_repo.changed_files+ task_file_repo = CONFIG.git_repo.new_file_repository(TASK_FILE_REPO)+ changed_task_files = task_file_repo.changed_files+ design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)++ changed_files = Documents()+ # Recode caused by upstream changes.+ for filename in changed_task_files:+ design_doc = await design_file_repo.get(filename)+ task_doc = await task_file_repo.get(filename)+ task_list = self._parse_tasks(task_doc)+ for task_filename in task_list:+ old_code_doc = await src_file_repo.get(task_filename)+ if not old_code_doc:+ old_code_doc = Document(root_path=str(src_file_repo.root_path), filename=task_filename, content="")+ context = CodingContext(+ filename=task_filename, design_doc=design_doc, task_doc=task_doc, code_doc=old_code_doc+ )+ coding_doc = Document(+ root_path=str(src_file_repo.root_path), filename=task_filename, content=context.json()+ )+ if task_filename in changed_files.docs:+ logger.warning(+ f"Log to expose potential conflicts: {coding_doc.json()} & "+ f"{changed_files.docs[task_filename].json()}"+ )+ changed_files.docs[task_filename] = coding_doc- self.todos = [WriteCode(context=i, llm=self._llm) for i in changed_files.docs.values()]++ self.code_todos = [WriteCode(context=i, llm=self._llm) for i in changed_files.docs.values()]+ # Code directly modified by the user.+ dependency = await CONFIG.git_repo.get_dependency()+ for filename in changed_src_files:+ if filename in changed_files.docs:+ continue+ coding_doc = await self._new_coding_doc(+ filename=filename,+ src_file_repo=src_file_repo,+ task_file_repo=task_file_repo,+ design_file_repo=design_file_repo,+ dependency=dependency,+ )+ changed_files.docs[filename] = coding_doc- self.todos.append(WriteCode(context=coding_doc, llm=self._llm))++ self.code_todos.append(WriteCode(context=coding_doc, llm=self._llm))+- if self.todos:- self._rc.todo = self.todos[0]- return self._rc.todo # For agent store++ if self.code_todos:++ self._rc.todo = self.code_todos[0]+- @staticmethod- async def _new_coding_context(- filename, src_file_repo, task_file_repo, design_file_repo, dependency- ) -> CodingContext:- old_code_doc = await src_file_repo.get(filename)- if not old_code_doc:- old_code_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content="")- dependencies = {Path(i) for i in await dependency.get(old_code_doc.root_relative_path)}- task_doc = None- design_doc = None- for i in dependencies:- if str(i.parent) == TASK_FILE_REPO:- task_doc = task_file_repo.get(i.filename)- elif str(i.parent) == SYSTEM_DESIGN_FILE_REPO:- design_doc = design_file_repo.get(i.filename)- context = CodingContext(filename=filename, design_doc=design_doc, task_doc=task_doc, code_doc=old_code_doc)- return context-- @staticmethod- async def _new_coding_doc(filename, src_file_repo, task_file_repo, design_file_repo, dependency):- context = await Engineer._new_coding_context(- filename, src_file_repo, task_file_repo, design_file_repo, dependency- )- coding_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content=context.json())- return coding_doc++ async def _new_summarize_actions(self):++ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)++ changed_src_files = src_file_repo.changed_files++ # Generate a SummarizeCode action for each pair of (system_design_doc, task_doc).++ summerizations = {}++ for filename in changed_src_files:++ depenencies = src_file_repo.get_dependency(filename=filename)++ ctx = CodeSummarizeContext.loads(filenames=depenencies)++ if ctx not in summerizations:++ summerizations[ctx] = set()++ srcs = summerizations.get(ctx)++ srcs.add(filename)++ for ctx, filenames in summerizations.items():++ ctx.codes_filenames = filenames++ self.summarize_todos.append(SummarizeCode(context=ctx, llm=self._llm))++ if self.summarize_todos:++ self._rc.todo = self.summarize_todos[0]diff --cc metagpt/roles/product_manager.pyindex bc6771829,f6172b607..a13a13f6c--- a/metagpt/roles/product_manager.py+++ b/metagpt/roles/product_manager.py@@@ -4,11 -4,8 +4,12 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : product_manager.py+@Modified By: mashenquan, 2023/11/27. Add `PrepareDocuments` action according to Section 2.2.3.5.1 of RFC 135."""- from metagpt.actions import BossRequirement, WritePRD+++ from metagpt.actions import UserRequirement, WritePRD+from metagpt.actions.prepare_documents import PrepareDocuments+from metagpt.config import CONFIGfrom metagpt.roles import Role@@@ -40,13 -37,5 +41,14 @@@ class ProductManager(Role)constraints (str): Constraints or limitations for the product manager."""super().__init__(name, profile, goal, constraints)- self._init_actions([WritePRD])- self._watch([UserRequirement])+++ self._init_actions([PrepareDocuments, WritePRD])- self._watch([BossRequirement, PrepareDocuments])++ self._watch([UserRequirement, PrepareDocuments])++ async def _think(self) -> None:+ """Decide what to do"""+ if CONFIG.git_repo:+ self._set_state(1)+ else:+ self._set_state(0)+ return self._rc.tododiff --cc metagpt/roles/qa_engineer.pyindex 763ab6a3f,313fe4aba..fd2dcc786--- a/metagpt/roles/qa_engineer.py+++ b/metagpt/roles/qa_engineer.py@@@ -4,25 -4,25 +4,27 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : qa_engineer.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.2.1 and 2.2.2 of RFC 116, modify the data+ type of the `cause_by` value in the `Message` to a string, and utilize the new message filtering feature.+@Modified By: mashenquan, 2023-11-27.+ 1. Following the think-act principle, solidify the task parameters when creating the+ WriteTest/RunCode/DebugError object, rather than passing them in when calling the run function.+ 2. According to Section 2.2.3.5.7 of RFC 135, change the method of transferring files from using the Message+ to using file references."""-import os-from pathlib import Path+from metagpt.actions import DebugError, RunCode, WriteCode, WriteCodeReview, WriteTest+-from metagpt.actions import (- DebugError,- RunCode,- WriteCode,- WriteCodeReview,- WriteDesign,- WriteTest,-)+ # from metagpt.const import WORKSPACE_ROOTfrom metagpt.config import CONFIG+from metagpt.const import (+ MESSAGE_ROUTE_TO_NONE,+ TEST_CODES_FILE_REPO,+ TEST_OUTPUTS_FILE_REPO,+)from metagpt.logs import loggerfrom metagpt.roles import Role-from metagpt.schema import Message-from metagpt.utils.common import CodeParser, parse_recipient-from metagpt.utils.special_tokens import FILENAME_CODE_SEP, MSG_SEP+from metagpt.schema import Document, Message, RunCodeContext, TestingContext+from metagpt.utils.common import any_to_str_set, parse_recipientclass QaEngineer(Role):@@@ -42,96 -42,116 +44,122 @@@self.test_round = 0self.test_round_allowed = test_round_allowed- @classmethod- def parse_workspace(cls, system_design_msg: Message) -> str:- if system_design_msg.instruct_content:- return system_design_msg.instruct_content.dict().get("project_name")- return CodeParser.parse_str(block="project_name", text=system_design_msg.content)-- def get_workspace(self, return_proj_dir=True) -> Path:- msg = self._rc.memory.get_by_action(WriteDesign)[-1]- if not msg:- return CONFIG.workspace_path / "src"- workspace = self.parse_workspace(msg)- # project directory: workspace/{package_name}, which contains package source code folder, tests folder, resources folder, etc.- if return_proj_dir:- return CONFIG.workspace_path / workspace- # development codes directory: workspace/{package_name}/{package_name}- return CONFIG.workspace_path / workspace / workspace-- def write_file(self, filename: str, code: str):- workspace = self.get_workspace() / "tests"- file = workspace / filename- file.parent.mkdir(parents=True, exist_ok=True)- file.write_text(code)-++ # <<<<<<< HEAD++ # =======++ # @classmethod++ # def parse_workspace(cls, system_design_msg: Message) -> str:++ # if system_design_msg.instruct_content:++ # return system_design_msg.instruct_content.dict().get("project_name")++ # return CodeParser.parse_str(block="project_name", text=system_design_msg.content)++ #++ # def get_workspace(self, return_proj_dir=True) -> Path:++ # msg = self._rc.memory.get_by_action(WriteDesign)[-1]++ # if not msg:++ # return CONFIG.workspace_path / "src"++ # workspace = self.parse_workspace(msg)++ # # project directory: workspace/{package_name}, which contains package source code folder, tests folder, resources folder, etc.++ # if return_proj_dir:++ # return CONFIG.workspace_path / workspace++ # # development codes directory: workspace/{package_name}/{package_name}++ # return CONFIG.workspace_path / workspace / workspace++ #++ # def write_file(self, filename: str, code: str):++ # workspace = self.get_workspace() / "tests"++ # file = workspace / filename++ # file.parent.mkdir(parents=True, exist_ok=True)++ # file.write_text(code)++ #++ # >>>>>>> feature/geekan_cli_etcasync def _write_test(self, message: Message) -> None:- code_msgs = message.content.split(MSG_SEP)- # result_msg_all = []- for code_msg in code_msgs:+ changed_files = message.content.splitlines()+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ tests_file_repo = CONFIG.git_repo.new_file_repository(TEST_CODES_FILE_REPO)+ for filename in changed_files:# write tests- file_name, file_path = code_msg.split(FILENAME_CODE_SEP)- code_to_test = open(file_path, "r").read()- if "test" in file_name:- continue # Engineer might write some test files, skip testing a test file- test_file_name = "test_" + file_name- test_file_path = self.get_workspace() / "tests" / test_file_name- logger.info(f"Writing {test_file_name}..")- test_code = await WriteTest().run(- code_to_test=code_to_test,- test_file_name=test_file_name,- # source_file_name=file_name,- source_file_path=file_path,- workspace=self.get_workspace(),+ if not filename or "test" in filename:+ continue+ code_doc = await src_file_repo.get(filename)+ test_doc = await tests_file_repo.get("test_" + code_doc.filename)+ if not test_doc:+ test_doc = Document(+ root_path=str(tests_file_repo.root_path), filename="test_" + code_doc.filename, content=""+ )+ logger.info(f"Writing {test_doc.filename}..")+ context = TestingContext(filename=test_doc.filename, test_doc=test_doc, code_doc=code_doc)+ context = await WriteTest(context=context, llm=self._llm).run()+ await tests_file_repo.save(+ filename=context.test_doc.filename,+ content=context.test_doc.content,+ dependencies={context.code_doc.root_relative_path},)- self.write_file(test_file_name, test_code)# prepare context for run tests in next round- command = ["python", f"tests/{test_file_name}"]- file_info = {- "file_name": file_name,- "file_path": str(file_path),- "test_file_name": test_file_name,- "test_file_path": str(test_file_path),- "command": command,- }- msg = Message(- content=str(file_info),- role=self.profile,- cause_by=WriteTest,- sent_from=self.profile,- send_to=self.profile,+ run_code_context = RunCodeContext(+ command=["python", context.test_doc.root_relative_path],+ code_filename=context.code_doc.filename,+ test_filename=context.test_doc.filename,+ working_directory=str(CONFIG.git_repo.workdir),+ additional_python_paths=[str(CONFIG.src_workspace)],+ )+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=WriteTest,+ sent_from=self,+ send_to=self,+ ))- self._publish_message(msg)- logger.info(f"Done {self.get_workspace()}/tests generating.")+ logger.info(f"Done {str(tests_file_repo.workdir)} generating.")async def _run_code(self, msg):- file_info = eval(msg.content)- development_file_path = file_info["file_path"]- test_file_path = file_info["test_file_path"]- if not os.path.exists(development_file_path) or not os.path.exists(test_file_path):+ run_code_context = RunCodeContext.loads(msg.content)+ src_doc = await CONFIG.git_repo.new_file_repository(CONFIG.src_workspace).get(run_code_context.code_filename)+ if not src_doc:return-- development_code = open(development_file_path, "r").read()- test_code = open(test_file_path, "r").read()- proj_dir = self.get_workspace()- development_code_dir = self.get_workspace(return_proj_dir=False)-- result_msg = await RunCode().run(- mode="script",- code=development_code,- code_file_name=file_info["file_name"],- test_code=test_code,- test_file_name=file_info["test_file_name"],- command=file_info["command"],- working_directory=proj_dir, # workspace/package_name, will run tests/test_xxx.py here- additional_python_paths=[development_code_dir], # workspace/package_name/package_name,- # import statement inside package code needs this+ test_doc = await CONFIG.git_repo.new_file_repository(TEST_CODES_FILE_REPO).get(run_code_context.test_filename)+ if not test_doc:+ return+ run_code_context.code = src_doc.content+ run_code_context.test_code = test_doc.content+ result = await RunCode(context=run_code_context, llm=self._llm).run()+ run_code_context.output_filename = run_code_context.test_filename + ".json"+ await CONFIG.git_repo.new_file_repository(TEST_OUTPUTS_FILE_REPO).save(+ filename=run_code_context.output_filename,+ content=result.json(),+ dependencies={src_doc.root_relative_path, test_doc.root_relative_path},+ )+ run_code_context.code = None+ run_code_context.test_code = None+ recipient = parse_recipient(result.summary) # the recipient might be Engineer or myself+ mappings = {"Engineer": "Alex", "QaEngineer": "Edward"}+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=RunCode,+ sent_from=self,+ send_to=mappings.get(recipient, MESSAGE_ROUTE_TO_NONE),+ ))-- recipient = parse_recipient(result_msg) # the recipient might be Engineer or myself- content = str(file_info) + FILENAME_CODE_SEP + result_msg- msg = Message(content=content, role=self.profile, cause_by=RunCode, sent_from=self.profile, send_to=recipient)- self._publish_message(msg)async def _debug_error(self, msg):- file_info, context = msg.content.split(FILENAME_CODE_SEP)- file_name, code = await DebugError().run(context)- if file_name:- self.write_file(file_name, code)- recipient = msg.sent_from # send back to the one who ran the code for another run, might be one's self- msg = Message(- content=file_info, role=self.profile, cause_by=DebugError, sent_from=self.profile, send_to=recipient+ run_code_context = RunCodeContext.loads(msg.content)+ code = await DebugError(context=run_code_context, llm=self._llm).run()+ await CONFIG.git_repo.new_file_repository(CONFIG.src_workspace).save(+ filename=run_code_context.code_filename, content=code+ )+ run_code_context.output = None+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=DebugError,+ sent_from=self,+ send_to=self,)- self._publish_message(msg)-- async def _observe(self) -> int:- await super()._observe()- self._rc.news = [- msg for msg in self._rc.news if msg.send_to == self.profile- ] # only relevant msgs count as observed news- return len(self._rc.news)+ )async def _act(self) -> Message:if self.test_round > self.test_round_allowed:diff --cc metagpt/roles/role.pyindex 2e3bcbbd5,5c5e7b76d..ba07c0c16--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -20,17 -7,19 +20,20 @@@"""from __future__ import annotations-from typing import Iterable, Type, Union+ from enum import Enum+from typing import Iterable, Set, Typefrom pydantic import BaseModel, Field-# from metagpt.environment import Environment-from metagpt.config import CONFIGfrom metagpt.actions import Action, ActionOutput+from metagpt.config import CONFIG- from metagpt.llm import LLM+ from metagpt.llm import LLM, HumanProviderfrom metagpt.logs import logger- from metagpt.memory import LongTermMemory, Memory+ from metagpt.memory import Memory+++ # from metagpt.memory import LongTermMemory-from metagpt.schema import Message+from metagpt.schema import Message, MessageQueue+from metagpt.utils.common import any_to_strPREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """@@@ -60,9 -51,18 +65,19 @@@ ROLE_TEMPLATE = """Your response shoul"""+ class RoleReactMode(str, Enum):+ REACT = "react"+ BY_ORDER = "by_order"+ PLAN_AND_ACT = "plan_and_act"++ @classmethod+ def values(cls):+ return [item.value for item in cls]++class RoleSetting(BaseModel):"""Role Settings"""+name: strprofile: strgoal: str@@@ -78,15 -79,15 +94,19 @@@class RoleContext(BaseModel):"""Role Runtime Context"""- env: 'Environment' = Field(default=None)++ env: "Environment" = Field(default=None)+ msg_buffer: MessageQueue = Field(default_factory=MessageQueue) # Message Buffer with Asynchronous Updatesmemory: Memory = Field(default_factory=Memory)- long_term_memory: LongTermMemory = Field(default_factory=LongTermMemory)- state: int = Field(default=0)+ # long_term_memory: LongTermMemory = Field(default_factory=LongTermMemory)- state: int = Field(default=-1) # -1 indicates initial or termination state where todo is None++ state: int = Field(default=-1) # -1 indicates initial or termination state where todo is Nonetodo: Action = Field(default=None)- watch: set[Type[Action]] = Field(default_factory=set)+ watch: set[str] = Field(default_factory=set)news: list[Type[Message]] = Field(default=[])- react_mode: RoleReactMode = RoleReactMode.REACT # see `Role._set_react_mode` for definitions of the following two attributes++ react_mode: RoleReactMode = (++ RoleReactMode.REACT++ ) # see `Role._set_react_mode` for definitions of the following two attributes+ max_react_loop: int = 1class Config:arbitrary_types_allowed = True@@@ -109,9 -110,10 +129,11 @@@class Role:"""Role/Agent"""- def __init__(self, name="", profile="", goal="", constraints="", desc=""):- self._llm = LLM()- self._setting = RoleSetting(name=name, profile=profile, goal=goal, constraints=constraints, desc=desc)+ def __init__(self, name="", profile="", goal="", constraints="", desc="", is_human=False):+ self._llm = LLM() if not is_human else HumanProvider()- self._setting = RoleSetting(name=name, profile=profile, goal=goal,- constraints=constraints, desc=desc, is_human=is_human)++ self._setting = RoleSetting(++ name=name, profile=profile, goal=goal, constraints=constraints, desc=desc, is_human=is_human++ )self._states = []self._actions = []self._role_id = str(self._setting)@@@ -126,44 -127,66 +148,87 @@@self._reset()for idx, action in enumerate(actions):if not isinstance(action, Action):- i = action("")+ i = action("", llm=self._llm)else:+ if self._setting.is_human and not isinstance(action.llm, HumanProvider):- logger.warning(f"is_human attribute does not take effect,"- f"as Role's {str(action)} was initialized using LLM, try passing in Action classes instead of initialized instances")++ logger.warning(++ f"is_human attribute does not take effect,"++ f"as Role's {str(action)} was initialized using LLM, try passing in Action classes instead of initialized instances"++ )i = action+ i.set_env(self._rc.env)i.set_prefix(self._get_prefix(), self.profile)self._actions.append(i)self._states.append(f"{idx}. {action}")+ def _set_react_mode(self, react_mode: str, max_react_loop: int = 1):+ """Set strategy of the Role reacting to observed Message. Variation lies in how+ this Role elects action to perform during the _think stage, especially if it is capable of multiple Actions.++ Args:+ react_mode (str): Mode for choosing action during the _think stage, can be one of:+ "react": standard think-act loop in the ReAct paper, alternating thinking and acting to solve the task, i.e. _think -> _act -> _think -> _act -> ...+ Use llm to select actions in _think dynamically;+ "by_order": switch action each time by order defined in _init_actions, i.e. _act (Action1) -> _act (Action2) -> ...;+ "plan_and_act": first plan, then execute an action sequence, i.e. _think (of a plan) -> _act -> _act -> ...+ Use llm to come up with the plan dynamically.+ Defaults to "react".+ max_react_loop (int): Maximum react cycles to execute, used to prevent the agent from reacting forever.+ Take effect only when react_mode is react, in which we use llm to choose actions, including termination.+ Defaults to 1, i.e. _think -> _act (-> return result and end)+ """+ assert react_mode in RoleReactMode.values(), f"react_mode must be one of {RoleReactMode.values()}"+ self._rc.react_mode = react_mode+ if react_mode == RoleReactMode.REACT:+ self._rc.max_react_loop = max_react_loop+def _watch(self, actions: Iterable[Type[Action]]):- """Listen to the corresponding behaviors"""- self._rc.watch.update(actions)+ """Watch Actions of interest. Role will select Messages caused by these Actions from its personal message+ buffer during _observe.+ """+ tags = {any_to_str(t) for t in actions}+ self._rc.watch.update(tags)# check RoleContext after adding watch actionsself._rc.check(self._role_id)+ def subscribe(self, tags: Set[str]):+ """Used to receive Messages with certain tags from the environment. Message will be put into personal message+ buffer to be further processed in _observe. By default, a Role subscribes Messages with a tag of its own name+ or profile.+ """+ self._subscription = tags+ if self._rc.env: # According to the routing feature plan in Chapter 2.2.3.2 of RFC 113+ self._rc.env.set_subscription(self, self._subscription)+- def _set_state(self, state):+ def _set_state(self, state: int):"""Update the current state."""self._rc.state = statelogger.debug(self._actions)- self._rc.todo = self._actions[self._rc.state]+ self._rc.todo = self._actions[self._rc.state] if state >= 0 else None- def set_env(self, env: 'Environment'):- """Set the environment in which the role works. The role can talk to the environment and can also receive messages by observing."""+ def set_env(self, env: "Environment"):+ """Set the environment in which the role works. The role can talk to the environment and can also receive+ messages by observing."""self._rc.env = env-- def set_doc(self, content: str, filename: str):- return self._rc.env.set_doc(content, filename)-- def get_doc(self, filename: str):- return self._rc.env.get_doc(filename)-- def set(self, k, v):- return self._rc.env.set(k, v)-- def get(self, k):- return self._rc.env.get(k)+ if env:+ env.set_subscription(self, self._subscription)+++ # # Replaced by FileRepository.set_file++ # def set_doc(self, content: str, filename: str):++ # return self._rc.env.set_doc(content, filename)++ #++ # # Replaced by FileRepository.get_file++ # def get_doc(self, filename: str):++ # return self._rc.env.get_doc(filename)++ #++ # # Replaced by CONFIG.xx++ # def set(self, k, v):++ # return self._rc.env.set(k, v)++ #++ # # Replaced by CONFIG.xx++ # def get(self, k):++ # return self._rc.env.get(k)+@propertydef profile(self):"""Get the role description (position)"""@@@ -192,28 -205,36 +257,36 @@@self._set_state(0)returnprompt = self._get_prefix()- prompt += STATE_TEMPLATE.format(history=self._rc.history, states="\n".join(self._states),- n_states=len(self._states) - 1, previous_state=self._rc.state)+ prompt += STATE_TEMPLATE.format(- history=self._rc.history, states="\n".join(self._states), n_states=len(self._states) - 1++ history=self._rc.history,++ states="\n".join(self._states),++ n_states=len(self._states) - 1,++ previous_state=self._rc.state,+ )+ # print(prompt)next_state = await self._llm.aask(prompt)logger.debug(f"{prompt=}")- if not next_state.isdigit() or int(next_state) not in range(len(self._states)):- logger.warning(f"Invalid answer of state, {next_state=}")- next_state = "0"- self._set_state(int(next_state))- if (not next_state.isdigit() and next_state != "-1") \- or int(next_state) not in range(-1, len(self._states)):- logger.warning(f'Invalid answer of state, {next_state=}, will be set to -1')++ if (not next_state.isdigit() and next_state != "-1") or int(next_state) not in range(-1, len(self._states)):++ logger.warning(f"Invalid answer of state, {next_state=}, will be set to -1")+ next_state = -1+ else:+ next_state = int(next_state)+ if next_state == -1:+ logger.info(f"End actions with {next_state=}")+ self._set_state(next_state)async def _act(self) -> Message:- # prompt = self.get_prefix()- # prompt += ROLE_TEMPLATE.format(name=self.profile, state=self.states[self.state], result=response,- # history=self.history)-logger.info(f"{self._setting}: ready to {self._rc.todo}")response = await self._rc.todo.run(self._rc.important_memory)- # logger.info(response)if isinstance(response, ActionOutput):- msg = Message(content=response.content, instruct_content=response.instruct_content,- role=self.profile, cause_by=type(self._rc.todo))+ msg = Message(+ content=response.content,+ instruct_content=response.instruct_content,+ role=self.profile,+ cause_by=self._rc.todo,+ )else:- msg = Message(content=response, role=self.profile, cause_by=type(self._rc.todo))- self._rc.memory.add(msg)- # logger.debug(f"{response}")+ msg = Message(content=response, role=self.profile, cause_by=self._rc.todo)return msg@@@ -243,31 -263,76 +316,87 @@@returnself._rc.env.publish_message(msg)+ def put_message(self, message):+ """Place the message into the Role object's private message buffer."""+ if not message:+ return+ self._rc.msg_buffer.push(message)+async def _react(self) -> Message:- """Think first, then act"""- await self._think()- logger.debug(f"{self._setting}: {self._rc.state=}, will do {self._rc.todo}")- return await self._act()+ """Think first, then act, until the Role _think it is time to stop and requires no more todo.- This is the standard think-act loop in the ReAct paper, which alternates thinking and acting in task solving, i.e. _think -> _act -> _think -> _act -> ...++ This is the standard think-act loop in the ReAct paper, which alternates thinking and acting in task solving, i.e. _think -> _act -> _think -> _act -> ...+ Use llm to select actions in _think dynamically+ """+ actions_taken = 0- rsp = Message("No actions taken yet") # will be overwritten after Role _act++ rsp = Message("No actions taken yet") # will be overwritten after Role _act+ while actions_taken < self._rc.max_react_loop:+ # think+ await self._think()+ if self._rc.todo is None:+ break+ # act+ logger.debug(f"{self._setting}: {self._rc.state=}, will do {self._rc.todo}")- rsp = await self._act()++ rsp = await self._act() # 这个rsp是否需要publish_message?+ actions_taken += 1- return rsp # return output from the last action++ return rsp # return output from the last action++ async def _act_by_order(self) -> Message:+ """switch action each time by order defined in _init_actions, i.e. _act (Action1) -> _act (Action2) -> ..."""+ for i in range(len(self._states)):+ self._set_state(i)+ rsp = await self._act()- return rsp # return output from the last action++ return rsp # return output from the last action++ async def _plan_and_act(self) -> Message:+ """first plan, then execute an action sequence, i.e. _think (of a plan) -> _act -> _act -> ... Use llm to come up with the plan dynamically."""+ # TODO: to be implemented+ return Message("")++ async def react(self) -> Message:+ """Entry to one of three strategies by which Role reacts to the observed Message"""+ if self._rc.react_mode == RoleReactMode.REACT:+ rsp = await self._react()+ elif self._rc.react_mode == RoleReactMode.BY_ORDER:+ rsp = await self._act_by_order()+ elif self._rc.react_mode == RoleReactMode.PLAN_AND_ACT:+ rsp = await self._plan_and_act()- self._set_state(state=-1) # current reaction is complete, reset state to -1 and todo back to None++ self._set_state(state=-1) # current reaction is complete, reset state to -1 and todo back to None+ return rsp+- def recv(self, message: Message) -> None:- """add message to history."""- # self._history += f"\n{message}"- # self._context = self._history- if message in self._rc.memory.get():- return- self._rc.memory.add(message)-- async def handle(self, message: Message) -> Message:- """Receive information and reply with actions"""- # logger.debug(f"{self.name=}, {self.profile=}, {message.role=}")- self.recv(message)-- return await self._react()++ # # Replaced by run()++ # def recv(self, message: Message) -> None:++ # """add message to history."""++ # # self._history += f"\n{message}"++ # # self._context = self._history++ # if message in self._rc.memory.get():++ # return++ # self._rc.memory.add(message)++++ # # Replaced by run()++ # async def handle(self, message: Message) -> Message:++ # """Receive information and reply with actions"""++ # # logger.debug(f"{self.name=}, {self.profile=}, {message.role=}")++ # self.recv(message)++ #++ # return await self._react()++ def get_memories(self, k=0) -> list[Message]:+ """A wrapper to return the most recent k memories of this role, return all when k=0"""+ return self._rc.memory.get(k=k)- async def run(self, message=None):+ async def run(self, with_message=None):"""Observe, and think and act based on the results of the observation"""- if message:- if isinstance(message, str):- message = Message(message)- if isinstance(message, Message):- self.recv(message)- if isinstance(message, list):- self.recv(Message("\n".join(message)))- elif not await self._observe():+ if with_message:+ msg = None+ if isinstance(with_message, str):+ msg = Message(with_message)+ elif isinstance(with_message, Message):+ msg = with_message+ elif isinstance(with_message, list):+ msg = Message("\n".join(with_message))+ self.put_message(msg)++ if not await self._observe():# If there is no new information, suspend and waitlogger.debug(f"{self._setting}: no news. waiting.")returndiff --cc metagpt/schema.pyindex 959e70dc1,bdca093c2..9e5854997--- a/metagpt/schema.py+++ b/metagpt/schema.py@@@ -13,24 -7,12 +13,27 @@@"""from __future__ import annotations-from dataclasses import dataclass, field-from typing import Type, TypedDict+import asyncio+import json+import os.path+from asyncio import Queue, QueueEmpty, wait_for+from json import JSONDecodeError++from pathlib import Path+from typing import Dict, List, Optional, Set, TypedDict-from pydantic import BaseModel+from pydantic import BaseModel, Field+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.common import any_to_str, any_to_str_setclass RawMessage(TypedDict):@@@ -139,176 -39,45 +142,194 @@@ class Message(BaseModel)return self.__str__()def to_dict(self) -> dict:- return {- "role": self.role,- "content": self.content- }+ """Return a dict containing `role` and `content` for the LLM call.l"""+ return {"role": self.role, "content": self.content}++ def dump(self) -> str:+ """Convert the object to json string"""+ return self.json(exclude_none=True)++ @staticmethod+ def load(val):+ """Convert the json string to object."""+ try:+ d = json.loads(val)+ return Message(**d)+ except JSONDecodeError as err:+ logger.error(f"parse json failed: {val}, error:{err}")+ return None-@dataclassclass UserMessage(Message):"""便于支持OpenAI的消息- Facilitate support for OpenAI messages+ Facilitate support for OpenAI messages"""+def __init__(self, content: str):- super().__init__(content, 'user')+ super().__init__(content=content, role="user")-@dataclassclass SystemMessage(Message):"""便于支持OpenAI的消息- Facilitate support for OpenAI messages+ Facilitate support for OpenAI messages"""+def __init__(self, content: str):- super().__init__(content, 'system')+ super().__init__(content=content, role="system")-@dataclassclass AIMessage(Message):"""便于支持OpenAI的消息- Facilitate support for OpenAI messages+ Facilitate support for OpenAI messages"""+def __init__(self, content: str):- super().__init__(content, 'assistant')---if __name__ == '__main__':- test_content = 'test_message'- msgs = [- UserMessage(test_content),- SystemMessage(test_content),- AIMessage(test_content),- Message(test_content, role='QA')- ]- logger.info(msgs)+ super().__init__(content=content, role="assistant")+++class MessageQueue:+ """Message queue which supports asynchronous updates."""++ def __init__(self):+ self._queue = Queue()++ def pop(self) -> Message | None:+ """Pop one message from the queue."""+ try:+ item = self._queue.get_nowait()+ if item:+ self._queue.task_done()+ return item+ except QueueEmpty:+ return None++ def pop_all(self) -> List[Message]:+ """Pop all messages from the queue."""+ ret = []+ while True:+ msg = self.pop()+ if not msg:+ break+ ret.append(msg)+ return ret++ def push(self, msg: Message):+ """Push a message into the queue."""+ self._queue.put_nowait(msg)++ def empty(self):+ """Return true if the queue is empty."""+ return self._queue.empty()++ async def dump(self) -> str:+ """Convert the `MessageQueue` object to a json string."""+ if self.empty():+ return "[]"++ lst = []+ try:+ while True:+ item = await wait_for(self._queue.get(), timeout=1.0)+ if item is None:+ break+ lst.append(item.dict(exclude_none=True))+ self._queue.task_done()+ except asyncio.TimeoutError:+ logger.debug("Queue is empty, exiting...")+ return json.dumps(lst)++ @staticmethod+ def load(self, v) -> "MessageQueue":+ """Convert the json string to the `MessageQueue` object."""+ q = MessageQueue()+ try:+ lst = json.loads(v)+ for i in lst:+ msg = Message(**i)+ q.push(msg)+ except JSONDecodeError as e:+ logger.warning(f"JSON load failed: {v}, error:{e}")++ return q+++class CodingContext(BaseModel):+ filename: str+ design_doc: Document+ task_doc: Document+ code_doc: Document++ @staticmethod+ def loads(val: str) -> CodingContext | None:+ try:+ m = json.loads(val)+ return CodingContext(**m)+ except Exception:+ return None+++class TestingContext(BaseModel):+ filename: str+ code_doc: Document+ test_doc: Document++ @staticmethod+ def loads(val: str) -> TestingContext | None:+ try:+ m = json.loads(val)+ return TestingContext(**m)+ except Exception:+ return None+++class RunCodeContext(BaseModel):+ mode: str = "script"+ code: Optional[str]+ code_filename: str = ""+ test_code: Optional[str]+ test_filename: str = ""+ command: List[str] = Field(default_factory=list)+ working_directory: str = ""+ additional_python_paths: List[str] = Field(default_factory=list)+ output_filename: Optional[str]+ output: Optional[str]++ @staticmethod+ def loads(val: str) -> RunCodeContext | None:+ try:+ m = json.loads(val)+ return RunCodeContext(**m)+ except Exception:+ return None+++class RunCodeResult(BaseModel):+ summary: str+ stdout: str+ stderr: str++ @staticmethod+ def loads(val: str) -> RunCodeResult | None:+ try:+ m = json.loads(val)+ return RunCodeResult(**m)+ except Exception:+ return None++++++class CodeSummarizeContext(BaseModel):++ design_filename: str = ""++ task_filename: str = ""++ codes_filenames: Set[str] = Field(default_factory=set)++++ @staticmethod++ def loads(filenames: Set) -> CodeSummarizeContext:++ ctx = CodeSummarizeContext()++ for filename in filenames:++ if Path(filename).is_relative_to(SYSTEM_DESIGN_FILE_REPO):++ ctx.design_filename = str(filename)++ continue++ if Path(filename).is_relative_to(TASK_FILE_REPO):++ ctx.task_filename = str(filename)++ continue++ return ctxdiff --cc metagpt/startup.pyindex 000000000,38f457fc2..35b9b8b66mode 000000,100644..100644--- a/metagpt/startup.py+++ b/metagpt/startup.py@@@ -1,0 -1,46 +1,52 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*--from pathlib import Path+ import asyncio+++ import typer++ app = typer.Typer()+++ @app.command()+ def startup(+ idea: str = typer.Argument(..., help="Your innovative idea, such as 'Create a 2048 game.'"),+ investment: float = typer.Option(3.0, help="Dollar amount to invest in the AI company."),+ n_round: int = typer.Option(5, help="Number of rounds for the simulation."),+ code_review: bool = typer.Option(True, help="Whether to use code review."),+ run_tests: bool = typer.Option(False, help="Whether to enable QA for adding & running tests."),+ implement: bool = typer.Option(True, help="Enable or disable code implementation."),+ project_name: str = typer.Option("", help="Unique project name, such as 'game_2048'."),+ inc: bool = typer.Option(False, help="Incremental mode. Use it to coop with existing repo."),+ ):+ """Run a startup. Be a boss."""- from metagpt.roles import ProductManager, Architect, ProjectManager, Engineer, QaEngineer++ from metagpt.roles import (++ Architect,++ Engineer,++ ProductManager,++ ProjectManager,++ QaEngineer,++ )+ from metagpt.team import Team++ company = Team()+ company.hire(+ [+ ProductManager(),+ Architect(),+ ProjectManager(),+ ]+ )++ if implement or code_review:+ company.hire([Engineer(n_borg=5, use_code_review=code_review)])++ if run_tests:+ company.hire([QaEngineer()])++ company.invest(investment)+ company.run_project(idea, project_name=project_name, inc=inc)+ asyncio.run(company.run(n_round=n_round))+++ if __name__ == "__main__":+ startup(idea="Make a 2048 game.")diff --cc metagpt/team.pyindex 72f28ab1d,a22a09fe4..e252935c4--- a/metagpt/team.py+++ b/metagpt/team.py@@@ -18,13 -16,12 +18,13 @@@ from metagpt.schema import Messagfrom metagpt.utils.common import NoMoneyException- class SoftwareCompany(BaseModel):+ class Team(BaseModel):"""- Software Company: Possesses a team, SOP (Standard Operating Procedures), and a platform for instant messaging,- dedicated to writing executable code.+ Team: Possesses one or more roles (agents), SOP (Standard Operating Procedures), and a platform for instant messaging,+ dedicated to perform any multi-agent activity, such as collaboratively writing executable code."""+- environment: Environment = Field(default_factory=Environment)+ env: Environment = Field(default_factory=Environment)investment: float = Field(default=10.0)idea: str = Field(default="")@@@ -43,15 -40,21 +43,21 @@@def _check_balance(self):if CONFIG.total_cost > CONFIG.max_budget:- raise NoMoneyException(CONFIG.total_cost, f'Insufficient funds: {CONFIG.max_budget}')+ raise NoMoneyException(CONFIG.total_cost, f"Insufficient funds: {CONFIG.max_budget}")- def start_project(self, idea):- """Start a project from publishing boss requirement."""+ def run_project(self, idea, send_to: str = "", project_name: str = "", inc: bool = False):+ """Start a project from publishing user requirement."""self.idea = idea- self.environment.publish_message(Message(role="BOSS", content=idea, cause_by=BossRequirement))+ # If user set project_name, then use it.+ if project_name:+ path = CONFIG.workspace_path / project_name+ self.env.load_existing_repo(path, inc=inc)++ # Human requirement.+ self.env.publish_message(Message(role="Human", content=idea, cause_by=UserRequirement, send_to=send_to))def _save(self):- logger.info(self.json())+ logger.info(self.json(ensure_ascii=False))async def run(self, n_round=3):"""Run company until target round or no money"""@@@ -60,7 -63,6 +66,7 @@@n_round -= 1logger.debug(f"{n_round=}")self._check_balance()- await self.environment.run()+ await self.env.run()+ if CONFIG.git_repo:+ CONFIG.git_repo.archive()- return self.environment.history+ return self.env.history-diff --cc metagpt/tools/sd_engine.pyindex a63dbe5ac,4f010a912..c6676a247--- a/metagpt/tools/sd_engine.py+++ b/metagpt/tools/sd_engine.py@@@ -13,11 -13,9 +13,10 @@@ from typing import Lisfrom aiohttp import ClientSessionfrom PIL import Image, PngImagePlugin- from metagpt.config import Config- from metagpt.const import WORKSPACE_ROOT- from metagpt.logs import logger+ from metagpt.config import CONFIG+- config = Config()+ # from metagpt.const import WORKSPACE_ROOT+ from metagpt.logs import loggerpayload = {"prompt": "",diff --cc metagpt/utils/common.pyindex fd3958a61,f09666beb..f08519f8e--- a/metagpt/utils/common.py+++ b/metagpt/utils/common.py@@@ -4,11 -4,7 +4,13 @@@@Time : 2023/4/29 16:07@Author : alexanderwu@File : common.py+@Modified By: mashenquan, 2023-11-1. According to Chapter 2.2.2 of RFC 116:+ Add generic class-to-string and object-to-string conversion functionality.+@Modified By: mashenquan, 2023/11/27. Bug fix: `parse_recipient` failed to parse the recipient in certain GPT-3.5+ responses."""++from __future__ import annotations++import astimport contextlibimport inspectdiff --cc metagpt/utils/file_repository.pyindex 018cac168,000000000..846bfcd0cmode 100644,000000..100644--- a/metagpt/utils/file_repository.py+++ b/metagpt/utils/file_repository.py@@@ -1,259 -1,0 +1,261 @@@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+@Time : 2023/11/20+@Author : mashenquan+@File : git_repository.py+@Desc: File repository management. RFC 135 2.2.3.2, 2.2.3.4 and 2.2.3.13.+"""+from __future__ import annotations++import json+import os+from datetime import datetime+from pathlib import Path+from typing import Dict, List, Set++import aiofiles++from metagpt.config import CONFIG+from metagpt.logs import logger+from metagpt.schema import Document+from metagpt.utils.json_to_markdown import json_to_markdown+++class FileRepository:+ """A class representing a FileRepository associated with a Git repository.++ :param git_repo: The associated GitRepository instance.+ :param relative_path: The relative path within the Git repository.++ Attributes:+ _relative_path (Path): The relative path within the Git repository.+ _git_repo (GitRepository): The associated GitRepository instance.+ """++ def __init__(self, git_repo, relative_path: Path = Path(".")):+ """Initialize a FileRepository instance.++ :param git_repo: The associated GitRepository instance.+ :param relative_path: The relative path within the Git repository.+ """+ self._relative_path = relative_path+ self._git_repo = git_repo++ # Initializing+ self.workdir.mkdir(parents=True, exist_ok=True)++ async def save(self, filename: Path | str, content, dependencies: List[str] = None):+ """Save content to a file and update its dependencies.++ :param filename: The filename or path within the repository.+ :param content: The content to be saved.+ :param dependencies: List of dependency filenames or paths.+ """+ pathname = self.workdir / filename+ pathname.parent.mkdir(parents=True, exist_ok=True)- async with aiofiles.open(str(pathname), mode="w") as writer:++ async with aiofiles.open(str(pathname), mode="wb") as writer:+ await writer.write(content)+ logger.info(f"save to: {str(pathname)}")++ if dependencies is not None:+ dependency_file = await self._git_repo.get_dependency()+ await dependency_file.update(pathname, set(dependencies))+ logger.info(f"update dependency: {str(pathname)}:{dependencies}")++ async def get_dependency(self, filename: Path | str) -> Set[str]:+ """Get the dependencies of a file.++ :param filename: The filename or path within the repository.+ :return: Set of dependency filenames or paths.+ """+ pathname = self.workdir / filename+ dependency_file = await self._git_repo.get_dependency()+ return await dependency_file.get(pathname)++ async def get_changed_dependency(self, filename: Path | str) -> Set[str]:+ """Get the dependencies of a file that have changed.++ :param filename: The filename or path within the repository.+ :return: List of changed dependency filenames or paths.+ """+ dependencies = await self.get_dependency(filename=filename)+ changed_files = self.changed_files+ changed_dependent_files = set()+ for df in dependencies:+ if df in changed_files.keys():+ changed_dependent_files.add(df)+ return changed_dependent_files++ async def get(self, filename: Path | str) -> Document | None:+ """Read the content of a file.++ :param filename: The filename or path within the repository.+ :return: The content of the file.+ """+ doc = Document(root_path=str(self.root_path), filename=str(filename))+ path_name = self.workdir / filename+ if not path_name.exists():+ return None+ try:- async with aiofiles.open(str(path_name), mode="r") as reader:++ async with aiofiles.open(str(path_name), mode="rb") as reader:+ doc.content = await reader.read()+ except FileNotFoundError as e:+ logger.info(f"open {str(path_name)} failed:{e}")+ return None+ except Exception as e:+ logger.info(f"open {str(path_name)} failed:{e}")+ return None+ return doc++ async def get_all(self) -> List[Document]:+ """Get the content of all files in the repository.++ :return: List of Document instances representing files.+ """+ docs = []+ for root, dirs, files in os.walk(str(self.workdir)):+ for file in files:+ file_path = Path(root) / file+ relative_path = file_path.relative_to(self.workdir)+ doc = await self.get(relative_path)+ docs.append(doc)+ return docs++ @property+ def workdir(self):+ """Return the absolute path to the working directory of the FileRepository.++ :return: The absolute path to the working directory.+ """+ return self._git_repo.workdir / self._relative_path++ @property+ def root_path(self):+ """Return the relative path from git repository root"""+ return self._relative_path++ @property+ def changed_files(self) -> Dict[str, str]:+ """Return a dictionary of changed files and their change types.++ :return: A dictionary where keys are file paths and values are change types.+ """+ files = self._git_repo.changed_files+ relative_files = {}+ for p, ct in files.items():+ try:+ rf = Path(p).relative_to(self._relative_path)+ except ValueError:+ continue+ relative_files[str(rf)] = ct+ return relative_files++ def get_change_dir_files(self, dir: Path | str) -> List:+ """Get the files in a directory that have changed.++ :param dir: The directory path within the repository.+ :return: List of changed filenames or paths within the directory.+ """+ changed_files = self.changed_files+ children = []+ for f in changed_files:+ try:+ Path(f).relative_to(Path(dir))+ except ValueError:+ continue+ children.append(str(f))+ return children++ @staticmethod+ def new_filename():+ """Generate a new filename based on the current timestamp and a UUID suffix.++ :return: A new filename string.+ """+ current_time = datetime.now().strftime("%Y%m%d%H%M%S")+ return current_time+ # guid_suffix = str(uuid.uuid4())[:8]+ # return f"{current_time}x{guid_suffix}"+- async def save_doc(self, doc: Document, with_suffix:str = None, dependencies: List[str] = None):++ async def save_doc(self, doc: Document, with_suffix: str = None, dependencies: List[str] = None):+ """Save a Document instance as a PDF file.++ This method converts the content of the Document instance to Markdown,+ saves it to a file with an optional specified suffix, and logs the saved file.++ :param doc: The Document instance to be saved.+ :type doc: Document+ :param with_suffix: An optional suffix to append to the saved file's name.+ :type with_suffix: str, optional+ :param dependencies: A list of dependencies for the saved file.+ :type dependencies: List[str], optional+ """+ m = json.loads(doc.content)+ filename = Path(doc.filename).with_suffix(with_suffix) if with_suffix is not None else Path(doc.filename)+ await self.save(filename=str(filename), content=json_to_markdown(m), dependencies=dependencies)+ logger.info(f"File Saved: {str(filename)}")++ @staticmethod+ async def get_file(filename: Path | str, relative_path: Path | str = ".") -> Document | None:+ """Retrieve a specific file from the file repository.++ :param filename: The name or path of the file to retrieve.+ :type filename: Path or str+ :param relative_path: The relative path within the file repository.+ :type relative_path: Path or str, optional+ :return: The document representing the file, or None if not found.+ :rtype: Document or None+ """+ file_repo = CONFIG.git_repo.new_file_repository(relative_path=relative_path)+ return await file_repo.get(filename=filename)++ @staticmethod+ async def get_all_files(relative_path: Path | str = ".") -> List[Document]:+ """Retrieve all files from the file repository.++ :param relative_path: The relative path within the file repository.+ :type relative_path: Path or str, optional+ :return: A list of documents representing all files in the repository.+ :rtype: List[Document]+ """+ file_repo = CONFIG.git_repo.new_file_repository(relative_path=relative_path)+ return await file_repo.get_all()++ @staticmethod+ async def save_file(filename: Path | str, content, dependencies: List[str] = None, relative_path: Path | str = "."):+ """Save a file to the file repository.++ :param filename: The name or path of the file to save.+ :type filename: Path or str+ :param content: The content of the file.+ :param dependencies: A list of dependencies for the file.+ :type dependencies: List[str], optional+ :param relative_path: The relative path within the file repository.+ :type relative_path: Path or str, optional+ """+ file_repo = CONFIG.git_repo.new_file_repository(relative_path=relative_path)+ return await file_repo.save(filename=filename, content=content, dependencies=dependencies)++ @staticmethod- async def save_as(doc:Document, with_suffix:str = None, dependencies: List[str] = None, relative_path: Path | str = "."):++ async def save_as(++ doc: Document, with_suffix: str = None, dependencies: List[str] = None, relative_path: Path | str = "."++ ):+ """Save a Document instance with optional modifications.++ This static method creates a new FileRepository, saves the Document instance+ with optional modifications (such as a suffix), and logs the saved file.++ :param doc: The Document instance to be saved.+ :type doc: Document+ :param with_suffix: An optional suffix to append to the saved file's name.+ :type with_suffix: str, optional+ :param dependencies: A list of dependencies for the saved file.+ :type dependencies: List[str], optional+ :param relative_path: The relative path within the file repository.+ :type relative_path: Path or str, optional+ :return: A boolean indicating whether the save operation was successful.+ :rtype: bool+ """+ file_repo = CONFIG.git_repo.new_file_repository(relative_path=relative_path)+ return await file_repo.save_doc(doc=doc, with_suffix=with_suffix, dependencies=dependencies)diff --cc metagpt/utils/token_counter.pyindex a5a65803a,33bcd01a5..53d9de345--- a/metagpt/utils/token_counter.py+++ b/metagpt/utils/token_counter.py@@@ -21,7 -21,9 +21,9 @@@ TOKEN_COSTS ="gpt-4-32k": {"prompt": 0.06, "completion": 0.12},"gpt-4-32k-0314": {"prompt": 0.06, "completion": 0.12},"gpt-4-0613": {"prompt": 0.06, "completion": 0.12},+ "gpt-4-1106-preview": {"prompt": 0.01, "completion": 0.03},"text-embedding-ada-002": {"prompt": 0.0004, "completion": 0.0},- "chatglm_turbo": {"prompt": 0.0, "completion": 0.00069} # 32k version, prompt + completion tokens=0.005¥/k-tokens++ "chatglm_turbo": {"prompt": 0.0, "completion": 0.00069}, # 32k version, prompt + completion tokens=0.005¥/k-tokens}@@@ -36,7 -38,9 +38,9 @@@ TOKEN_MAX ="gpt-4-32k": 32768,"gpt-4-32k-0314": 32768,"gpt-4-0613": 8192,+ "gpt-4-1106-preview": 128000,"text-embedding-ada-002": 8192,- "chatglm_turbo": 32768++ "chatglm_turbo": 32768,}diff --cc requirements.txtindex e72efc76c,f233e398f..99f738448--- a/requirements.txt+++ b/requirements.txt@@@ -14,7 -15,7 +15,7 @@@ langchain==0.0.23loguru==0.6.0meilisearch==0.21.0numpy==1.24.3- openai==0.28.1-openai>=0.28.0++openai>=0.28.1openpyxlbeautifulsoup4==4.12.2pandas==2.0.3@@@ -44,5 -45,4 +45,7 @@@ ta==0.10.semantic-kernel==0.3.13.dev0wrapt==1.15.0websocket-client==0.58.0+aiofiles==23.2.1- gitpython==3.1.40++gitpython==3.1.40+ zhipuai==1.0.7++diff --cc setup.pyindex f9ae768e6,e7462767f..6d3708c32--- a/setup.py+++ b/setup.py@@@ -52,4 -52,9 +52,9 @@@ setupcmdclass={"install_mermaid": InstallMermaidCLI,},+ entry_points={- 'console_scripts': [- 'metagpt=metagpt.startup:app',++ "console_scripts": [++ "metagpt=metagpt.startup:app",+ ],+ },)diff --cc tests/metagpt/actions/test_write_prd.pyindex 07d701cb9,18675ecc3..8f8ef84f5--- a/tests/metagpt/actions/test_write_prd.py+++ b/tests/metagpt/actions/test_write_prd.py@@@ -18,7 -17,7 +18,7 @@@ from metagpt.schema import Messagasync def test_write_prd():product_manager = ProductManager()requirements = "开发一个基于大语言模型与私有知识库的搜索引擎,希望可以基于大语言模型进行搜索总结"- prd = await product_manager.run(Message(content=requirements, cause_by=BossRequirement))- prd = await product_manager.handle(Message(content=requirements, cause_by=UserRequirement))++ prd = await product_manager.run(Message(content=requirements, cause_by=UserRequirement))logger.info(requirements)logger.info(prd)diff --cc tests/metagpt/memory/test_longterm_memory.pyindex c5b5c6eb1,ac9362937..b6ae0ac79--- a/tests/metagpt/memory/test_longterm_memory.py+++ b/tests/metagpt/memory/test_longterm_memory.py@@@ -1,14 -1,12 +1,14 @@@#!/usr/bin/env python# -*- coding: utf-8 -*--# @Desc : unittest of `metagpt/memory/longterm_memory.py`+"""+@Desc : unittest of `metagpt/memory/longterm_memory.py`+"""- from metagpt.actions import BossRequirement-from metagpt.config import CONFIG-from metagpt.schema import Message+ from metagpt.actions import UserRequirement-from metagpt.roles.role import RoleContext+from metagpt.config import CONFIGfrom metagpt.memory import LongTermMemory+from metagpt.roles.role import RoleContext+from metagpt.schema import Messagedef test_ltm_search():@@@ -16,25 -14,25 +16,25 @@@openai_api_key = CONFIG.openai_api_keyassert len(openai_api_key) > 20- role_id = 'UTUserLtm(Product Manager)'+ role_id = "UTUserLtm(Product Manager)"- rc = RoleContext(watch=[BossRequirement])+ rc = RoleContext(watch=[UserRequirement])ltm = LongTermMemory()ltm.recover_memory(role_id, rc)- idea = 'Write a cli snake game'- message = Message(role='User', content=idea, cause_by=UserRequirement)+ idea = "Write a cli snake game"- message = Message(role="BOSS", content=idea, cause_by=BossRequirement)++ message = Message(role="User", content=idea, cause_by=UserRequirement)news = ltm.find_news([message])assert len(news) == 1ltm.add(message)- sim_idea = 'Write a game of cli snake'- sim_message = Message(role='User', content=sim_idea, cause_by=UserRequirement)+ sim_idea = "Write a game of cli snake"- sim_message = Message(role="BOSS", content=sim_idea, cause_by=BossRequirement)++ sim_message = Message(role="User", content=sim_idea, cause_by=UserRequirement)news = ltm.find_news([sim_message])assert len(news) == 0ltm.add(sim_message)- new_idea = 'Write a 2048 web game'- new_message = Message(role='User', content=new_idea, cause_by=UserRequirement)+ new_idea = "Write a 2048 web game"- new_message = Message(role="BOSS", content=new_idea, cause_by=BossRequirement)++ new_message = Message(role="User", content=new_idea, cause_by=UserRequirement)news = ltm.find_news([new_message])assert len(news) == 1ltm.add(new_message)@@@ -49,8 -47,8 +49,8 @@@news = ltm_new.find_news([sim_message])assert len(news) == 0- new_idea = 'Write a Battle City'- new_message = Message(role='User', content=new_idea, cause_by=UserRequirement)+ new_idea = "Write a Battle City"- new_message = Message(role="BOSS", content=new_idea, cause_by=BossRequirement)++ new_message = Message(role="User", content=new_idea, cause_by=UserRequirement)news = ltm_new.find_news([new_message])assert len(news) == 1diff --cc tests/metagpt/memory/test_memory_storage.pyindex 251c70b02,bd4441641..c67ca689f--- a/tests/metagpt/memory/test_memory_storage.py+++ b/tests/metagpt/memory/test_memory_storage.py@@@ -7,16 -4,17 +7,16 @@@from typing import List- from metagpt.actions import BossRequirement, WritePRD++from metagpt.actions import UserRequirement, WritePRD+from metagpt.actions.action_output import ActionOutputfrom metagpt.memory.memory_storage import MemoryStoragefrom metagpt.schema import Message-from metagpt.actions import UserRequirement-from metagpt.actions import WritePRD-from metagpt.actions.action_output import ActionOutputdef test_idea_message():- idea = 'Write a cli snake game'- role_id = 'UTUser1(Product Manager)'- message = Message(role='User', content=idea, cause_by=UserRequirement)+ idea = "Write a cli snake game"+ role_id = "UTUser1(Product Manager)"- message = Message(role="BOSS", content=idea, cause_by=BossRequirement)++ message = Message(role="User", content=idea, cause_by=UserRequirement)memory_storage: MemoryStorage = MemoryStorage()messages = memory_storage.recover_memory(role_id)@@@ -25,13 -23,13 +25,13 @@@memory_storage.add(message)assert memory_storage.is_initialized is True- sim_idea = 'Write a game of cli snake'- sim_message = Message(role='User', content=sim_idea, cause_by=UserRequirement)+ sim_idea = "Write a game of cli snake"- sim_message = Message(role="BOSS", content=sim_idea, cause_by=BossRequirement)++ sim_message = Message(role="User", content=sim_idea, cause_by=UserRequirement)new_messages = memory_storage.search(sim_message)- assert len(new_messages) == 0 # similar, return []+ assert len(new_messages) == 0 # similar, return []- new_idea = 'Write a 2048 web game'- new_message = Message(role='User', content=new_idea, cause_by=UserRequirement)+ new_idea = "Write a 2048 web game"- new_message = Message(role="BOSS", content=new_idea, cause_by=BossRequirement)++ new_message = Message(role="User", content=new_idea, cause_by=UserRequirement)new_messages = memory_storage.search(new_message)assert new_messages[0].content == message.content@@@ -40,15 -38,22 +40,15 @@@def test_actionout_message():- out_mapping = {- 'field1': (str, ...),- 'field2': (List[str], ...)- }- out_data = {- 'field1': 'field1 value',- 'field2': ['field2 value1', 'field2 value2']- }- ic_obj = ActionOutput.create_model_class('prd', out_mapping)-- role_id = 'UTUser2(Architect)'- content = 'The user has requested the creation of a command-line interface (CLI) snake game'- message = Message(content=content,- instruct_content=ic_obj(**out_data),- role='user',- cause_by=WritePRD) # WritePRD as test action+ out_mapping = {"field1": (str, ...), "field2": (List[str], ...)}+ out_data = {"field1": "field1 value", "field2": ["field2 value1", "field2 value2"]}+ ic_obj = ActionOutput.create_model_class("prd", out_mapping)++ role_id = "UTUser2(Architect)"- content = "The boss has requested the creation of a command-line interface (CLI) snake game"++ content = "The user has requested the creation of a command-line interface (CLI) snake game"+ message = Message(+ content=content, instruct_content=ic_obj(**out_data), role="user", cause_by=WritePRD+ ) # WritePRD as test actionmemory_storage: MemoryStorage = MemoryStorage()messages = memory_storage.recover_memory(role_id)diff --cc tests/metagpt/planner/test_action_planner.pyindex b8d4c1ad9,8efe6cfc4..1bc451db8--- a/tests/metagpt/planner/test_action_planner.py+++ b/tests/metagpt/planner/test_action_planner.py@@@ -25,7 -23,7 +25,8 @@@ async def test_action_planner()role.import_skill(TimeSkill(), "time")role.import_skill(TextSkill(), "text")task = "What is the sum of 110 and 990?"- role.put_message(Message(content=task, cause_by=BossRequirement))- role.recv(Message(content=task, cause_by=UserRequirement))+++ role.put_message(Message(content=task, cause_by=UserRequirement))+ await role._observe()await role._think() # it will choose mathskill.Addassert "1100" == (await role._act()).contentdiff --cc tests/metagpt/planner/test_basic_planner.pyindex 24250a0b0,f6d44ba03..f406143ee--- a/tests/metagpt/planner/test_basic_planner.py+++ b/tests/metagpt/planner/test_basic_planner.py@@@ -28,8 -26,7 +28,8 @@@ async def test_basic_planner()role.import_semantic_skill_from_directory(SKILL_DIRECTORY, "WriterSkill")role.import_skill(TextSkill(), "TextSkill")# using BasicPlanner- role.put_message(Message(content=task, cause_by=BossRequirement))- role.recv(Message(content=task, cause_by=UserRequirement))++ role.put_message(Message(content=task, cause_by=UserRequirement))+ await role._observe()await role._think()# assuming sk_agent will think he needs WriterSkill.Brainstorm and WriterSkill.Translateassert "WriterSkill.Brainstorm" in role.plan.generated_plan.resultdiff --cc tests/metagpt/provider/test_zhipuai_api.pyindex 000000000,6a0c70de5..4684e8887mode 000000,100644..100644--- a/tests/metagpt/provider/test_zhipuai_api.py+++ b/tests/metagpt/provider/test_zhipuai_api.py@@@ -1,0 -1,47 +1,37 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : the unittest of ZhiPuAIGPTAPI++ import pytest++ from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI+++default_resp = {"code": 200, "data": {"choices": [{"role": "assistant", "content": "I'm chatglm-turbo"}]}}+-default_resp = {- "code": 200,- "data": {- "choices": [- {"role": "assistant", "content": "I'm chatglm-turbo"}- ]- }-}--messages = [- {"role": "user", "content": "who are you"}-]++messages = [{"role": "user", "content": "who are you"}]+++ def mock_llm_ask(self, messages: list[dict]) -> dict:+ return default_resp+++ def test_zhipuai_completion(mocker):+ mocker.patch("metagpt.provider.zhipuai_api.ZhiPuAIGPTAPI.completion", mock_llm_ask)++ resp = ZhiPuAIGPTAPI().completion(messages)+ assert resp["code"] == 200+ assert "chatglm-turbo" in resp["data"]["choices"][0]["content"]+++ async def mock_llm_aask(self, messgaes: list[dict], stream: bool = False) -> dict:+ return default_resp+++ @pytest.mark.asyncio+ async def test_zhipuai_acompletion(mocker):+ mocker.patch("metagpt.provider.zhipuai_api.ZhiPuAIGPTAPI.acompletion_text", mock_llm_aask)++ resp = await ZhiPuAIGPTAPI().acompletion_text(messages, stream=False)++ assert resp["code"] == 200+ assert "chatglm-turbo" in resp["data"]["choices"][0]["content"]diff --cc tests/metagpt/roles/mock.pyindex 1b02fbaa5,c06844389..5500b69f7--- a/tests/metagpt/roles/mock.py+++ b/tests/metagpt/roles/mock.py@@@ -71,7 -71,7 +71,7 @@@ PRD = '''## 原始需�```'''- SYSTEM_DESIGN = """## Python package name-SYSTEM_DESIGN = '''## project_name++SYSTEM_DESIGN = """## project_name```python"smart_search_engine"```diff --cc tests/metagpt/roles/test_ui.pyindex 2d9cb85c9,ec507f75d..5904bee8f--- a/tests/metagpt/roles/test_ui.py+++ b/tests/metagpt/roles/test_ui.py@@@ -2,8 -2,9 +2,8 @@@# @Date : 2023/7/22 02:40# @Author : stellahong ([email protected])#-from metagpt.team import Teamfrom metagpt.roles import ProductManager- from metagpt.software_company import SoftwareCompany-++from metagpt.team import Teamfrom tests.metagpt.roles.ui_role import UIdiff --cc tests/metagpt/roles/ui_role.pyindex a45a89cde,102c6ebd6..ee36befbd--- a/tests/metagpt/roles/ui_role.py+++ b/tests/metagpt/roles/ui_role.py@@@ -8,7 -8,8 +8,9 @@@ from functools import wrapfrom importlib import import_modulefrom metagpt.actions import Action, ActionOutput, WritePRD- from metagpt.const import WORKSPACE_ROOT+++ # from metagpt.const import WORKSPACE_ROOT+ from metagpt.config import CONFIGfrom metagpt.logs import loggerfrom metagpt.roles import Rolefrom metagpt.schema import Messagediff --cc tests/metagpt/test_startup.pyindex 000000000,53a8d8735..53d3509edmode 000000,100644..100644--- a/tests/metagpt/test_startup.py+++ b/tests/metagpt/test_startup.py@@@ -1,0 -1,28 +1,27 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ """+ @Time : 2023/5/15 11:40+ @Author : alexanderwu+ @File : test_startup.py+ """+ import pytest+ from typer.testing import CliRunner+-runner = CliRunner()-+ from metagpt.logs import logger+ from metagpt.team import Team-from metagpt.startup import app++++runner = CliRunner()+++ @pytest.mark.asyncio+ async def test_team():+ company = Team()+ company.run_project("做一个基础搜索引擎,可以支持知识库")+ history = await company.run(n_round=5)+ logger.info(history)+++ # def test_startup():+ # args = ["Make a 2048 game"]+ # result = runner.invoke(app, args)diff --cc tests/metagpt/tools/test_sd_tool.pyindex 4edd8fb3b,fea58bc29..edb23df42--- a/tests/metagpt/tools/test_sd_tool.py+++ b/tests/metagpt/tools/test_sd_tool.py@@@ -4,9 -4,11 +4,10 @@@#import os- from metagpt.tools.sd_engine import WORKSPACE_ROOT, SDEngine+ from metagpt.config import CONFIG+ from metagpt.tools.sd_engine import SDEngine-def test_sd_engine_init():sd_engine = SDEngine()assert sd_engine.payload["seed"] == -1@@@ -21,5 -23,5 +22,5 @@@ def test_sd_engine_generate_prompt()async def test_sd_engine_run_t2i():sd_engine = SDEngine()await sd_engine.run_t2i(prompts=["test"])- img_path = WORKSPACE_ROOT / "resources" / "SD_Output" / "output_0.png"- assert os.path.exists(img_path) == True+ img_path = CONFIG.workspace_path / "resources" / "SD_Output" / "output_0.png"- assert os.path.exists(img_path) == True++ assert os.path.exists(img_path)diff --cc tests/metagpt/utils/test_common.pyindex 6474b1233,b6c000f9b..4bd38db63--- a/tests/metagpt/utils/test_common.py+++ b/tests/metagpt/utils/test_common.py@@@ -8,16 -7,10 +8,16 @@@"""import os+from typing import Any, Setimport pytest+from pydantic import BaseModel+from metagpt.actions import RunCode- from metagpt.const import get_project_root+ from metagpt.const import get_metagpt_root+from metagpt.roles.tutorial_assistant import TutorialAssistant+from metagpt.schema import Message+from metagpt.utils.common import any_to_str, any_to_str_setclass TestGetProjectRoot:@@@ -27,56 -20,11 +27,56 @@@os.chdir(abs_root)def test_get_project_root(self):- project_root = get_project_root()- assert project_root.name == "MetaGPT"+ project_root = get_metagpt_root()- assert project_root.name == 'metagpt'++ assert project_root.name == "metagpt"def test_get_root_exception(self):with pytest.raises(Exception) as exc_info:self.change_etc_dir()- get_project_root()+ get_metagpt_root()assert str(exc_info.value) == "Project root not found."++ def test_any_to_str(self):+ class Input(BaseModel):+ x: Any+ want: str++ inputs = [+ Input(x=TutorialAssistant, want="metagpt.roles.tutorial_assistant.TutorialAssistant"),+ Input(x=TutorialAssistant(), want="metagpt.roles.tutorial_assistant.TutorialAssistant"),+ Input(x=RunCode, want="metagpt.actions.run_code.RunCode"),+ Input(x=RunCode(), want="metagpt.actions.run_code.RunCode"),+ Input(x=Message, want="metagpt.schema.Message"),+ Input(x=Message(""), want="metagpt.schema.Message"),+ Input(x="A", want="A"),+ ]+ for i in inputs:+ v = any_to_str(i.x)+ assert v == i.want++ def test_any_to_str_set(self):+ class Input(BaseModel):+ x: Any+ want: Set++ inputs = [+ Input(+ x=[TutorialAssistant, RunCode(), "a"],+ want={"metagpt.roles.tutorial_assistant.TutorialAssistant", "metagpt.actions.run_code.RunCode", "a"},+ ),+ Input(+ x={TutorialAssistant, RunCode(), "a"},+ want={"metagpt.roles.tutorial_assistant.TutorialAssistant", "metagpt.actions.run_code.RunCode", "a"},+ ),+ Input(+ x=(TutorialAssistant, RunCode(), "a"),+ want={"metagpt.roles.tutorial_assistant.TutorialAssistant", "metagpt.actions.run_code.RunCode", "a"},+ ),+ ]+ for i in inputs:+ v = any_to_str_set(i.x)+ assert v == i.want+++if __name__ == "__main__":+ pytest.main([__file__, "-s"])diff --cc tests/metagpt/utils/test_output_parser.pyindex 7a3aedbe8,99ab1f79e..c9f5813d9--- a/tests/metagpt/utils/test_output_parser.py+++ b/tests/metagpt/utils/test_output_parser.py@@@ -218,9 -216,9 +218,9 @@@ We need clarification on how the high s"Requirement Pool": (List[Tuple[str, str]], ...),"Anything UNCLEAR": (str, ...),}- t_text1 = '''## Original Requirements:+ t_text1 = """## Original Requirements:- The boss wants to create a web-based version of the game "Fly Bird".+ The user wants to create a web-based version of the game "Fly Bird".## Product Goals: