import os import json import requests from dotenv import load_dotenv from openai import OpenAI from flask import Flask, render_template_string, request # Load environment variables load_dotenv() # Initialize API clients OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") openai_client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") app = Flask(__name__) # ---------- Agent implementations ---------- class TopicAgent: def generate_outline(self, topic, duration, difficulty): if not openai_client: print("OpenAI API not set - using enhanced mock data for outline.") return self._mock_outline(topic, duration, difficulty) try: response = openai_client.chat.completions.create( model="gpt-4-turbo", messages=[ { "role": "system", "content": ( "You are an expert corporate trainer with 20+ years of experience creating " "high-value workshops for Fortune 500 companies. Create a professional workshop outline that " "includes: 1) Clear learning objectives, 2) Practical real-world exercises, " "3) Industry case studies, 4) Measurable outcomes. Format as JSON." ) }, { "role": "user", "content": ( f"Create a comprehensive {duration}-hour {difficulty} workshop outline on '{topic}' for corporate executives. " "Structure: title, duration, difficulty, learning_goals (3-5 bullet points), " "modules (5-7 modules). Each module should have: title, duration, learning_points (3 bullet points), " "case_study (real company example), exercises (2 practical exercises)." ) } ], temperature=0.3, max_tokens=1500, response_format={"type": "json_object"} ) return json.loads(response.choices[0].message.content) except Exception as e: print(f"Error during OpenAI outline generation: {e}. Falling back to mock outline.") return self._mock_outline(topic, duration, difficulty) def _mock_outline(self, topic, duration, difficulty): return { "title": f"Mastering {topic} for Business Impact", "duration": f"{duration} hours", "difficulty": difficulty, "learning_goals": [ "Apply advanced techniques to real business challenges", "Measure ROI of prompt engineering initiatives", "Develop organizational prompt engineering standards", "Implement ethical AI governance frameworks" ], "modules": [ { "title": "Strategic Foundations", "duration": "45 min", "learning_points": [ "Business value assessment framework", "ROI calculation models", "Stakeholder alignment strategies" ], "case_study": "How JPMorgan reduced operational costs by 37% with prompt optimization", "exercises": [ "Calculate potential ROI for your organization", "Develop stakeholder communication plan" ] }, { "title": "Advanced Pattern Engineering", "duration": "60 min", "learning_points": [ "Chain-of-thought implementations", "Self-correcting prompt architectures", "Domain-specific pattern libraries" ], "case_study": "McKinsey's knowledge management transformation", "exercises": [ "Design pattern library for your industry", "Implement self-correction workflow" ] } ] } class ContentAgent: def generate_content(self, outline): if not openai_client: print("OpenAI API not set - using enhanced mock data for content.") return self._mock_content(outline) try: response = openai_client.chat.completions.create( model="gpt-4-turbo", messages=[ { "role": "system", "content": ( "You are a senior instructional designer creating premium corporate training materials. " "Develop comprehensive workshop content with: 1) Practitioner-level insights, " "2) Actionable frameworks, 3) Real-world examples, 4) Practical exercises. " "Avoid generic AI content - focus on business impact." ) }, { "role": "user", "content": ( f"Create premium workshop content for this outline: {json.dumps(outline)}. " "For each module: " "1) Detailed script (executive summary, 3 key concepts, business applications) " "2) Speaker notes (presentation guidance) " "3) 3 discussion questions with executive-level responses " "4) 2 practical exercises with solution blueprints " "Format as JSON." ) } ], temperature=0.4, max_tokens=3000, response_format={"type": "json_object"} ) return json.loads(response.choices[0].message.content) except Exception as e: print(f"Error during OpenAI content generation: {e}. Falling back to mock content.") return self._mock_content(outline) def _mock_content(self, outline): return { "workshop_title": outline.get("title", "Premium AI Workshop"), "modules": [ { "title": "Strategic Foundations", "script": ( "## Executive Summary\n" "This module establishes the business case for advanced prompt engineering, " "focusing on measurable ROI and stakeholder alignment.\n\n" "### Key Concepts:\n" "1. **Value Assessment Framework**: Quantify potential savings and revenue opportunities\n" "2. **ROI Calculation Models**: Custom models for different industries\n" "3. **Stakeholder Alignment**: Executive communication strategies\n\n" "### Business Applications:\n" "- Cost reduction in customer service operations\n" "- Acceleration of R&D processes\n" "- Enhanced competitive intelligence" ), "speaker_notes": [ "Emphasize real dollar impact - use JPMorgan case study numbers", "Show ROI calculator template", "Highlight C-suite communication strategies" ], "discussion_questions": [ { "question": "How could prompt engineering impact your bottom line?", "response": "Typical results: 30-40% operational efficiency gains, 15-25% innovation acceleration" } ], "exercises": [ { "title": "ROI Calculation Workshop", "instructions": "Calculate potential savings using our enterprise ROI model", "solution": "Template: (Current Cost × Efficiency Gain) - Implementation Cost" } ] } ] } class SlideAgent: def generate_slides(self, content): if not openai_client: print("OpenAI API not set - using enhanced mock slides.") return self._professional_slides(content) try: response = openai_client.chat.completions.create( model="gpt-4-turbo", messages=[ { "role": "system", "content": ( "You are a McKinsey-level presentation specialist. Create professional slides with: " "1) Clean, executive-friendly design 2) Data visualization frameworks " "3) Action-oriented content 4) Brand-compliant styling. " "Use Marp Markdown format with the 'gaia' theme." ) }, { "role": "user", "content": ( f"Create a boardroom-quality slide deck for: {json.dumps(content)}. " "Structure: Title slide, module slides (objective, 3 key points, case study, exercise), " "summary slide. Include placeholders for data visualization." ) } ], temperature=0.2, max_tokens=2500 ) return response.choices[0].message.content except Exception as e: print(f"Error during slide generation: {e}. Using mock slides.") return self._professional_slides(content) def _professional_slides(self, content): return f"""--- marp: true theme: gaia class: lead paginate: true backgroundColor: #fff backgroundImage: url('https://marp.app/assets/hero-background.svg') --- # {content.get('workshop_title', 'Executive AI Workshop')} ## Transforming Business Through Advanced AI --- ## Module 1: Strategic Foundations ### Driving Measurable Business Value  - **ROI Framework**: Quantifying impact - **Stakeholder Alignment**: Executive buy-in strategies - **Implementation Roadmap**: Phased adoption plan --- ## Case Study: Financial Services Transformation ### JPMorgan Chase | Metric | Before | After | Improvement | |--------|--------|-------|-------------| | Operation Costs | $4.2M | $2.6M | 38% reduction | | Process Time | 14 days | 3 days | 79% faster | | Error Rate | 8.2% | 0.4% | 95% reduction | --- ## Practical Exercise: ROI Calculation ```mermaid graph TD A[Current Costs] --> B[Potential Savings] C[Implementation Costs] --> D[Net ROI] B --> D Document current process costs Estimate efficiency gains Calculate net ROI Q&A Let's discuss your specific challenges ```""" class CodeAgent: def generate_code(self, content): if not openai_client: print("OpenAI API not set - using enhanced mock code.") return self._professional_code(content) try: response = openai_client.chat.completions.create( model="gpt-4-turbo", messages=[ { "role": "system", "content": ( "You are an enterprise solutions architect. Create professional-grade code labs with: " "1) Production-ready patterns 2) Comprehensive documentation " "3) Enterprise security practices 4) Scalable architectures. " "Use Python with the latest best practices." ) }, { "role": "user", "content": ( f"Create a professional code lab for: {json.dumps(content)}. " "Include: Setup instructions, business solution patterns, " "enterprise integration examples, and security best practices." ) } ], temperature=0.3, max_tokens=2500 ) return response.choices[0].message.content except Exception as e: print(f"Error during code generation: {e}. Using mock code.") return self._professional_code(content) def _professional_code(self, content): return f"""# Enterprise-Grade Prompt Engineering Lab # Business Solution Framework class PromptOptimizer: def __init__(self, model="gpt-4-turbo"): self.model = model self.pattern_library = {{ "financial_analysis": "Extract key metrics from financial reports", "customer_service": "Resolve tier-2 support tickets" }} def optimize_prompt(self, business_case): # Implement enterprise optimization logic return f"Business-optimized prompt for {{business_case}}" def calculate_roi(self, current_cost, expected_efficiency): return current_cost * expected_efficiency # Example usage optimizer = PromptOptimizer() print(optimizer.calculate_roi(500000, 0.35)) # $175,000 savings # Security Best Practices def secure_prompt_handling(user_input): # Implement OWASP security standards sanitized = sanitize_input(user_input) validate_business_context(sanitized) return apply_enterprise_guardrails(sanitized) # Integration Pattern: CRM System def integrate_with_salesforce(prompt, salesforce_data): # Enterprise integration example enriched_prompt = f"{{prompt}} using {{salesforce_data}}" return call_ai_api(enriched_prompt) """ class DesignAgent: def generate_design(self, slide_content): if not openai_client: print("OpenAI API not set - skipping design generation.") return None try: response = openai_client.images.generate( model="dall-e-3", prompt=( f"Professional corporate slide background for '{slide_content[:200]}' workshop. " "Modern business style, clean lines, premium gradient, boardroom appropriate. " "Include abstract technology elements in corporate colors." ), n=1, size="1024x1024" ) return response.data[0].url except Exception as e: print(f"Error during design generation: {e}.") return None class VoiceoverAgent: def __init__(self): self.api_key = ELEVENLABS_API_KEY self.voice_id = "21m00Tcm4TlvDq8ikWAM" # Default voice ID self.model = "eleven_monolingual_v1" def generate_voiceover(self, text, voice_id=None): if not self.api_key: print("ElevenLabs API key not set - skipping voiceover generation.") return None try: voice = voice_id if voice_id else self.voice_id url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice}" headers = { "Accept": "audio/mpeg", "Content-Type": "application/json", "xi-api-key": self.api_key } data = { "text": text, "model_id": self.model, "voice_settings": { "stability": 0.7, "similarity_boost": 0.8, "style": 0.5, "use_speaker_boost": True } } response = requests.post(url, json=data, headers=headers) response.raise_for_status() return response.content except requests.exceptions.RequestException as e: print(f"Error generating voiceover: {e}") return None def get_voices(self): if not self.api_key: print("ElevenLabs API key not set - cannot fetch voices.") return [] try: url = "https://api.elevenlabs.io/v1/voices" headers = {"xi-api-key": self.api_key} response = requests.get(url, headers=headers) response.raise_for_status() return response.json().get("voices", []) except requests.exceptions.RequestException as e: print(f"Error fetching voices: {e}") return [] # ---------- Simple frontend to show workshop focus input ---------- HTML_PAGE = """