youtube-summarizer/backend/integrations/example_integration.py

266 lines
9.0 KiB
Python

#!/usr/bin/env python3
"""
Example integration script demonstrating YouTube Summarizer agent framework usage
Run this script to see how different agent frameworks can be used
"""
import asyncio
import json
import sys
import os
from pathlib import Path
# Add backend to path for imports
backend_path = Path(__file__).parent.parent
sys.path.insert(0, str(backend_path))
from agent_framework import (
AgentFactory, AgentOrchestrator, FrameworkType,
create_youtube_agent_orchestrator, quick_process_video
)
from langchain_tools import get_youtube_langchain_tools
def print_section(title: str):
"""Print formatted section header"""
print(f"\n{'='*60}")
print(f" {title}")
print(f"{'='*60}")
def print_result(result: dict, indent: int = 0):
"""Print formatted result"""
spacing = " " * indent
if isinstance(result, dict):
for key, value in result.items():
if isinstance(value, dict):
print(f"{spacing}{key}:")
print_result(value, indent + 1)
elif isinstance(value, list) and len(value) > 3:
print(f"{spacing}{key}: [{len(value)} items]")
else:
print(f"{spacing}{key}: {value}")
else:
print(f"{spacing}{result}")
async def demo_langchain_tools():
"""Demonstrate LangChain tools"""
print_section("LangChain Tools Demo")
try:
# Get tools
tools = get_youtube_langchain_tools()
print(f"Available tools: {len(tools)}")
for i, tool in enumerate(tools):
print(f"{i+1}. {tool.name}: {tool.description[:80]}...")
# Test transcript extraction
if tools:
print("\nTesting transcript extraction tool...")
transcript_tool = tools[0]
result = await transcript_tool._arun("https://youtube.com/watch?v=dQw4w9WgXcQ")
print("Transcript extraction result:")
try:
parsed_result = json.loads(result)
print_result(parsed_result)
except json.JSONDecodeError:
print(result[:200] + "..." if len(result) > 200 else result)
# Test summarization
if len(tools) > 1:
print("\nTesting summarization tool...")
summary_tool = tools[1]
result = await summary_tool._arun(
"https://youtube.com/watch?v=dQw4w9WgXcQ",
summary_type="brief"
)
print("Summarization result:")
try:
parsed_result = json.loads(result)
print_result(parsed_result)
except json.JSONDecodeError:
print(result[:200] + "..." if len(result) > 200 else result)
except Exception as e:
print(f"Error in LangChain tools demo: {e}")
async def demo_agent_factory():
"""Demonstrate AgentFactory"""
print_section("Agent Factory Demo")
try:
# Check available frameworks
available = AgentFactory.get_available_frameworks()
print(f"Available frameworks: {[f.value for f in available]}")
# Create agents for each available framework
agents = {}
for framework in available:
try:
agent = AgentFactory.create_agent(framework)
agents[framework] = agent
print(f"✓ Created {framework.value} agent")
except Exception as e:
print(f"✗ Failed to create {framework.value} agent: {e}")
# Test video processing with each agent
test_url = "https://youtube.com/watch?v=dQw4w9WgXcQ"
for framework, agent in agents.items():
print(f"\nTesting {framework.value} agent...")
result = await agent.process_video(test_url, "summarize")
print(f"{framework.value} result:")
print_result(result)
except Exception as e:
print(f"Error in agent factory demo: {e}")
async def demo_orchestrator():
"""Demonstrate AgentOrchestrator"""
print_section("Agent Orchestrator Demo")
try:
# Create orchestrator
orchestrator = create_youtube_agent_orchestrator()
# Get capabilities summary
capabilities = orchestrator.get_capabilities_summary()
print("Orchestrator capabilities:")
print_result(capabilities)
# Test video processing
test_url = "https://youtube.com/watch?v=dQw4w9WgXcQ"
print(f"\nProcessing video: {test_url}")
result = await orchestrator.process_video(test_url, task_type="summarize")
print("Processing result:")
print_result(result)
# Test batch processing
video_urls = [
"https://youtube.com/watch?v=dQw4w9WgXcQ",
"https://youtube.com/watch?v=abc123xyz789"
]
print(f"\nBatch processing {len(video_urls)} videos...")
batch_result = await orchestrator.process_batch(video_urls, task_type="transcribe")
print("Batch result:")
print_result(batch_result)
# Compare frameworks (if multiple available)
if len(orchestrator.agents) > 1:
print(f"\nComparing frameworks for: {test_url}")
comparison = await orchestrator.compare_frameworks(test_url)
print("Framework comparison:")
print_result(comparison)
except Exception as e:
print(f"Error in orchestrator demo: {e}")
async def demo_quick_functions():
"""Demonstrate quick utility functions"""
print_section("Quick Functions Demo")
try:
test_url = "https://youtube.com/watch?v=dQw4w9WgXcQ"
# Test quick processing with different frameworks
frameworks = ["langchain", "crewai", "autogen"]
for framework in frameworks:
print(f"\nQuick processing with {framework}...")
result = await quick_process_video(test_url, "summarize", framework)
print(f"{framework.title()} result:")
print_result(result)
except Exception as e:
print(f"Error in quick functions demo: {e}")
async def demo_advanced_features():
"""Demonstrate advanced integration features"""
print_section("Advanced Features Demo")
try:
# Create orchestrator
orchestrator = create_youtube_agent_orchestrator()
# Test with different video types and parameters
test_cases = [
{
"url": "https://youtube.com/watch?v=dQw4w9WgXcQ",
"task": "transcribe",
"params": {"source": "youtube"}
},
{
"url": "https://youtube.com/watch?v=abc123xyz789",
"task": "summarize",
"params": {"summary_type": "comprehensive", "format": "structured"}
}
]
for i, test_case in enumerate(test_cases, 1):
print(f"\nTest case {i}: {test_case['task']} - {test_case['url']}")
result = await orchestrator.process_video(
test_case["url"],
task_type=test_case["task"],
**test_case["params"]
)
print(f"Result for test case {i}:")
print_result(result)
except Exception as e:
print(f"Error in advanced features demo: {e}")
def print_usage():
"""Print usage instructions"""
print_section("YouTube Summarizer Agent Integration Demo")
print("""
This script demonstrates the YouTube Summarizer agent framework integration.
Features demonstrated:
1. LangChain Tools - Direct tool usage for transcript/summarization
2. Agent Factory - Creating framework-specific agents
3. Agent Orchestrator - Multi-framework management
4. Quick Functions - Simple utility functions
5. Advanced Features - Complex parameter handling
The demo will run with mock/fallback implementations if external frameworks
(LangChain, CrewAI, AutoGen) are not installed.
Run: python example_integration.py
""")
async def main():
"""Main demo function"""
print_usage()
# Run all demos
try:
await demo_langchain_tools()
await demo_agent_factory()
await demo_orchestrator()
await demo_quick_functions()
await demo_advanced_features()
print_section("Demo Complete")
print("All integration demos completed successfully!")
print("\nNext steps:")
print("1. Install framework dependencies (langchain, crewai, autogen)")
print("2. Configure API keys for real backend services")
print("3. Integrate with your specific agent workflows")
print("4. Customize agent capabilities and context")
except KeyboardInterrupt:
print("\n\nDemo interrupted by user")
except Exception as e:
print(f"\nDemo error: {e}")
print("This is expected if framework dependencies are not installed")
if __name__ == "__main__":
# Run the async demo
asyncio.run(main())