当前位置: 首页 > article >正文

2.metagpt中的软件公司智能体 (ProductManager 角色)

1. 代码

ProductManager 类

from metagpt.actions import UserRequirement, WritePRD
from metagpt.actions.prepare_documents import PrepareDocuments
from metagpt.roles.role import Role, RoleReactMode
from metagpt.utils.common import any_to_name


class ProductManager(Role):
    """
    Represents a Product Manager role responsible for product development and management.

    Attributes:
        name (str): Name of the product manager.
        profile (str): Role profile, default is 'Product Manager'.
        goal (str): Goal of the product manager.
        constraints (str): Constraints or limitations for the product manager.
    """

    name: str = "Alice"
    profile: str = "Product Manager"
    goal: str = "efficiently create a successful product that meets market demands and user expectations"
    constraints: str = "utilize the same language as the user requirements for seamless communication"
    todo_action: str = ""

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)

        self.set_actions([PrepareDocuments, WritePRD])
        self._watch([UserRequirement, PrepareDocuments])
        self.rc.react_mode = RoleReactMode.BY_ORDER
        self.todo_action = any_to_name(WritePRD)

    async def _observe(self, ignore_memory=False) -> int:
        return await super()._observe(ignore_memory=True)

context上下文,即数据结构

# 初始化 Context
context = Context()

断言

assert context.git_repo is None
assert context.repo is None

2. 示例:

from metagpt.schema import Message
USER_REQUIREMENT = """开发一个贪吃蛇游戏"""

user_msg = Message(role="User", content=USER_REQUIREMENT, cause_by=UserRequirement)
product_manager = ProductManager(context=context)
rsp = await product_manager.run(user_msg)

输出:

2024-12-16 21:37:30.446 | INFO     | metagpt.roles.role:_act:403 - Alice(Product Manager): to do PrepareDocuments(PrepareDocuments)
2024-12-16 21:37:31.897 | INFO     | metagpt.utils.file_repository:save:57 - save to: D:\llm\MetaGPT\workspace\20241216213730\docs\requirement.txt
2024-12-16 21:37:31.898 | INFO     | metagpt.roles.role:_act:403 - Alice(Product Manager): to do WritePRD(WritePRD)
2024-12-16 21:37:31.900 | INFO     | metagpt.actions.write_prd:run:86 - New requirement detected: 开发一个贪吃蛇游戏


[CONTENT]
{
    "Language": "en_us",
    "Programming Language": "Python",
    "Original Requirements": "开发一个贪吃蛇游戏",
    "Project Name": "snake_game",
    "Product Goals": [
        "Create an engaging and intuitive user experience",
        "Ensure the game is scalable and performs well on various devices",
        "Implement a high-quality UI/UX design"
    ],
    "User Stories": [
        "As a player, I want to easily navigate the game controls to play the game",
        "As a player, I want to see my score and high scores displayed clearly on the screen",
        "As a player, I want the ability to pause and resume the game at any time",
        "As a player, I want to have the option to restart the game from the beginning",
        "As a player, I want the game to be visually appealing and responsive on different screen sizes"
    ],
    "Competitive Analysis": [
        "Snake Game A: Basic gameplay, lacks advanced features and customization",
        "Snake Game B: Offers a variety of themes and power-ups, but can be slow on older devices",
        "Snake Game C: Features a simple and clean UI, but lacks multiplayer functionality"
    ],
    "Competitive Quadrant Chart": "quadrantChart\n    title \"Performance and User Engagement\"\n    x-axis \"Low Performance\" --> \"High Performance\"\n    y-axis \"Low Engagement\" --> \"High Engagement\"\n    quadrant-1 \"We should expand\"\n    quadrant-2 \"Need to promote\"\n    quadrant-3 \"Re-evaluate\"\n    quadrant-4 \"May be improved\"\n    \"Game A\": [0.2, 0.4]\n    \"Game B\": [0.5, 0.6]\n    \"Game C\": [0.3, 0.5]\n    \"Our Target Product\": [0.7, 0.7]",
    "Requirement Analysis": "The game should be designed to be accessible to players of all skill levels, with a focus on ease of use and a high-quality visual experience. The game should also be optimized for performance on a range of devices, from low-end to high-end.",
    "Requirement Pool": [
        [
            "P0",
            "Develop the core gameplay logic for the snake movement and food generation"
        ],
        [
            "P0",
            "Implement a user-friendly interface with clear score tracking and game controls"
        ],
        [
            "P1",
            "Add features such as pause, resume, and restart functionality"
        ],
        [
            "P1",
            "Optimize the game for performance on various devices"
        ],
        [
            "P2",
            "Design and implement a high-quality UI/UX"
        ]
    ],
    "UI Design draft": "A simple and intuitive UI with a clear score display, easy-to-use controls, and a responsive design that adapts to different screen sizes.",
    "Anything UNCLEAR": "It is unclear whether there are specific design preferences or branding requirements for the game."
}
[/CONTENT]

