Skip to content

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

fixbug: rfc243

莘权 马e1b3bd3869cf
diff --cc examples/mgx_write_project_framework.py
index dca684478,000000000..359b90080
mode 100644,000000..100644
--- a/examples/mgx_write_project_framework.py
+++ b/examples/mgx_write_project_framework.py
@@@ -1,143 -1,0 +1,135 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/6/13
+@Author : mashenquan
+@File : write_project_framework.py
+@Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb
+"""
+import asyncio
+import json
+import uuid
+from pathlib import Path
+from typing import Dict, List
+
+import typer
+from pydantic import BaseModel
+
+from metagpt.config2 import Config
+from metagpt.const import DEFAULT_WORKSPACE_ROOT
+from metagpt.context import Context
+from metagpt.environment import Environment
++from metagpt.environment.mgx.mgx_env import MGXEnv
+from metagpt.logs import logger
+from metagpt.roles import Architect
+from metagpt.roles.di.team_leader import TeamLeader
+from metagpt.schema import AIMessage, UserMessage
- from metagpt.utils.common import any_to_str, aread, to_markdown_code_block
++from metagpt.utils.common import aread, to_markdown_code_block
+
+app = typer.Typer(add_completion=False)
+
+
+class EnvBuilder(BaseModel):
+ context: Context
+ user_requirements: List[str]
+ actors: Dict[str, str]
+ acknowledge: str
+ technical_constraint: str
+ output_dir: Path
+
+ def build(self) -> Environment:
- env = Environment(context=self.context)
++ env = MGXEnv(context=self.context)
+ team_leader = TeamLeader()
+ architect = Architect()
- architect.tools.extend(
- [
- "CompressExternalInterfaces",
- "DetectInteraction",
- "EvaluateTRD",
- "WriteTRD",
- "WriteFramework",
- "EvaluateFramework",
- ]
- )
+
+ # Prepare context
+ use_case_actors = "".join([f"- {v}: {k}\n" for k, v in self.actors.items()])
+ msg = """
+The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram.
+## Actor, System, External System
+{use_case_actors}
+ """
+ architect.rc.memory.add(AIMessage(content=msg.format(use_case_actors=use_case_actors)))
+
+ # Prepare acknowledge
+ msg = """
+The descriptions of the interfaces used in TRD can be found in the "Acknowledge" section.
+## Acknowledge
+{acknowledge}
+ """
+ architect.rc.memory.add(AIMessage(content=msg.format(acknowledge=to_markdown_code_block(val=self.acknowledge))))
+
+ # Prepare technical requirements
+ msg = """
+"Additional Technical Requirements" specifies the additional technical requirements that the generated software framework code must meet.
+## Additional Technical Requirements
+{technical_requirements}
+"""
+ architect.rc.memory.add(AIMessage(content=msg.format(technical_requirements=self.technical_constraint)))
+
+ env.add_roles([team_leader, architect])
+ return env
+
+
+async def develop(
+ context: Context,
+ user_requirement_filename: str,
+ actors_filename: str,
+ acknowledge_filename: str,
+ constraint_filename: str,
+ output_dir: str,
+):
+ output_dir = Path(output_dir) if output_dir else DEFAULT_WORKSPACE_ROOT / uuid.uuid4().hex
+
+ v = await aread(filename=user_requirement_filename)
+ user_requirements = json.loads(v)
+ v = await aread(filename=actors_filename)
+ actors = json.loads(v)
+ acknowledge = await aread(filename=acknowledge_filename)
+ technical_constraint = await aread(filename=constraint_filename)
+ env_builder = EnvBuilder(
+ context=context,
+ user_requirements=user_requirements,
+ actors=actors,
+ acknowledge=acknowledge,
+ technical_constraint=technical_constraint,
+ output_dir=output_dir,
+ )
+ env = env_builder.build()
+ msg = """
+根据"User Requirements"中的用户需求,写TRD
+## User Requirements
+{user_requirements}
+ """
+ env.publish_message(
- UserMessage(content=msg.format(user_requirements="\n".join(user_requirements)), send_to=any_to_str(TeamLeader))
++ UserMessage(content=msg.format(user_requirements="\n".join(user_requirements)), send_to="Bob"),
++ user_defined_recipient="Bob",
+ )
+
+ while not env.is_idle:
+ await env.run()
+
+
+def startup(
+ user_requirement_filename: str = typer.Argument(..., help="The filename of the user requirements."),
+ actors_filename: str = typer.Argument(..., help="The filename of UML use case actors description."),
+ acknowledge_filename: str = typer.Argument(..., help="External interfaces declarations."),
+ llm_config: str = typer.Option(default="", help="Low-cost LLM config"),
+ constraint_filename: str = typer.Option(default="", help="What technical dependency constraints are."),
+ output_dir: str = typer.Option(default="", help="Output directory."),
+):
+ if llm_config and Path(llm_config).exists():
+ config = Config.from_yaml_file(Path(llm_config))
+ else:
+ logger.info("GPT 4 turbo is recommended")
+ config = Config.default()
+ ctx = Context(config=config)
+
+ asyncio.run(
+ develop(ctx, user_requirement_filename, actors_filename, acknowledge_filename, constraint_filename, output_dir)
+ )
+
+
+if __name__ == "__main__":
+ app()
diff --cc examples/write_project_framework.py
index 4e8a03789,000000000..bf713bbce
mode 100644,000000..100644
--- a/examples/write_project_framework.py
+++ b/examples/write_project_framework.py
@@@ -1,192 -1,0 +1,194 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/6/13
+@Author : mashenquan
+@File : write_project_framework.py
+@Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb
+"""
+import asyncio
+import json
+import uuid
+from pathlib import Path
+from typing import Dict, List
+
+import typer
+
+from metagpt.actions.requirement_analysis.framework import (
+ EvaluateFramework,
+ WriteFramework,
+ save_framework,
+)
+from metagpt.actions.requirement_analysis.trd import (
+ CompressExternalInterfaces,
+ DetectInteraction,
+ EvaluateTRD,
+ WriteTRD,
+)
+from metagpt.config2 import Config
+from metagpt.const import DEFAULT_WORKSPACE_ROOT
+from metagpt.context import Context
+from metagpt.logs import logger
+from metagpt.utils.common import aread
+
+app = typer.Typer(add_completion=False)
+
+
+async def _write_trd(
+ context: Context, actors: Dict[str, str], user_requirements: List[str], available_external_interfaces: str
+) -> (str, str):
+ detect_interaction = DetectInteraction(context=context)
+ write_trd = WriteTRD(context=context)
+ evaluate_trd = EvaluateTRD(context=context)
+ use_case_actors = "".join([f"- {v}: {k}\n" for k, v in actors.items()])
+ legacy_user_requirements = []
+ legacy_user_requirements_interaction_events = []
+ legacy_user_requirements_trd = ""
+ for ix, r in enumerate(user_requirements):
+ is_pass = False
+ evaluation_conclusion = ""
+ interaction_events = ""
+ trd = ""
- while not is_pass:
++ while not is_pass and (context.cost_manager.total_cost < context.cost_manager.max_budget):
+ interaction_events = await detect_interaction.run(
+ user_requirements=r,
+ use_case_actors=use_case_actors,
+ legacy_interaction_events=interaction_events,
+ evaluation_conclusion=evaluation_conclusion,
+ )
+ if ix == 0:
+ trd = await write_trd.run(
+ user_requirements=r,
+ use_case_actors=use_case_actors,
+ available_external_interfaces=available_external_interfaces,
+ evaluation_conclusion=evaluation_conclusion,
+ interaction_events=interaction_events,
+ previous_version_trd=trd,
+ )
+ else:
+ trd = await write_trd.run(
+ user_requirements=r,
+ use_case_actors=use_case_actors,
+ available_external_interfaces=available_external_interfaces,
+ evaluation_conclusion=evaluation_conclusion,
+ interaction_events=interaction_events,
+ previous_version_trd=trd,
+ legacy_user_requirements="\n".join(legacy_user_requirements),
+ legacy_user_requirements_trd=legacy_user_requirements_trd,
+ legacy_user_requirements_interaction_events="\n".join(legacy_user_requirements_interaction_events),
+ )
+ evaluation = await evaluate_trd.run(
+ user_requirements=r,
+ use_case_actors=use_case_actors,
+ trd=trd,
+ interaction_events=interaction_events,
+ legacy_user_requirements_interaction_events="\n".join(legacy_user_requirements_interaction_events),
+ )
+ is_pass = evaluation.is_pass
+ evaluation_conclusion = evaluation.conclusion
+ legacy_user_requirements.append(r)
+ legacy_user_requirements_interaction_events.append(interaction_events)
+ legacy_user_requirements_trd = trd
+
+ return use_case_actors, legacy_user_requirements_trd
+
+
+async def _write_framework(context: Context, use_case_actors: str, trd: str, acknowledge: str, constraint: str) -> str:
+ write_framework = WriteFramework(context=context)
+ evaluate_framework = EvaluateFramework(context=context)
+ is_pass = False
+ framework = ""
+ evaluation_conclusion = ""
- while not is_pass:
++ while not is_pass and (context.cost_manager.total_cost < context.cost_manager.max_budget):
+ try:
+ framework = await write_framework.run(
+ use_case_actors=use_case_actors,
+ trd=trd,
+ acknowledge=acknowledge,
+ legacy_output=framework,
+ evaluation_conclusion=evaluation_conclusion,
+ additional_technical_requirements=constraint,
+ )
+ except Exception as e:
+ logger.info(f"{e}")
+ break
+ evaluation = await evaluate_framework.run(
+ use_case_actors=use_case_actors,
+ trd=trd,
+ acknowledge=acknowledge,
+ legacy_output=framework,
+ additional_technical_requirements=constraint,
+ )
+ is_pass = evaluation.is_pass
+ evaluation_conclusion = evaluation.conclusion
+ return framework
+
+
+async def develop(
+ context: Context,
+ user_requirement_filename: str,
+ actors_filename: str,
+ acknowledge_filename: str,
+ constraint_filename: str,
+ output_dir: str,
+):
+ output_dir = Path(output_dir) if output_dir else DEFAULT_WORKSPACE_ROOT / uuid.uuid4().hex
+
+ v = await aread(filename=user_requirement_filename)
+ user_requirements = json.loads(v)
+ v = await aread(filename=actors_filename)
+ actors = json.loads(v)
+ acknowledge = await aread(filename=acknowledge_filename)
+ technical_constraint = await aread(filename=constraint_filename)
+
+ # Compress acknowledge
+ compress_acknowledge = CompressExternalInterfaces(context=context)
+ available_external_interfaces = await compress_acknowledge.run(acknowledge=acknowledge)
+
+ # Write TRD
+ use_case_actors, trd = await _write_trd(
+ context=context,
+ actors=actors,
+ user_requirements=user_requirements,
+ available_external_interfaces=available_external_interfaces,
+ )
+
+ # Write framework
+ framework = await _write_framework(
+ context=context,
+ use_case_actors=use_case_actors,
+ trd=trd,
+ acknowledge=acknowledge,
+ constraint=technical_constraint,
+ )
+
+ # Save
+ file_list = await save_framework(dir_data=framework, output_dir=output_dir)
+ logger.info(f"Output:\n{file_list}")
+
+
+def startup(
+ user_requirement_filename: str = typer.Argument(..., help="The filename of the user requirements."),
+ actors_filename: str = typer.Argument(..., help="The filename of UML use case actors description."),
+ acknowledge_filename: str = typer.Argument(..., help="External interfaces declarations."),
+ llm_config: str = typer.Option(default="", help="Low-cost LLM config"),
+ constraint_filename: str = typer.Option(default="", help="What technical dependency constraints are."),
+ output_dir: str = typer.Option(default="", help="Output directory."),
++ investment: float = typer.Option(default=15.0, help="Dollar amount to invest in the AI company."),
+):
+ if llm_config and Path(llm_config).exists():
+ config = Config.from_yaml_file(Path(llm_config))
+ else:
+ logger.info("GPT 4 turbo is recommended")
+ config = Config.default()
+ ctx = Context(config=config)
++ ctx.cost_manager.max_budget = investment
+
+ asyncio.run(
+ develop(ctx, user_requirement_filename, actors_filename, acknowledge_filename, constraint_filename, output_dir)
+ )
+
+
+if __name__ == "__main__":
+ app()
diff --cc metagpt/actions/requirement_analysis/framework/__init__.py
index 0f6022444,000000000..c59884746
mode 100644,000000..100644
--- a/metagpt/actions/requirement_analysis/framework/__init__.py
+++ b/metagpt/actions/requirement_analysis/framework/__init__.py
@@@ -1,47 -1,0 +1,49 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/6/13
+@Author : mashenquan
+@File : __init__.py
+@Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb
+"""
+import json
+import uuid
+from pathlib import Path
+from typing import Optional, Union, List
+
+from pydantic import BaseModel
+
+from metagpt.actions.requirement_analysis.framework.evaluate_framework import EvaluateFramework
+from metagpt.actions.requirement_analysis.framework.write_framework import WriteFramework
+from metagpt.const import DEFAULT_WORKSPACE_ROOT
+from metagpt.tools.tool_registry import register_tool
- from metagpt.utils.common import CodeParser, awrite
++from metagpt.utils.common import awrite
+
+
+@register_tool(tags=["software framework"])
+async def save_framework(dir_data: str, output_dir: Optional[Union[str, Path]] = None) -> List[str]:
+ output_dir = Path(output_dir) if output_dir else DEFAULT_WORKSPACE_ROOT / uuid.uuid4().hex
+ output_dir.mkdir(parents=True, exist_ok=True)
+
- json_data = CodeParser.parse_code(text=dir_data, lang="json")
++ json_data = dir_data.removeprefix("```json").removesuffix("```")
+ items = json.loads(json_data)
+
+ class Data(BaseModel):
+ path: str
+ filename: str
+ content: str
+
+ files = []
+ for i in items:
+ v = Data.model_validate(i)
++ if v.path and v.path[0] == "/":
++ v.path = "." + v.path
+ pathname = output_dir / v.path
+ pathname.mkdir(parents=True, exist_ok=True)
+ pathname = pathname / v.filename
+ await awrite(filename=pathname, data=v.content)
+ files.append(str(pathname))
+ return files
+
+
+__all__ = [WriteFramework, EvaluateFramework]
diff --cc metagpt/actions/requirement_analysis/framework/evaluate_framework.py
index 10b2c65b9,000000000..851b3af9f
mode 100644,000000..100644
--- a/metagpt/actions/requirement_analysis/framework/evaluate_framework.py
+++ b/metagpt/actions/requirement_analysis/framework/evaluate_framework.py
@@@ -1,62 -1,0 +1,102 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/6/13
+@Author : mashenquan
+@File : evaluate_framework.py
+@Desc : The implementation of Chapter 2.1.8 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb
+"""
+
+from metagpt.actions.requirement_analysis import EvaluateAction, EvaluationData
++from metagpt.tools.tool_registry import register_tool
+from metagpt.utils.common import to_markdown_code_block
+
+
++@register_tool(include_functions=["run"])
+class EvaluateFramework(EvaluateAction):
++ """WriteFramework deal with the following situations:
++ 1. Given a TRD and the software framework based on the TRD, evaluate the quality of the software framework.
++ """
++
+ async def run(
+ self,
+ *,
+ use_case_actors: str,
+ trd: str,
+ acknowledge: str,
+ legacy_output: str,
+ additional_technical_requirements: str,
+ ) -> EvaluationData:
++ """
++ Run the evaluation of the software framework based on the provided TRD and related parameters.
++
++ Args:
++ use_case_actors (str): A description of the actors involved in the use case.
++ trd (str): The Technical Requirements Document (TRD) that outlines the requirements for the software framework.
++ acknowledge (str): External acknowledgments or acknowledgments information related to the framework.
++ legacy_output (str): The previous versions of software framework returned by `WriteFramework`.
++ additional_technical_requirements (str): Additional technical requirements that need to be considered during evaluation.
++
++ Returns:
++ EvaluationData: An object containing the results of the evaluation.
++
++ Example:
++ >>> evaluate_framework = EvaluateFramework()
++ >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;"
++ >>> trd = "## TRD\\n..."
++ >>> acknowledge = "## Interfaces\\n..."
++ >>> framework = '{"path":"balabala", "filename":"...", ...'
++ >>> constraint = "Using Java language, ..."
++ >>> evaluation = await evaluate_framework.run(
++ >>> use_case_actors=use_case_actors,
++ >>> trd=trd,
++ >>> acknowledge=acknowledge,
++ >>> legacy_output=framework,
++ >>> additional_technical_requirements=constraint,
++ >>> )
++ >>> is_pass = evaluation.is_pass
++ >>> print(is_pass)
++ True
++ >>> evaluation_conclusion = evaluation.conclusion
++ >>> print(evaluation_conclusion)
++ Balabala...
++ """
+ prompt = PROMPT.format(
+ use_case_actors=use_case_actors,
+ trd=to_markdown_code_block(val=trd),
+ acknowledge=to_markdown_code_block(val=acknowledge),
+ legacy_output=to_markdown_code_block(val=legacy_output),
+ additional_technical_requirements=to_markdown_code_block(val=additional_technical_requirements),
+ )
+ return await self._vote(prompt)
+
+
+PROMPT = """
+## Actor, System, External System
+{use_case_actors}
+
+## Legacy TRD
+{trd}
+
+## Acknowledge
+{acknowledge}
+
+## Legacy Outputs
+{legacy_output}
+
+## Additional Technical Requirements
+{additional_technical_requirements}
+
+---
+You are a tool that evaluates the quality of framework code based on the TRD content;
+You need to refer to the content of the "Legacy TRD" section to check for any errors or omissions in the framework code found in "Legacy Outputs";
+The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram;
+Information missing from the "Legacy TRD" can be found in the "Acknowledge" section;
+Parts not mentioned in the "Legacy TRD" will be handled by other TRDs, therefore, processes not present in the "Legacy TRD" are considered ready;
+"Additional Technical Requirements" specifies the additional technical requirements that the generated software framework code must meet;
+Return a markdown JSON object with:
+- a "is_pass" key containing a true boolean value if there is not any issue in the "Legacy Outputs";
+- an "issues" key containing a string list of natural text about the issues found in the "Legacy Outputs" if any, each issue found must provide a detailed description and include reasons;
+- a "conclusion" key containing the evaluation conclusion;
+- a "misalignment" key containing the judgement detail of the natural text string list about the misalignment with "Legacy TRD";
+"""
diff --cc metagpt/actions/requirement_analysis/framework/write_framework.py
index 5101a4d5e,000000000..b2e3f2d67
mode 100644,000000..100644
--- a/metagpt/actions/requirement_analysis/framework/write_framework.py
+++ b/metagpt/actions/requirement_analysis/framework/write_framework.py
@@@ -1,91 -1,0 +1,136 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/6/13
+@Author : mashenquan
+@File : write_framework.py
+@Desc : The implementation of Chapter 2.1.8 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb
+"""
+import json
+
+from tenacity import retry, stop_after_attempt, wait_random_exponential
+
+from metagpt.actions import Action
+from metagpt.logs import logger
- from metagpt.utils.common import CodeParser, general_after_log, to_markdown_code_block
++from metagpt.tools.tool_registry import register_tool
++from metagpt.utils.common import general_after_log, to_markdown_code_block
+
+
++@register_tool(include_functions=["run"])
+class WriteFramework(Action):
++ """WriteFramework deal with the following situations:
++ 1. Given a TRD, write out the software framework.
++ """
++
+ async def run(
+ self,
+ *,
+ use_case_actors: str,
+ trd: str,
+ acknowledge: str,
+ legacy_output: str,
+ evaluation_conclusion: str,
+ additional_technical_requirements: str,
+ ) -> str:
++ """
++ Run the action to generate a software framework based on the provided TRD and related information.
++
++ Args:
++ use_case_actors (str): Description of the use case actors involved.
++ trd (str): Technical Requirements Document detailing the requirements.
++ acknowledge (str): External acknowledgements or acknowledgements required.
++ legacy_output (str): Previous version of the software framework returned by `WriteFramework.run`.
++ evaluation_conclusion (str): Conclusion from the evaluation of the requirements.
++ additional_technical_requirements (str): Any additional technical requirements.
++
++ Returns:
++ str: The generated software framework as a string.
++
++ Example:
++ >>> write_framework = WriteFramework()
++ >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;"
++ >>> trd = "## TRD\\n..."
++ >>> acknowledge = "## Interfaces\\n..."
++ >>> legacy_output = '{"path":"balabala", "filename":"...", ...'
++ >>> evaluation_conclusion = "Balabala..."
++ >>> constraint = "Using Java language, ..."
++ >>> framework = await write_framework.run(
++ >>> use_case_actors=use_case_actors,
++ >>> trd=trd,
++ >>> acknowledge=acknowledge,
++ >>> legacy_output=framework,
++ >>> evaluation_conclusion=evaluation_conclusion,
++ >>> additional_technical_requirements=constraint,
++ >>> )
++ >>> print(framework)
++ {"path":"balabala", "filename":"...", ...
++
++ """
+ prompt = PROMPT.format(
+ use_case_actors=use_case_actors,
+ trd=to_markdown_code_block(val=trd),
+ acknowledge=to_markdown_code_block(val=acknowledge),
+ legacy_output=to_markdown_code_block(val=legacy_output),
+ evaluation_conclusion=evaluation_conclusion,
+ additional_technical_requirements=to_markdown_code_block(val=additional_technical_requirements),
+ )
+ return await self._write(prompt)
+
+ @retry(
+ wait=wait_random_exponential(min=1, max=20),
+ stop=stop_after_attempt(6),
+ after=general_after_log(logger),
+ )
+ async def _write(self, prompt: str) -> str:
+ rsp = await self.llm.aask(prompt)
- json_data = CodeParser.parse_code(text=rsp, lang="json")
++ # Do not use `CodeParser` here.
++ tags = ["```json", "```"]
++ bix = rsp.find(tags[0])
++ eix = rsp.rfind(tags[1])
++ if bix >= 0:
++ rsp = rsp[bix : eix + len(tags[1])]
++ json_data = rsp.removeprefix("```json").removesuffix("```")
+ json.loads(json_data) # validate
+ return json_data
+
+
+PROMPT = """
+## Actor, System, External System
+{use_case_actors}
+
+## TRD
+{trd}
+
+## Acknowledge
+{acknowledge}
+
+## Legacy Outputs
+{legacy_output}
+
+## Evaluation Conclusion
+{evaluation_conclusion}
+
+## Additional Technical Requirements
+{additional_technical_requirements}
+
+---
+You are a tool that generates software framework code based on TRD.
+The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram;
+The descriptions of the interfaces used in the "TRD" can be found in the "Acknowledge" section;
+"Legacy Outputs" contains the software framework code generated by you last time, which you can improve by addressing the issues raised in "Evaluation Conclusion";
+"Additional Technical Requirements" specifies the additional technical requirements that the generated software framework code must meet;
+Develop source code based on the content of the "TRD";
+- The `README.md` file should include:
+ - The folder structure diagram of the entire project;
++ - Class diagram and sequence diagram in PlantUML format;
+ - Correspondence between classes, interfaces, and functions with the content in the "TRD" section;
+ - Prerequisites if necessary;
+ - Installation if necessary;
+ - Configuration if necessary;
+ - Usage if necessary;
- - The `CLASS.md` file should include class diagram in PlantUML format;
- - The `SEQUENCE.md` file should include sequence diagram in PlantUML format;
+
+Return a markdown JSON object list, each object containing:
+- a "path" key with a value specifying its path;
+- a "filename" key with a value specifying its file name;
+- a "content" key with a value containing its file content;
+"""
diff --cc metagpt/prompts/di/team_leader.py
index 5f2f6b27d,7af5a6e07..8abd13165
--- a/metagpt/prompts/di/team_leader.py
+++ b/metagpt/prompts/di/team_leader.py
@@@ -18,8 -18,9 +18,10 @@@ Note
1. If the requirement is a pure DATA-RELATED requirement, such as bug fixes, issue reporting, environment setup, terminal operations, pip install, web browsing, web scraping, web searching, web imitation, data science, data analysis, machine learning, deep learning, text-to-image etc. DON'T decompose it, assign a single task with the original user requirement as instruction directly to Data Analyst.
2. If the requirement is developing a software, game, app, or website, excluding the above data-related tasks, you should decompose the requirement into multiple tasks and assign them to different team members based on their expertise, usually the sequence of Product Manager -> Architect -> Project Manager -> Engineer -> (optional: QaEngine if present) -> (optional: DataAnalyst if user requests deployment), each assigned ONE task. When publishing message to Product Manager, you should directly copy the full original user requirement.
3. If the requirement contains both DATA-RELATED part mentioned in 1 and software development part mentioned in 2, you should decompose the software development part and assign them to different team members based on their expertise, and assign the DATA-RELATED part to Data Analyst David directly.
- 4. It is helpful for Engineer to have both the system design and the project schedule for writing the code, so include paths of both files (if available) when publishing message to Engineer.
- 5. If the requirement is writing a TRD, you should assign it to Architect. When publishing message to Architect, you should directly copy the full original user requirement.
+ 4. If the requirement is a common-sense, logical, or math problem, you should respond directly without assigning any task to team members.
+ 5. If you think the requirement is not clear or ambiguous, you should ask the user for clarification immediately. Assign tasks only after all info is clear.
+ 6. It is helpful for Engineer to have both the system design and the project schedule for writing the code, so include paths of both files (if available) when publishing message to Engineer.
++7. If the requirement is writing a TRD, you should assign it to Architect. When publishing message to Architect, you should directly copy the full original user requirement.
"""
FINISH_CURRENT_TASK_CMD = """
diff --cc metagpt/roles/architect.py
index afa234a3c,afa234a3c..90781abef
--- a/metagpt/roles/architect.py
+++ b/metagpt/roles/architect.py
@@@ -7,7 -7,7 +7,18 @@@
"""
from metagpt.actions import WritePRD
from metagpt.actions.design_api import WriteDesign
++from metagpt.actions.requirement_analysis.framework import (
++ EvaluateFramework,
++ WriteFramework,
++)
++from metagpt.actions.requirement_analysis.trd import (
++ CompressExternalInterfaces,
++ DetectInteraction,
++ EvaluateTRD,
++ WriteTRD,
++)
from metagpt.roles.di.role_zero import RoleZero
++from metagpt.utils.common import tool2name
class Architect(RoleZero):
@@@ -29,9 -29,9 +40,19 @@@
"libraries. Use same language as user requirement"
)
-- instruction: str = """Use WriteDesign tool to write a system design document"""
++ instruction: str = """Use WriteDesign tool to write a system design document if a system design is required; Use WriteTRD tool to write a TRD if a TRD is required;"""
max_react_loop: int = 1 # FIXME: Read and edit files requires more steps, consider later
-- tools: list[str] = ["Editor:write,read,write_content", "RoleZero", "WriteDesign"]
++ tools: list[str] = [
++ "Editor:write,read,write_content",
++ "RoleZero",
++ "WriteDesign",
++ "CompressExternalInterfaces",
++ "DetectInteraction",
++ "EvaluateTRD",
++ "WriteTRD",
++ "WriteFramework",
++ "EvaluateFramework",
++ ]
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
@@@ -45,10 -45,10 +66,17 @@@
self._watch({WritePRD})
def _update_tool_execution(self):
-- wd = WriteDesign()
-- self.tool_execution_map.update(
-- {
-- "WriteDesign.run": wd.run,
-- "WriteDesign": wd.run, # alias
-- }
-- )
++ write_design = WriteDesign()
++ self.tool_execution_map.update(tool2name(WriteDesign, ["run"], write_design.run))
++ compress_external_interfaces = CompressExternalInterfaces()
++ self.tool_execution_map.update(tool2name(CompressExternalInterfaces, ["run"], compress_external_interfaces.run))
++ detect_interaction = DetectInteraction()
++ self.tool_execution_map.update(tool2name(DetectInteraction, ["run"], detect_interaction.run))
++ evaluate_trd = EvaluateTRD()
++ self.tool_execution_map.update(tool2name(EvaluateTRD, ["run"], evaluate_trd.run))
++ write_trd = WriteTRD()
++ self.tool_execution_map.update(tool2name(WriteTRD, ["run"], write_trd.run))
++ write_framework = WriteFramework()
++ self.tool_execution_map.update(tool2name(WriteFramework, ["run"], write_framework.run))
++ evaluate_framework = EvaluateFramework()
++ self.tool_execution_map.update(tool2name(EvaluateFramework, ["run"], evaluate_framework.run))
diff --cc metagpt/strategy/experience_retriever.py
index 97fb9a9b0,e268e9460..d04f0b5a1
--- a/metagpt/strategy/experience_retriever.py
+++ b/metagpt/strategy/experience_retriever.py
@@@ -14,7 -14,7 +14,174 @@@ class DummyExpRetriever(ExpRetriever)
"""A dummy experience retriever that returns empty string."""
def retrieve(self, context: str = "") -> str:
-- return ""
++ return self.EXAMPLE
++
++ EXAMPLE: str = """
++ ## example 1
++ User Requirement: Given some user requirements, write a TRD, and implement the TRD within a software framework.
++ Explanation:
++ Given a complete requirement, 要写TRD需要follow如下步骤:
++ 1. 调用`CompressExternalInterfaces.run`,从acknowledgement中抽取external interfaces的信息;
++ 2. 按顺序执行如下步骤:
++ 2.1. 执行`DetectInteraction.run`;
++ 2.2. 执行`WriteTRD.run`;
++ 2.3. 执行`EvaluateTRD.run`;
++ 2.4. 检查`EvaluateTRD.run`的结果:
++ 2.4.1. 如果`EvaluateTRD.run`的结果被判定为pass,则执行步骤3;
++ 2.4.2. 如果`EvaluateTRD.run`的结果被判定为deny,则继续执行步骤2;
++ 3. 按顺序执行如下步骤:
++ 3.1. 执行`WriteFramework.run`;
++ 3.2. 执行`EvaluateFramework.run`;
++ 3.3. 检查`EvaluateFramework.run`的结果:
++ 3.3.1. 如果`EvaluateFramework.run`的结果被判定为pass,则执行步骤4;
++ 3.3.2. 如果`EvaluateFramework.run`的结果被判定为deny,则继续执行步骤3;
++ 3.3.3. 如果已经重复执行步骤3超过9次,则执行步骤4;
++ 4. 执行`save_framework`,将`WriteFramework.run`的结果保存下来;
++ ```json
++ [
++ {
++ "command_name": "CompressExternalInterfaces.run",
++ "args": {
++ "task_id": "1",
++ "dependent_task_ids": [],
++ "instruction": "Execute `DetectInteraction.run` to extract external interfaces information from acknowledgement.",
++ "acknowledge": "## Interfaces\n balabala..."
++ }
++ },
++ {
++ "command_name": "DetectInteraction.run",
++ "args": {
++ "task_id": "2",
++ "dependent_task_ids": ["1"],
++ "instruction": "Execute `DetectInteraction.run` to extract external interfaces information from acknowledgement.",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ }
++ },
++ {
++ "command_name": "WriteTRD.run",
++ "args": {
++ "task_id": "3",
++ "dependent_task_ids": ["2"],
++ "instruction": "Execute `WriteTRD.run` to write TRD",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "available_external_interfaces": "<compressed_external_interfaces_output> returned by `CompressExternalInterfaces.run`",
++ "interaction_events": "<detected_interaction_events_output> returned by `DetectInteraction.run`"
++ }
++ },
++ {
++ "command_name": "EvaluateTRD.run",
++ "args": {
++ "task_id": "4",
++ "dependent_task_ids": ["3"],
++ "instruction": "Execute `EvaluateTRD.run` to evaluate the TRD",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "available_external_interfaces": "<compressed_external_interfaces_output> returned by `CompressExternalInterfaces.run`",
++ "interaction_events": "<detected_interaction_events_output>",
++ "trd": "<trd> returned by `EvaluateTRD.run`"
++ }
++ },
++ {
++ "command_name": "DetectInteraction.run",
++ "args": {
++ "task_id": "5",
++ "dependent_task_ids": ["4"],
++ "instruction": "Execute `DetectInteraction.run` to extract external interfaces information from acknowledgement.",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "evaluation_conclusion": "<evaluation_conclusion> returned by `EvaluateTRD.run`"
++ }
++ },
++ {
++ "command_name": "WriteTRD.run",
++ "args": {
++ "task_id": "6",
++ "dependent_task_ids": ["5"],
++ "instruction": "Execute `WriteTRD.run` to write TRD",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "available_external_interfaces": "<compressed_external_interfaces_output> returned by `CompressExternalInterfaces.run`",
++ "interaction_events": "<detected_interaction_events_output> returned by `DetectInteraction.run`",
++ "previous_version_trd": "<trd> returned by `WriteTRD.run`"
++ }
++ },
++ {
++ "command_name": "EvaluateTRD.run",
++ "args": {
++ "task_id": "7",
++ "dependent_task_ids": ["6"],
++ "instruction": "Execute `EvaluateTRD.run` to evaluate the TRD",
++ "user_requirements": "This is user requirement balabala...",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "available_external_interfaces": "<compressed_external_interfaces_output> returned by `CompressExternalInterfaces.run`",
++ "interaction_events": "<detected_interaction_events_output> returned by `DetectInteraction.run`",
++ "trd": "<trd> returned by `WriteTRD.run`",
++ }
++ },
++ {
++ "command_name": "WriteFramework.run",
++ "args": {
++ "task_id": "8",
++ "dependent_task_ids": ["7"],
++ "instruction": "Execute `WriteFramework.run` to write a software framework according to the TRD",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "trd": "<trd> returned by `WriteTRD.run`",
++ "acknowledge": "## Interfaces\n balabala...",
++ "additional_technical_requirements": "These are additional technical requirements, balabala...",
++ }
++ },
++ {
++ "command_name": "EvaluateFramework.run",
++ "args": {
++ "task_id": "9",
++ "dependent_task_ids": ["8"],
++ "instruction": "Execute `EvaluateFramework.run` to evaluate the software framework returned by `WriteFramework.run`",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "trd": "<trd> returned by `WriteTRD.run`",
++ "acknowledge": "## Interfaces\n balabala...",
++ "legacy_output": "<framework> returned by `WriteFramework.run`",
++ "additional_technical_requirements": "These are additional technical requirements, balabala...",
++ }
++ },
++ {
++ "command_name": "WriteFramework.run",
++ "args": {
++ "task_id": "10",
++ "dependent_task_ids": ["9"],
++ "instruction": "Execute `WriteFramework.run` to write a software framework according to the TRD",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "trd": "<trd> returned by `WriteTRD.run`",
++ "acknowledge": "## Interfaces\n balabala...",
++ "additional_technical_requirements": "These are additional technical requirements, balabala...",
++ }
++ },
++ {
++ "command_name": "EvaluateFramework.run",
++ "args": {
++ "task_id": "11",
++ "dependent_task_ids": ["10"],
++ "instruction": "Execute `EvaluateFramework.run` to evaluate the software framework returned by `WriteFramework.run`",
++ "use_case_actors": "These are actors involved in the use case, balabala...",
++ "trd": "<trd> returned by `WriteTRD.run`",
++ "acknowledge": "## Interfaces\n balabala...",
++ "legacy_output": "<framework> returned by `WriteFramework.run`",
++ "additional_technical_requirements": "These are additional technical requirements, balabala...",
++ }
++ },
++ {
++ "command_name": "save_framework",
++ "args": {
++ "task_id": "12",
++ "dependent_task_ids": ["11"],
++ "instruction": "Execute `save_framework` to save the software framework returned by `WriteFramework.run`",
++ "dir_data": "<framework> returned by `WriteFramework.run`",
++ }
++ }
++ ]
++ ```
++ """
class SimpleExpRetriever(ExpRetriever):
diff --cc metagpt/tools/libs/terminal.py
index faf2893a7,faf2893a7..e6d059636
--- a/metagpt/tools/libs/terminal.py
+++ b/metagpt/tools/libs/terminal.py
@@@ -26,7 -26,7 +26,7 @@@ class Terminal
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
-- executable="/bin/bash"
++ executable="/bin/bash",
)
self.stdout_queue = Queue()
self.observer = TerminalReporter()
diff --cc metagpt/utils/common.py
index b58ac99da,b58ac99da..dfd3a8919
--- a/metagpt/utils/common.py
+++ b/metagpt/utils/common.py
@@@ -26,7 -26,7 +26,7 @@@ import sy
import traceback
from io import BytesIO
from pathlib import Path
--from typing import Any, Callable, List, Literal, Optional, Tuple, Union
++from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
from urllib.parse import quote, unquote
import aiofiles
@@@ -1013,3 -1013,3 +1013,34 @@@ async def save_json_to_markdown(content
logger.warning(f"An unexpected error occurred: {e}")
return
await awrite(filename=output_filename, data=json_to_markdown(m))
++
++
++def tool2name(cls, methods: List[str], entry) -> Dict[str, Any]:
++ """
++ Generates a mapping of class methods to a given entry with class name as a prefix.
++
++ Args:
++ cls: The class from which the methods are derived.
++ methods (List[str]): A list of method names as strings.
++ entry (Any): The entry to be mapped to each method.
++
++ Returns:
++ Dict[str, Any]: A dictionary where keys are method names prefixed with the class name and
++ values are the given entry. If the number of methods is less than 2,
++ the dictionary will contain a single entry with the class name as the key.
++
++ Example:
++ >>> class MyClass:
++ >>> pass
++ >>>
++ >>> tool2name(MyClass, ['method1', 'method2'], 'some_entry')
++ {'MyClass.method1': 'some_entry', 'MyClass.method2': 'some_entry'}
++
++ >>> tool2name(MyClass, ['method1'], 'some_entry')
++ {'MyClass': 'some_entry', 'MyClass.method1': 'some_entry'}
++ """
++ class_name = cls.__name__
++ mappings = {f"{class_name}.{i}": entry for i in methods}
++ if len(mappings) < 2:
++ mappings[class_name] = entry
++ return mappings
diff --cc tests/data/requirements/1.constraint.md
index e09fef4b7,000000000..af7be1c84
mode 100644,000000..100644
--- a/tests/data/requirements/1.constraint.md
+++ b/tests/data/requirements/1.constraint.md
@@@ -1,2 -1,0 +1,3 @@@
+- 基于dingtalk框架编码;
- - 用java编程语言;
++- 用java编程语言;
++- 接口类的功能要放到implement子类中实现;
diff --cc tests/data/requirements/1.json
index c995ea28f,000000000..8e608bbca
mode 100644,000000..100644
--- a/tests/data/requirements/1.json
+++ b/tests/data/requirements/1.json
@@@ -1,5 -1,0 +1,5 @@@
+[
- "【按国家名维度搜索】\n法务查询者在国际小超人钉钉小程序搜索框中进行检索时采用 typeahead,只能下拉选择数据库中有的国家名。",
- "法务查询者从国际小超人钉钉小程序UI侧的国家名称列表中选中国家名,进入国家详情界面。\n法务查询者从国家详情中的业务线名列表中选出业务线名。",
++ "【按国家名维度搜索】\n法务查询者在国际小超人钉钉小程序搜索框中进行检索时采用 typeahead,只能下拉选择法务中台中有的国家名。",
++ "法务查询者从国际小超人钉钉小程序UI侧的国家名称列表中选中国家名,进入国家详情界面。\n在国家详情界面里,法务查询者从国家详情中的业务线名列表中选出业务线名。",
+ "国际小超人钉钉小程序用国家代码和业务代码做参数,查询法律意见详情,然后将结果展示给法务查询者。"
+]