🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge geekan:main
莘权 马829dfd899759
diff --cc metagpt/actions/action.pyindex 2fd130cf5,27d8db649..1d9be60e0--- a/metagpt/actions/action.py+++ b/metagpt/actions/action.py@@@ -14,8 -14,9 +14,9 @@@ from tenacity import retry, stop_after_from metagpt.actions.action_output import ActionOutputfrom metagpt.llm import LLMfrom metagpt.logs import logger++from metagpt.provider.postprecess.llm_output_postprecess import llm_output_postprecessfrom metagpt.utils.common import OutputParser- from metagpt.utils.custom_decoder import CustomDecoder+ from metagpt.utils.utils import general_after_log-from metagpt.provider.postprecess.llm_output_postprecess import llm_output_postprecessclass Action(ABC):@@@ -66,8 -63,12 +71,8 @@@system_msgs: Optional[list[str]] = None,format="markdown", # compatible to original format) -> ActionOutput:- """Append default prefix"""- if not system_msgs:- system_msgs = []- system_msgs.append(self.prefix)content = await self.llm.aask(prompt, system_msgs)- logger.debug(content)+ logger.debug(f"llm raw output:\n{content}")output_class = ActionOutput.create_model_class(output_class_name, output_data_mapping)if format == "json":diff --cc metagpt/actions/debug_error.pyindex e66eadeaa,101cc2025..df60c2e61--- a/metagpt/actions/debug_error.py+++ b/metagpt/actions/debug_error.py@@@ -26,26 -19,11 +26,26 @@@ Based on the message, first, figure outhen rewrite the development code or the test code based on your role, the error, and the summary, such that all bugs are fixed and the code performs well.Attention: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the test case or script and triple quotes.The message is as follows:-{context}+# Legacy Code+```python+{code}+```+---+# Unit Test Code+```python+{test_code}+```+---+# Console logs+```text+{logs}+```---Now you should start rewriting the code:- ## file name of the code to rewrite: Write code with triple quoto. Do your best to implement THIS IN ONLY ONE FILE.+ ## file name of the code to rewrite: Write code with triple quote. Do your best to implement THIS IN ONLY ONE FILE."""++class DebugError(Action):def __init__(self, name="DebugError", context=None, llm=None):super().__init__(name, context, llm)diff --cc metagpt/actions/design_api.pyindex fd58e0ca8,fc3be602b..5a5f52de7--- a/metagpt/actions/design_api.py+++ b/metagpt/actions/design_api.py@@@ -4,38 -4,149 +4,41 @@@@Time : 2023/5/11 19:26@Author : alexanderwu@File : design_api.py+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.3 of RFC 135, add incremental iteration functionality.+@Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD."""-import shutil+import jsonfrom pathlib import Path- # from typing import List-from typing import Listfrom metagpt.actions import Action, ActionOutput+from metagpt.actions.design_api_an import DESIGN_API_NODEfrom metagpt.config import CONFIG-from metagpt.const import WORKSPACE_ROOT+from metagpt.const import (+ DATA_API_DESIGN_FILE_REPO,+ PRDS_FILE_REPO,+ SEQ_FLOW_FILE_REPO,+ SYSTEM_DESIGN_FILE_REPO,+ SYSTEM_DESIGN_PDF_FILE_REPO,+)from metagpt.logs import logger-from metagpt.utils.common import CodeParser-from metagpt.utils.get_template import get_template-from metagpt.utils.json_to_markdown import json_to_markdown+from metagpt.schema import Document, Documents+from metagpt.utils.file_repository import FileRepository+++# from metagpt.utils.get_template import get_templatefrom metagpt.utils.mermaid import mermaid_to_file-templates = {- "json": {- "PROMPT_TEMPLATE": """-# Context-{context}++# from typing import List+-## Format example-{format_example}-------Role: You are an architect; the goal is to design a SOTA PEP8-compliant python system; make the best use of good open source tools-Requirement: Fill in the following missing information based on the context, each section name is a key in json-Max Output: 8192 chars or 2048 tokens. Try to use them up.--## Implementation approach: Provide as Plain text. Analyze the difficult points of the requirements, select the appropriate open-source framework.--## Python package name: Provide as Python str with python triple quote, concise and clear, characters only use a combination of all lowercase and underscores--## File list: Provided as Python list[str], the list of ONLY REQUIRED files needed to write the program(LESS IS MORE!). Only need relative paths, comply with PEP8 standards. ALWAYS write a main.py or app.py here--## Data structures and interface definitions: Use mermaid classDiagram code syntax, including classes (INCLUDING __init__ method) and functions (with type annotations), CLEARLY MARK the RELATIONSHIPS between classes, and comply with PEP8 standards. The data structures SHOULD BE VERY DETAILED and the API should be comprehensive with a complete design.--## Program call flow: Use sequenceDiagram code syntax, COMPLETE and VERY DETAILED, using CLASSES AND API DEFINED ABOVE accurately, covering the CRUD AND INIT of each object, SYNTAX MUST BE CORRECT.--## Anything UNCLEAR: Provide as Plain text. Make clear here.--output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like format example,-and only output the json inside this tag, nothing else-""",- "FORMAT_EXAMPLE": """-[CONTENT]-{- "Implementation approach": "We will ...",- "Python package name": "snake_game",- "File list": ["main.py"],- "Data structures and interface definitions": '- classDiagram- class Game{- +int score- }- ...- Game "1" -- "1" Food: has- ',- "Program call flow": '- sequenceDiagram- participant M as Main- ...- G->>M: end game- ',- "Anything UNCLEAR": "The requirement is clear to me."-}-[/CONTENT]-""",- },- "markdown": {- "PROMPT_TEMPLATE": """-# Context-{context}+-## Format example-{format_example}-------Role: You are an architect; the goal is to design a SOTA PEP8-compliant python system; make the best use of good open source tools-Requirement: Fill in the following missing information based on the context, note that all sections are response with code form separately-Max Output: 8192 chars or 2048 tokens. Try to use them up.-Attention: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the code and triple quote.--## Implementation approach: Provide as Plain text. Analyze the difficult points of the requirements, select the appropriate open-source framework.--## Python package name: Provide as Python str with python triple quote, concise and clear, characters only use a combination of all lowercase and underscores--## File list: Provided as Python list[str], the list of ONLY REQUIRED files needed to write the program(LESS IS MORE!). Only need relative paths, comply with PEP8 standards. ALWAYS write a main.py or app.py here--## Data structures and interface definitions: Use mermaid classDiagram code syntax, including classes (INCLUDING __init__ method) and functions (with type annotations), CLEARLY MARK the RELATIONSHIPS between classes, and comply with PEP8 standards. The data structures SHOULD BE VERY DETAILED and the API should be comprehensive with a complete design.--## Program call flow: Use sequenceDiagram code syntax, COMPLETE and VERY DETAILED, using CLASSES AND API DEFINED ABOVE accurately, covering the CRUD AND INIT of each object, SYNTAX MUST BE CORRECT.--## Anything UNCLEAR: Provide as Plain text. Make clear here.--""",- "FORMAT_EXAMPLE": """-----## Implementation approach-We will ...--## Python package name-```python-"snake_game"-```--## File list-```python-[- "main.py",-]-```--## Data structures and interface definitions-```mermaid-classDiagram- class Game{- +int score- }- ...- Game "1" -- "1" Food: has-```--## Program call flow-```mermaid-sequenceDiagram- participant M as Main- ...- G->>M: end game-```--## Anything UNCLEAR-The requirement is clear to me.-----""",- },-}--OUTPUT_MAPPING = {- "Implementation approach": (str, ...),- "Python package name": (str, ...),- "File list": (List[str], ...),- "Data structures and interface definitions": (str, ...),- "Program call flow": (str, ...),- "Anything UNCLEAR": (str, ...),-}+NEW_REQ_TEMPLATE = """+### Legacy Content+{old_design}++### New Requirements+{context}+"""class WriteDesign(Action):@@@ -47,93 -158,60 +50,91 @@@"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(json_to_markdown(context[-1].instruct_content.dict()))-- async def _save_system_design(self, docs_path, resources_path, system_design):- data_api_design = system_design.instruct_content.dict()[- "Data structures and interface definitions"- ] # CodeParser.parse_code(block="Data structures and interface definitions", 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((json_to_markdown(system_design.instruct_content.dict())))-- async def _save(self, context, system_design):- if isinstance(system_design, ActionOutput):- ws_name = system_design.instruct_content.dict()["Python package name"]+ 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)++ async def _new_system_design(self, context, format=CONFIG.prompt_format):+ node = await DESIGN_API_NODE.fill(context=context, llm=self.llm, to=format)+ return node++ async def _merge(self, prd_doc, system_design_doc, format=CONFIG.prompt_format):- context = NEW_REQ_TEMPLATE.format(- old_design=system_design_doc.content, context=prd_doc.content- )++ context = NEW_REQ_TEMPLATE.format(old_design=system_design_doc.content, context=prd_doc.content)+ node = await DESIGN_API_NODE.fill(context=context, llm=self.llm, to=format)+ system_design_doc.content = node.instruct_content.json(ensure_ascii=False)+ return system_design_doc++ 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(ensure_ascii=False),+ )else:- ws_name = CodeParser.parse_str(block="Python package name", text=system_design)- workspace = WORKSPACE_ROOT / ws_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):- 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- setattr(- system_design.instruct_content,- "Python package name",- system_design.instruct_content.dict()["Python package name"].strip().strip("'").strip('"'),+ 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(context, system_design)- return system_design+ 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 interfaces")+ if not data_api_design:+ return+ pathname = CONFIG.git_repo.workdir / 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/write_code.pyindex 1dda6466f,a89bce60f..a2501db2a--- a/metagpt/actions/write_code.py+++ b/metagpt/actions/write_code.py@@@ -4,28 -4,14 +4,33 @@@@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 metagpt.actions import WriteDesign+import json++from tenacity import retry, stop_after_attempt, wait_random_exponential+from metagpt.actions.action import Action-from metagpt.const import WORKSPACE_ROOT+from metagpt.config import CONFIG- from metagpt.const import CODE_SUMMARIES_FILE_REPO, TEST_OUTPUTS_FILE_REPO, TASK_FILE_REPO, BUGFIX_FILENAME, \- DOCS_FILE_REPO++from metagpt.const import (++ BUGFIX_FILENAME,++ CODE_SUMMARIES_FILE_REPO,++ DOCS_FILE_REPO,++ TASK_FILE_REPO,++ TEST_OUTPUTS_FILE_REPO,++)from metagpt.logs import logger-from metagpt.schema import Message+from metagpt.schema import CodingContext, Document, RunCodeResultfrom metagpt.utils.common import CodeParser-from tenacity import retry, stop_after_attempt, wait_random_exponential+from metagpt.utils.file_repository import FileRepositoryPROMPT_TEMPLATE = """NOTICE@@@ -95,52 -72,11 +100,51 @@@ class WriteCode(Action)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:+ bug_feedback = await FileRepository.get_file(filename=BUGFIX_FILENAME, relative_path=DOCS_FILE_REPO)+ 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+ )+ summary_doc = None+ if coding_context.design_doc.filename:+ summary_doc = await FileRepository.get_file(+ filename=coding_context.design_doc.filename, relative_path=CODE_SUMMARIES_FILE_REPO+ )+ logs = ""+ if test_doc:+ test_detail = RunCodeResult.loads(test_doc.content)+ logs = test_detail.stderr+ code_context = await self._get_codes(coding_context.task_doc)+ prompt = PROMPT_TEMPLATE.format(+ design=coding_context.design_doc.content,+ tasks=coding_context.task_doc.content if coding_context.task_doc else "",+ code=code_context,+ logs=logs,+ feedback=bug_feedback.content if bug_feedback else "",+ filename=self.context.filename,+ summary_log=summary_doc.content if summary_doc else "",+ )+ 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-+ if not coding_context.code_doc:+ coding_context.code_doc = Document(filename=coding_context.filename, root_path=CONFIG.src_workspace)+ coding_context.code_doc.content = code+ return coding_context++ @staticmethod+ async def _get_codes(task_doc) -> str:+ if not task_doc:+ return ""+ if not task_doc.content:+ task_doc.content = FileRepository.get_file(filename=task_doc.filename, relative_path=TASK_FILE_REPO)+ m = json.loads(task_doc.content)+ code_filenames = m.get("Task list", [])+ codes = []+ src_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)+ for filename in code_filenames:+ doc = await src_file_repo.get(filename=filename)+ if not doc:+ continue+ codes.append(doc.content)+ return "\n----------\n".join(codes)-diff --cc metagpt/actions/write_prd.pyindex e61743e7f,52a99dafc..b9bad2233--- a/metagpt/actions/write_prd.py+++ b/metagpt/actions/write_prd.py@@@ -4,182 -4,238 +4,191 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : write_prd.py+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.2 of RFC 135, add incremental iteration functionality.+ 3. Move the document storage operations related to WritePRD from the save operation of WriteDesign.+@Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD."""-from typing import List+from __future__ import annotations++import json+from pathlib import Path- # from typing import Listfrom metagpt.actions import Action, ActionOutput-from metagpt.actions.search_and_summarize import SearchAndSummarize+from metagpt.actions.action_node import ActionNode- from metagpt.actions.write_prd_an import WRITE_PRD_NODE, WP_ISSUE_TYPE_NODE, WP_IS_RELATIVE_NODE+from metagpt.actions.fix_bug import FixBug- from metagpt.actions.search_and_summarize import SearchAndSummarize++from metagpt.actions.write_prd_an import (++ WP_IS_RELATIVE_NODE,++ WP_ISSUE_TYPE_NODE,++ WRITE_PRD_NODE,++)from metagpt.config import CONFIG+from metagpt.const import (++ BUGFIX_FILENAME,+ COMPETITIVE_ANALYSIS_FILE_REPO,+ DOCS_FILE_REPO,+ PRD_PDF_FILE_REPO,+ PRDS_FILE_REPO,- REQUIREMENT_FILENAME, BUGFIX_FILENAME,++ REQUIREMENT_FILENAME,+)from metagpt.logs import logger- from metagpt.schema import Document, Documents, Message, BugFixContext-from metagpt.utils.get_template import get_template++from metagpt.schema import BugFixContext, Document, Documents, Message+from metagpt.utils.common import CodeParser+from metagpt.utils.file_repository import FileRepository+-templates = {- "json": {- "PROMPT_TEMPLATE": """-# Context-## Original Requirements-{requirements}+# from metagpt.utils.get_template import get_template+from metagpt.utils.mermaid import mermaid_to_file+++# from typing import List+++++CONTEXT_TEMPLATE = """+### Project Name+{project_name}-## Search Information-{search_information}--## mermaid quadrantChart code syntax example. DONT USE QUOTE IN CODE DUE TO INVALID SYNTAX. Replace the <Campain X> with REAL COMPETITOR NAME-```mermaid-quadrantChart- title Reach and engagement of campaigns- x-axis Low Reach --> High Reach- y-axis Low Engagement --> High Engagement- quadrant-1 We should expand- quadrant-2 Need to promote- quadrant-3 Re-evaluate- quadrant-4 May be improved- "Campaign: A": [0.3, 0.6]- "Campaign B": [0.45, 0.23]- "Campaign C": [0.57, 0.69]- "Campaign D": [0.78, 0.34]- "Campaign E": [0.40, 0.34]- "Campaign F": [0.35, 0.78]- "Our Target Product": [0.5, 0.6]-```--## Format example-{format_example}-------Role: You are a professional product manager; the goal is to design a concise, usable, efficient product-Requirements: According to the context, fill in the following missing information, each section name is a key in json ,If the requirements are unclear, ensure minimum viability and avoid excessive design--## Original Requirements: Provide as Plain text, place the polished complete original requirements here--## Product Goals: Provided as Python list[str], up to 3 clear, orthogonal product goals. If the requirement itself is simple, the goal should also be simple--## User Stories: Provided as Python list[str], up to 5 scenario-based user stories, If the requirement itself is simple, the user stories should also be less--## Competitive Analysis: Provided as Python list[str], up to 7 competitive product analyses, consider as similar competitors as possible--## Competitive Quadrant Chart: Use mermaid quadrantChart code syntax. up to 14 competitive products. Translation: Distribute these competitor scores evenly between 0 and 1, trying to conform to a normal distribution centered around 0.5 as much as possible.--## Requirement Analysis: Provide as Plain text. Be simple. LESS IS MORE. Make your requirements less dumb. Delete the parts unnessasery.--## Requirement Pool: Provided as Python list[list[str], the parameters are requirement description, priority(P0/P1/P2), respectively, comply with PEP standards; no more than 5 requirements and consider to make its difficulty lower--## UI Design draft: Provide as Plain text. Be simple. Describe the elements and functions, also provide a simple style description and layout description.-## Anything UNCLEAR: Provide as Plain text. Make clear here.--output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like format example,-and only output the json inside this tag, nothing else-""",- "FORMAT_EXAMPLE": """-[CONTENT]-{- "Original Requirements": "",- "Search Information": "",- "Requirements": "",- "Product Goals": [],- "User Stories": [],- "Competitive Analysis": [],- "Competitive Quadrant Chart": "quadrantChart- title Reach and engagement of campaigns- x-axis Low Reach --> High Reach- y-axis Low Engagement --> High Engagement- quadrant-1 We should expand- quadrant-2 Need to promote- quadrant-3 Re-evaluate- quadrant-4 May be improved- Campaign A: [0.3, 0.6]- Campaign B: [0.45, 0.23]- Campaign C: [0.57, 0.69]- Campaign D: [0.78, 0.34]- Campaign E: [0.40, 0.34]- Campaign F: [0.35, 0.78]",- "Requirement Analysis": "",- "Requirement Pool": [["P0","P0 requirement"],["P1","P1 requirement"]],- "UI Design draft": "",- "Anything UNCLEAR": "",-}-[/CONTENT]-""",- },- "markdown": {- "PROMPT_TEMPLATE": """-# Context-## Original Requirements+### Original Requirements{requirements}-## Search Information-{search_information}--## mermaid quadrantChart code syntax example. DONT USE QUOTE IN CODE DUE TO INVALID SYNTAX. Replace the <Campain X> with REAL COMPETITOR NAME-```mermaid-quadrantChart- title Reach and engagement of campaigns- x-axis Low Reach --> High Reach- y-axis Low Engagement --> High Engagement- quadrant-1 We should expand- quadrant-2 Need to promote- quadrant-3 Re-evaluate- quadrant-4 May be improved- "Campaign: A": [0.3, 0.6]- "Campaign B": [0.45, 0.23]- "Campaign C": [0.57, 0.69]- "Campaign D": [0.78, 0.34]- "Campaign E": [0.40, 0.34]- "Campaign F": [0.35, 0.78]- "Our Target Product": [0.5, 0.6]-```--## Format example-{format_example}-------Role: You are a professional product manager; the goal is to design a concise, usable, efficient product-Requirements: According to the context, fill in the following missing information, note that each sections are returned in Python code triple quote form seperatedly. If the requirements are unclear, ensure minimum viability and avoid excessive design-ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. AND '## <SECTION_NAME>' SHOULD WRITE BEFORE the code and triple quote. Output carefully referenced "Format example" in format.--## Original Requirements: Provide as Plain text, place the polished complete original requirements here--## Product Goals: Provided as Python list[str], up to 3 clear, orthogonal product goals. If the requirement itself is simple, the goal should also be simple--## User Stories: Provided as Python list[str], up to 5 scenario-based user stories, If the requirement itself is simple, the user stories should also be less--## Competitive Analysis: Provided as Python list[str], up to 7 competitive product analyses, consider as similar competitors as possible--## Competitive Quadrant Chart: Use mermaid quadrantChart code syntax. up to 14 competitive products. Translation: Distribute these competitor scores evenly between 0 and 1, trying to conform to a normal distribution centered around 0.5 as much as possible.--## Requirement Analysis: Provide as Plain text. Be simple. LESS IS MORE. Make your requirements less dumb. Delete the parts unnessasery.--## Requirement Pool: Provided as Python list[list[str], the parameters are requirement description, priority(P0/P1/P2), respectively, comply with PEP standards; no more than 5 requirements and consider to make its difficulty lower--## UI Design draft: Provide as Plain text. Be simple. Describe the elements and functions, also provide a simple style description and layout description.-## Anything UNCLEAR: Provide as Plain text. Make clear here.-""",- "FORMAT_EXAMPLE": """-----## Original Requirements-The boss ...--## Product Goals-```python-[- "Create a ...",-]-```--## User Stories-```python-[- "As a user, ...",-]-```--## Competitive Analysis-```python-[- "Python Snake Game: ...",-]-```--## Competitive Quadrant Chart-```mermaid-quadrantChart- title Reach and engagement of campaigns- ...- "Our Target Product": [0.6, 0.7]-```--## Requirement Analysis-The product should be a ...--## Requirement Pool-```python-[- ["End game ...", "P0"]-]-```--## UI Design draft-Give a basic function description, and a draft--## Anything UNCLEAR-There are no unclear points.-----""",- },-}--OUTPUT_MAPPING = {- "Original Requirements": (str, ...),- "Product Goals": (List[str], ...),- "User Stories": (List[str], ...),- "Competitive Analysis": (List[str], ...),- "Competitive Quadrant Chart": (str, ...),- "Requirement Analysis": (str, ...),- "Requirement Pool": (List[List[str]], ...),- "UI Design draft": (str, ...),- "Anything UNCLEAR": (str, ...),-}+### Search Information+-+"""++NEW_REQ_TEMPLATE = """+### Legacy Content+{old_prd}++### New Requirements+{requirements}+"""class WritePRD(Action):def __init__(self, name="", context=None, llm=None):super().__init__(name, context, llm)- async def run(self, requirements, format=CONFIG.prompt_format, *args, **kwargs) -> ActionOutput:- sas = SearchAndSummarize()- # rsp = await sas.run(context=requirements, system_text=SEARCH_AND_SUMMARIZE_SYSTEM_EN_US)- rsp = ""- info = f"### Search Results\n{sas.result}\n\n### Search Summary\n{rsp}"- if sas.result:- logger.info(sas.result)- logger.info(rsp)-- prompt_template, format_example = get_template(templates, format)- prompt = prompt_template.format(- requirements=requirements, search_information=info, format_example=format_example+ async def run(self, with_messages, format=CONFIG.prompt_format, *args, **kwargs) -> ActionOutput | Message:+ # Determine which requirement documents need to be rewritten: Use LLM to assess whether new requirements are+ # related to the PRD. If they are related, rewrite the PRD.+ docs_file_repo = CONFIG.git_repo.new_file_repository(relative_path=DOCS_FILE_REPO)+ requirement_doc = await docs_file_repo.get(filename=REQUIREMENT_FILENAME)+ if await self._is_bugfix(requirement_doc.content):+ await docs_file_repo.save(filename=BUGFIX_FILENAME, content=requirement_doc.content)+ await docs_file_repo.save(filename=REQUIREMENT_FILENAME, content="")+ bug_fix = BugFixContext(filename=BUGFIX_FILENAME)- return Message(content=bug_fix.json(), instruct_content=bug_fix,- role="",- cause_by=FixBug,- sent_from=self,- send_to="Alex", # the name of Engineer- )++ return Message(++ content=bug_fix.json(),++ instruct_content=bug_fix,++ role="",++ cause_by=FixBug,++ sent_from=self,++ send_to="Alex", # the name of Engineer++ )+ else:+ await docs_file_repo.delete(filename=BUGFIX_FILENAME)++ prds_file_repo = CONFIG.git_repo.new_file_repository(PRDS_FILE_REPO)+ prd_docs = await prds_file_repo.get_all()+ change_files = Documents()+ for prd_doc in prd_docs:+ prd_doc = await self._update_prd(+ requirement_doc=requirement_doc, prd_doc=prd_doc, prds_file_repo=prds_file_repo, *args, **kwargs+ )+ if not prd_doc:+ continue+ change_files.docs[prd_doc.filename] = prd_doc+ logger.info(f"rewrite prd: {prd_doc.filename}")+ # If there is no existing PRD, generate one using 'docs/requirement.txt'.+ if not change_files.docs:+ prd_doc = await self._update_prd(+ requirement_doc=requirement_doc, prd_doc=None, prds_file_repo=prds_file_repo, *args, **kwargs+ )+ if prd_doc:+ change_files.docs[prd_doc.filename] = prd_doc+ logger.debug(f"new prd: {prd_doc.filename}")+ # Once all files under 'docs/prds/' have been compared with the newly added requirements, trigger the+ # 'publish' message to transition the workflow to the next stage. This design allows room for global+ # optimization in subsequent steps.+ return ActionOutput(content=change_files.json(), instruct_content=change_files)++ async def _run_new_requirement(self, requirements, format=CONFIG.prompt_format) -> ActionOutput:+ # sas = SearchAndSummarize()+ # # rsp = await sas.run(context=requirements, system_text=SEARCH_AND_SUMMARIZE_SYSTEM_EN_US)+ # rsp = ""+ # info = f"### Search Results\n{sas.result}\n\n### Search Summary\n{rsp}"+ # if sas.result:+ # logger.info(sas.result)+ # logger.info(rsp)+ project_name = CONFIG.project_name if CONFIG.project_name else ""+ context = CONTEXT_TEMPLATE.format(requirements=requirements, project_name=project_name)+ node = await WRITE_PRD_NODE.fill(context=context, llm=self.llm, to=format)+ await self._rename_workspace(node)+ return node++ async def _is_relative(self, new_requirement_doc, old_prd_doc) -> bool:+ context = NEW_REQ_TEMPLATE.format(old_prd=old_prd_doc.content, requirements=new_requirement_doc.content)+ node = await WP_IS_RELATIVE_NODE.fill(context, self.llm)+ return node.get("is_relative") == "YES"++ async def _merge(self, new_requirement_doc, prd_doc, format=CONFIG.prompt_format) -> Document:+ if not CONFIG.project_name:+ CONFIG.project_name = Path(CONFIG.project_path).name+ prompt = NEW_REQ_TEMPLATE.format(requirements=new_requirement_doc.content, old_prd=prd_doc.content)+ node = await WRITE_PRD_NODE.fill(context=prompt, llm=self.llm, to=format)+ prd_doc.content = node.instruct_content.json(ensure_ascii=False)+ await self._rename_workspace(node)+ 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(ensure_ascii=False),+ )+ elif await self._is_relative(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("")++ CONFIG.git_repo.workdir / Path(COMPETITIVE_ANALYSIS_FILE_REPO) / Path(prd_doc.filename).with_suffix(""))- logger.debug(prompt)- # prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING)- prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING, format=format)- return prd+ 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)++ @staticmethod+ async def _rename_workspace(prd):+ if CONFIG.project_path: # Updating on the old version has already been specified if it's valid. According to+ # Section 2.2.3.10 of RFC 135+ if not CONFIG.project_name:+ CONFIG.project_name = Path(CONFIG.project_path).name+ return++ if not CONFIG.project_name:+ if isinstance(prd, ActionOutput) or isinstance(prd, ActionNode):+ ws_name = prd.instruct_content.dict()["Project Name"]+ else:+ ws_name = CodeParser.parse_str(block="Project Name", text=prd)+ CONFIG.project_name = ws_name+ CONFIG.git_repo.rename_root(CONFIG.project_name)++ async def _is_bugfix(self, context) -> bool:+ node = await WP_ISSUE_TYPE_NODE.fill(context, self.llm)+ return node.get("issue_type") == "BUG"diff --cc metagpt/config.pyindex d2390f704,2ce75b013..d04da1d91--- a/metagpt/config.py+++ b/metagpt/config.py@@@ -55,14 -46,23 +55,22 @@@ class Config(metaclass=Singleton)self.openai_api_key = self._get("OPENAI_API_KEY")self.anthropic_api_key = self._get("Anthropic_API_KEY")self.zhipuai_api_key = self._get("ZHIPUAI_API_KEY")-+ self.open_llm_api_base = self._get("OPEN_LLM_API_BASE")+ self.open_llm_api_model = self._get("OPEN_LLM_API_MODEL")-+ self.fireworks_api_key = self._get("FIREWORKS_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) and \- (not self.open_llm_api_base) and \- (not self.fireworks_api_key or "YOUR_API_KEY" == self.fireworks_api_key):- raise NotConfiguredException("Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first "- "or FIREWORKS_API_KEY or OPEN_LLM_API_BASE")+ 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)++ and (not self.open_llm_api_base)++ and (not self.fireworks_api_key or "YOUR_API_KEY" == self.fireworks_api_key)+ ):- raise NotConfiguredException("Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first")++ raise NotConfiguredException(++ "Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first "++ "or FIREWORKS_API_KEY or OPEN_LLM_API_BASE"++ )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)@@@ -102,19 -104,14 +113,20 @@@self.mermaid_engine = self._get("MERMAID_ENGINE", "nodejs")self.pyppeteer_executable_path = self._get("PYPPETEER_EXECUTABLE_PATH", "")+ self.repair_llm_output = self._get("REPAIR_LLM_OUTPUT", False)self.prompt_format = self._get("PROMPT_FORMAT", "markdown")+ self.workspace_path = Path(self._get("WORKSPACE_PATH", DEFAULT_WORKSPACE_ROOT))+ self._ensure_workspace_exists()- def _init_with_config_files_and_env(self, configs: dict, yaml_file):+ def _ensure_workspace_exists(self):+ self.workspace_path.mkdir(parents=True, exist_ok=True)+ logger.debug(f"WORKSPACE_PATH set to {self.workspace_path}")++ 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/llm.pyindex eaa4880a5,7b490ec4a..7c0ad7975--- a/metagpt/llm.py+++ b/metagpt/llm.py@@@ -7,18 -7,17 +7,19 @@@"""from metagpt.config import CONFIG--from metagpt.provider.anthropic_api import Claude2 as Claude-from metagpt.provider.openai_api import OpenAIGPTAPI-from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI-from metagpt.provider.spark_api import SparkAPI-from metagpt.provider.open_llm_api import OpenLLMGPTAPI++from metagpt.provider.base_gpt_api import BaseGPTAPI+ from metagpt.provider.fireworks_api import FireWorksGPTAPIfrom metagpt.provider.human_provider import HumanProvider++from metagpt.provider.open_llm_api import OpenLLMGPTAPI+from metagpt.provider.openai_api import OpenAIGPTAPI+from metagpt.provider.spark_api import SparkAPI+from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI- from metagpt.provider.base_gpt_api import BaseGPTAPI++_ = HumanProvider() # Avoid pre-commit error-def LLM() -> "BaseGPTAPI":- """ initialize different LLM instance according to the key field existence"""+def LLM() -> BaseGPTAPI:+ """initialize different LLM instance according to the key field existence"""# TODO a little trick, can use registry to initialize LLM instance furtherif CONFIG.openai_api_key:llm = OpenAIGPTAPI()diff --cc metagpt/logs.pyindex 092b4c476,471d57fe9..ab1bc4e94--- a/metagpt/logs.py+++ b/metagpt/logs.py@@@ -14,10 -15,15 +15,13 @@@ 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"""+ current_date = datetime.now()+ formatted_date = current_date.strftime("%Y%m%d")+_logger.remove()_logger.add(sys.stderr, level=print_level)- _logger.add(METAGPT_ROOT / "logs/log.txt", level=logfile_level)- _logger.add(PROJECT_ROOT / f"logs/{formatted_date}.log", level=logfile_level)++ _logger.add(METAGPT_ROOT / f"logs/{formatted_date}.txt", level=logfile_level)return _loggerdiff --cc metagpt/roles/role.pyindex 7c9341adb,140910f0a..633ad6051--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -25,17 -12,16 +25,15 @@@ from typing import Iterable, Set, Typfrom pydantic import BaseModel, Field-# from metagpt.environment import Environment-from metagpt.config import CONFIGfrom metagpt.actions import Action, ActionOutput+from metagpt.actions.action_node import ActionNode- from metagpt.config import CONFIGfrom metagpt.llm import LLM, HumanProviderfrom metagpt.logs import logger-from metagpt.memory import Memory, LongTermMemory-from metagpt.schema import Message+from metagpt.memory import Memory-- # from metagpt.memory import LongTermMemory+from metagpt.schema import Message, MessageQueue+from metagpt.utils.common import any_to_str+ from metagpt.utils.repair_llm_raw_output import extract_state_value_from_output-PREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """STATE_TEMPLATE = """Here are your conversation records. You can decide which stage you should enter or stay in based on these records.@@@ -113,9 -94,9 +111,10 @@@ class RoleContext(BaseModel)arbitrary_types_allowed = Truedef check(self, role_id: str):-- if hasattr(CONFIG, "long_term_memory") and CONFIG.long_term_memory:-- self.long_term_memory.recover_memory(role_id, self)-- self.memory = self.long_term_memory # use memory to act as long_term_memory for unify operation++ # if hasattr(CONFIG, "long_term_memory") and CONFIG.long_term_memory:++ # self.long_term_memory.recover_memory(role_id, self)++ # self.memory = self.long_term_memory # use memory to act as long_term_memory for unify operation++ pass@propertydef important_memory(self) -> list[Message]:@@@ -152,12 -131,10 +151,13 @@@ class Rolei = 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, "- f"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"++ f"is_human attribute does not take effect, "++ f"as Role's {str(action)} was initialized using LLM, "++ f"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}")@@@ -258,17 -194,15 +258,18 @@@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,+ previous_state=self._rc.state,+ )# print(prompt)next_state = await self._llm.aask(prompt)+ next_state = extract_state_value_from_output(next_state)logger.debug(f"{prompt=}")- 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 = -1else:next_state = int(next_state)