Skip to content

add PPTMaker #1830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions metagpt/actions/generate_latex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : gernerate_latex.py
@Time : 2025/05/20 20:15:13
@Author : Deng Mingyi
@Desc : Action to generate LaTeX content for presentations. Action to validate LaTeX content.
"""
from metagpt.prompts.PPTmaker import (
SYSTEM_PROMPT,
USER_CONTENT,
TEXT_VALIDATION_PROMPT,
USER_VALIDATION_CONTENT,
)
from metagpt.actions import Action
from metagpt.logs import logger
from typing import List
from metagpt.schema import Message


class LatexGeneratorAction(Action):
"""
Action to generate LaTeX content for presentations.
"""

name: str = "latexgenerator"
description: str = """
This agent generates complete, high-quality LaTeX documents with a focus on Beamer presentations. It accepts topic-specific input and produces fully self-contained LaTeX source code, including all required packages, structures, and rich content elements such as equations, figures, and formatted text. The agent ensures completeness by avoiding any placeholders or incomplete sections.

In addition to generation, the agent supports iterative refinement: it evaluates and improves the generated LaTeX code based on validation feedback to ensure correctness, formatting quality, and logical structure. The final output is ready for immediate compilation and professional presentation use.
"""

async def generate(self, request: str, history_messages: List[Message]) -> str:
"""
Generate LaTeX content.
Args:
request: Initial user request or refined request with feedback.
history_messages: List of historical messages for context.
Returns:
Generated LaTeX code as string
"""
logger.info(f"Actual max_tokens used: {self.llm.config.max_token}")
logger.info(f"Executing {self.name} Action: Generating LaTeX content for request \n'{request}'")

system_content = SYSTEM_PROMPT
history_str = "\n".join([f"{msg.role}: {msg.content}" for msg in history_messages])
user_content = USER_CONTENT.format(request=request, history=history_str)

generated_latex = await self._aask(user_content, [system_content])

logger.debug(f"Generated LaTeX content: {generated_latex}")
return generated_latex

async def run(self, request: str, history: List[Message]) -> str:
"""Execute the current action"""
return await self.generate(request, history)


class ValidatorAction(Action):
"""
Action to validate LaTeX content.
"""

name: str = "validator"
description: str = """
This tool evaluates the quality and completeness of a subtask result against a set of predefined criteria.
It checks whether the result fully satisfies task requirements, maintains high quality in terms of clarity, accuracy, and formatting,
and determines whether improvements have been made in comparison to prior versions.
If the result is satisfactory or improvements are minimal, it returns "No further feedback." or "The step result has already reached the requirement.".
Otherwise, it provides detailed feedback and a revised version of the result that meets all requirements and is ready for downstream use.
"""

async def validate(self, request: str, current_latex_to_validate: str, history_messages: List[Message]) -> str:
"""
Validate the generated content.
Args:
request: Initial user request.
current_latex_to_validate: The LaTeX content to be validated.
history_messages: List of historical messages for context.
Returns:
Validation feedback string
"""
logger.info(f"Executing {self.name} Action: Validating current content")

system_content = TEXT_VALIDATION_PROMPT
history_str = "\n".join([f"{msg.role}: {msg.content}" for msg in history_messages])
validation_input_for_prompt = f"Initial Request: {request}\n\nLaTeX to Validate:\n{current_latex_to_validate}\n\nConversation History:\n{history_str}"

user_content = USER_VALIDATION_CONTENT.format(request=validation_input_for_prompt, history="") # Adjust as per prompt needs

feedback = await self._aask(user_content, [system_content])
logger.debug(f"Validation feedback: {feedback}")

return feedback

async def run(self, request: str, history: List[Message]) -> str:
"""Execute the current action.
'request' here is the 'input_for_action' passed from PPTMaker._act,
which is self.optimized_result for ValidatorAction.
"""
initial_user_request = history[0].content if history else ""
content_to_validate = request
return await self.validate(initial_user_request, content_to_validate, history)
94 changes: 94 additions & 0 deletions metagpt/prompts/PPTmaker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
SYSTEM_PROMPT = """
You are a LaTeX Beamer Presentation Generator. Your task is to generate a complete, informative, and ready-to-compile Beamer slide deck in LaTeX, based on the task description and any past drafts or feedback.

## Goals:
- Each slide must be **self-contained**, meaning the audience should understand the slide without external explanations.
- The presentation must **teach** or **explain** the topic in sufficient detail using structured LaTeX slides.
- Each slide must contribute meaningfully to the overall structure and flow of the presentation.



## Requirements:

1. Preamble & Setup
- Start with `\\documentclass{beamer}`.
- Use packages such as `amsmath`, `amsfonts`, and `graphicx`.
- Use the `Madrid` theme unless otherwise specified.
- Include full metadata: `\\title{}`, `\\author{}`, and `\\date{\\today}`.

2. Slide Design
- MUST mark each slide with a comment indicating its number, `% Slide 1`, `% Slide 2`.
- - Slides must follow a **logical order** that ensures smooth flow and coherence.
- AIM for a **minimum of 300 words per slide* Contain **enough detail** (text, bullets, equations, definitions, or examples)

3. Depth of Content
- For important concept, include motivation, problem, intuitive explanation, mathematical formulation or equation (if applicable)
- practical example or application can also be included

4. Completeness & Validity
- Reflect all provided feedback and correct deficiencies from past versions.
- MUST No placeholders or incomplete content.
- Your output will be used directly. Therefore, it must be a ready-to-use result.
- Include `\\end{document}`.
- Ensure valid LaTeX syntax.

5. Style & Clarity
- Maintain consistent formatting and indentation.
- Use bullet points or short paragraphs for clarity.
- Keep math readable and contextualized with supporting text.

**Only output the final LaTeX source code. Do not include explanations, notes, or comments.**
"""

USER_CONTENT = """
## Task
{request}

## Past Drafts & Feedback
{history}
"""

TEXT_VALIDATION_PROMPT = """
You are a task result evaluator responsible for determining whether a task result meets the task requirements, if not, you need to improve it.

# Objective and Steps
1. **Completeness and Quality Check:**
- Verify that the result includes all required elements of the task.
- Evaluate whether the output meets overall quality criteria (accuracy, clarity, formatting, and completeness).

2. **Change Detection:**
- If this is a subsequent result, compare it with previous iterations.
- If the differences are minimal or the result has not significantly improved, consider it "good enough" for finalization.

3. **Feedback and Escalation:**
- If the result meets the criteria or the improvements are negligible compared to previous iterations, return **"No further feedback"**.
- Otherwise, provide **direct and precise feedback** and **output the improved result in the required format** for finalization.

4. **Ensure Completeness:**
- Your output must meet all requirements of the task.
- Include all necessary details so that the output is self-contained and can be directly used as input for downstream tasks.

5. **Do NOT:**
- Leave any section with placeholders (e.g., "TODO", "Add content here").
- Include any commentary or reminders to the writer or user (e.g., "We can add more later").
- Output partial slides or omit essential details assuming future input.

- **If the result meets the standard:**
- Return **"No further feedback."**.

- **If the result does not meet the standard:**
- add detailed jusification for the change start with "here are some feedbacks" and directly write an improved new result start with "here are the changes".

# Note that: Any output containing incomplete sections, placeholders is not allowed.
"""

USER_VALIDATION_CONTENT = """
## Current Task Requirement:
{request}

---

## Current Task Latest Result:
{history}
"""

Loading
Loading