MetaGPT实战案例:从游戏开发到企业应用
MetaGPT作为一款多智能体框架,能够基于一行需求描述,生成产品需求文档(PRD)、设计、任务列表及代码仓库。本文将通过游戏开发和企业应用两个场景,详细介绍MetaGPT的实战应用。
游戏开发实战
2048游戏开发
MetaGPT提供了便捷的游戏开发能力,以2048游戏为例,通过examples/write_game_code.py可以快速实现游戏的开发。该脚本创建了MGXEnv环境,并添加了TeamLeader和Engineer2角色,通过简单的需求描述即可生成游戏代码。
async def main(requirement="", user_defined_recipient="", enable_human_input=False, allow_idle_time=30):
env = MGXEnv()
env.add_roles([TeamLeader(), Engineer2()])
msg = Message(content=requirement)
env.attach_images(msg) # attach image content if applicable
if user_defined_recipient:
msg.send_to = {user_defined_recipient}
env.publish_message(msg, user_defined_recipient=user_defined_recipient)
else:
env.publish_message(msg)
allow_idle_time = allow_idle_time if enable_human_input else 1
start_time = time.time()
while time.time() - start_time < allow_idle_time:
if not env.is_idle:
await env.run()
start_time = time.time() # reset start time
贪吃蛇游戏开发
除了2048游戏,MetaGPT还支持贪吃蛇等其他游戏的开发。通过examples/di/software_company.py,可以实现从需求分析到代码生成、测试和提交的全流程。该脚本使用DataInterpreter角色,集成了WritePRD、WriteDesign、WritePlan、WriteCode、RunCode和DebugError等工具。
async def main():
prompt = """
This is a software requirement:
```text
write a snake game
-
Writes a PRD based on software requirements.
-
Writes a design to the project repository, based on the PRD of the project.
-
Writes a project plan to the project repository, based on the design of the project.
-
Writes codes to the project repository, based on the project plan of the project.
-
Run QA test on the project repository.
-
Stage and commit changes for the project repository using Git. Note: All required dependencies and environments have been fully installed and configured. """ di = DataInterpreter( tools=[ "WritePRD", "WriteDesign", "WritePlan", "WriteCode", "RunCode", "DebugError", # "git_archive", ] )
await di.run(prompt)
## 企业应用实战
### 数据分析与可视化
MetaGPT在企业应用中也有广泛的应用,特别是在数据分析和可视化方面。通过[examples/di/data_analyst_write_code.py](https://link.gitcode.com/i/2a3ce05dc57e0b35791e5585b33c2e81),可以实现数据分析师角色的模拟,生成数据分析代码。
```python
async def main():
# Create an instance of DataAnalyst role
analyst = DataAnalyst()
# Set the main goal for the planner - constructing a 2D array
analyst.planner.plan.goal = "construct a two-dimensional array"
# Add a specific task to the planner with detailed parameters:
# - task_id: Unique identifier for the task
# - dependent_task_ids: List of tasks that need to be completed before this one (empty in this case)
# - instruction: Description of what needs to be done
# - assignee: Who will execute the task (David)
# - task_type: Category of the task (DATA_ANALYSIS)
analyst.planner.plan.append_task(
task_id="1",
dependent_task_ids=[],
instruction="construct a two-dimensional array",
assignee="David",
task_type="DATA_ANALYSIS",
)
# Execute the code generation and execution for creating a 2D array
# The write_and_exec_code method will:
# 1. Generate the necessary code for creating a 2D array
# 2. Execute the generated code
# 3. Return the result
result = await analyst.write_and_exec_code("construct a two-dimensional array")
# Log the result of the code execution
logger.info(result)
同时,examples/di/data_visualization.py提供了数据可视化的能力,可以对数据集进行分析并生成可视化图表。
企业级应用开发框架
MetaGPT还提供了企业级应用开发的框架,通过metagpt/software_company.py可以实现完整的团队协作开发流程。该脚本定义了TeamLeader、ProductManager、Architect、Engineer2和DataAnalyst等角色,能够模拟软件公司的开发流程,从需求分析到代码实现。
def generate_repo(
idea,
investment=3.0,
n_round=5,
code_review=True,
run_tests=False,
implement=True,
project_name="",
inc=False,
project_path="",
reqa_file="",
max_auto_summarize_code=0,
recover_path=None,
):
"""Run the startup logic. Can be called from CLI or other Python scripts."""
from metagpt.config2 import config
from metagpt.context import Context
from metagpt.roles import (
Architect,
DataAnalyst,
Engineer2,
ProductManager,
TeamLeader,
)
from metagpt.team import Team
config.update_via_cli(project_path, project_name, inc, reqa_file, max_auto_summarize_code)
ctx = Context(config=config)
if not recover_path:
company = Team(context=ctx)
company.hire(
[
TeamLeader(),
ProductManager(),
Architect(),
Engineer2(),
# ProjectManager(),
DataAnalyst(),
]
)
# if implement or code_review:
# company.hire([Engineer(n_borg=5, use_code_review=code_review)])
#
# if run_tests:
# company.hire([QaEngineer()])
# if n_round < 8:
# n_round = 8 # If `--run-tests` is enabled, at least 8 rounds are required to run all QA actions.
else:
stg_path = Path(recover_path)
if not stg_path.exists() or not str(stg_path).endswith("team"):
raise FileNotFoundError(f"{recover_path} not exists or not endswith `team`")
company = Team.deserialize(stg_path=stg_path, context=ctx)
idea = company.idea
company.invest(investment)
asyncio.run(company.run(n_round=n_round, idea=idea))
return ctx.kwargs.get("project_path")
总结
MetaGPT作为一款强大的多智能体框架,无论是游戏开发还是企业应用,都能够提供高效、便捷的解决方案。通过本文介绍的实战案例,我们可以看到MetaGPT在不同场景下的应用能力,相信在未来会有更广泛的应用前景。官方文档:docs/tutorial/usage_cn.md。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



