【AI的未来 - AI Agent系列】【MetaGPT】5. 更复杂的Agent实战 - 实现技术文档助手

简介: 【AI的未来 - AI Agent系列】【MetaGPT】5. 更复杂的Agent实战 - 实现技术文档助手

0. 本文实现内容

今天我们来实现一个有实际意义的Agent - 实现一个技术文档助手,用户只需要输入技术文档的标题,例如“Git教程”,Agent自动将Git教程写成文档,分目录,分块,条理清晰,并有代码示例。

先看下要实现的效果(全程用户只需要输入“Git 教程”):

  • MarkDown格式
  • 分目录,一级标题、二级标题
  • 有代码示例

1. 实现思路

因为token限制的原因,我们先通过 LLM 大模型生成教程的目录,再对目录按照二级标题进行分块,对于每块目录按照标题生成详细内容,最后再将标题和内容进行拼接,解决 LLM 大模型长文本的限制问题。

整体流程如下(下图来自《MetaGPT智能体开发入门》):

分析上述流程图,我们需要实现:

  • 生成文档大纲的Action:WriteDirectory
  • 子任务的Action:WriteContent
  • 在得到文档大纲之后,要对大纲进行拆分(本例按目录进行拆分),然后根据拆分内容动态添加子任务Action,让子任务去根据目录写技术文档的内容
  • 将子任务Action生成的内容最后做拼接,形成最终的MarkDown文档

2. 完整代码及细节注释

直接放出完整代码,代码中添加了一些细节注释来帮助你理解,用的MetaGPT 0.5.2版本。建议你一定要实操一遍,因为不实操,你永远不知道自己会遇到多少坑…

代码并不复杂

  • WriteDirectory的实现:基本就是我们把自己的需求放入我们准备好的提示词模板里,询问大模型得到结果,然后我们对得到的内容做一个解析。(数据格式化)
  • WriteContent的实现:直接根据传入的子标题内容调用大模型生成回答
# 加载 .env 到环境变量
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
from datetime import datetime
from typing import Dict
import asyncio
from metagpt.actions.write_tutorial import WriteDirectory, WriteContent
from metagpt.const import TUTORIAL_PATH
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.utils.file import File
import fire
import time
from typing import Dict
from metagpt.actions import Action
from metagpt.prompts.tutorial_assistant import DIRECTORY_PROMPT, CONTENT_PROMPT
from metagpt.utils.common import OutputParser
## 1. 生成文档大纲目录
class WriteDirectory(Action):
    """Action class for writing tutorial directories.
    Args:
        name: The name of the action.
        language: The language to output, default is "Chinese".
    """
    def __init__(self, name: str = "", language: str = "Chinese", *args, **kwargs):
        super().__init__(name, *args, **kwargs)
        self.language = language
    async def run(self, topic: str, *args, **kwargs) -> Dict:
        COMMON_PROMPT = """
        You are now a seasoned technical professional in the field of the internet. 
        We need you to write a technical tutorial with the topic "{topic}".
        """
        DIRECTORY_PROMPT = COMMON_PROMPT + """
        Please provide the specific table of contents for this tutorial, strictly following the following requirements:
        1. The output must be strictly in the specified language, {language}.
        2. 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"]}}]}}.
        3. The directory should be as specific and sufficient as possible, with a primary and secondary directory.The secondary directory is in the array.
        4. Do not have extra spaces or line breaks.
        5. Each directory title has practical significance.
        """
        prompt = DIRECTORY_PROMPT.format(topic=topic, language=self.language)
        resp = await self._aask(prompt=prompt)
        return OutputParser.extract_struct(resp, dict) ## 1.1 对结果进行校验,必须符合Dict结构,否则报错
## 2. 子任务Action,这里是根据拆分的目录标题写技术文档内容
class WriteContent(Action):
    """Action class for writing tutorial content.
    Args:
        name: The name of the action.
        directory: The content to write.
        language: The language to output, default is "Chinese".
    """
    def __init__(self, name: str = "", directory: str = "", language: str = "Chinese", *args, **kwargs):
        super().__init__(name, *args, **kwargs)
        self.language = language
        self.directory = directory
    async def run(self, topic: str, *args, **kwargs) -> str:
        COMMON_PROMPT = """
        You are now a seasoned technical professional in the field of the internet. 
        We need you to write a technical tutorial with the topic "{topic}".
        """
        CONTENT_PROMPT = COMMON_PROMPT + """
        Now I will give you the module directory titles for the topic. 
        Please output the detailed principle content of this title in detail. 
        If there are code examples, please provide them according to standard code specifications. 
        Without a code example, it is not necessary.
        The module directory titles for the topic is as follows:
        {directory}
        Strictly limit output according to the following requirements:
        1. Follow the Markdown syntax format for layout.
        2. If there are code examples, they must follow standard syntax specifications, have document annotations, and be displayed in code blocks.
        3. The output must be strictly in the specified language, {language}.
        4. Do not have redundant output, including concluding remarks.
        5. Strict requirement not to output the topic "{topic}".
        """
        prompt = CONTENT_PROMPT.format(
            topic=topic, language=self.language, directory=self.directory)
        return await self._aask(prompt=prompt)
