Learn AI Agent Development in 11 Days: Day 9 – Create Your Custom Tutorial Writing Agent with Zigent Framework

In this age of information explosion, tutorial writing has become an important skill. Whether it’s technical sharing, knowledge dissemination, or education and training, high-quality tutorials can bring great value to users. Today, we will teach you step by step how to create a tutorial writing agent using the Zigent framework, allowing it to automatically generate high-quality tutorial content!

1. What is a Tutorial Writing Agent?

A tutorial writing agent is an automated tool based on a large language model (LLM) that can automatically generate complete tutorial content based on the topic input by the user. Its core functions include:

  1. Generating Tutorial Directory: Generate a reasonable directory structure based on the topic.
  2. Chunk-wise Content Generation: Generate detailed content chunk by chunk according to the secondary headings of the directory.
  3. Assembling Complete Tutorial: Assemble the directory and content into a complete tutorial document.

Through this chunked design, the agent can effectively solve the limitations of large models in processing long texts, ensuring that the generated tutorial content is both comprehensive and detailed.

2. Design Approach

Our tutorial writing agent mainly consists of the following steps:

  1. Generate Directory: Generate the tutorial’s directory structure using the large model.
  2. Chunk-wise Content Generation: Generate detailed content chunk by chunk according to the secondary headings of the directory.
  3. Assemble Complete Tutorial: Assemble the directory and content into a complete tutorial document.

This chunked design not only effectively solves the limitations of large models in processing long texts but also ensures that the generated tutorial content is both comprehensive and detailed.

3. Code Implementation

1. Preparation

First, we need to prepare the relevant configuration for the large model. With the Zigent framework, we can easily call the large model to generate tutorial content.

import os
from dotenv import load_dotenv
from zigent.llm.agent_llms import LLM

# Load environment variables
load_dotenv()
# Read api_key from environment variables
api_key = os.getenv('ZISHU_API_KEY')
base_url = "http://114.114.114.114:8008/v1"
chat_model = "glm-4-flash"

llm = LLM(api_key=api_key, base_url=base_url, model_name=chat_model)

2. Define Action Class for Generating Tutorial Directory

Next, we define a <span>WriteDirectoryAction</span> class to generate the tutorial’s directory structure. This class will call the large model to generate a reasonable directory based on the user input topic.

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"""
        Please generate the tutorial directory structure for the topic "{topic}", requirements:
        1. Output language must be {language}
        2. Strictly output in the following dictionary format: {{"title": "xxx", "directory": [{{"Chapter 1": ["Section 1", "Section 2"]}}, {{"Chapter 2": ["Section 3", "Section 4"]}}]}}
        3. The directory hierarchy must be reasonable, including main and subdirectories
        4. Each directory title must have actual meaning
        5. No extra spaces or line breaks
        """
        
        # Call LLM to generate directory
        directory_data = llm.run(directory_prompt)
        try:
            directory_data = json.loads(directory_data)
        except:
            directory_data = {"title": topic, "directory": []}
            
        return {
            "topic": topic,
            "language": language,
            "directory_data": directory_data
        }

3. Define Action Class for Generating Tutorial Content

With the directory ready, we need to generate detailed content for each chapter. The <span>WriteContentAction</span> class is used to accomplish this task.

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"""
        Please generate detailed content for the tutorial chapter:
        Tutorial Title: {directory_data.get('title', '')}
        Chapter: {chapter}
        Section: {title}
        
        Requirements:
        1. Content must be detailed and accurate
        2. If code examples are needed, please provide them according to standard specifications
        3. Use Markdown format
        4. Output language must be {language}
        5. Content length should be moderate, typically between 500-1000 words
        """
        
        # Call LLM to generate content
        content = llm.run(content_prompt)
        return content

4. Define the Tutorial Writing Agent

Finally, we integrate the logic for directory generation and content generation into a single agent. The <span>TutorialAssistant</span> class is responsible for managing the entire tutorial generation process.

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("## Directory\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]
        ifnot 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 Basics"

        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 Basics", "directory": [
            {"Chapter 1: Introduction to Python": ["1.1 What is Python", "1.2 Setting up the Environment"]},
            {"Chapter 2: Basic Syntax": ["2.1 Variables and Data Types", "2.2 Control Flow"]}
        ]}"""

        act_3 = AgentAct(
            name=self.content_action.action_name,
            params={
                "title": "What is Python",
                "chapter": "Chapter 1: Introduction to Python",
                "directory_data": json.loads(obs_2),
                "language": self.language
            }
        )
        obs_3 = """# Chapter 1: Introduction to Python\n## What is Python\n\nPython is a high-level programming language..."""

        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
        )

5. Interactive Operation to Call the Tutorial Writing Agent

Finally, we can call this tutorial writing agent through interactive operation. Users can input the tutorial topic they want to create, and the agent will automatically generate the corresponding tutorial content and save the results to a local file.

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

     # Interactive tutorial generation
    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)

        # Create output directory
        output_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        os.makedirs(output_dir, exist_ok=True)
        
        # Save file
        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

6. Run the Agent

Input “Big Data Audit Lesson Plan” and “Write a Lesson Plan on Artificial Intelligence and Auditing”, and the agent will automatically generate the corresponding tutorial content and save the results to a local file.

4. Conclusion

Through the Zigent framework, we successfully implemented a tutorial writing agent. It can not only generate a reasonable directory structure based on the user’s input topic but also generate detailed tutorial content chunk by chunk and save the final result as a Markdown file. This chunked design not only solves the limitations of large models in processing long texts but also ensures that the generated tutorial content is both comprehensive and detailed.

In the future, we can further optimize this agent, such as adding more interactive features, supporting multiple output formats, or even integrating it into online education platforms. We hope this article can provide you with some inspiration to help you create your own tutorial writing agent!

Learn AI Agent Development in 11 Days, Day 8: Implementing Multi-Agent Philosophers with Zigent: A Philosophical Dialogue Across Time and Space

Learn AI Agent Development in 11 Days, Day 7: Introduction to Zigent: Build Your Intelligent Search Agent.

Learn AI Agent Development in 11 Days, Day 6: Agents with Web Search Capabilities.

Learn AI Agent Development in 11 Days, Day 5: Integrating RAG with Agents.

Learn AI Agent Development in 11 Days, Day 4: Creating Agents with Llama-index.

Learn AI Agent Development in 11 Days, Day 3: Implementing Grading Agents.

Learn AI Agent Development in 11 Days, Day 2: Building a Simple Agent from Scratch.

Learn AI Agent Development in 11 Days, Day 1: Choosing an Agent Framework – wow-agent.

Learn AI Agent Development in 11 Days, Day 0: What is an Agent.

Leave a Comment