效率提升1000%!开源agent大模型智能体强势崛起,动动嘴皮子,教程自动生成!

"GPT-4弱爆了?"开源大模型智能体强势崛起,动动嘴皮子,教程自动生成!等等,你说啥?自动写教程?还开源?! 🤯🤯🤯

没错!今天小编要给大家介绍一个颠覆认知的AI神器——大模型智能体!它不仅能听懂人话,还能根据你的需求,自动生成各种高质量教程!先别急着划走,这可不是标题党,看完保证你直呼“真香”!

"卷"出新高度:AI时代,大模型智能体才是真·生产力!

还在为写教程熬夜秃头?还在为创意枯竭抓耳挠腮?还在为平台流量焦虑不安?醒醒吧!AI时代,效率才是王道!

 



想想看,以前写一篇教程,你需要:

1.  选题策划:绞尽脑汁想读者爱看啥(这可能是最难的😭)
2.  资料搜集:各种网站、论坛、论文,翻个底朝天(眼睛都要瞎了😵)
3.  结构梳理:搭框架、列大纲,逻辑要清晰(脑细胞不够用啊😫)
4.  内容填充:逐字逐句敲键盘,写到手抽筋(颈椎病又要犯了😖)
5.  排版美化:调整格式、插入图片,力求美观(审美跟不上啊😩)
6.  反复修改:检查错别字、润色语句,精益求精(改到怀疑人生🤮)

一套流程下来,没个几天根本搞不定!更别提还要保证教程质量,吸引读者点赞、评论、转发了…

但现在,有了大模型智能体,一切都变得so easy!你只需要:

告诉它你想写什么主题的教程!

就这么简单?!是的,就这么简单!剩下的,交给AI!😎

大模型智能体:比你更懂你的“写作神器”

什么是大模型智能体?简单来说,它就是一个基于大型语言模型(LLM)构建的“超级大脑”,拥有强大的自然语言处理能力,可以理解、生成、推理、规划…

"等等,这不就是GPT-4吗?"

这位同学,你很敏锐!👍 但大模型智能体可不仅仅是GPT-4的“平替”,它更像是一个“超级加强版”!

*   更懂你:通过深度学习,智能体可以理解你的需求,甚至比你更懂你自己!
*   更专业:针对特定领域(比如写教程),智能体可以进行专门优化,输出更专业的内容!
*   更高效:智能体可以自动完成绝大部分写作任务,效率提升N倍!
*   更开放:开源大模型智能体,意味着你可以自由定制、自由发挥!

开源福利:从零打造你的专属教程生成智能体!

心动了吗?想不想拥有自己的专属教程生成智能体?别急,小编这就手把手教你!

核心代码揭秘:

# 导入必要的库
import os
from dotenv import load_dotenv
import json
import re
from typing import List
from zigent.agents import ABCAgent, BaseAgent
from zigent.llm.agent_llms import LLM
from zigent.commons import TaskPackage
from zigent.actions.BaseAction import BaseAction
from duckduckgo_search import DDGS

# 加载环境变量
load_dotenv()
# 从环境变量中读取api_key
api_key = os.getenv('MOTA_API_KEY')
base_url = "https://api-inference.modelscope.cn/v1/"
chat_model = "deepseek-ai/DeepSeek-V3"

# 初始化LLM
llm = LLM(api_key=api_key, base_url=base_url, model_name=chat_model)

# ... (此处省略部分代码, 关注公众号:XXXX,回复“教程智能体”获取完整代码)

代码解读(看不懂没关系,直接跳到下一步):

这段代码主要做了几件事:

1.  引入关键模块: 就像搭积木,先把需要的“零件”准备好。
2.  配置环境: 告诉程序去哪里找“大脑”(LLM)。
3.  初始化LLM: 让“大脑”开始运转。

有了这些准备,我们就可以开始构建智能体了!

两大核心Action:让智能体“动”起来!

如果说LLM是智能体的“大脑”,那么Action就是智能体的“手脚”。我们通过定义不同的Action,让智能体能够执行各种任务。

1.  WriteDirectoryAction:生成教程目录结构

