youtube-summarizer/backend/examples/template_usage_example.py

212 lines
8.2 KiB
Python

"""Example demonstrating the template-based analysis system."""
import asyncio
from pathlib import Path
import sys
# Add parent directories to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
sys.path.insert(0, str(Path(__file__).parent.parent))
from backend.services.template_driven_agent import (
TemplateDrivenAgent,
TemplateAnalysisRequest
)
from backend.services.template_defaults import create_default_registry
from backend.models.analysis_templates import TemplateType
async def demonstrate_educational_templates():
"""Demonstrate the educational template system with beginner/expert/scholarly lenses."""
print("🎓 Educational Template System Demonstration")
print("=" * 60)
# Sample content to analyze
sample_content = """
Machine Learning is a subset of artificial intelligence that enables computers to learn and improve
from experience without being explicitly programmed. At its core, ML algorithms build mathematical
models based on training data to make predictions or decisions. The process involves feeding data
to an algorithm, which identifies patterns and relationships within that data. These patterns are
then used to make predictions about new, unseen data.
There are three main types of machine learning: supervised learning (using labeled data),
unsupervised learning (finding hidden patterns in unlabeled data), and reinforcement learning
(learning through trial and error with rewards). Popular applications include image recognition,
natural language processing, recommendation systems, and autonomous vehicles.
The field has seen explosive growth due to increases in computing power, availability of big data,
and advances in algorithms like deep neural networks. However, challenges remain around bias,
interpretability, and ensuring AI systems are fair and ethical.
"""
# Initialize template agent with default registry
registry = create_default_registry()
agent = TemplateDrivenAgent(template_registry=registry)
print("📝 Analyzing content using Educational Template Set...")
print("Content: Machine Learning overview")
print()
# Analyze with educational template set
try:
results = await agent.analyze_with_template_set(
content=sample_content,
template_set_id="educational_perspectives",
context={
"topic": "Machine Learning",
"content_type": "educational article"
}
)
print("✅ Analysis Complete!")
print(f"📊 Processed {len(results)} perspectives")
print()
# Display results for each template
template_order = ["educational_beginner", "educational_expert", "educational_scholarly"]
for template_id in template_order:
if template_id in results:
result = results[template_id]
print(f"🔍 {result.template_name} Analysis")
print("-" * 50)
print(f"📈 Confidence Score: {result.confidence_score:.0%}")
print(f"⏱️ Processing Time: {result.processing_time_seconds:.2f}s")
print()
print("🎯 Key Insights:")
for i, insight in enumerate(result.key_insights, 1):
print(f" {i}. {insight}")
print()
print("📋 Detailed Analysis:")
print(result.analysis)
print()
print("=" * 60)
print()
# Generate synthesis
print("🔗 Generating Educational Synthesis...")
synthesis = await agent.synthesize_results(
results=results,
template_set_id="educational_perspectives"
)
if synthesis:
print(f"🎓 {synthesis.template_name}")
print("-" * 50)
print(f"📈 Confidence Score: {synthesis.confidence_score:.0%}")
print()
print("🎯 Unified Learning Insights:")
for i, insight in enumerate(synthesis.key_insights, 1):
print(f" {i}. {insight}")
print()
print("📋 Complete Educational Journey:")
print(synthesis.analysis)
print()
except Exception as e:
print(f"❌ Error during analysis: {e}")
# For demonstration, show what the templates look like
educational_set = registry.get_template_set("educational_perspectives")
if educational_set:
print("📚 Available Educational Templates:")
for template_id, template in educational_set.templates.items():
print(f"{template.name} ({template.complexity_level})")
print(f" Focus: {', '.join(template.analysis_focus[:3])}...")
print(f" Audience: {template.target_audience}")
print()
async def demonstrate_template_customization():
"""Demonstrate template customization capabilities."""
print("🛠️ Template Customization Demonstration")
print("=" * 60)
registry = create_default_registry()
# Show available templates
print("📋 Available Template Types:")
for template_type in TemplateType:
templates = registry.list_templates(template_type)
print(f"{template_type.value.title()}: {len(templates)} templates")
print()
# Show template details
print("🔍 Educational Template Details:")
educational_templates = registry.list_templates(TemplateType.EDUCATIONAL)
for template in educational_templates:
if template.complexity_level:
print(f" 📚 {template.name}")
print(f" Complexity: {template.complexity_level.value}")
print(f" Audience: {template.target_audience}")
print(f" Tone: {template.tone}")
print(f" Depth: {template.depth}")
print(f" Focus Areas: {len(template.analysis_focus)} areas")
print(f" Variables: {list(template.variables.keys())}")
print()
# Show how templates can be customized
beginner_template = registry.get_template("educational_beginner")
if beginner_template:
print("🎯 Template Variable Customization Example:")
print(f"Original variables: {beginner_template.variables}")
custom_context = {
"topic": "Quantum Computing",
"content_type": "introductory video",
"examples_count": 3,
"use_analogies": True
}
try:
rendered_prompt = beginner_template.render_prompt(custom_context)
print("✨ Customized prompt preview:")
print(rendered_prompt[:200] + "..." if len(rendered_prompt) > 200 else rendered_prompt)
except Exception as e:
print(f"Template rendering example: {e}")
async def main():
"""Run the template system demonstration."""
print("🚀 Template-Based Multi-Agent Analysis System")
print("=" * 80)
print("Demonstrating customizable templates for different perspectives")
print("=" * 80)
print()
# Demonstrate educational templates
await demonstrate_educational_templates()
print()
print("=" * 80)
print()
# Demonstrate template customization
await demonstrate_template_customization()
print()
print("✅ Demonstration Complete!")
print("🎓 The template system provides:")
print(" • Beginner's Lens: Simplified, accessible explanations")
print(" • Expert's Lens: Professional depth and strategic insights")
print(" • Scholarly Lens: Academic rigor and research connections")
print(" • Educational Synthesis: Progressive learning pathway")
print(" • Full Customization: Swappable templates and variables")
if __name__ == "__main__":
# Note: This is a demonstration script
# In practice, you would use a real AI service
print("📝 Note: This is a structural demonstration")
print("Real AI analysis requires proper API keys and service configuration")
print()
# Run async demonstration
asyncio.run(main())