2024-12-16 21:37:53.890 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4-flash not found in TOKEN_COSTS.
2024-12-16 21:37:53.951 | WARNING  | metagpt.utils.git_repository:rename_root:214 - Move D:\llm\MetaGPT\workspace\20241216213730 to D:\llm\MetaGPT\workspace\snake_game error: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'D:\\llm\\MetaGPT\\workspace\\20241216213730'
2024-12-16 21:37:53.952 | INFO     | metagpt.utils.git_repository:rename_root:219 - Rename directory D:\llm\MetaGPT\workspace\20241216213730 to D:\llm\MetaGPT\workspace\snake_game

2024-12-16 21:37:54.134 | INFO     | metagpt.utils.file_repository:save:57 - save to: D:\llm\MetaGPT\workspace\snake_game\docs\prd\20241216213754.json
2024-12-16 21:37:54.191 | WARNING  | metagpt.utils.mermaid:mermaid_to_file:35 - RUN `npm install -g @mermaid-js/mermaid-cli` to install mmdc,or consider changing engine to `playwright`, `pyppeteer`, or `ink`.
2024-12-16 21:37:54.193 | INFO     | metagpt.utils.file_repository:save:57 - save to: D:\llm\MetaGPT\workspace\snake_game\resources\prd\20241216213754.md

解释:
- 根据用户消息生成项目结构,并在requirement文件中添加用户消息
- 在项目结构的prd文件中添加内容

print(rsp)
Alice(Product Manager): {'docs': {'20241216213754.json': {'root_path': 'docs\\prd', 'filename': '20241216213754.json', 'content': '{"Language":"en_us","Programming Language":"Python","Original Requirements":"开发一个贪吃蛇游戏","Project Name":"snake_game","Product Goals":["Create an engaging and intuitive user experience","Ensure the game is scalable and performs well on various devices","Implement a high-quality UI/UX design"],"User Stories":["As a player, I want to easily navigate the game controls to play the game","As a player, I want to see my score and high scores displayed clearly on the screen","As a player, I want the ability to pause and resume the game at any time","As a player, I want to have the option to restart the game from the beginning","As a player, I want the game to be visually appealing and responsive on different screen sizes"],"Competitive Analysis":["Snake Game A: Basic gameplay, lacks advanced features and customization","Snake Game B: Offers a variety of themes and power-ups, but can be slow on older devices","Snake Game C: Features a simple and clean UI, but lacks multiplayer functionality"],"Competitive Quadrant Chart":"quadrantChart\\n    title \\"Performance and User Engagement\\"\\n    x-axis \\"Low Performance\\" --> \\"High Performance\\"\\n    y-axis \\"Low Engagement\\" --> \\"High Engagement\\"\\n    quadrant-1 \\"We should expand\\"\\n    quadrant-2 \\"Need to promote\\"\\n    quadrant-3 \\"Re-evaluate\\"\\n    quadrant-4 \\"May be improved\\"\\n    \\"Game A\\": [0.2, 0.4]\\n    \\"Game B\\": [0.5, 0.6]\\n    \\"Game C\\": [0.3, 0.5]\\n    \\"Our Target Product\\": [0.7, 0.7]","Requirement Analysis":"The game should be designed to be accessible to players of all skill levels, with a focus on ease of use and a high-quality visual experience. The game should also be optimized for performance on a range of devices, from low-end to high-end.","Requirement Pool":[["P0","Develop the core gameplay logic for the snake movement and food generation"],["P0","Implement a user-friendly interface with clear score tracking and game controls"],["P1","Add features such as pause, resume, and restart functionality"],["P1","Optimize the game for performance on various devices"],["P2","Design and implement a high-quality UI/UX"]],"UI Design draft":"A simple and intuitive UI with a clear score display, easy-to-use controls, and a responsive design that adapts to different screen sizes.","Anything UNCLEAR":"It is unclear whether there are specific design preferences or branding requirements for the game."}'}}}