class WriteDirectoryAction(BaseAction):
        """Generate tutorial directory structure action"""
        def __init__(self) -> None:
            action_name = "WriteDirectory"
            action_desc = "Generate tutorial directory structure"
            params_doc = {
                "topic": "(Type: string): The tutorial topic name",
                "language": "(Type: string): Output language (default: 'Chinese')"
            }
            super().__init__(action_name, action_desc, params_doc)
            
        def __call__(self, **kwargs):
            topic = kwargs.get("topic", "")
            language = kwargs.get("language", "Chinese")
           
            directory_prompt = f"""
            请为主题"{topic}"生成教程目录结构,要求:
            1. 输出语言必须是{language}
            2. 严格按照以下字典格式输出: {{"title": "xxx", "directory": [{{"章节1": ["小节1", "小节2"]}}, {{"章节2": ["小节3", "小节4"]}}]}}
            3. 目录层次要合理,包含主目录和子目录
            4. 每个目录标题要有实际意义
            5. 不要有多余的空格或换行
            """
           
            # 调用 LLM 生成目录
            directory_data = llm.run({"prompt": directory_prompt})
            try:
                directory_data = json.loads(directory_data)
            except:
                directory_data = {"title": topic, "directory": []}
               
            return {
                "topic": topic,
                "language": language,
                "directory_data": directory_data
            }



    这个Action的作用是根据用户输入的主题,生成一个合理的教程目录结构。就像写书前先列个大纲,让内容更有条理。

    99%的人不知道的细节:

    *   `directory_prompt`变量定义了生成目录的指令,这里面有很多技巧,比如:
        *   明确输出语言:避免AI“自作主张”用英文输出。
        *   指定输出格式:让AI按照我们想要的格式输出,方便后续处理。
        *   强调目录层次:确保生成的目录结构清晰、合理。
    *   `llm.run()`函数负责调用LLM,让“大脑”根据指令生成目录。
    *   `try...except...`语句块用于处理可能出现的错误,让程序更健壮。

2.  WriteContentAction:生成教程详细内容

class WriteContentAction(BaseAction):
        """Generate tutorial content action"""
        def __init__(self) -> None:
            action_name = "WriteContent"
            action_desc = "Generate detailed tutorial content based on directory structure"
            params_doc = {
                "title": "(Type: string): The section title",
                "chapter": "(Type: string): The chapter title",
                "directory_data": "(Type: dict): The complete directory structure",
                "language": "(Type: string): Output language (default: 'Chinese')"
            }
            super().__init__(action_name, action_desc, params_doc)
           
        def __call__(self, **kwargs):
            title = kwargs.get("title", "")
            chapter = kwargs.get("chapter", "")
            language = kwargs.get("language", "Chinese")
            directory_data = kwargs.get("directory_data", {})
           
            content_prompt = f"""
            请为教程章节生成详细内容:
            教程标题: {directory_data.get('title', '')}
            章节: {chapter}
            小节: {title}
           
            要求:
            1. 内容要详细且准确
            2. 如果需要代码示例,请按标准规范提供
            3. 使用 Markdown 格式
            4. 输出语言必须是{language}
            5. 内容长度适中,通常在500-1000字之间
            """
           
            # 调用 LLM 生成内容
            content = llm.run({"prompt": content_prompt})
            return content



    这个Action的作用是根据目录结构,生成每个章节的详细内容。就像写书的每个章节,把具体内容填充进去。

    3个关键点,让你的教程更受欢迎:

    *   `content_prompt`变量定义了生成内容的指令,这里面也有很多讲究:
        *   明确章节信息:告诉AI要写哪个章节的内容。
        *   强调内容质量:要求内容详细、准确,避免AI“胡编乱造”。
        *   指定输出格式:使用Markdown格式,方便后续排版。
        *   控制内容长度:避免AI“长篇大论”,影响阅读体验。
    *   `llm.run()`函数同样负责调用LLM,生成内容。
    *   返回值`content`就是生成的教程内容。

智能体“总指挥”:TutorialAssistant

有了“手脚”,我们还需要一个“指挥官”,来协调各个Action,完成整个教程生成任务。

 