## 3. 技术文档角色,用来执行Action
class TutorialAssistant(Role):
    def __init__(
        self,
        name: str = "Stitch",
        profile: str = "Tutorial Assistant",
        goal: str = "Generate tutorial documents",
        constraints: str = "Strictly follow Markdown's syntax, with neat and standardized layout",
        language: str = "Chinese",
    ):
        super().__init__(name, profile, goal, constraints)
        self._init_actions([WriteDirectory(language=language)]) ## 3.1 初始化时,先只添加WriteDirectory Action,生成目录。WriteContent Action后面根据目录动态添加,这里你也不知道要添加多少个,添加的内容是什么。
        self.topic = ""
        self.main_title = "" ## 3.2 记录文章题目
        self.total_content = "" ## 3.3 生成的所有内容,拼接到这里
        self.language = language
    async def _think(self) -> None:
        """Determine the next action to be taken by the role."""
        if self._rc.todo is None:
            self._set_state(0) ## 3.4 转到第一个Action执行
            return
        if self._rc.state + 1 < len(self._states):
            self._set_state(self._rc.state + 1) ## 3.5 将要执行下一个Action
        else:
            self._rc.todo = None
  ## 3.6 根据生成的目录,拆分出一级标题和二级标题,动态添加到WriteContent Action中,输入的titles必须是Dict类型,这就要求WriteDirectory的输出必须能按Dict类型解析,否则报错,程序无法继续执行。
    async def _handle_directory(self, titles: Dict) -> Message:
        self.main_title = titles.get("title")
        directory = f"{self.main_title}\n"
        self.total_content += f"# {self.main_title}"
        actions = list()
        for first_dir in titles.get("directory"):
            actions.append(WriteContent(
                language=self.language, directory=first_dir)) ## 3.7 动态添加 WriteContent Action,将一级目录内容传入
            key = list(first_dir.keys())[0]
            directory += f"- {key}\n"
            for second_dir in first_dir[key]:
                directory += f"  - {second_dir}\n"
        self._init_actions(actions) ## 3.8 执行了这一句,此时动作列表全是WriteContent了
        self._rc.todo = None
        return Message(content=directory)
    async def _act(self) -> Message:
        """Perform an action as determined by the role.
        Returns:
            A message containing the result of the action.
        """
        time.sleep(20) ## 3.9 这是为了避免OpenAI接口调用频率限制,不是办法的办法
        todo = self._rc.todo
        if type(todo) is WriteDirectory: 
            msg = self._rc.memory.get(k=1)[0] ## 3.10 获取记忆,这里是获取用户输入,因为任何动作都还没执行,所以只有用户输入
            self.topic = msg.content
            resp = await todo.run(topic=self.topic) ## 3.11 根据用户输入生成目录
            logger.info(resp)
            return await self._handle_directory(resp)
        resp = await todo.run(topic=self.topic) ## 3.12 走到这里的都是WriteContent Action。 这里的self.topic还是用户输入,因为并没有其它地方更新该值。这里传入的目的是让WriteContent写的内容以这个为范围限制
        logger.info(resp)
        if self.total_content != "":
            self.total_content += "\n\n\n"
        self.total_content += resp ## 3.13 拼接数据
        return Message(content=resp, role=self.profile)
    async def _react(self) -> Message:
        """Execute the assistant's think and actions.
        Returns:
            A message containing the final result of the assistant's actions.
        """
        while True:
            await self._think()
            if self._rc.todo is None:
                break
            msg = await self._act()
    ## 3.14 全部Action执行完毕,写文件
        root_path = TUTORIAL_PATH / datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        await File.write(root_path, f"{self.main_title}.md", self.total_content.encode('utf-8'))
        return msg
async def main():
    msg = "Git 教程"
    role = TutorialAssistant()
    logger.info(msg)
    result = await role.run(msg)
    logger.info(result)
