from core.agentpress.tool import ToolResult, openapi_schema, tool_metadata
from core.sandbox.tool_base import SandboxToolsBase
from core.agentpress.thread_manager import ThreadManager
from core.utils.logger import logger
from core.services.http_client import get_http_client
from typing import List, Dict, Optional, Union, TYPE_CHECKING
import json
import os
from datetime import datetime
import re
import asyncio
from urllib.parse import unquote
if TYPE_CHECKING:
import httpx
@tool_metadata(
display_name="Presentations",
description="Create and manage stunning presentation slides",
icon="Presentation",
color="bg-orange-100 dark:bg-orange-800/50",
weight=70,
visible=True,
usage_guide="""
### PRESENTATION CREATION WORKFLOW
**šØ CRITICAL: This tool provides the create_slide function for presentations!**
- **ALWAYS** use create_slide when creating presentation slides
- **NEVER** use generic create_file to create presentation slides
- This tool is specialized for presentation creation with proper formatting, validation, and navigation
**šØ ABSOLUTE REQUIREMENT - NO SEARCHES BEFORE INITIALIZATION:**
- **DO NOT perform ANY web search, image search, or research BEFORE initializing the presentation tool**
- **MUST initialize the presentation tool FIRST** using initialize_tools
- **ONLY AFTER initialization**, follow the guide phases in exact order - Phase 1 ā Phase 2 ā Phase 3 ā Phase 4 ā Final Phase
- **MUST FOLLOW THE GUIDE BLINDLY** - execute each phase exactly as specified, in order, without skipping steps or doing work out of sequence
- The guide specifies exactly when to do searches (Phase 2 and Phase 3) - do NOT do them earlier
**DEFAULT: CUSTOM THEME (ALWAYS USE UNLESS USER EXPLICITLY REQUESTS TEMPLATE)**
Always create truly unique presentations with custom design systems based on the topic's actual brand colors and visual identity.
**EFFICIENCY RULES - CRITICAL:**
1. **Web/Image Search:** ALWAYS use batch mode with multiple queries - use web_search with multiple queries - ALL queries in ONE call
2. **Shell Commands:** Chain ALL folder creation + downloads in ONE command
3. **Task Updates:** ONLY update tasks when completing a PHASE. Batch updates in SAME call
**FOLDER STRUCTURE:**
```
presentations/
āāā images/ (shared images folder - used BEFORE presentation folder created)
ā āāā image1.png
āāā [title]/ (created when first slide made)
āāā slide01.html
```
- Images go to `presentations/images/` BEFORE the presentation folder exists
- Reference images using `../images/[filename]` (go up one level from presentation folder)
**CUSTOM THEME WORKFLOW (DEFAULT):**
Follow this workflow for every presentation. **Complete each phase fully before moving to the next.**
**Phase 1: Topic Confirmation** š
1. **Extract Topic from User Input**: Identify the presentation topic from the user's message. If the user has already provided clear topic information, proceed directly to Phase 2 with reasonable defaults:
- **Target audience**: Default to "General public" unless explicitly specified
- **Presentation goals**: Default to "Informative overview" unless explicitly specified
- **Requirements**: Use sensible defaults based on the topic
2. **Only Ask if Truly Ambiguous**: ONLY use the `ask` tool if:
- The topic is completely unclear or missing
- There are multiple valid interpretations that would significantly change the presentation
- The user explicitly requests clarification
**DO NOT ask for:**
- Target audience if not specified (use "General public" default)
- Presentation goals if not specified (use "Informative overview" default)
- Requirements if not specified (proceed with sensible defaults)
**Action-first approach**: When the topic is clear, immediately proceed to Phase 2. Don't ask unnecessary questions that delay creation.
**Phase 2: Theme and Content Planning** š
1. **Batch Web Search for Brand Identity**: Use `web_search` in BATCH MODE to research the topic's visual identity efficiently:
```
use web_search with multiple queries ([topic] brand colors, [topic] visual identity, [topic] official website design, [topic] brand guidelines)
```
**ALL queries in ONE call.** Search for specific brand colors, visual identity, and design elements:
- For companies/products: Search for their official website, brand guidelines, marketing materials
- For people: Search for their personal website, portfolio, professional profiles
- For topics: Search for visual identity, brand colors, or design style associated with the topic
2. **Define Context-Based Custom Color Scheme and Design Elements**: Based on the research findings, define the custom color palette, font families, typography, and layout patterns. **šØ CRITICAL REQUIREMENTS - NO GENERIC COLORS ALLOWED**:
- **USE ACTUAL TOPIC-SPECIFIC COLORS**: The color scheme MUST be based on the actual topic's brand colors, visual identity, or associated colors discovered in research, NOT generic color associations:
- **CORRECT APPROACH**: Research the actual topic's brand colors, visual identity, or design elements from official sources (website, brand guidelines, marketing materials, etc.) and use those specific colors discovered in research
- **WRONG APPROACH**: Using generic color associations like "blue for tech", "red for speed", "green for innovation", "purple-to-blue gradient for tech" without first checking what the actual topic's brand uses
- **For companies/products**: Use their actual brand colors from their official website, brand guidelines, or marketing materials discovered in research
- **For people**: Use your research to find their actual visual identity from relevant sources (website, portfolio, professional profiles, etc.)
- **For topics**: Use visual identity, brand colors, or design style associated with the topic discovered through research
- **Always verify first**: Never use generic industry color stereotypes without checking the actual topic's brand/visual identity
- **šØ ABSOLUTELY FORBIDDEN**: Do NOT use generic tech color schemes like "purple-to-blue gradient", "blue for tech", "green for innovation" unless your research specifically shows these are the topic's actual brand colors. Always verify first!
- **Research-Driven**: If the topic has specific brand colors discovered in research, you MUST use those. If research shows no specific brand colors exist, only then use colors that are contextually associated with the topic based on your research findings, but EXPLAIN why those colors are contextually appropriate based on your research.
- **No Generic Associations**: Avoid generic color meanings like "blue = tech", "red = speed", "green = growth", "purple-to-blue gradient = tech" unless your research specifically shows these colors are associated with the topic. These generic associations are FORBIDDEN.
- **For People Specifically**: If researching a person, you MUST use your research to find their actual color scheme and visual identity from relevant sources. Determine what sources are appropriate based on the person's profession, field, and what you discover in research (could be website, portfolio, professional profiles, social media, etc. - decide based on context). Only if you cannot find any visual identity, then use colors contextually appropriate based on their field/work, but EXPLAIN the reasoning and what research you did.
- **Match Visual Identity**: Font families, typography, and layout patterns should also align with the topic's actual visual identity if discoverable, or be contextually appropriate based on research
- **Document Your Theme**: When defining the theme, you MUST document:
- Where you found the color information (specific URLs, portfolio link, brand website, etc.)
- If no specific colors were found, explain what research you did and why you chose the colors based on context
- Never use generic tech/industry color schemes without explicit research justification
**ā Update tasks: Mark Phase 2 complete + Start Phase 3 in ONE call**
**Phase 3: Research and Content Planning** š
**Complete ALL steps in this phase, including ALL image downloads, before proceeding to Phase 4.**
1. **Batch Content Research**: Use `web_search` in BATCH MODE to thoroughly research the topic efficiently:
```
use web_search with multiple queries ([topic] history background, [topic] key features characteristics, [topic] statistics data facts, [topic] significance importance impact)
```
**ALL queries in ONE call.** Then use `web_scrape` to gather detailed information, facts, data, and insights. The more context you gather, the better you can select appropriate images.
2. **Create Content Outline** (MANDATORY): Develop a structured outline that maps out content for each slide. Focus on one main idea per slide. For each image needed, note the specific query. **CRITICAL**: Use your research context to create intelligent, context-aware image queries that are **TOPIC-SPECIFIC**, not generic:
- **CORRECT APPROACH**: Always include the actual topic name, brand, product, person's name, or entity in your queries:
- `"[actual topic name] [specific attribute]"`
- `"[actual brand] [specific element]"`
- `"[actual person name] [relevant context]"`
- `"[actual location] [specific feature]"`
- **WRONG APPROACH**: Generic category queries without the specific topic name (e.g., using "technology interface" instead of including the actual topic name, or "tropical destination" instead of including the actual location name)
- **For companies/products**: Include the actual company/product name in queries (e.g., "[company name] headquarters", "[product name] interface")
- **For people**: ALWAYS include the person's full name in the query along with relevant context
- **For topics/locations**: ALWAYS include the topic/location name in the query along with specific attributes
- Match image queries to the EXACT topic being researched, not just the category
- Use specific names, brands, products, people, locations you discovered in research
- **Document which slide needs which image** - you'll need this mapping in Phase 4
3. **Batch Image Search** (MANDATORY): Use `image_search` in BATCH MODE with ALL topic-specific queries:
```
use image_search with multiple queries ([topic] exterior view, [topic] interior detail, [topic] key feature, [topic] overview context) and num_results 2
```
**ALL queries in ONE call.** Results now include enriched metadata for each image:
```json
{
"batch_results": [{
"query": "...",
"images": [{
"imageUrl": "https://...",
"title": "Image title",
"width": 1920,
"height": 1080,
"description": "Text extracted from the image",
"source": "example.com"
}, ...]
}, ...]
}
```
- **TOPIC-SPECIFIC IMAGES REQUIRED**: Images MUST be specific to the actual topic/subject being researched, NOT generic category images
- **For companies/products**: ALWAYS include the actual company/product name in every image query
- **For people**: ALWAYS include the person's full name in every image query along with relevant context
- **For topics/locations**: ALWAYS include the topic/location name in every image query along with specific attributes
- Use context-aware queries based on your research that include the specific topic name/brand/product/person/location
- Set `num_results=2` to get 2-3 relevant results per query for selection flexibility
4. **Extract and Select Topic-Specific Image URLs** (MANDATORY): From the batch results, extract image URLs and **select the most contextually appropriate image** for each slide based on:
- **TOPIC SPECIFICITY FIRST**: Does it show the actual topic/subject being researched or just a generic category? Always prefer images that directly show the specific topic, brand, product, person, or entity over generic category images
- **USE OCR TEXT FOR CONTEXT**: Check the `description` field - if it contains relevant text (brand names, product names, labels), this confirms the image is topic-specific
- **USE DIMENSIONS FOR LAYOUT**: Check `width` and `height` to determine image orientation:
- **Landscape (width > height)**: Best for full-width backgrounds, hero images, banner sections
- **Portrait (height > width)**: Best for side panels, profile photos, vertical accent images
- **Square-ish**: Flexible for various layouts
- How well it matches the slide content and your research findings
- How well it aligns with your research findings (specific names, brands, products discovered)
- How well it fits the presentation theme and color scheme
- Visual quality and relevance
5. **Single Command - Folder + All Downloads + Verify** (MANDATORY): Download ALL images in ONE chained command:
```bash
mkdir -p presentations/images && wget "URL1" -O presentations/images/slide1_exterior.jpg && wget "URL2" -O presentations/images/slide2_interior.jpg && wget "URL3" -O presentations/images/slide3_detail.jpg && wget "URL4" -O presentations/images/slide4_overview.jpg && ls -lh presentations/images/
```
**ONE COMMAND** creates folder, downloads ALL images, and verifies. NEVER use multiple separate commands!
- **CRITICAL**: Do NOT use `2>/dev/null` to suppress errors - you need to see if downloads fail
- **CRITICAL**: After the `ls -lh` command, VERIFY that ALL expected image files are present
- **CRITICAL**: If any image download fails, you MUST retry or find alternative image URLs
- **CRITICAL**: Count the files in `ls` output and ensure it matches the number of images you attempted to download
- Use descriptive filenames that clearly identify the image's purpose (e.g., `slide1_intro_image.jpg`, `slide2_team_photo.jpg`)
- Preserve or add appropriate file extensions (.jpg, .png, etc.) based on the image URL
- If using `curl` instead of `wget`, use: `curl -L "URL" -o filename` (without suppressing errors)
6. **Document Image Mapping with Metadata** (MANDATORY): Create a clear mapping of slide number ā image filename with layout info for reference in Phase 4:
- Slide 1 ā `slide1_exterior.jpg` (1920x1080, landscape, OCR: "Company Name")
- Slide 2 ā `slide2_interior.jpg` (800x1200, portrait, OCR: "Product Label")
- Slide 3 ā `slide3_team.jpg` (1000x1000, square, no text)
- etc.
- **INCLUDE METADATA**: For each image, note:
- Dimensions (width x height) from image_search results
- Orientation (landscape/portrait/square)
- OCR text summary (if any relevant text was detected)
- Planned placement (background, side panel, hero image, etc.)
- **CRITICAL VERIFICATION**: After `ls -lh`, count the files and ensure the number matches the number of images you attempted to download
- **CRITICAL VERIFICATION**: Check that ALL expected filenames appear in the `ls` output
- **CRITICAL**: If any image is missing, you MUST retry the download or find alternative image URLs - do NOT proceed to Phase 4 with missing images
- Confirm every expected image file exists and is accessible from the `ls` output
**ā Update tasks: Mark Phase 3 complete + Start Phase 4 in ONE call**
**Phase 4: Slide Creation** (USE AS MANY IMAGES AS POSSIBLE)
**Only start after Phase 3 checkpoint - all images must be downloaded and verified.**
1. **Create Slides in PARALLEL** (MANDATORY): Use the `create_slide` tool to create ALL slides simultaneously using parallel execution. **DO NOT create slides one-by-one sequentially** - create them all at once in parallel for efficiency:
**šØ CRITICAL - EXACT PARAMETER NAMES REQUIRED:**
- **MUST use**: `presentation_name` (string) - Name of the presentation folder
- **MUST use**: `slide_number` (integer) - Slide number starting from 1
- **MUST use**: `slide_title` (string) - Title of this specific slide
- **MUST use**: `content` (string) - HTML body content for the slide
- **OPTIONAL**: `presentation_title` (string) - Main title of the presentation (defaults to "Presentation")
- **ā NEVER use**: `file_path` - This parameter does NOT exist! Use `presentation_name` instead.
**Example correct call:**
```
create_slide(
presentation_name="my_presentation",
slide_number=1,
slide_title="Introduction",
content="
...
",
presentation_title="My Awesome Presentation"
)
```
- Prepare all slide content first (based on your outline from Phase 3)
- Call `create_slide` for ALL slides in parallel (e.g., slide 1, 2, 3, 4, 5 all at once)
- This dramatically speeds up presentation creation
- All styling MUST be derived from the **custom color scheme and design elements** defined in Phase 2. Use the custom color palette, fonts, and layout patterns consistently across all slides.
- **CRITICAL - PRESENTATION DESIGN NOT WEBSITE**: Design for fixed 1920x1080 dimensions. DO NOT use responsive design patterns (no `width: 100%`, `max-width`, `vw/vh` units, or responsive breakpoints). This is a PRESENTATION SLIDE, not a website - use fixed pixel dimensions, absolute positioning, and fixed layouts. **FORBIDDEN**: Multi-column grid layouts with cards (like 2x3 grids of feature cards) - these look like websites. Use centered, focused layouts with large content instead.
2. **Use Downloaded Images with Smart Placement**: For each slide that requires images, **MANDATORY**: Use the images that were downloaded in Phase 3. **CRITICAL PATH REQUIREMENTS**:
- **Image Path Structure**: Images are in `presentations/images/` (shared folder), and slides are in `presentations/[title]/` (presentation folder)
- **Reference Path**: Use `../images/[filename]` to reference images (go up one level from presentation folder to shared images folder)
- Example: If image is `presentations/images/slide1_intro_image.jpg` and slide is `presentations/[presentation-title]/slide_01.html`, use path: `../images/slide1_intro_image.jpg`
**šÆ IMAGE PLACEMENT BASED ON DIMENSIONS** (use metadata from Phase 3):
- **Landscape Images (width > height)**:
- Use as full-width backgrounds with `width: 100%; object-fit: cover`
- Or as hero images spanning 60-80% of slide width
- Great for banner sections at top/bottom of slides
- **Portrait Images (height > width)**:
- Use in side panels (30-40% of slide width)
- Or as accent images alongside text content
- Never stretch to full width - looks distorted
- **Square Images**:
- Flexible - work well in grids or as centered focal points
- Good for profile photos, logos, icons
**š¤ USE OCR TEXT FOR CONTEXT**:
- If `description` contains brand names, product names, or labels - this confirms the image is relevant
- Use OCR text to inform caption text or surrounding content
- If OCR reveals unexpected text (wrong brand, irrelevant content), consider using a different image
- **CRITICAL REQUIREMENTS**:
- **DO NOT skip images** - if a slide outline specified images, they must be included in the slide HTML
- Use the exact filenames you verified in Phase 3 (e.g., `../images/slide1_intro_image.jpg`)
- Include images in `` tags within your slide HTML content
- Match image dimensions to layout - don't force portrait images into landscape slots
- If an image doesn't appear, verify the filename matches exactly (including extension) and the path is correct (`../images/` not `images/`)
**Final Phase: Deliver** šÆ
1. **Review and Verify**: Before presenting, review all slides to ensure they are visually consistent and that all content is displayed correctly.
2. **Deliver the Presentation**: Use the `complete` tool with the **first slide** (e.g., `presentations/[name]/slide_01.html`) attached to deliver the final, polished presentation to the user. **IMPORTANT**: Only attach the opening/first slide to keep the UI tidy - the presentation card will automatically appear and show the full presentation when any presentation slide file is attached.
### TYPOGRAPHY & ICONS
**Google Fonts (Inter) is pre-loaded** - All slides automatically use Inter font family for modern, clean typography. No need to load additional fonts unless specifically required.
**Icons & Graphics:**
- **Use emoji** for icons: š š š” š ā” šÆ ā ā¤ļø š„ š š š¤ š š etc.
- **Unicode symbols** for simple graphics: ā ā ā ā ⢠ā ā ā” ā
- **NO Font Awesome** - Use emoji or Unicode symbols instead
- For bullet points, use emoji or styled divs with Unicode symbols
**Typography Guidelines:**
- **Titles**: 48-72px (bold, weight: 700-900)
- **Subtitles**: 32-42px (semi-bold, weight: 600-700)
- **Headings**: 28-36px (semi-bold, weight: 600)
- **Body**: 20-24px (normal, weight: 400-500)
- **Small**: 16-18px (light, weight: 300-400)
- **Line Height**: 1.5-1.8 for readability
### DESIGN PRINCIPLES
**Visual Consistency:**
- Maintain consistent color scheme throughout entire presentation
- Use theme colors: Primary (backgrounds), Secondary (subtle backgrounds), Accent (highlights), Text (all text)
- Consistent spacing: 40-60px between major sections, 20-30px between related items
**Content Richness:**
- Include real data: specific numbers, percentages, metrics
- Add quotes & testimonials for credibility
- Use case examples to illustrate concepts
- Include emotional hooks and storytelling elements
**Layout Best Practices:**
- Focus on 1-2 main ideas per slide
- Limit to 3-5 bullet points max
- Use `overflow: hidden` on containers
- Always use `box-sizing: border-box` on containers with padding
- Embrace whitespace - don't fill every pixel
- **CRITICAL**: Use centered, focused layouts - NOT multi-column card grids (which look like websites)
- For multiple items: Use simple vertical lists or 2-3 large items side-by-side (NOT 6+ cards in grid)
- Think PowerPoint slide: Large title, centered content, minimal elements - NOT website feature sections
**Dimension Requirements:**
- Slide size: 1920x1080 pixels (16:9 aspect ratio)
- Container padding: Maximum 40px on all edges
- **CRITICAL**: Never add conflicting body styles - template already sets fixed dimensions
"""
)
class SandboxPresentationTool(SandboxToolsBase):
"""
Per-slide HTML presentation tool for creating presentation slides.
Each slide is created as a basic HTML document without predefined CSS styling.
Users can include their own CSS styling inline or in style tags as needed.
"""
def __init__(self, project_id: str, thread_manager: ThreadManager):
super().__init__(project_id, thread_manager)
self.presentations_dir = "presentations"
# Path to built-in templates (on the backend filesystem, not in sandbox)
self.templates_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates", "presentations")
async def _ensure_presentations_dir(self):
"""Ensure the presentations directory exists"""
full_path = f"{self.workspace_path}/{self.presentations_dir}"
try:
await self.sandbox.fs.create_folder(full_path, "755")
except:
pass
async def _ensure_presentation_dir(self, presentation_name: str):
"""Ensure a specific presentation directory exists"""
safe_name = self._sanitize_filename(presentation_name)
presentation_path = f"{self.workspace_path}/{self.presentations_dir}/{safe_name}"
try:
await self.sandbox.fs.create_folder(presentation_path, "755")
except:
pass
return safe_name, presentation_path
def _sanitize_filename(self, name: str) -> str:
"""Convert presentation name to safe filename"""
return "".join(c for c in name if c.isalnum() or c in "-_").lower()
def _create_slide_html(self, slide_content: str, slide_number: int, total_slides: int, presentation_title: str) -> str:
"""Create a basic HTML document with Google Fonts"""
html_template = f"""
{presentation_title} - Slide {slide_number}
{slide_content}
"""
return html_template
async def _load_presentation_metadata(self, presentation_path: str):
"""Load presentation metadata, create if doesn't exist"""
metadata_path = f"{presentation_path}/metadata.json"
try:
metadata_content = await self.sandbox.fs.download_file(metadata_path)
return json.loads(metadata_content.decode())
except:
# Create default metadata
return {
"presentation_name": "",
"title": "Presentation",
"description": "",
"slides": {},
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat()
}
async def _save_presentation_metadata(self, presentation_path: str, metadata: Dict):
"""Save presentation metadata"""
metadata["updated_at"] = datetime.now().isoformat()
metadata_path = f"{presentation_path}/metadata.json"
await self.sandbox.fs.upload_file(json.dumps(metadata, indent=2).encode(), metadata_path)
def _load_template_metadata(self, template_name: str) -> Dict:
"""Load metadata from a template on the backend filesystem"""
metadata_path = os.path.join(self.templates_dir, template_name, "metadata.json")
try:
with open(metadata_path, 'r') as f:
return json.load(f)
except Exception as e:
return {}
def _read_template_slide(self, template_name: str, slide_filename: str) -> str:
"""Read a slide HTML file from a template"""
slide_path = os.path.join(self.templates_dir, template_name, slide_filename)
try:
with open(slide_path, 'r') as f:
return f.read()
except Exception as e:
return ""
async def _copy_template_to_workspace(self, template_name: str, presentation_name: str) -> str:
"""Copy entire template directory structure to workspace using os.walk
Returns:
The presentation path in the workspace
"""
await self._ensure_sandbox()
await self._ensure_presentations_dir()
template_path = os.path.join(self.templates_dir, template_name)
safe_name = self._sanitize_filename(presentation_name)
presentation_path = f"{self.workspace_path}/{self.presentations_dir}/{safe_name}"
# Ensure presentation directory exists
await self._ensure_presentation_dir(presentation_name)
# Use os.walk to recursively copy all files
copied_files = []
for root, dirs, files in os.walk(template_path):
# Calculate relative path from template root
rel_path = os.path.relpath(root, template_path)
# Create corresponding directory in workspace (if not root)
if rel_path != '.':
target_dir = os.path.join(presentation_path, rel_path)
target_dir_path = target_dir.replace('\\', '/') # Normalize path separators
try:
await self.sandbox.fs.create_folder(target_dir_path, "755")
except:
pass # Directory might already exist
else:
target_dir_path = presentation_path
# Copy all files
for file in files:
source_file = os.path.join(root, file)
rel_file_path = os.path.relpath(source_file, template_path)
target_file = os.path.join(presentation_path, rel_file_path).replace('\\', '/')
try:
with open(source_file, 'rb') as f:
file_content = f.read()
await self.sandbox.fs.upload_file(file_content, target_file)
copied_files.append(rel_file_path)
except Exception as e:
# Log error but continue with other files
print(f"Error copying {rel_file_path}: {str(e)}")
# Update metadata.json with correct paths for the new presentation
metadata = await self._load_presentation_metadata(presentation_path)
template_metadata = self._load_template_metadata(template_name)
# Update presentation name and preserve slides structure
metadata["presentation_name"] = presentation_name
metadata["title"] = template_metadata.get("title", presentation_name)
metadata["description"] = template_metadata.get("description", "")
metadata["created_at"] = datetime.now().isoformat()
metadata["updated_at"] = datetime.now().isoformat()
# Update slide paths to match new presentation name
if "slides" in template_metadata:
updated_slides = {}
for slide_num, slide_data in template_metadata["slides"].items():
slide_filename = slide_data.get("filename", f"slide_{int(slide_num):02d}.html")
updated_slides[str(slide_num)] = {
"title": slide_data.get("title", f"Slide {slide_num}"),
"filename": slide_filename,
"file_path": f"{self.presentations_dir}/{safe_name}/{slide_filename}",
"preview_url": f"{self.workspace_path}/{self.presentations_dir}/{safe_name}/{slide_filename}",
"created_at": datetime.now().isoformat()
}
metadata["slides"] = updated_slides
# Save updated metadata
await self._save_presentation_metadata(presentation_path, metadata)
return presentation_path
def _extract_style_from_html(self, html_content: str) -> Dict:
"""Extract CSS styles and design patterns from HTML content"""
style_info = {
"fonts": [],
"colors": [],
"layout_patterns": [],
"key_css_classes": []
}
# Extract font imports
font_imports = re.findall(r'@import url\([\'"]([^\'"]+)[\'"]', html_content)
font_families = re.findall(r'font-family:\s*[\'"]?([^;\'"]+)[\'"]?', html_content)
style_info["fonts"] = list(set(font_imports + font_families))
# Extract color values (hex, rgb, rgba)
hex_colors = re.findall(r'#[0-9A-Fa-f]{3,6}', html_content)
rgb_colors = re.findall(r'rgba?\([^)]+\)', html_content)
style_info["colors"] = list(set(hex_colors + rgb_colors))[:20] # Limit to top 20
# Extract class names
class_names = re.findall(r'class=[\'"]([^\'"]+)[\'"]', html_content)
style_info["key_css_classes"] = list(set(class_names))[:30]
# Identify layout patterns
if 'display: flex' in html_content or 'display:flex' in html_content:
style_info["layout_patterns"].append("flexbox")
if 'display: grid' in html_content or 'display:grid' in html_content:
style_info["layout_patterns"].append("grid")
if 'position: absolute' in html_content:
style_info["layout_patterns"].append("absolute positioning")
return style_info
@openapi_schema({
"type": "function",
"function": {
"name": "list_templates",
"description": "List all available presentation templates. ** CRITICAL: ONLY USE WHEN USER EXPLICITLY REQUESTS TEMPLATES ** **WHEN TO USE**: Call this tool ONLY when the user explicitly asks for templates (e.g., 'use a template', 'show me templates', 'use the minimalist template', 'I want to use a template'). **WHEN TO SKIP**: Do NOT call this tool by default. The default workflow is CUSTOM THEME which creates truly unique designs. Do NOT call this tool if: (1) the user requests a presentation without mentioning templates (use custom theme instead), (2) the user explicitly requests a custom theme, or (3) the user wants a unique/original design. **IMPORTANT**: Templates are optional - only use when explicitly requested. The default is always a custom, unique design based on the topic's actual brand colors and visual identity.",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
}
})
async def list_templates(self) -> ToolResult:
"""List all available presentation templates with metadata and images"""
try:
templates = []
# Check if templates directory exists
if not os.path.exists(self.templates_dir):
return self.success_response({
"message": "No templates directory found",
"templates": []
})
# List all subdirectories in templates folder
for item in os.listdir(self.templates_dir):
template_path = os.path.join(self.templates_dir, item)
if os.path.isdir(template_path) and not item.startswith('.'):
# Load metadata for this template
metadata = self._load_template_metadata(item)
# Check if image.png exists
image_path = os.path.join(template_path, "image.png")
has_image = os.path.exists(image_path)
template_info = {
"id": item,
"name": item, # Use folder name directly
"has_image": has_image
}
templates.append(template_info)
if not templates:
return self.success_response({
"message": "No templates found",
"templates": []
})
# Sort templates by name
templates.sort(key=lambda x: x["name"])
return self.success_response({
"message": f"Found {len(templates)} template(s)",
"templates": templates,
"note": "Use load_template_design with a template id to get the complete design reference. If you don't like any of these templates, you can choose a custom theme instead."
})
except Exception as e:
return self.fail_response(f"Failed to list templates: {str(e)}")
@openapi_schema({
"type": "function",
"function": {
"name": "load_template_design",
"description": "Load complete design reference from a presentation template including all slide HTML and extracted style patterns (colors, fonts, layouts). If presentation_name is provided, the entire template will be copied to /workspace/presentations/{presentation_name}/ so you can edit ONLY the text content using full_file_rewrite - you MUST preserve 100% of the CSS styling, colors, fonts, and HTML structure. The visual design must remain identical; only text/data should change. Otherwise, use this template as DESIGN INSPIRATION ONLY - study the visual styling, CSS patterns, and layout structure to create your own original slides with similar aesthetics but completely different content.",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to load (e.g., 'textbook')"
},
"presentation_name": {
"type": "string",
"description": "Optional: Name for the presentation. If provided, the entire template will be copied to /workspace/presentations/{presentation_name}/ so you can edit the slides directly. All files from the template (including HTML slides, images, and subdirectories) will be copied."
}
},
"required": ["template_name"]
}
}
})
async def load_template_design(self, template_name: str, presentation_name: Optional[str] = None) -> ToolResult:
"""Load complete template design including all slides HTML and extracted style patterns.
If presentation_name is provided, copies the entire template to workspace for editing.
"""
try:
template_path = os.path.join(self.templates_dir, template_name)
if not os.path.exists(template_path):
return self.fail_response(f"Template '{template_name}' not found")
# If presentation_name is provided, copy template to workspace
presentation_path = None
if presentation_name:
try:
presentation_path = await self._copy_template_to_workspace(template_name, presentation_name)
except Exception as e:
return self.fail_response(f"Failed to copy template to workspace: {str(e)}")
# Load template metadata
metadata = self._load_template_metadata(template_name)
if not metadata or "slides" not in metadata:
return self.fail_response(f"Template '{template_name}' has no metadata or slides")
# Extract all slides HTML
slides = []
all_fonts = set()
all_colors = set()
all_layout_patterns = set()
all_css_classes = set()
for slide_num, slide_data in sorted(metadata["slides"].items(), key=lambda x: int(x[0])):
slide_filename = slide_data.get("filename", f"slide_{int(slide_num):02d}.html")
html_content = self._read_template_slide(template_name, slide_filename)
if html_content:
# Add slide info
slides.append({
"slide_number": int(slide_num),
"title": slide_data.get("title", f"Slide {slide_num}"),
"filename": slide_filename,
"html_content": html_content,
"html_length": len(html_content)
})
# Extract style information from this slide
style_info = self._extract_style_from_html(html_content)
all_fonts.update(style_info["fonts"])
all_colors.update(style_info["colors"])
all_layout_patterns.update(style_info["layout_patterns"])
all_css_classes.update(style_info["key_css_classes"])
if not slides:
return self.fail_response(f"Could not load any slides from template '{template_name}'")
# Build response
response_data = {
"template_name": template_name,
"template_title": metadata.get("title", template_name),
"description": metadata.get("description", ""),
"total_slides": len(slides),
"slides": slides,
"design_system": {
"fonts": list(all_fonts)[:10], # Top 10 fonts
"color_palette": list(all_colors)[:20], # Top 20 colors
"layout_patterns": list(all_layout_patterns),
"common_css_classes": list(all_css_classes)[:30] # Top 30 classes
}
}
# Add workspace path info if template was copied
if presentation_path:
safe_name = self._sanitize_filename(presentation_name)
response_data["presentation_path"] = f"{self.presentations_dir}/{safe_name}"
response_data["presentation_name"] = presentation_name.lower()
response_data["copied_to_workspace"] = True
response_data["note"] = f"Template copied to /workspace/{self.presentations_dir}/{safe_name}/. **CRITICAL**: Use full_file_rewrite to edit slides. ONLY change text content - preserve ALL CSS, styling, colors, fonts, and HTML structure 100% exactly. The template's visual design must remain identical. This template provides ALL slides and extracted design patterns in one response."
response_data["usage_instructions"] = {
"purpose": "TEMPLATE COPIED TO WORKSPACE - Edit ONLY the content, preserve ALL design/styling",
"do": [
"Use full_file_rewrite tool to edit the copied slide HTML files",
"ONLY modify text content inside HTML elements (headings, paragraphs, list items, data values)",
"Replace placeholder/example data with actual presentation content",
"Keep ALL ,