class TutorialAssistant(BaseAgent):
    """Tutorial generation assistant that manages directory and content creation"""
    def __init__(
        self,
        llm: llm,
        language: str = "Chinese"
    ):
        name = "TutorialAssistant"
        role = """You are a professional tutorial writer. You can create well-structured,
        comprehensive tutorials on various topics. You excel at organizing content logically
        and explaining complex concepts clearly."""
       
        super().__init__(
            name=name,
            role=role,
            llm=llm,
        )
       
        self.language = language
        self.directory_action = WriteDirectoryAction()
        self.content_action = WriteContentAction()
   
        # Add example for the tutorial assistant
        self._add_tutorial_example()
       
    def _generate_tutorial(self, directory_data: Dict) -> str:
        """Generate complete tutorial content based on directory structure"""
        full_content = []
        title = directory_data["title"]
        full_content.append(f"# {title}\n")
       
        # Generate table of contents
        full_content.append("## 目录\n")
        for idx, chapter in enumerate(directory_data["directory"], 1):
            for chapter_title, sections in chapter.items():
                full_content.append(f"{idx}. {chapter_title}")
                for section_idx, section in enumerate(sections, 1):
                    full_content.append(f"   {idx}.{section_idx}. {section}")
        full_content.append("\n---\n")
       
        # Generate content for each section
        for chapter in directory_data["directory"]:
            for chapter_title, sections in chapter.items():
                for section in sections:
                    content = self.content_action(
                        title=section,
                        chapter=chapter_title,
                        directory_data=directory_data,
                        language=self.language
                    )
                    full_content.append(content)
                    full_content.append("\n---\n")
       
        return "\n".join(full_content)

    def __call__(self, task: TaskPackage):
        """Process the tutorial generation task"""
        # Extract topic from task
        topic = task.instruction.split("Create a ")[-1].split(" tutorial")[0]
        if not topic:
            topic = task.instruction
           
        # Generate directory structure
        directory_result = self.directory_action(
            topic=topic,
            language=self.language
        )

        print(directory_result)
       
        # Generate complete tutorial
        tutorial_content = self._generate_tutorial(directory_result["directory_data"])

        # Save the result
        task.answer = tutorial_content
        task.completion = "completed"
       
        return task

    def _add_tutorial_example(self):
        """Add an illustration example for the tutorial assistant"""
        exp_task = "Create a Python tutorial for beginners"
        exp_task_pack = TaskPackage(instruction=exp_task)
        topic = "Python基础教程"

        act_1 = AgentAct(
            name=ThinkAct.action_name,
            params={INNER_ACT_KEY: """First, I'll create a directory structure for the Python tutorial,
            then generate detailed content for each section."""}
        )
        obs_1 = "OK. I'll start with the directory structure."

        act_2 = AgentAct(
            name=self.directory_action.action_name,
            params={
                "topic": topic,
                "language": self.language
            }
        )
        obs_2 = """{"title": "Python基础教程", "directory": [
            {"第一章:Python介绍": ["1.1 什么是Python", "1.2 环境搭建"]},
            {"第二章:基础语法": ["2.1 变量和数据类型", "2.2 控制流"]}
        ]}"""

        act_3 = AgentAct(
            name=self.content_action.action_name,
            params={
                "title": "什么是Python",
                "chapter": "第一章:Python介绍",
                "directory_data": json.loads(obs_2),
                "language": self.language
            }
        )
        obs_3 = """# 第一章:Python介绍\n## 什么是Python\n\nPython是一种高级编程语言..."""

        act_4 = AgentAct(
            name=FinishAct.action_name,
            params={INNER_ACT_KEY: "Tutorial structure and content generated successfully."}
        )
        obs_4 = "Tutorial generation task completed successfully."

        exp_act_obs = [(act_1, obs_1), (act_2, obs_2), (act_3, obs_3), (act_4, obs_4)]
       
        self.prompt_gen.add_example(
            task=exp_task_pack,
            action_chain=exp_act_obs
        )

保姆级教程,手把手教你“调教”AI:

1.  角色设定:告诉AI它扮演什么角色,比如“专业教程写手”。
2.  实例化Action:把前面定义的“手脚”装到智能体身上。
3.  \_generate\_tutorial()函数:负责根据目录结构,调用`content_action`生成完整教程内容。
4.  \_\_call\_\_()函数:负责接收用户输入的任务,调用`directory_action`生成目录,然后调用`_generate_tutorial()`生成完整教程。
5.  \_add\_tutorial\_example() 加入范例,帮助模型理解如何生成。

实战演练:一句话生成你的专属教程!

if __name__ == "__main__":
    assistant = TutorialAssistant(llm=llm)

     # 交互式生成教程
    FLAG_CONTINUE = True
    while FLAG_CONTINUE:
        input_text = input("What tutorial would you like to create?\n")
        task = TaskPackage(instruction=input_text)
        result = assistant(task)
        print("\nGenerated Tutorial:\n")
        print(result.answer)

        # 创建输出目录
        output_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        os.makedirs(output_dir, exist_ok=True)
       
        # 保存文件
        output_file = os.path.join(output_dir, f"{input_text}.md")
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(result.answer)
        if input("\nDo you want to create another tutorial? (y/n): ").lower() != "y":
            FLAG_CONTINUE = False

运行这段代码,你只需要输入你想写的教程主题,比如“Python入门教程”、“JavaScipt高级技巧”、“如何用AI写代码”… 然后,见证奇迹的时刻到了!

"这也太酷了吧!"

我知道你在想什么!😎

进阶玩法:打造你的专属“爆款”教程!

掌握了基本操作,你还可以尝试更多进阶玩法:

*   定制prompt:修改`directory_prompt`和`content_prompt`,让AI生成更符合你要求的教程。
*   增加Action:比如增加一个“自动配图”的Action,让你的教程更生动。
*   优化模型:使用更强大的LLM,或者对模型进行微调,让AI更懂你的写作风格。
*   接入其他工具:比如接入搜索引擎,让AI自动搜索最新资料。

评论区互动:

*   你最想用AI生成什么主题的教程?🤔
*   你觉得AI写教程还有哪些潜力可以挖掘?🤩
*   你认为AI会取代人类写作者吗?😨

大胆说出你的想法,点赞最高的评论,送神秘大礼包! 🎁🎁🎁

分享预告:

觉得这篇文章有用?别忘了点赞、评论、转发三连!👍💬↗️

免责声明:

*   本文提供的代码仅供学习交流,请勿用于非法用途。
*   AI生成的内容可能存在偏差,请谨慎使用。
*   请遵守相关法律法规,尊重知识产权。

友情提示:

道路千万条,安全第一条;
AI虽好用,学习不能少!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值