asyncio.run(main())
相关文章
|
4月前
|
SQL 人工智能 关系型数据库
AI Agent的未来之争:任务规划,该由人主导还是AI自主?——阿里云RDS AI助手的最佳实践
AI Agent的规划能力需权衡自主与人工。阿里云RDS AI助手实践表明:开放场景可由大模型自主规划,高频垂直场景则宜采用人工SOP驱动,结合案例库与混合架构,实现稳定、可解释的企业级应用,推动AI从“能聊”走向“能用”。
1075 39
AI Agent的未来之争:任务规划,该由人主导还是AI自主?——阿里云RDS AI助手的最佳实践
|
4月前
|
存储 人工智能 OLAP
AI Agent越用越笨?阿里云AnalyticDB「AI上下文工程」一招破解!
AI上下文工程是优化大模型交互的系统化框架,通过管理指令、记忆、知识库等上下文要素,解决信息缺失、长度溢出与上下文失效等问题。依托AnalyticDB等技术,实现上下文的采集、存储、组装与调度,提升AI Agent的准确性与协同效率,助力企业构建高效、稳定的智能应用。
|
5月前
|
存储 人工智能 Serverless
企业级 AI Agent 开发指南:基于函数计算 FC Sandbox 方案实现类 Chat Coding AI Agent
本文深入解析AI Agent系统架构,特别是以Sandbox为核心的落地实践。聚焦泛Chat模式下AI应用的挑战与解决方案,涵盖会话亲和性、隔离性、存储机制、会话恢复、资源弹性等关键技术点,阿里云函数计算(FC)为 AI Agent 系统在企业中的落地实践提供实际解决方案,展示了如何高效、安全地构建可扩展的 AI 应用系统。
|
5月前
|
存储 人工智能 安全
企业级 AI Agent 开发指南:基于函数计算 FC Sandbox 方案实现类 Chat Coding AI Agent
通过 Sandbox 与 Serverless 的深度融合,AI Agent 不再是“黑盒”实验,而是可被企业精准掌控的生产力工具。这种架构不仅适配当前 AI Agent 的动态交互特性,更为未来多模态 Agent、跨系统协作等复杂场景提供了可复用的技术底座。若您的企业正面临 AI Agent 规模化落地的挑战,不妨从 Sandbox 架构入手,结合函数计算 FC 的能力,快速验证并构建安全、高效、可扩展的 AI 应用系统。
|
6月前
|
数据采集 人工智能 定位技术
分享一个开源的MCP工具使用的AI Agent 支持常用的AI搜索/地图/金融/浏览器等工具
介绍一个开源可用的 MCP Tool Use 通用工具使用的 AI Agent (GitHub: https://github.com/AI-Agent-Hub/mcp-marketplace ,Web App https://agent.deepnlp.org/agent/mcp_tool_use,支持大模型从Open MCP Marketplace (http://deepnlp.org/store/ai-agent/mcp-server) 的1w+ 的 MCP Server的描述和 Tool Schema 里面,根据用户问题 query 和 工具 Tool描述的 相关性,选择出来可以满足
|
6月前
|
存储 人工智能 Serverless
AI Agent 运行时相比传统应用有什么不同:百家企业 AI 实践观察(二)
本文深入探讨了AI Agent运行时的核心挑战及解决方案,分析了AI Agent从理论走向实践过程中所面临的动态推理、资源成本与安全风险等问题,并详细介绍了阿里云函数计算FC如何作为AI Agent运行时及沙箱环境(Sandbox),有效应对脉冲式计算需求、突发性负载、数据隔离与会话亲和性等挑战。同时,文章结合典型场景,展示了函数计算FC在编码式与流程式AI Agent构建中的优势,涵盖Chat AI Agent、营销素材组装、仿真训练等应用,为AI Agent的高效、安全运行提供了完整的技术路径。
713 2
|
存储 人工智能 自然语言处理
AI经营|多Agent择优生成商品标题
商品标题中关键词的好坏是商品能否被主搜检索到的关键因素,使用大模型自动优化标题成为【AI经营】中的核心能力之一,本文讲述大模型如何帮助商家优化商品素材,提升商品竞争力。
1558 62
AI经营|多Agent择优生成商品标题
|
机器学习/深度学习 人工智能 自然语言处理
Gemini 2.0:谷歌推出的原生多模态输入输出 + Agent 为核心的 AI 模型
谷歌最新推出的Gemini 2.0是一款原生多模态输入输出的AI模型,以Agent技术为核心,支持多种数据类型的输入与输出,具备强大的性能和多语言音频输出能力。本文将详细介绍Gemini 2.0的主要功能、技术原理及其在多个领域的应用场景。
1349 20
Gemini 2.0:谷歌推出的原生多模态输入输出 + Agent 为核心的 AI 模型
|
人工智能 自然语言处理 前端开发
Director:构建视频智能体的 AI 框架,用自然语言执行搜索、编辑、合成和生成等复杂视频任务
Director 是一个构建视频智能体的 AI 框架,用户可以通过自然语言命令执行复杂的视频任务,如搜索、编辑、合成和生成视频内容。该框架基于 VideoDB 的“视频即数据”基础设施,集成了多个预构建的视频代理和 AI API,支持高度定制化,适用于开发者和创作者。
827 9
Director:构建视频智能体的 AI 框架,用自然语言执行搜索、编辑、合成和生成等复杂视频任务

热门文章

最新文章