ycUS1DclBQmAGNFJKy
2024-02-29 22:28:36
230
https://rehomi.com/blog/
2025-01-24 11:29:25
sales0001@rehomi.store
MetaGPT把Agent想象成环境中的数字人,其中Agent = 大语言模型(LLM) + 观察 + 思考 + 行动 + 记忆这个公式概括了智能体的功能本质。为了理解每个组成部分,让我们将其与人类进行类比:大语言模型(LLM):LLM作为智能体的“大脑”部分,使其能够处理信息,从交互中学习,做出决策并执行行动。观察:这是智能体的感知机制,使其能够感知其环境。智能体可能会接收来自另一个智能体的文本
智图AI,metaGPT,单智能体,多智能体,agent
230
多智能体实战:MetaGPT框架组件介绍
3
[{"insert":"MetaGPT把Agent想象成环境中的数字人,其中\n"},{"attributes":{"bold":true},"insert":"Agent = 大语言模型(LLM) + 观察 + 思考 + 行动 + 记忆"},{"insert":"\n这个公式概括了智能体的功能本质。为了理解每个组成部分,让我们将其与人类进行类比:\n"},{"attributes":{"bold":true},"insert":"大语言模型(LLM)"},{"insert":":LLM作为智能体的“大脑”部分,使其能够处理信息,从交互中学习,做出决策并执行行动。"},{"attributes":{"list":"number"},"insert":"\n"},{"attributes":{"bold":true},"insert":"观察"},{"insert":":这是智能体的感知机制,使其能够感知其环境。智能体可能会接收来自另一个智能体的文本消息、来自监视摄像头的视觉数据或来自客户服务录音的音频等一系列信号。这些观察构成了所有后续行动的基础。"},{"attributes":{"list":"number"},"insert":"\n"},{"attributes":{"bold":true},"insert":"思考"},{"insert":":思考过程涉及分析观察结果和记忆内容并考虑可能的行动。这是智能体内部的决策过程,其可能由LLM进行驱动。"},{"attributes":{"list":"number"},"insert":"\n"},{"attributes":{"bold":true},"insert":"行动"},{"insert":":这些是智能体对其思考和观察的显式响应。行动可以是利用 LLM 生成代码,或是手动预定义的操作,如阅读本地文件。此外,智能体还可以执行使用工具的操作,包括在互联网上搜索天气,使用计算器进行数学计算等。"},{"attributes":{"list":"number"},"insert":"\n"},{"attributes":{"bold":true},"insert":"记忆"},{"insert":":智能体的记忆存储过去的经验。这对学习至关重要,因为它允许智能体参考先前的结果并据此调整未来的行动。"},{"attributes":{"list":"number"},"insert":"\n"},{"insert":"\n\n在MetaGPT中定义的一个agent运行示例如下:\n"},{"insert":{"image":"ad4f16d442904d3286b9a62dc554cb63_40375_561_484.png"}},{"attributes":{"align":"center"},"insert":"\n"},{"insert":"一个agent在启动后他会观察自己能获取到的信息,加入自己的记忆中"},{"attributes":{"list":"bullet"},"insert":"\n"},{"insert":"下一步进行思考,决定下一步的行动,也就是从Action1,Action2,Action3中选择执行的Action"},{"attributes":{"list":"bullet"},"insert":"\n"},{"insert":"决定行动后,紧接着就执行对应行动,得到这个环节的结果"},{"attributes":{"list":"bullet"},"insert":"\n"},{"insert":"而"},{"attributes":{"bold":true},"insert":"在MetaGPT内 "},{"attributes":{"bold":true,"code":true},"insert":"Role"},{"attributes":{"bold":true},"insert":" 类是智能体的逻辑抽象"},{"insert":"。一个 "},{"attributes":{"code":true},"insert":"Role"},{"insert":" 能执行特定的 "},{"attributes":{"code":true},"insert":"Action"},{"insert":",拥有记忆、思考并采用各种策略行动。基本上,它充当一个将所有这些组件联系在一起的凝聚实体。目前,让我们只关注一个执行动作的智能体,并看看如何实现一个最简单的 Agent\n\n\n"},{"attributes":{"bold":true},"insert":"实现一个单动作Agent"},{"attributes":{"blockquote":true},"insert":"\n"},{"insert":"\n- 背景介绍:使用MetaGPT框架,实现一个生成代码的Agent,根据用户需求生成代码。\n- 需求分析:实现一个`SimpleCoder`,获取用户输入的需求,记忆用户需求,编写对应的代码。\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"编写SimpleWriteCode动作"},{"insert":"\nimport re\nimport asyncio\nfrom metagpt.actions import Action\n"},{"insert":{"image":"f77ee7d5bd733bdd82719d9c975a967f_51797_885_556.png"}},{"insert":"\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"设计SimpleCoder角色"},{"insert":"\nfrom metagpt.roles import Role\nfrom metagpt.schema import Message\nfrom metagpt.logs import logger\n\n"},{"insert":{"image":"95dbbdb922b489381fc56f4292b526a6_57361_822_614.png"}},{"insert":"\n\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"运行SimpleCoder角色"},{"insert":"\n"},{"insert":{"image":"f24b1b6953f651d551fe83781f436929_11125_639_143.png"}},{"insert":"\nawait main()\n\n\n\n"},{"attributes":{"bold":true},"insert":"实现一个多动作Agent"},{"attributes":{"blockquote":true},"insert":"\n"},{"insert":"\n- 背景介绍:使用MetaGPT框架,实现一个多动作Agent,根据用户需求生成代码。\n- 需求分析:通过自然语言编写代码,并且生成的代码立即执行。\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"编写SimpleRunCode动作"},{"insert":"\n"},{"insert":{"image":"eb8267cee1b140c0d2b12a4d1f798a5d_25413_984_307.png"}},{"insert":"\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"定义RunableCoder角色"},{"insert":"\n"},{"insert":{"image":"0e56ed9c677ccee7fcb9e7c40b7f2880_58244_836_583.png"}},{"insert":"\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"运行RunnableCoder角色"},{"insert":"\n"},{"insert":{"image":"2a60c7b3cede1dc9ba6991f5b0770aaa_12555_645_154.png"}},{"insert":"\nawait main()\n\n"},{"attributes":{"bold":true},"insert":"Agent:技术文件助手"},{"attributes":{"blockquote":true},"insert":"\n"},{"insert":"\n- 背景介绍:使用MetaGPT实现一个更复杂的Agent,将需求进行拆解。\n- 需求分析:实现一个技术文件助手,获取用户输入的需求,生成文档大纲,将任务根据大纲拆解出子任务,然后逐步完成各个子任务,最后将任务汇总输出完整文档。\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"编写WriteDirectory动作"},{"insert":"\nfrom datetime import datetime\nfrom typing import Dict\nfrom metagpt.const import TUTORIAL_PATH\nfrom metagpt.logs import logger\nfrom metagpt.roles.role import Role, RoleReactMode\nfrom metagpt.schema import Message\nfrom metagpt.utils.file import File\nfrom metagpt.actions import Action\nfrom metagpt.utils.common import OutputParser\n\nCOMMON_PROMPT = \"\"\"\nYou are now a seasoned technical professional in the field of the internet. \nWe need you to write a technical tutorial with the topic \"{topic}\".\n\"\"\"\n\nDIRECTORY_PROMPT = (\n  COMMON_PROMPT\n  + \"\"\"\nPlease provide the specific table of contents for this tutorial, strictly following the following requirements:\n1. The output must be strictly in the specified language, {language}.\n2. Answer strictly in the dictionary format like {{\"title\": \"xxx\", \"directory\": [{{\"dir 1\": [\"sub dir 1\", \"sub dir 2\"]}}, {{\"dir 2\": [\"sub dir 3\", \"sub dir 4\"]}}]}}.\n3. The Answer strictl use English punctuation.\n4. The directory should be as specific and sufficient as possible, with a primary and secondary directory.The secondary directory is in the array.\n5. Do not have extra spaces or line breaks.\n6. Each directory title has practical significance.\n\"\"\"\n)\n\nCONTENT_PROMPT = (\n  COMMON_PROMPT\n  + \"\"\"\nNow I will give you the module directory titles for the topic. \nPlease output the detailed principle content of this title in detail. \nIf there are code examples, please provide them according to standard code specifications. \nWithout a code example, it is not necessary.\n\nThe module directory titles for the topic is as follows:\n{directory}\n\nStrictly limit output according to the following requirements:\n1. Follow the Markdown syntax format for layout.\n2. If there are code examples, they must follow standard syntax specifications, have document annotations, and be displayed in code blocks.\n3. The output must be strictly in the specified language, {language}.\n4. Do not have redundant output, including concluding remarks.\n5. Strict requirement not to output the topic \"{topic}\".\n\"\"\"\n)\n"},{"attributes":{"width":"666"},"insert":{"image":"03242d3cf071c0a99415a8708590be56_71098_1268_686.png"}},{"insert":"\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"编写WriteContent动作"},{"insert":"\n"},{"insert":{"image":"ef654eaebf71f570f47d7db6b4fb7b8e_51524_973_614.png"}},{"insert":"\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"编写TutorialAssistant角色"},{"insert":"\nclass TutorialAssistant(Role):\n  \"\"\"Tutorial assistant, input one sentence to generate a tutorial document in markup format.\n\n  Args:\n    name: The name of the role.\n    profile: The role profile description.\n    goal: The goal of the role.\n    constraints: Constraints or requirements for the role.\n    language: The language in which the tutorial documents will be generated.\n  \"\"\"\n\n  name: str = \"Stitch\"\n  profile: str = \"Tutorial Assistant\"\n  goal: str = \"Generate tutorial documents\"\n  # 内容以markdown格式输出\n  constraints: str = \"Strictly follow Markdown's syntax, with neat and standardized layout\"\n  language: str = \"Chinese\"\n\n  topic: str = \"\"\n  main_title: str = \"\"\n  total_content: str = \"\"\n\n  def __init__(self, **kwargs):\n    super().__init__(**kwargs)\n    self._init_actions([WriteDirectory(language=self.language)])\n    self._set_react_mode(react_mode=RoleReactMode.BY_ORDER.value)\n    \n  async def _think(self) -\u003e None:\n    \"\"\"Determine the next action to be taken by the role.\"\"\"\n    logger.info(self.rc.state)\n    logger.info(self,)\n    # 如果没有动作需要执行,则执行第一个动作\n    if self.rc.todo is None:\n      self._set_state(0)\n      return\n    \n    # 继续执行下一个动作\n    if self.rc.state + 1 \u003c len(self.states):\n      self._set_state(self.rc.state + 1)\n    else:\n      self.rc.todo = None\n\n  async def _handle_directory(self, titles: Dict) -\u003e Message:\n    \"\"\"Handle the directories for the tutorial document.\n\n    Args:\n      titles: A dictionary containing the titles and directory structure,\n          such as {\"title\": \"xxx\", \"directory\": [{\"dir 1\": [\"sub dir 1\", \"sub dir 2\"]}]}\n\n    Returns:\n      A message containing information about the directory.\n    \"\"\"\n    self.main_title = titles.get(\"title\")\n    directory = f\"{self.main_title}\\n\"\n    self.total_content += f\"# {self.main_title}\"\n    actions = list()\n    for first_dir in titles.get(\"directory\"):\n      # 添加生成子任务内容的动作\n      actions.append(WriteContent(\n        language=self.language, directory=first_dir))\n      key = list(first_dir.keys())[0]\n      directory += f\"- {key}\\n\"\n      for second_dir in first_dir[key]:\n        directory += f\" - {second_dir}\\n\"\n    # 更新action列表    \n    self._init_actions(actions)\n    self.rc.todo = None\n    return Message(content=directory)\n  \n  async def _act(self) -\u003e Message:\n    \"\"\"Perform an action as determined by the role.\n\n    Returns:\n      A message containing the result of the action.\n    \"\"\"\n    todo = self.rc.todo    \n    if type(todo) is WriteDirectory:\n      # 生成目录\n      msg = self.rc.memory.get(k=1)[0]\n      self.topic = msg.content\n      resp = await todo.run(topic=self.topic)\n      logger.info(resp)\n      # 根据目录内容,生成子任务\n      return await self._handle_directory(resp)\n    resp = await todo.run(topic=self.topic)\n    logger.info(resp)\n    if self.total_content != \"\":\n      self.total_content += \"\\n\\n\\n\"\n    self.total_content += resp\n    return Message(content=resp, role=self.profile)\n  \n  async def react(self) -\u003e Message:\n    \"\"\"Execute the assistant's think and actions.\n\n    Returns:\n      A message containing the final result of the assistant's actions.\n    \"\"\"\n    while True:\n      # 先思考\n      await self._think()\n      if self.rc.todo is None:\n        break\n      # 再执行动作  \n      msg = await self._act()\n    \n    root_path = TUTORIAL_PATH / datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n    await File.write(root_path, f\"{self.main_title}.md\", self.total_content.encode('utf-8'))\n    return msg\n\n"},{"attributes":{"background":"#1f1f1f","bold":true,"color":"#569cd6","lineHeight":"19px"},"insert":"运行TutorialAssistant角色"},{"insert":"\n"},{"insert":{"image":"9820ab506e76f2debf8391776f66bca4_9638_376_159.png"}},{"insert":"\nawait main()\n\n智图AI体验:"},{"attributes":{"link":"https://rehomi.com/tools/AI"},"insert":"https://rehomi.com/tools/AI"},{"insert":"\n"}]
https://cdn.rehomi.com/photos/files/7a1a9c2456aa9914d3d894861adb9d12_690546_743_457.png
0
["智图AI","metaGPT","单智能体","多智能体","agent"]
3
1
285