File size: 20,289 Bytes
e049e86 af64a0f a6fe3fc e049e86 2594e34 e049e86 2594e34 4726c28 e049e86 c185f68 bc18c0a e049e86 bc18c0a 28545a7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 |
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
---
<!-- _class: invert -->
## 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 = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Executive Workshop Configuration</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body { font-family: system-ui,-apple-system,BlinkMacSystemFont,sans-serif; background:#f0f4f8; padding:30px; }
.card { background:#fff; padding:20px; border-radius:12px; max-width:500px; margin:auto; box-shadow:0 10px 25px rgba(0,0,0,0.05); }
h1 { font-size:1.75rem; margin-bottom:4px; display:flex; align-items:center; gap:8px; }
label { display:block; margin-top:16px; font-weight:600; }
input { width:100%; padding:10px 14px; border:1px solid #cbd5e1; border-radius:6px; font-size:1rem; transition: all .2s; color:#1f2937; background:#fff; }
input:focus { outline:none; border-color:#2563eb; box-shadow:0 0 0 3px rgba(59,130,246,0.35); }
input::placeholder { color:#94a3b8; }
::selection { background: rgba(59,130,246,0.4); color:#000; }
.status { margin-bottom:12px; padding:12px; border-radius:8px; }
.warn { background:#fff8e1; border:1px solid #f5e1a4; color:#886f1b; }
.ok { background:#e6f6ed; border:1px solid #b8e0c5; color:#1e5f3d; }
.note { margin-top:8px; font-size:.9rem; color:#475569; }
</style>
</head>
<body>
<div class="card">
<div class="status {{ 'ok' if openai_set else 'warn' }}">
{% if openai_set %}
<div class="ok">OpenAI API Key Found</div>
{% else %}
<div class="warn">OpenAI API not set - using enhanced mock data</div>
{% endif %}
{% if elevenlabs_set %}
<div class="ok" style="margin-top:6px;">ElevenLabs API Key Found</div>
{% else %}
<div class="warn" style="margin-top:6px;">ElevenLabs API Key not set</div>
{% endif %}
</div>
<h1>Executive Workshop Configuration</h1>
<form method="post" action="/submit">
<label for="focus">Workshop Focus</label>
<input id="focus" name="focus" placeholder="e.g., AI-Driven Business Transformation" value="{{ prefill }}" autocomplete="off" />
<div class="note">Type here to set the workshop's focus. Selection and text are styled for clarity.</div>
<button type="submit" style="margin-top:16px; padding:10px 16px; border:none; background:#2563eb; color:#fff; border-radius:6px; cursor:pointer;">Save</button>
</form>
</div>
</body>
</html>
"""
@app.route("/", methods=["GET"])
def index():
return render_template_string(
HTML_PAGE,
openai_set=bool(OPENAI_API_KEY),
elevenlabs_set=bool(ELEVENLABS_API_KEY),
prefill=""
)
@app.route("/submit", methods=["POST"])
def submit():
focus = request.form.get("focus", "")
# For demo: echo back with prefill
return render_template_string(
HTML_PAGE,
openai_set=bool(OPENAI_API_KEY),
elevenlabs_set=bool(ELEVENLABS_API_KEY),
prefill=focus
)
if __name__ == "__main__":
print(f"Loaded OPENAI_API_KEY: {bool(OPENAI_API_KEY)}, ELEVENLABS_API_KEY: {bool(ELEVENLABS_API_KEY)}")
app.run(host="0.0.0.0", port=8080, debug=True, use_reloader=False)
|