Skip to content

🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming

merge main to dev

mannaandpoem76d4451fc673
diff --cc metagpt/actions/design_api.py
index c6f608b7e,d24cd2ae3..4060d211c
--- a/metagpt/actions/design_api.py
+++ b/metagpt/actions/design_api.py
@@@ -14,10 -14,25 +14,17 @@@ from pathlib import Pat
from typing import Optional
from metagpt.actions import Action, ActionOutput
- from metagpt.actions.design_api_an import DESIGN_API_NODE
+ from metagpt.actions.design_api_an import (
+ DATA_STRUCTURES_AND_INTERFACES,
+ DESIGN_API_NODE,
+ PROGRAM_CALL_FLOW,
+ REFINED_DATA_STRUCTURES_AND_INTERFACES,
+ REFINED_DESIGN_NODE,
+ REFINED_PROGRAM_CALL_FLOW,
+ )
-from metagpt.config import CONFIG
-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.const import DATA_API_DESIGN_FILE_REPO, SEQ_FLOW_FILE_REPO
from metagpt.logs import logger
from metagpt.schema import Document, Documents, Message
-from metagpt.utils.file_repository import FileRepository
from metagpt.utils.mermaid import mermaid_to_file
NEW_REQ_TEMPLATE = """
@@@ -62,13 -83,13 +69,13 @@@ class WriteDesign(Action)
# leaving room for global optimization in subsequent steps.
return ActionOutput(content=changed_files.model_dump_json(), instruct_content=changed_files)
- async def _new_system_design(self, context, schema=CONFIG.prompt_schema):
- node = await DESIGN_API_NODE.fill(context=context, llm=self.llm, schema=schema)
+ async def _new_system_design(self, context):
+ node = await DESIGN_API_NODE.fill(context=context, llm=self.llm)
return node
- async def _merge(self, prd_doc, system_design_doc, schema=CONFIG.prompt_schema):
+ async def _merge(self, prd_doc, system_design_doc):
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)
- node = await REFINED_DESIGN_NODE.fill(context=context, llm=self.llm, schema=schema)
++ node = await REFINED_DESIGN_NODE.fill(context=context, llm=self.llm)
system_design_doc.content = node.instruct_content.model_dump_json()
return system_design_doc
@@@ -84,30 -105,39 +91,30 @@@
)
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.repo.docs.system_design.save_doc(doc=doc, dependencies={prd.root_relative_path})
await self._save_data_api_design(doc)
await self._save_seq_flow(doc)
- await self._save_pdf(doc)
+ await self.repo.resources.system_design.save_pdf(doc=doc)
return doc
- @staticmethod
- async def _save_data_api_design(design_doc):
+ async def _save_data_api_design(self, design_doc):
m = json.loads(design_doc.content)
- data_api_design = m.get("Data structures and interfaces")
+ data_api_design = m.get(DATA_STRUCTURES_AND_INTERFACES.key) or m.get(REFINED_DATA_STRUCTURES_AND_INTERFACES.key)
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)
+ pathname = self.repo.workdir / DATA_API_DESIGN_FILE_REPO / Path(design_doc.filename).with_suffix("")
+ await self._save_mermaid_file(data_api_design, pathname)
logger.info(f"Save class view to {str(pathname)}")
- @staticmethod
- async def _save_seq_flow(design_doc):
+ async def _save_seq_flow(self, design_doc):
m = json.loads(design_doc.content)
- seq_flow = m.get("Program call flow")
+ seq_flow = m.get(PROGRAM_CALL_FLOW.key) or m.get(REFINED_PROGRAM_CALL_FLOW.key)
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)
+ pathname = self.repo.workdir / Path(SEQ_FLOW_FILE_REPO) / Path(design_doc.filename).with_suffix("")
+ await self._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):
+ async def _save_mermaid_file(self, data: str, pathname: Path):
pathname.parent.mkdir(parents=True, exist_ok=True)
- await mermaid_to_file(data, pathname)
+ await mermaid_to_file(self.config.mermaid_engine, data, pathname)
diff --cc metagpt/actions/project_management.py
index 7988dd4e8,448a8afcd..d417bf538
--- a/metagpt/actions/project_management.py
+++ b/metagpt/actions/project_management.py
@@@ -13,12 -13,19 +13,12 @@@
import json
from typing import Optional
-from metagpt.actions import ActionOutput
from metagpt.actions.action import Action
+from metagpt.actions.action_output import ActionOutput
- from metagpt.actions.project_management_an import PM_NODE
+ from metagpt.actions.project_management_an import PM_NODE, REFINED_PM_NODE
-from metagpt.config import CONFIG
-from metagpt.const import (
- PACKAGE_REQUIREMENTS_FILENAME,
- SYSTEM_DESIGN_FILE_REPO,
- TASK_FILE_REPO,
- TASK_PDF_FILE_REPO,
-)
+from metagpt.const import PACKAGE_REQUIREMENTS_FILENAME
from metagpt.logs import logger
from metagpt.schema import Document, Documents
-from metagpt.utils.file_repository import FileRepository
NEW_REQ_TEMPLATE = """
### Legacy Content
@@@ -56,29 -70,30 +56,29 @@@ class WriteTasks(Action)
# global optimization in subsequent steps.
return ActionOutput(content=change_files.model_dump_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)
+ async def _update_tasks(self, filename):
+ system_design_doc = await self.repo.docs.system_design.get(filename)
+ task_doc = await self.repo.docs.task.get(filename)
if task_doc:
task_doc = await self._merge(system_design_doc=system_design_doc, task_doc=task_doc)
+ await self.repo.docs.task.save_doc(doc=task_doc, dependencies={system_design_doc.root_relative_path})
else:
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.model_dump_json()
+ task_doc = await self.repo.docs.task.save(
+ filename=filename,
+ content=rsp.instruct_content.model_dump_json(),
+ dependencies={system_design_doc.root_relative_path},
)
- 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, schema=CONFIG.prompt_schema):
- node = await PM_NODE.fill(context, self.llm, schema)
+ async def _run_new_tasks(self, context):
+ node = await PM_NODE.fill(context, self.llm, schema=self.prompt_schema)
return node
- async def _merge(self, system_design_doc, task_doc, schema=CONFIG.prompt_schema) -> Document:
+ async def _merge(self, system_design_doc, task_doc) -> Document:
context = NEW_REQ_TEMPLATE.format(context=system_design_doc.content, old_tasks=task_doc.content)
- node = await PM_NODE.fill(context, self.llm, schema=self.prompt_schema)
- node = await REFINED_PM_NODE.fill(context, self.llm, schema)
++ node = await REFINED_PM_NODE.fill(context, self.llm, schema=self.prompt_schema)
task_doc.content = node.instruct_content.model_dump_json()
return task_doc
diff --cc metagpt/actions/write_code.py
index aaaa9648a,818990991..df1e383e7
--- a/metagpt/actions/write_code.py
+++ b/metagpt/actions/write_code.py
@@@ -21,10 -22,23 +22,17 @@@ from pydantic import Fiel
from tenacity import retry, stop_after_attempt, wait_random_exponential
from metagpt.actions.action import Action
- from metagpt.const import BUGFIX_FILENAME
+ from metagpt.actions.project_management_an import REFINED_TASK_LIST, TASK_LIST
+ from metagpt.actions.write_code_plan_and_change_an import REFINED_TEMPLATE
-from metagpt.config import CONFIG
+ from metagpt.const import (
+ BUGFIX_FILENAME,
- CODE_PLAN_AND_CHANGE_FILE_REPO,
+ CODE_PLAN_AND_CHANGE_FILENAME,
- CODE_SUMMARIES_FILE_REPO,
- DOCS_FILE_REPO,
+ REQUIREMENT_FILENAME,
- TASK_FILE_REPO,
- TEST_OUTPUTS_FILE_REPO,
+ )
from metagpt.logs import logger
from metagpt.schema import CodingContext, Document, RunCodeResult
from metagpt.utils.common import CodeParser
-from metagpt.utils.file_repository import FileRepository
++from metagpt.utils.project_repo import ProjectRepo
PROMPT_TEMPLATE = """
NOTICE
@@@ -88,12 -102,21 +96,15 @@@ class WriteCode(Action)
return code
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
- )
- code_plan_and_change_doc = await FileRepository.get_file(
- filename=CODE_PLAN_AND_CHANGE_FILENAME, relative_path=CODE_PLAN_AND_CHANGE_FILE_REPO
- )
+ bug_feedback = await self.repo.docs.get(filename=BUGFIX_FILENAME)
+ coding_context = CodingContext.loads(self.i_context.content)
+ test_doc = await self.repo.test_outputs.get(filename="test_" + coding_context.filename + ".json")
++ code_plan_and_change_doc = await self.repo.docs.code_plan_and_change.get(filename=CODE_PLAN_AND_CHANGE_FILENAME)
+ code_plan_and_change = code_plan_and_change_doc.content if code_plan_and_change_doc else ""
- requirement_doc = await FileRepository.get_file(filename=REQUIREMENT_FILENAME, relative_path=DOCS_FILE_REPO)
++ requirement_doc = await self.repo.docs.requirement.get(filename=REQUIREMENT_FILENAME)
summary_doc = None
if coding_context.design_doc and coding_context.design_doc.filename:
- summary_doc = await FileRepository.get_file(
- filename=coding_context.design_doc.filename, relative_path=CODE_SUMMARIES_FILE_REPO
- )
+ summary_doc = await self.repo.docs.code_summary.get(filename=coding_context.design_doc.filename)
logs = ""
if test_doc:
test_detail = RunCodeResult.loads(test_doc.content)
@@@ -101,22 -124,35 +112,39 @@@
if bug_feedback:
code_context = coding_context.code_doc.content
+ elif code_plan_and_change:
+ code_context = await self.get_codes(
- coding_context.task_doc, exclude=self.context.filename, mode="incremental"
++ coding_context.task_doc, exclude=self.context.filename, project_repo=self.repo, mode="incremental"
+ )
else:
- code_context = await self.get_codes(coding_context.task_doc, exclude=self.context.filename)
+ code_context = await self.get_codes(
+ coding_context.task_doc,
+ exclude=self.i_context.filename,
+ project_repo=self.repo.with_src_path(self.context.src_workspace),
+ )
- prompt = PROMPT_TEMPLATE.format(
- design=coding_context.design_doc.content if coding_context.design_doc else "",
- 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.i_context.filename,
- summary_log=summary_doc.content if summary_doc else "",
- )
+ if code_plan_and_change:
+ prompt = REFINED_TEMPLATE.format(
+ user_requirement=requirement_doc.content if requirement_doc else "",
+ code_plan_and_change=code_plan_and_change,
+ design=coding_context.design_doc.content if coding_context.design_doc else "",
+ 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 "",
+ )
+ else:
+ prompt = PROMPT_TEMPLATE.format(
+ design=coding_context.design_doc.content if coding_context.design_doc else "",
+ 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,
++ filename=self.i_context.filename,
+ summary_log=summary_doc.content if summary_doc else "",
+ )
logger.info(f"Writing {coding_context.filename}..")
code = await self.write_code(prompt)
if not coding_context.code_doc:
@@@ -127,20 -163,69 +155,71 @@@
return coding_context
@staticmethod
- async def get_codes(task_doc, exclude, project_repo) -> str:
- async def get_codes(task_doc: Document, exclude: str, mode: Literal["normal", "incremental"] = "normal") -> str:
++ async def get_codes(
++ task_doc: Document, exclude: str, project_repo: ProjectRepo, mode: Literal["normal", "incremental"] = "normal"
++ ) -> str:
+ """
+ Get code snippets based on different modes.
+
+ Attributes:
+ task_doc (Document): Document object of the task file.
+ exclude (str): Specifies the filename to be excluded from the code snippets.
++ project_repo (ProjectRepo): ProjectRepo object of the project.
+ mode (str): Specifies the mode, either "normal" or "incremental" (default is "normal").
+
+ Returns:
+ str: Code snippets.
+
+ Description:
+ If mode is set to "normal", it returns code snippets for the regular coding phase,
+ i.e., all the code generated before writing the current file.
+
+ If mode is set to "incremental", it returns code snippets for generating the code plan and change,
+ building upon the existing code in the "normal" mode and adding code for the current file's older versions.
+ """
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)
+ task_doc = project_repo.docs.task.get(filename=task_doc.filename)
m = json.loads(task_doc.content)
- code_filenames = m.get("Task list", [])
+ code_filenames = m.get(TASK_LIST.key, []) if mode == "normal" else m.get(REFINED_TASK_LIST.key, [])
codes = []
- src_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)
+ src_file_repo = project_repo.srcs
- for filename in code_filenames:
- if filename == exclude:
- continue
- doc = await src_file_repo.get(filename=filename)
- if not doc:
- continue
- codes.append(f"----- {filename}\n" + doc.content)
+
+ if mode == "incremental":
+ src_files = src_file_repo.all_files
- old_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.old_workspace)
++ old_file_repo = project_repo.git_repo.new_file_repository(relative_path=project_repo.old_workspace)
+ old_files = old_file_repo.all_files
+ # Get the union of the files in the src and old workspaces
+ union_files_list = list(set(src_files) | set(old_files))
+ for filename in union_files_list:
+ # Exclude the current file from the all code snippets to get the context code snippets for generating
+ if filename == exclude:
+ # If the file is in the old workspace, use the legacy code
+ # Exclude unnecessary code to maintain a clean and focused main.py file, ensuring only relevant and
+ # essential functionality is included for the project’s requirements
+ if filename in old_files and filename != "main.py":
+ # Use legacy code
+ doc = await old_file_repo.get(filename=filename)
+ # If the file is in the src workspace, skip it
+ else:
+ continue
+ codes.insert(0, f"-----Now, {filename} to be rewritten\n```{doc.content}```\n=====")
+ # The context code snippets are generated from the src workspace
+ else:
+ doc = await src_file_repo.get(filename=filename)
+ # If the file does not exist in the src workspace, skip it
+ if not doc:
+ continue
+ codes.append(f"----- {filename}\n```{doc.content}```")
+
+ elif mode == "normal":
+ for filename in code_filenames:
+ # Exclude the current file to get the context code snippets for generating the current file
+ if filename == exclude:
+ continue
+ doc = await src_file_repo.get(filename=filename)
+ if not doc:
+ continue
+ codes.append(f"----- {filename}\n```{doc.content}```")
-
return "\n".join(codes)
diff --cc metagpt/actions/write_code_plan_and_change_an.py
index 000000000,8bf20e494..188520ba8
mode 000000,100644..100644
--- a/metagpt/actions/write_code_plan_and_change_an.py
+++ b/metagpt/actions/write_code_plan_and_change_an.py
@@@ -1,0 -1,209 +1,207 @@@
+ #!/usr/bin/env python
+ # -*- coding: utf-8 -*-
+ """
+ @Time : 2023/12/26
+ @Author : mannaandpoem
+ @File : write_code_plan_and_change_an.py
+ """
+ import os
+
+ from pydantic import Field
+
+ from metagpt.actions.action import Action
+ from metagpt.actions.action_node import ActionNode
-from metagpt.config import CONFIG
+ from metagpt.schema import CodePlanAndChangeContext
+
+ CODE_PLAN_AND_CHANGE = ActionNode(
+ key="Code Plan And Change",
+ expected_type=str,
+ instruction="Developing comprehensive and step-by-step incremental development plan, and write Incremental "
+ "Change by making a code draft that how to implement incremental development including detailed steps based on the "
+ "context. Note: Track incremental changes using mark of '+' or '-' for add/modify/delete code, and conforms to the "
+ "output format of git diff",
+ example="""
+ 1. Plan for calculator.py: Enhance the functionality of `calculator.py` by extending it to incorporate methods for subtraction, multiplication, and division. Additionally, implement robust error handling for the division operation to mitigate potential issues related to division by zero.
+ ```python
+ class Calculator:
+ self.result = number1 + number2
+ return self.result
+
+ - def sub(self, number1, number2) -> float:
+ + def subtract(self, number1: float, number2: float) -> float:
+ + '''
+ + Subtracts the second number from the first and returns the result.
+ +
+ + Args:
+ + number1 (float): The number to be subtracted from.
+ + number2 (float): The number to subtract.
+ +
+ + Returns:
+ + float: The difference of number1 and number2.
+ + '''
+ + self.result = number1 - number2
+ + return self.result
+ +
+ def multiply(self, number1: float, number2: float) -> float:
+ - pass
+ + '''
+ + Multiplies two numbers and returns the result.
+ +
+ + Args:
+ + number1 (float): The first number to multiply.
+ + number2 (float): The second number to multiply.
+ +
+ + Returns:
+ + float: The product of number1 and number2.
+ + '''
+ + self.result = number1 * number2
+ + return self.result
+ +
+ def divide(self, number1: float, number2: float) -> float:
+ - pass
+ + '''
+ + ValueError: If the second number is zero.
+ + '''
+ + if number2 == 0:
+ + raise ValueError('Cannot divide by zero')
+ + self.result = number1 / number2
+ + return self.result
+ +
+ - def reset_result(self):
+ + def clear(self):
+ + if self.result != 0.0:
+ + print("Result is not zero, clearing...")
+ + else:
+ + print("Result is already zero, no need to clear.")
+ +
+ self.result = 0.0
+ ```
+
+ 2. Plan for main.py: Integrate new API endpoints for subtraction, multiplication, and division into the existing codebase of `main.py`. Then, ensure seamless integration with the overall application architecture and maintain consistency with coding standards.
+ ```python
+ def add_numbers():
+ result = calculator.add_numbers(num1, num2)
+ return jsonify({'result': result}), 200
+
+ -# TODO: Implement subtraction, multiplication, and division operations
+ [email protected]('/subtract_numbers', methods=['POST'])
+ +def subtract_numbers():
+ + data = request.get_json()
+ + num1 = data.get('num1', 0)
+ + num2 = data.get('num2', 0)
+ + result = calculator.subtract_numbers(num1, num2)
+ + return jsonify({'result': result}), 200
+ +
+ [email protected]('/multiply_numbers', methods=['POST'])
+ +def multiply_numbers():
+ + data = request.get_json()
+ + num1 = data.get('num1', 0)
+ + num2 = data.get('num2', 0)
+ + try:
+ + result = calculator.divide_numbers(num1, num2)
+ + except ValueError as e:
+ + return jsonify({'error': str(e)}), 400
+ + return jsonify({'result': result}), 200
+ +
+ if __name__ == '__main__':
+ app.run()
+ ```""",
+ )
+
+ CODE_PLAN_AND_CHANGE_CONTEXT = """
+ ## User New Requirements
+ {requirement}
+
+ ## PRD
+ {prd}
+
+ ## Design
+ {design}
+
+ ## Tasks
+ {tasks}
+
+ ## Legacy Code
+ {code}
+ """
+
+ REFINED_TEMPLATE = """
+ NOTICE
+ Role: You are a professional engineer; The main goal is to complete incremental development by combining legacy code and plan and Incremental Change, ensuring the integration of new features.
+
+ # Context
+ ## User New Requirements
+ {user_requirement}
+
+ ## Code Plan And Change
+ {code_plan_and_change}
+
+ ## Design
+ {design}
+
+ ## Tasks
+ {tasks}
+
+ ## Legacy Code
+ ```Code
+ {code}
+ ```
+
+ ## Debug logs
+ ```text
+ {logs}
+
+ {summary_log}
+ ```
+
+ ## Bug Feedback logs
+ ```text
+ {feedback}
+ ```
+
+ # Format example
+ ## Code: {filename}
+ ```python
+ ## {filename}
+ ...
+ ```
+
+ # Instruction: Based on the context, follow "Format example", write or rewrite code.
+ ## Write/Rewrite Code: Only write one file {filename}, write or rewrite complete code using triple quotes based on the following attentions and context.
+ 1. Only One file: do your best to implement THIS ONLY ONE FILE.
+ 2. COMPLETE CODE: Your code will be part of the entire project, so please implement complete, reliable, reusable code snippets.
+ 3. Set default value: If there is any setting, ALWAYS SET A DEFAULT VALUE, ALWAYS USE STRONG TYPE AND EXPLICIT VARIABLE. AVOID circular import.
+ 4. Follow design: YOU MUST FOLLOW "Data structures and interfaces". DONT CHANGE ANY DESIGN. Do not use public member functions that do not exist in your design.
+ 5. Follow Code Plan And Change: If there is any Incremental Change or Legacy Code files contain "{filename} to be rewritten", you must merge it into the code file according to the plan.
+ 6. CAREFULLY CHECK THAT YOU DONT MISS ANY NECESSARY CLASS/FUNCTION IN THIS FILE.
+ 7. Before using a external variable/module, make sure you import it first.
+ 8. Write out EVERY CODE DETAIL, DON'T LEAVE TODO.
+ 9. Attention: Retain content that is not related to incremental development but important for consistency and clarity.".
+ """
+
+ WRITE_CODE_PLAN_AND_CHANGE_NODE = ActionNode.from_children("WriteCodePlanAndChange", [CODE_PLAN_AND_CHANGE])
+
+
+ class WriteCodePlanAndChange(Action):
+ name: str = "WriteCodePlanAndChange"
- context: CodePlanAndChangeContext = Field(default_factory=CodePlanAndChangeContext)
++ i_context: CodePlanAndChangeContext = Field(default_factory=CodePlanAndChangeContext)
+
+ async def run(self, *args, **kwargs):
+ self.llm.system_prompt = "You are a professional software engineer, your primary responsibility is to "
+ "meticulously craft comprehensive incremental development plan and deliver detailed incremental change"
- requirement = self.context.requirement_doc.content
- prd = "\n".join([doc.content for doc in self.context.prd_docs])
- design = "\n".join([doc.content for doc in self.context.design_docs])
- tasks = "\n".join([doc.content for doc in self.context.tasks_docs])
++ requirement = self.i_context.requirement_doc.content
++ prd = "\n".join([doc.content for doc in self.i_context.prd_docs])
++ design = "\n".join([doc.content for doc in self.i_context.design_docs])
++ tasks = "\n".join([doc.content for doc in self.i_context.tasks_docs])
+ code_text = await self.get_old_codes()
+ context = CODE_PLAN_AND_CHANGE_CONTEXT.format(
+ requirement=requirement, prd=prd, design=design, tasks=tasks, code=code_text
+ )
+ return await WRITE_CODE_PLAN_AND_CHANGE_NODE.fill(context=context, llm=self.llm, schema="json")
+
- @staticmethod
- async def get_old_codes() -> str:
- CONFIG.old_workspace = CONFIG.git_repo.workdir / os.path.basename(CONFIG.project_path)
- old_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.old_workspace)
++ async def get_old_codes(self) -> str:
++ self.repo.old_workspace = self.repo.git_repo.workdir / os.path.basename(self.config.project_path)
++ old_file_repo = self.repo.git_repo.new_file_repository(relative_path=self.repo.old_workspace)
+ old_codes = await old_file_repo.get_all()
+ codes = [f"----- {code.filename}\n```{code.content}```" for code in old_codes]
+ return "\n".join(codes)
diff --cc metagpt/actions/write_code_review.py
index ec56afc61,1410e3318..40dc0c342
--- a/metagpt/actions/write_code_review.py
+++ b/metagpt/actions/write_code_review.py
@@@ -13,6 -13,13 +13,7 @@@ from tenacity import retry, stop_after_
from metagpt.actions import WriteCode
from metagpt.actions.action import Action
-from metagpt.config import CONFIG
-from metagpt.const import (
- CODE_PLAN_AND_CHANGE_FILE_REPO,
- CODE_PLAN_AND_CHANGE_FILENAME,
- DOCS_FILE_REPO,
- REQUIREMENT_FILENAME,
-)
++from metagpt.const import CODE_PLAN_AND_CHANGE_FILENAME, REQUIREMENT_FILENAME
from metagpt.logs import logger
from metagpt.schema import CodingContext
from metagpt.utils.common import CodeParser
@@@ -135,23 -143,43 +136,43 @@@ class WriteCodeReview(Action)
return result, code
async def run(self, *args, **kwargs) -> CodingContext:
- iterative_code = self.context.code_doc.content
- k = CONFIG.code_review_k_times or 1
- code_plan_and_change_doc = await FileRepository.get_file(
- filename=CODE_PLAN_AND_CHANGE_FILENAME, relative_path=CODE_PLAN_AND_CHANGE_FILE_REPO
- )
+ iterative_code = self.i_context.code_doc.content
+ k = self.context.config.code_review_k_times or 1
++ code_plan_and_change_doc = await self.repo.get(filename=CODE_PLAN_AND_CHANGE_FILENAME)
+ code_plan_and_change = code_plan_and_change_doc.content if code_plan_and_change_doc else ""
+ mode = "incremental" if code_plan_and_change else "normal"
-
for i in range(k):
- format_example = FORMAT_EXAMPLE.format(filename=self.context.code_doc.filename)
- task_content = self.context.task_doc.content if self.context.task_doc else ""
- code_context = await WriteCode.get_codes(self.context.task_doc, exclude=self.context.filename, mode=mode)
+ format_example = FORMAT_EXAMPLE.format(filename=self.i_context.code_doc.filename)
+ task_content = self.i_context.task_doc.content if self.i_context.task_doc else ""
+ code_context = await WriteCode.get_codes(
+ self.i_context.task_doc,
+ exclude=self.i_context.filename,
+ project_repo=self.repo.with_src_path(self.context.src_workspace),
++ mode=mode,
+ )
- context = "\n".join(
- [
- "## System Design\n" + str(self.i_context.design_doc) + "\n",
- "## Tasks\n" + task_content + "\n",
- "## Code Files\n" + code_context + "\n",
- ]
- )
+
+ if not code_plan_and_change:
+ context = "\n".join(
+ [
+ "## System Design\n" + str(self.context.design_doc) + "\n",
+ "## Tasks\n" + task_content + "\n",
+ "## Code Files\n" + code_context + "\n",
+ ]
+ )
+ else:
- requirement_doc = await FileRepository.get_file(
- filename=REQUIREMENT_FILENAME, relative_path=DOCS_FILE_REPO
- )
++ requirement_doc = await self.repo.get(filename=REQUIREMENT_FILENAME)
+ user_requirement = requirement_doc.content if requirement_doc else ""
+
+ context = "\n".join(
+ [
+ "## User New Requirements\n" + user_requirement + "\n",
+ "## Code Plan And Change\n" + code_plan_and_change + "\n",
+ "## System Design\n" + str(self.context.design_doc) + "\n",
+ "## Tasks\n" + task_content + "\n",
+ "## Code Files\n" + code_context + "\n",
+ ]
+ )
+
context_prompt = PROMPT_TEMPLATE.format(
context=context,
code=iterative_code,
diff --cc metagpt/actions/write_prd.py
index d401cc588,8cf133da3..000c1731e
--- a/metagpt/actions/write_prd.py
+++ b/metagpt/actions/write_prd.py
@@@ -20,7 -22,10 +20,9 @@@ from metagpt.actions import Action, Act
from metagpt.actions.action_node import ActionNode
from metagpt.actions.fix_bug import FixBug
from metagpt.actions.write_prd_an import (
+ COMPETITIVE_QUADRANT_CHART,
PROJECT_NAME,
+ REFINED_PRD_NODE,
- REFINED_TEMPLATE,
WP_IS_RELATIVE_NODE,
WP_ISSUE_TYPE_NODE,
WRITE_PRD_NODE,
@@@ -134,33 -133,58 +136,33 @@@ class WritePRD(Action)
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, schema=CONFIG.prompt_schema) -> Document:
- if not CONFIG.project_name:
- CONFIG.project_name = Path(CONFIG.project_path).name
- prompt = REFINED_TEMPLATE.format(
- requirements=new_requirement_doc.content,
- old_prd=prd_doc.content,
- project_name=CONFIG.project_name,
- )
- node = await REFINED_PRD_NODE.fill(context=prompt, llm=self.llm, schema=schema)
- prd_doc.content = node.instruct_content.model_dump_json()
+ async def _merge(self, req: Document, related_doc: Document) -> Document:
+ if not self.project_name:
+ self.project_name = Path(self.project_path).name
+ prompt = NEW_REQ_TEMPLATE.format(requirements=req.content, old_prd=related_doc.content)
- node = await WRITE_PRD_NODE.fill(context=prompt, llm=self.llm, schema=self.prompt_schema)
++ node = await REFINED_PRD_NODE.fill(context=prompt, llm=self.llm, schema=self.prompt_schema)
+ related_doc.content = node.instruct_content.model_dump_json()
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 if requirement_doc else ""], *args, **kwargs
- )
- new_prd_doc = Document(
- root_path=PRDS_FILE_REPO,
- filename=FileRepository.new_filename() + ".json",
- content=prd.instruct_content.model_dump_json(),
- )
- 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)
+ return related_doc
+
+ async def _update_prd(self, req: Document, prd_doc: Document) -> Document:
+ new_prd_doc: Document = await self._merge(req, prd_doc)
+ self.repo.docs.prd.save_doc(doc=new_prd_doc)
await self._save_competitive_analysis(new_prd_doc)
- await self._save_pdf(new_prd_doc)
+ await self.repo.resources.prd.save_pdf(doc=new_prd_doc)
return new_prd_doc
- @staticmethod
- async def _save_competitive_analysis(prd_doc):
+ async def _save_competitive_analysis(self, prd_doc: Document):
m = json.loads(prd_doc.content)
- quadrant_chart = m.get("Competitive Quadrant Chart")
+ quadrant_chart = m.get(COMPETITIVE_QUADRANT_CHART.key)
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)
+ pathname = self.repo.workdir / COMPETITIVE_ANALYSIS_FILE_REPO / Path(prd_doc.filename).stem
+ pathname.parent.mkdir(parents=True, exist_ok=True)
+ await mermaid_to_file(self.config.mermaid_engine, 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 not CONFIG.project_name:
+ async def _rename_workspace(self, prd):
+ if not self.project_name:
if isinstance(prd, (ActionOutput, ActionNode)):
ws_name = prd.instruct_content.model_dump()["Project Name"]
else:
diff --cc metagpt/actions/write_prd_an.py
index 715e8fc55,c65860822..4baa46b12
--- a/metagpt/actions/write_prd_an.py
+++ b/metagpt/actions/write_prd_an.py
@@@ -152,6 -216,33 +202,22 @@@ NODES =
ANYTHING_UNCLEAR,
]
+ REFINED_NODES = [
+ LANGUAGE,
+ PROGRAMMING_LANGUAGE,
+ REFINED_REQUIREMENTS,
+ PROJECT_NAME,
+ REFINED_PRODUCT_GOALS,
+ REFINED_USER_STORIES,
+ COMPETITIVE_ANALYSIS,
+ COMPETITIVE_QUADRANT_CHART,
+ REFINED_REQUIREMENT_ANALYSIS,
+ REFINED_REQUIREMENT_POOL,
+ UI_DESIGN_DRAFT,
+ ANYTHING_UNCLEAR,
+ ]
+
WRITE_PRD_NODE = ActionNode.from_children("WritePRD", NODES)
+ REFINED_PRD_NODE = ActionNode.from_children("RefinedPRD", REFINED_NODES)
WP_ISSUE_TYPE_NODE = ActionNode.from_children("WP_ISSUE_TYPE", [ISSUE_TYPE, REASON])
WP_IS_RELATIVE_NODE = ActionNode.from_children("WP_IS_RELATIVE", [IS_RELATIVE, REASON])
-
-
-def main():
- prompt = WRITE_PRD_NODE.compile(context="")
- logger.info(prompt)
- prompt = REFINED_PRD_NODE.compile(context="")
- logger.info(prompt)
-
-
-if __name__ == "__main__":
- main()
diff --cc metagpt/const.py
index 0ae425a47,b3acf2fe3..a1c650ce3
--- a/metagpt/const.py
+++ b/metagpt/const.py
@@@ -82,25 -87,28 +82,28 @@@ MESSAGE_ROUTE_TO_NONE = "<none>
REQUIREMENT_FILENAME = "requirement.txt"
BUGFIX_FILENAME = "bugfix.txt"
PACKAGE_REQUIREMENTS_FILENAME = "requirements.txt"
+ CODE_PLAN_AND_CHANGE_FILENAME = "code_plan_and_change.json"
DOCS_FILE_REPO = "docs"
-PRDS_FILE_REPO = "docs/prds"
+PRDS_FILE_REPO = "docs/prd"
SYSTEM_DESIGN_FILE_REPO = "docs/system_design"
-TASK_FILE_REPO = "docs/tasks"
+TASK_FILE_REPO = "docs/task"
+ CODE_PLAN_AND_CHANGE_FILE_REPO = "docs/code_plan_and_change"
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"
+TASK_PDF_FILE_REPO = "resources/api_spec_and_task"
+ CODE_PLAN_AND_CHANGE_PDF_FILE_REPO = "resources/code_plan_and_change"
TEST_CODES_FILE_REPO = "tests"
TEST_OUTPUTS_FILE_REPO = "test_outputs"
-CODE_SUMMARIES_FILE_REPO = "docs/code_summaries"
-CODE_SUMMARIES_PDF_FILE_REPO = "resources/code_summaries"
+CODE_SUMMARIES_FILE_REPO = "docs/code_summary"
+CODE_SUMMARIES_PDF_FILE_REPO = "resources/code_summary"
RESOURCES_FILE_REPO = "resources"
-SD_OUTPUT_FILE_REPO = "resources/SD_Output"
+SD_OUTPUT_FILE_REPO = "resources/sd_output"
GRAPH_REPO_FILE_REPO = "docs/graph_repo"
-CLASS_VIEW_FILE_REPO = "docs/class_views"
+CLASS_VIEW_FILE_REPO = "docs/class_view"
YAPI_URL = "http://yapi.deepwisdomai.com/"
diff --cc metagpt/roles/engineer.py
index c83a776c2,b1588f9ef..c30a0ebbb
--- a/metagpt/roles/engineer.py
+++ b/metagpt/roles/engineer.py
@@@ -26,8 -27,22 +27,16 @@@ from typing import Literal, Se
from metagpt.actions import Action, WriteCode, WriteCodeReview, WriteTasks
from metagpt.actions.fix_bug import FixBug
+ from metagpt.actions.project_management_an import REFINED_TASK_LIST, TASK_LIST
from metagpt.actions.summarize_code import SummarizeCode
- from metagpt.const import SYSTEM_DESIGN_FILE_REPO, TASK_FILE_REPO
+ from metagpt.actions.write_code_plan_and_change_an import WriteCodePlanAndChange
-from metagpt.config import CONFIG
+ from metagpt.const import (
+ CODE_PLAN_AND_CHANGE_FILE_REPO,
+ CODE_PLAN_AND_CHANGE_FILENAME,
- CODE_PLAN_AND_CHANGE_PDF_FILE_REPO,
- CODE_SUMMARIES_FILE_REPO,
- CODE_SUMMARIES_PDF_FILE_REPO,
- DOCS_FILE_REPO,
- PRDS_FILE_REPO,
+ REQUIREMENT_FILENAME,
+ SYSTEM_DESIGN_FILE_REPO,
+ TASK_FILE_REPO,
+ )
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import (
@@@ -79,8 -95,8 +89,8 @@@ class Engineer(Role)
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
- self._init_actions([WriteCode])
+ self.set_actions([WriteCode])
- self._watch([WriteTasks, SummarizeCode, WriteCode, WriteCodeReview, FixBug])
+ self._watch([WriteTasks, SummarizeCode, WriteCode, WriteCodeReview, FixBug, WriteCodePlanAndChange])
self.code_todos = []
self.summarize_todos = []
self.next_todo_action = any_to_name(WriteCode)
@@@ -88,10 -104,11 +98,10 @@@
@staticmethod
def _parse_tasks(task_msg: Document) -> list[str]:
m = json.loads(task_msg.content)
- return m.get("Task list")
+ return m.get(TASK_LIST.key) or m.get(REFINED_TASK_LIST.key)
- async def _act_sp_with_cr(self, review=False) -> Set[str]:
+ async def _act_sp_with_cr(self, review=False, mode: Literal["normal", "incremental"] = "normal") -> Set[str]:
changed_files = set()
- src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)
for todo in self.code_todos:
"""
# Select essential information from the historical data to reduce the length of the prompt (summarized from human experience):
@@@ -103,12 -120,16 +113,16 @@@
coding_context = await todo.run()
# Code review
if review:
- action = WriteCodeReview(context=coding_context, llm=self.llm)
- self._init_action_system_message(action)
+ action = WriteCodeReview(i_context=coding_context, context=self.context, llm=self.llm)
+ self._init_action(action)
coding_context = await action.run()
+
+ dependencies = {coding_context.design_doc.root_relative_path, coding_context.task_doc.root_relative_path}
+ if mode == "incremental":
+ dependencies.add(os.path.join(CODE_PLAN_AND_CHANGE_FILE_REPO, CODE_PLAN_AND_CHANGE_FILENAME))
- await src_file_repo.save(
- coding_context.filename,
+ await self.project_repo.srcs.save(
+ filename=coding_context.filename,
- dependencies={coding_context.design_doc.root_relative_path, coding_context.task_doc.root_relative_path},
+ dependencies=dependencies,
content=coding_context.code_doc.content,
)
msg = Message(
@@@ -187,6 -213,39 +204,36 @@@
content=json.dumps(tasks), role=self.profile, cause_by=SummarizeCode, send_to=self, sent_from=self
)
+ async def _act_code_plan_and_change(self):
+ """Write code plan and change that guides subsequent WriteCode and WriteCodeReview"""
+ logger.info("Writing code plan and change..")
- code_plan_and_change_file_repo = CONFIG.git_repo.new_file_repository(CODE_PLAN_AND_CHANGE_FILE_REPO)
- code_plan_and_change_pdf_file_repo = CONFIG.git_repo.new_file_repository(CODE_PLAN_AND_CHANGE_PDF_FILE_REPO)
-
+ node = await self.rc.todo.run()
+ code_plan_and_change = node.instruct_content.model_dump_json()
+ dependencies = {
- self.rc.todo.context.requirement_doc.filename,
- self.rc.todo.context.prd_docs[0].filename,
- self.rc.todo.context.design_docs[0].filename,
- self.rc.todo.context.tasks_docs[0].filename,
++ self.rc.todo.i_context.requirement_doc.filename,
++ self.rc.todo.i_context.prd_docs[0].filename,
++ self.rc.todo.i_context.design_docs[0].filename,
++ self.rc.todo.i_context.tasks_docs[0].filename,
+ }
+
+ code_plan_and_change_filename = os.path.join(CODE_PLAN_AND_CHANGE_FILE_REPO, CODE_PLAN_AND_CHANGE_FILENAME)
- await code_plan_and_change_file_repo.save(
++ await self.project_repo.resources.code_plan_and_change.save(
+ filename=code_plan_and_change_filename, content=code_plan_and_change, dependencies=dependencies
+ )
- await code_plan_and_change_pdf_file_repo.save(
++ await self.project_repo.docs.code_plan_and_change.save(
+ filename=Path(code_plan_and_change_filename).with_suffix(".md").name,
+ content=node.content,
+ dependencies=dependencies,
+ )
+
+ return Message(
+ content=code_plan_and_change,
+ role=self.profile,
+ cause_by=WriteCodePlanAndChange,
+ send_to=self,
+ sent_from=self,
+ )
+
async def _is_pass(self, summary) -> (str, str):
rsp = await self.llm.aask(msg=IS_PASS_PROMPT.format(context=summary), stream=False)
logger.info(rsp)
@@@ -195,13 -254,18 +242,18 @@@
return False, rsp
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.src_workspace:
+ self.src_workspace = self.git_repo.workdir / self.git_repo.workdir.name
- write_code_filters = any_to_str_set([WriteTasks, SummarizeCode, FixBug])
+ write_plan_and_change_filters = any_to_str_set([WriteTasks])
+ write_code_filters = any_to_str_set([WriteTasks, WriteCodePlanAndChange, SummarizeCode, FixBug])
summarize_code_filters = any_to_str_set([WriteCode, WriteCodeReview])
if not self.rc.news:
return None
msg = self.rc.news[0]
- if CONFIG.inc and msg.cause_by in write_plan_and_change_filters:
++ if self.config.inc and msg.cause_by in write_plan_and_change_filters:
+ logger.debug(f"TODO WriteCodePlanAndChange:{msg.model_dump_json()}")
+ await self._new_code_plan_and_change_action()
+ return self.rc.todo
if msg.cause_by in write_code_filters:
logger.debug(f"TODO WriteCode:{msg.model_dump_json()}")
await self._new_code_actions(bug_fix=msg.cause_by == any_to_str(FixBug))
@@@ -292,10 -367,25 +344,25 @@@
summarizations[ctx].append(filename)
for ctx, filenames in summarizations.items():
ctx.codes_filenames = filenames
- self.summarize_todos.append(SummarizeCode(context=ctx, llm=self.llm))
+ self.summarize_todos.append(SummarizeCode(i_context=ctx, llm=self.llm))
if self.summarize_todos:
- self.rc.todo = self.summarize_todos[0]
+ self.set_todo(self.summarize_todos[0])
+ async def _new_code_plan_and_change_action(self):
+ """Create a WriteCodePlanAndChange action for subsequent to-do actions."""
- requirement_doc = await FileRepository.get_file(filename=REQUIREMENT_FILENAME, relative_path=DOCS_FILE_REPO)
- prd_docs = await FileRepository.get_all_files(relative_path=PRDS_FILE_REPO)
- design_docs = await FileRepository.get_all_files(relative_path=SYSTEM_DESIGN_FILE_REPO)
- tasks_docs = await FileRepository.get_all_files(relative_path=TASK_FILE_REPO)
++ requirement_doc = await self.project_repo.docs.requirement.get(REQUIREMENT_FILENAME)
++ prd_docs = await self.project_repo.docs.prd.get_all()
++ design_docs = await self.project_repo.docs.system_design.get_all()
++ task_docs = await self.project_repo.docs.task.get_all()
+
+ code_plan_and_change_context = CodePlanAndChangeContext(
+ requirement_doc=requirement_doc,
+ prd_docs=prd_docs,
+ design_docs=design_docs,
- tasks_docs=tasks_docs,
++ task_docs=task_docs,
+ )
- self.rc.todo = WriteCodePlanAndChange(context=code_plan_and_change_context, llm=self.llm)
++ self.rc.todo = WriteCodePlanAndChange(i_context=code_plan_and_change_context, llm=self.llm)
+
@property
def todo(self) -> str:
"""AgentStore uses this attribute to display to the user what actions the current role should take."""
diff --cc metagpt/schema.py
index 22bb359b6,ebfbe9b80..88e1712fc
--- a/metagpt/schema.py
+++ b/metagpt/schema.py
@@@ -470,6 -453,14 +470,14 @@@ class BugFixContext(BaseContext)
filename: str = ""
+ class CodePlanAndChangeContext(BaseContext):
+ filename: str = ""
+ requirement_doc: Document
+ prd_docs: List[Document]
+ design_docs: List[Document]
- tasks_docs: List[Document]
++ task_docs: List[Document]
+
+
# mermaid class view
class ClassMeta(BaseModel):
name: str = ""
diff --cc metagpt/utils/project_repo.py
index 77ac4f897,000000000..72bca7ea0
mode 100644,000000..100644
--- a/metagpt/utils/project_repo.py
+++ b/metagpt/utils/project_repo.py
@@@ -1,133 -1,0 +1,139 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/1/8
+@Author : mashenquan
+@File : project_repo.py
+@Desc : Wrapper for GitRepository and FileRepository of project.
+ Implementation of Chapter 4.6 of https://deepwisdom.feishu.cn/wiki/CUK4wImd7id9WlkQBNscIe9cnqh
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+from metagpt.const import (
+ CLASS_VIEW_FILE_REPO,
++ CODE_PLAN_AND_CHANGE_FILE_REPO,
++ CODE_PLAN_AND_CHANGE_PDF_FILE_REPO,
+ CODE_SUMMARIES_FILE_REPO,
+ CODE_SUMMARIES_PDF_FILE_REPO,
+ COMPETITIVE_ANALYSIS_FILE_REPO,
+ DATA_API_DESIGN_FILE_REPO,
+ DOCS_FILE_REPO,
+ GRAPH_REPO_FILE_REPO,
+ PRD_PDF_FILE_REPO,
+ PRDS_FILE_REPO,
+ REQUIREMENT_FILENAME,
+ RESOURCES_FILE_REPO,
+ SD_OUTPUT_FILE_REPO,
+ SEQ_FLOW_FILE_REPO,
+ SYSTEM_DESIGN_FILE_REPO,
+ SYSTEM_DESIGN_PDF_FILE_REPO,
+ TASK_FILE_REPO,
+ TASK_PDF_FILE_REPO,
+ TEST_CODES_FILE_REPO,
+ TEST_OUTPUTS_FILE_REPO,
+)
+from metagpt.utils.file_repository import FileRepository
+from metagpt.utils.git_repository import GitRepository
+
+
+class DocFileRepositories(FileRepository):
+ prd: FileRepository
+ system_design: FileRepository
+ task: FileRepository
+ code_summary: FileRepository
+ graph_repo: FileRepository
+ class_view: FileRepository
++ code_plan_and_change: FileRepository
+
+ def __init__(self, git_repo):
+ super().__init__(git_repo=git_repo, relative_path=DOCS_FILE_REPO)
+
+ self.prd = git_repo.new_file_repository(relative_path=PRDS_FILE_REPO)
+ self.system_design = git_repo.new_file_repository(relative_path=SYSTEM_DESIGN_FILE_REPO)
+ self.task = git_repo.new_file_repository(relative_path=TASK_FILE_REPO)
+ self.code_summary = git_repo.new_file_repository(relative_path=CODE_SUMMARIES_FILE_REPO)
+ self.graph_repo = git_repo.new_file_repository(relative_path=GRAPH_REPO_FILE_REPO)
+ self.class_view = git_repo.new_file_repository(relative_path=CLASS_VIEW_FILE_REPO)
++ self.code_plan_and_change = git_repo.new_file_repository(relative_path=CODE_PLAN_AND_CHANGE_FILE_REPO)
+
+
+class ResourceFileRepositories(FileRepository):
+ competitive_analysis: FileRepository
+ data_api_design: FileRepository
+ seq_flow: FileRepository
+ system_design: FileRepository
+ prd: FileRepository
+ api_spec_and_task: FileRepository
+ code_summary: FileRepository
+ sd_output: FileRepository
++ code_plan_and_change: FileRepository
+
+ def __init__(self, git_repo):
+ super().__init__(git_repo=git_repo, relative_path=RESOURCES_FILE_REPO)
+
+ self.competitive_analysis = git_repo.new_file_repository(relative_path=COMPETITIVE_ANALYSIS_FILE_REPO)
+ self.data_api_design = git_repo.new_file_repository(relative_path=DATA_API_DESIGN_FILE_REPO)
+ self.seq_flow = git_repo.new_file_repository(relative_path=SEQ_FLOW_FILE_REPO)
+ self.system_design = git_repo.new_file_repository(relative_path=SYSTEM_DESIGN_PDF_FILE_REPO)
+ self.prd = git_repo.new_file_repository(relative_path=PRD_PDF_FILE_REPO)
+ self.api_spec_and_task = git_repo.new_file_repository(relative_path=TASK_PDF_FILE_REPO)
+ self.code_summary = git_repo.new_file_repository(relative_path=CODE_SUMMARIES_PDF_FILE_REPO)
+ self.sd_output = git_repo.new_file_repository(relative_path=SD_OUTPUT_FILE_REPO)
++ self.code_plan_and_change = git_repo.new_file_repository(relative_path=CODE_PLAN_AND_CHANGE_PDF_FILE_REPO)
+
+
+class ProjectRepo(FileRepository):
+ def __init__(self, root: str | Path | GitRepository):
+ if isinstance(root, str) or isinstance(root, Path):
+ git_repo_ = GitRepository(local_path=Path(root))
+ elif isinstance(root, GitRepository):
+ git_repo_ = root
+ else:
+ raise ValueError("Invalid root")
+ super().__init__(git_repo=git_repo_, relative_path=Path("."))
+ self._git_repo = git_repo_
+ self.docs = DocFileRepositories(self._git_repo)
+ self.resources = ResourceFileRepositories(self._git_repo)
+ self.tests = self._git_repo.new_file_repository(relative_path=TEST_CODES_FILE_REPO)
+ self.test_outputs = self._git_repo.new_file_repository(relative_path=TEST_OUTPUTS_FILE_REPO)
+ self._srcs_path = None
+
+ @property
+ async def requirement(self):
+ return await self.docs.get(filename=REQUIREMENT_FILENAME)
+
+ @property
+ def git_repo(self) -> GitRepository:
+ return self._git_repo
+
+ @property
+ def workdir(self) -> Path:
+ return Path(self.git_repo.workdir)
+
+ @property
+ def srcs(self) -> FileRepository:
+ if not self._srcs_path:
+ raise ValueError("Call with_srcs first.")
+ return self._git_repo.new_file_repository(self._srcs_path)
+
+ def code_files_exists(self) -> bool:
+ git_workdir = self.git_repo.workdir
+ src_workdir = git_workdir / git_workdir.name
+ if not src_workdir.exists():
+ return False
+ code_files = self.with_src_path(path=git_workdir / git_workdir.name).srcs.all_files
+ if not code_files:
+ return False
+
+ def with_src_path(self, path: str | Path) -> ProjectRepo:
+ try:
+ self._srcs_path = Path(path).relative_to(self.workdir)
+ except ValueError:
+ self._srcs_path = Path(path)
+ return self
+
+ @property
+ def src_relative_path(self) -> Path | None:
+ return self._srcs_path
diff --cc tests/metagpt/actions/test_write_prd_an.py
index 000000000,3bfb4d3be..e8e347e5c
mode 000000,100644..100644
--- a/tests/metagpt/actions/test_write_prd_an.py
+++ b/tests/metagpt/actions/test_write_prd_an.py
@@@ -1,0 -1,48 +1,49 @@@
+ #!/usr/bin/env python
+ # -*- coding: utf-8 -*-
+ """
+ @Time : 2024/01/03
+ @Author : mannaandpoem
+ @File : test_write_prd_an.py
+ """
+ import pytest
+ from openai._models import BaseModel
+
+ from metagpt.actions.action_node import ActionNode
-from metagpt.actions.write_prd_an import REFINED_PRD_NODE, REFINED_TEMPLATE
++from metagpt.actions.write_prd import NEW_REQ_TEMPLATE
++from metagpt.actions.write_prd_an import REFINED_PRD_NODE
+ from metagpt.llm import LLM
+ from tests.data.incremental_dev_project.mock import (
+ NEW_REQUIREMENT_SAMPLE,
+ PRD_SAMPLE,
+ REFINED_PRD_JSON,
+ )
+
+
+ @pytest.fixture()
+ def llm():
+ return LLM()
+
+
+ def mock_refined_prd_json():
+ return REFINED_PRD_JSON
+
+
+ @pytest.mark.asyncio
+ async def test_write_prd_an(mocker):
+ root = ActionNode.from_children("RefinedPRD", [ActionNode(key="", expected_type=str, instruction="", example="")])
+ root.instruct_content = BaseModel()
+ root.instruct_content.model_dump = mock_refined_prd_json
+ mocker.patch("metagpt.actions.write_prd_an.REFINED_PRD_NODE.fill", return_value=root)
+
- prompt = REFINED_TEMPLATE.format(
++ prompt = NEW_REQ_TEMPLATE.format(
+ requirements=NEW_REQUIREMENT_SAMPLE,
+ old_prd=PRD_SAMPLE,
+ project_name="",
+ )
+ node = await REFINED_PRD_NODE.fill(prompt, llm)
+
+ assert "Refined Requirements" in node.instruct_content.model_dump()
+ assert "Refined Product Goals" in node.instruct_content.model_dump()
+ assert "Refined User Stories" in node.instruct_content.model_dump()
+ assert "Refined Requirement Analysis" in node.instruct_content.model_dump()
+ assert "Refined Requirement Pool" in node.instruct_content.model_dump()