3. 代码解释

ProductManager(产品经理)角色类,继承自 Role 类,主要用于模拟产品经理在一个工作流中的行为,尤其是在产品开发过程中。

以下是对代码的逐部分解释:

类 ProductManager 说明
ProductManager 代表一个产品经理角色,负责产品开发和管理。
类中定义了几个主要属性:name、profile、goal 和 constraints,用来描述产品经理的基本信息和角色目标。
属性

  • name: str = “Alice”:定义了产品经理的名字为 Alice。
  • profile: str = “Product Manager”:定义了角色的身份为“产品经理”。
  • goal: str = “efficiently create a successful product that meets market demands and user expectations”:定义了产品经理的目标,即“有效地创建一个符合市场需求和用户期望的成功产品”。
  • constraints: str = “utilize the same language as the user requirements for seamless communication”:定义了产品经理的约束条件,即“使用与用户需求一致的语言进行无缝沟通”。
  • todo_action: str = “”:初始化了待执行的任务动作为空字符串。

init 方法
该方法初始化 ProductManager 类的实例。

  • super().init(**kwargs):调用父类 Role 的初始化方法,以确保继承的属性得到正确初始化。
  • self.set_actions([PrepareDocuments, WritePRD]):设置该角色可以执行的动作。这里设置了两个动作,分别是 PrepareDocuments(准备文档)和 WritePRD(撰写产品需求文档)。
  • self._watch([UserRequirement, PrepareDocuments]):使角色“观察” UserRequirement 和 PrepareDocuments 这两个事件或动作。观察是为了跟踪某些条件或状态的变化。
  • self.rc.react_mode = RoleReactMode.BY_ORDER:设置角色的反应模式为“按顺序反应”,意味着角色将按照顺序执行动作。
  • self.todo_action = any_to_name(WritePRD):将 WritePRD 动作的名称赋值给 todo_action,可能是为了后续跟踪或执行。

async def _observe(self, ignore_memory=False) -> int 方法

  • 这是一个异步方法,用于观察并执行某些操作。该方法通过调用父类的 _observe 方法来实现观察,并返回一个整数值,表示观察结果。ignore_memory 参数默认设置为 False,表示是否忽略记忆。

http://www.kler.cn/a/443804.html

相关文章:

  • 【数据结构练习题】链表与LinkedList
  • pro文件转换为CMakeLists.txt文件,QT官方工具使用教程
  • 【看海的算法日记✨优选篇✨】第二回:流动之窗,探索算法的优雅之道
  • UVM 验证方法学之interface学习系列文章(十二)virtual interface 终结篇
  • 【优选算法---归并排序衍生题目】剑指offer51---数组中的逆序对、计算右侧小于当前元素的个数、翻转对
  • jvm栈帧中的动态链接
  • @Resource与@Autowire
  • VGGNet:深度学习中的卷积神经网络经典之作
  • Elasticsearch 实战应用:开启数据搜索与分析新征程
  • c++ 找第一个只出现一次的字符
  • 人力资本管理SaaS的升级之路:群硕以本地化+云创新驱动行业变革
  • Java聊天室系统的设计与实现【源码+文档】
  • java数据类型(补充-引用类型)
  • 整点(枚举)
  • React 19有哪些新特性?
  • WPF+MVVM案例实战与特效(四十四)- WPF多语言支持全解析:轻松实现国际化应用
  • List;Set;Map集合
  • C++总结联想文档
  • Leetcode3266:K 次乘运算后的最终数组 II
  • TanStack——为现代前端开发提供高性能和灵活的工具
  • 应用程序设置开机自启动
  • MyBatis-Plus(一)
  • 论文笔记:是什么让多模态学习变得困难?
  • Vmware 安装Ubuntu系统 服务器版本
  • 盈养科技二面
  • 3D可视化引擎HOOPS Visualize与HOOPS Luminate Bridge的功能与应用