mgbam commited on
Commit
c1da7c1
·
verified ·
1 Parent(s): 8fe3ec0

Update agents/agents.py

Browse files
Files changed (1) hide show
  1. agents/agents.py +159 -172
agents/agents.py CHANGED
@@ -11,12 +11,12 @@ load_dotenv()
11
  openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) if os.getenv("OPENAI_API_KEY") else None
12
  ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
13
 
 
14
  class TopicAgent:
15
  def generate_outline(self, topic, duration, difficulty):
16
  if not openai_client:
17
- print("OpenAI API not set - using enhanced mock data for outline.")
18
  return self._mock_outline(topic, duration, difficulty)
19
-
20
  try:
21
  response = openai_client.chat.completions.create(
22
  model="gpt-4-turbo",
@@ -45,10 +45,9 @@ class TopicAgent:
45
  response_format={"type": "json_object"}
46
  )
47
  return json.loads(response.choices[0].message.content)
48
- except Exception as e:
49
- print(f"Error generating outline with OpenAI: {e}. Using mock data.")
50
  return self._mock_outline(topic, duration, difficulty)
51
-
52
  def _mock_outline(self, topic, duration, difficulty):
53
  return {
54
  "title": f"Mastering {topic} for Business Impact",
@@ -92,12 +91,12 @@ class TopicAgent:
92
  ]
93
  }
94
 
 
95
  class ContentAgent:
96
  def generate_content(self, outline):
97
  if not openai_client:
98
- print("OpenAI API not set - using enhanced mock data for content.")
99
  return self._mock_content(outline)
100
-
101
  try:
102
  response = openai_client.chat.completions.create(
103
  model="gpt-4-turbo",
@@ -125,14 +124,13 @@ class ContentAgent:
125
  }
126
  ],
127
  temperature=0.4,
128
- max_tokens=4000,
129
  response_format={"type": "json_object"}
130
  )
131
  return json.loads(response.choices[0].message.content)
132
- except Exception as e:
133
- print(f"Error generating content with OpenAI: {e}. Using mock data.")
134
  return self._mock_content(outline)
135
-
136
  def _mock_content(self, outline):
137
  return {
138
  "workshop_title": outline.get("title", "Premium AI Workshop"),
@@ -174,12 +172,12 @@ class ContentAgent:
174
  ]
175
  }
176
 
 
177
  class SlideAgent:
178
  def generate_slides(self, content):
179
  if not openai_client:
180
- print("OpenAI API not set - using enhanced mock data for slides.")
181
  return self._professional_slides(content)
182
-
183
  try:
184
  response = openai_client.chat.completions.create(
185
  model="gpt-4-turbo",
@@ -206,10 +204,9 @@ class SlideAgent:
206
  max_tokens=2500
207
  )
208
  return response.choices[0].message.content
209
- except Exception as e:
210
- print(f"Error generating slides with OpenAI: {e}. Using mock data.")
211
  return self._professional_slides(content)
212
-
213
  def _professional_slides(self, content):
214
  return f"""---
215
  marp: true
@@ -251,170 +248,160 @@ graph TD
251
  A[Current Costs] --> B[Potential Savings]
252
  C[Implementation Costs] --> D[Net ROI]
253
  B --> D
254
- Use code with caution.
255
- Python
256
  Document current process costs
 
257
  Estimate efficiency gains
 
258
  Calculate net ROI
259
- Q&A: Let's discuss your specific challenges
260
- """
 
 
 
 
261
  class CodeAgent:
262
- def generate_code(self, content):
263
- if not openai_client:
264
- print("OpenAI API not set - using enhanced mock data for code.")
265
- return self._professional_code(content)
266
- Generated code
267
- try:
268
- response = openai_client.chat.completions.create(
269
- model="gpt-4-turbo",
270
- messages=[
271
- {
272
- "role": "system",
273
- "content": (
274
- "You are an enterprise solutions architect. Create professional-grade code labs with: "
275
- "1) Production-ready patterns 2) Comprehensive documentation "
276
- "3) Enterprise security practices 4) Scalable architectures. "
277
- "Use Python with the latest best practices."
278
- )
279
- },
280
- {
281
- "role": "user",
282
- "content": (
283
- f"Create a professional code lab for: {json.dumps(content)}. "
284
- "Include: Setup instructions, business solution patterns, "
285
- "enterprise integration examples, and security best practices."
286
- )
287
- }
288
- ],
289
- temperature=0.3,
290
- max_tokens=2500
291
- )
292
- return response.choices[0].message.content
293
- except Exception as e:
294
- print(f"Error generating code with OpenAI: {e}. Using mock data.")
295
- return self._professional_code(content)
296
-
297
- def _professional_code(self, content):
298
- return """
299
- Use code with caution.
300
- --- Enterprise-Grade Prompt Engineering Lab ---
301
- --- Business Solution Framework ---
302
  class PromptOptimizer:
303
- """A class to optimize prompts and calculate ROI."""
304
- def init(self, model="gpt-4-turbo"):
305
- self.model = model
306
- self.pattern_library = {
307
- "financial_analysis": "Extract key metrics from financial reports",
308
- "customer_service": "Resolve tier-2 support tickets"
309
- }
310
- Generated code
311
- def optimize_prompt(self, business_case):
312
- \"\"\"Implement enterprise optimization logic.\"\"\"
313
- return f"Business-optimized prompt for {business_case}"
314
-
315
- def calculate_roi(self, current_cost, expected_efficiency):
316
- \"\"\"Calculate ROI based on cost and efficiency gain.\"\"\"
317
- return current_cost * expected_efficiency
318
- Use code with caution.
319
- --- Security Best Practices ---
320
- def _sanitize_input(user_input):
321
- """Placeholder for input sanitization logic."""
322
- # In a real implementation, use a library like bleach to prevent XSS
323
- return user_input
324
- def _validate_business_context(sanitized_input):
325
- """Placeholder for validating input against business rules."""
326
- return True
327
- def _apply_enterprise_guardrails(sanitized_input):
328
- """Placeholder for applying enterprise-level safety guardrails."""
329
- return sanitized_input
330
  def secure_prompt_handling(user_input):
331
- """Implement OWASP security standards for prompt handling."""
332
- sanitized = _sanitize_input(user_input)
333
- if _validate_business_context(sanitized):
334
- return _apply_enterprise_guardrails(sanitized)
335
- raise ValueError("Input failed business context validation.")
336
- --- Integration Pattern: CRM System ---
337
- def _call_ai_api(enriched_prompt):
338
- """Placeholder for the actual AI API call."""
339
- return f"AI Response for: {enriched_prompt}"
340
  def integrate_with_salesforce(prompt, salesforce_data):
341
- """Enterprise integration example with a CRM."""
342
- enriched_prompt = f"{prompt} using data: {salesforce_data}"
343
- return _call_ai_api(enriched_prompt)
344
  """
 
 
345
  class DesignAgent:
346
- def generate_design(self, slide_content):
347
- if not openai_client:
348
- print("OpenAI API not set - skipping design generation.")
349
- return None
350
- Generated code
351
- try:
352
- response = openai_client.images.generate(
353
- model="dall-e-3",
354
- prompt=(
355
- f"Professional corporate slide background for '{slide_content[:200]}' workshop. "
356
- "Modern business style, clean lines, premium gradient, boardroom appropriate. "
357
- "Include abstract technology elements in corporate colors."
358
- ),
359
- n=1,
360
- size="1024x1024"
361
- )
362
- return response.data[0].url
363
- except Exception as e:
364
- print(f"Error generating design with OpenAI: {e}. Skipping design generation.")
365
- return None
366
- Use code with caution.
367
  class VoiceoverAgent:
368
- def init(self):
369
- self.api_key = ELEVENLABS_API_KEY
370
- self.voice_id = "21m00Tcm4TlvDq8ikWAM" # Default voice ID for "Rachel"
371
- self.model = "eleven_monolingual_v1"
372
- Generated code
373
- def generate_voiceover(self, text, voice_id=None):
374
- if not self.api_key:
375
- print("ElevenLabs API key not set - skipping voiceover generation.")
376
- return None
377
-
378
- try:
379
- voice = voice_id if voice_id else self.voice_id
380
-
381
- url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice}"
382
- headers = {
383
- "Accept": "audio/mpeg",
384
- "Content-Type": "application/json",
385
- "xi-api-key": self.api_key
386
- }
387
- data = {
388
- "text": text,
389
- "model_id": self.model,
390
- "voice_settings": {
391
- "stability": 0.7,
392
- "similarity_boost": 0.8,
393
- "style": 0.5,
394
- "use_speaker_boost": True
395
  }
396
- }
397
- response = requests.post(url, json=data, headers=headers)
398
- response.raise_for_status() # Raise an exception for bad status codes
399
- return response.content
400
-
401
- except requests.exceptions.RequestException as e:
402
- print(f"Error generating voiceover with ElevenLabs: {e}")
403
- return None
404
-
405
- def get_voices(self):
406
- if not self.api_key:
407
- print("ElevenLabs API key not set - cannot fetch voices.")
408
- return []
409
-
410
- try:
411
- url = "https://api.elevenlabs.io/v1/voices"
412
- headers = {"xi-api-key": self.api_key}
413
- response = requests.get(url, headers=headers)
414
- response.raise_for_status()
415
- return response.json().get("voices", [])
416
-
417
- except requests.exceptions.RequestException as e:
418
- print(f"Error fetching voices from ElevenLabs: {e}")
419
- return []
420
-
 
 
 
 
 
 
 
 
11
  openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) if os.getenv("OPENAI_API_KEY") else None
12
  ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
13
 
14
+
15
  class TopicAgent:
16
  def generate_outline(self, topic, duration, difficulty):
17
  if not openai_client:
 
18
  return self._mock_outline(topic, duration, difficulty)
19
+
20
  try:
21
  response = openai_client.chat.completions.create(
22
  model="gpt-4-turbo",
 
45
  response_format={"type": "json_object"}
46
  )
47
  return json.loads(response.choices[0].message.content)
48
+ except Exception:
 
49
  return self._mock_outline(topic, duration, difficulty)
50
+
51
  def _mock_outline(self, topic, duration, difficulty):
52
  return {
53
  "title": f"Mastering {topic} for Business Impact",
 
91
  ]
92
  }
93
 
94
+
95
  class ContentAgent:
96
  def generate_content(self, outline):
97
  if not openai_client:
 
98
  return self._mock_content(outline)
99
+
100
  try:
101
  response = openai_client.chat.completions.create(
102
  model="gpt-4-turbo",
 
124
  }
125
  ],
126
  temperature=0.4,
127
+ max_tokens=3000,
128
  response_format={"type": "json_object"}
129
  )
130
  return json.loads(response.choices[0].message.content)
131
+ except Exception:
 
132
  return self._mock_content(outline)
133
+
134
  def _mock_content(self, outline):
135
  return {
136
  "workshop_title": outline.get("title", "Premium AI Workshop"),
 
172
  ]
173
  }
174
 
175
+
176
  class SlideAgent:
177
  def generate_slides(self, content):
178
  if not openai_client:
 
179
  return self._professional_slides(content)
180
+
181
  try:
182
  response = openai_client.chat.completions.create(
183
  model="gpt-4-turbo",
 
204
  max_tokens=2500
205
  )
206
  return response.choices[0].message.content
207
+ except Exception:
 
208
  return self._professional_slides(content)
209
+
210
  def _professional_slides(self, content):
211
  return f"""---
212
  marp: true
 
248
  A[Current Costs] --> B[Potential Savings]
249
  C[Implementation Costs] --> D[Net ROI]
250
  B --> D
 
 
251
  Document current process costs
252
+
253
  Estimate efficiency gains
254
+
255
  Calculate net ROI
256
+
257
+ Q&A
258
+ Let's discuss your specific challenges
259
+ ```"""
260
+
261
+
262
  class CodeAgent:
263
+ def generate_code(self, content):
264
+ if not openai_client:
265
+ return self._professional_code(content)
266
+
267
+ try:
268
+ response = openai_client.chat.completions.create(
269
+ model="gpt-4-turbo",
270
+ messages=[
271
+ {
272
+ "role": "system",
273
+ "content": (
274
+ "You are an enterprise solutions architect. Create professional-grade code labs with: "
275
+ "1) Production-ready patterns 2) Comprehensive documentation "
276
+ "3) Enterprise security practices 4) Scalable architectures. "
277
+ "Use Python with the latest best practices."
278
+ )
279
+ },
280
+ {
281
+ "role": "user",
282
+ "content": (
283
+ f"Create a professional code lab for: {json.dumps(content)}. "
284
+ "Include: Setup instructions, business solution patterns, "
285
+ "enterprise integration examples, and security best practices."
286
+ )
287
+ }
288
+ ],
289
+ temperature=0.3,
290
+ max_tokens=2500
291
+ )
292
+ return response.choices[0].message.content
293
+ except Exception:
294
+ return self._professional_code(content)
295
+
296
+ def _professional_code(self, content):
297
+ return f"""# Enterprise-Grade Prompt Engineering Lab
298
+ Business Solution Framework
299
+ python
 
 
 
300
  class PromptOptimizer:
301
+ def __init__(self, model="gpt-4-turbo"):
302
+ self.model = model
303
+ self.pattern_library = {{
304
+ "financial_analysis": "Extract key metrics from financial reports",
305
+ "customer_service": "Resolve tier-2 support tickets"
306
+ }}
307
+
308
+ def optimize_prompt(self, business_case):
309
+ # Implement enterprise optimization logic
310
+ return f"Business-optimized prompt for {{business_case}}"
311
+
312
+ def calculate_roi(self, current_cost, expected_efficiency):
313
+ return current_cost * expected_efficiency
314
+
315
+ # Example usage
316
+ optimizer = PromptOptimizer()
317
+ print(optimizer.calculate_roi(500000, 0.35)) # $175,000 savings
318
+
319
+ Security Best Practices
320
+ python
 
 
 
 
 
 
 
321
  def secure_prompt_handling(user_input):
322
+ # Implement OWASP security standards
323
+ sanitized = sanitize_input(user_input)
324
+ validate_business_context(sanitized)
325
+ return apply_enterprise_guardrails(sanitized)
326
+
327
+ Integration Pattern: CRM System
328
+ python
 
 
329
  def integrate_with_salesforce(prompt, salesforce_data):
330
+ # Enterprise integration example
331
+ enriched_prompt = f"{{prompt}} using {{salesforce_data}}"
332
+ return call_ai_api(enriched_prompt)
333
  """
334
+
335
+
336
  class DesignAgent:
337
+ def generate_design(self, slide_content):
338
+ if not openai_client:
339
+ return None
340
+
341
+ try:
342
+ response = openai_client.images.generate(
343
+ model="dall-e-3",
344
+ prompt=(
345
+ f"Professional corporate slide background for '{slide_content[:200]}' workshop. "
346
+ "Modern business style, clean lines, premium gradient, boardroom appropriate. "
347
+ "Include abstract technology elements in corporate colors."
348
+ ),
349
+ n=1,
350
+ size="1024x1024"
351
+ )
352
+ return response.data[0].url
353
+ except Exception:
354
+ return None
355
+
356
+
 
357
  class VoiceoverAgent:
358
+ def __init__(self):
359
+ self.api_key = ELEVENLABS_API_KEY
360
+ self.voice_id = "21m00Tcm4TlvDq8ikWAM" # Default voice ID
361
+ self.model = "eleven_monolingual_v1"
362
+
363
+ def generate_voiceover(self, text, voice_id=None):
364
+ if not self.api_key:
365
+ return None
366
+
367
+ try:
368
+ voice = voice_id if voice_id else self.voice_id
369
+
370
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice}"
371
+ headers = {
372
+ "Accept": "audio/mpeg",
373
+ "Content-Type": "application/json",
374
+ "xi-api-key": self.api_key
 
 
 
 
 
 
 
 
 
 
375
  }
376
+ data = {
377
+ "text": text,
378
+ "model_id": self.model,
379
+ "voice_settings": {
380
+ "stability": 0.7,
381
+ "similarity_boost": 0.8,
382
+ "style": 0.5,
383
+ "use_speaker_boost": True
384
+ }
385
+ }
386
+ response = requests.post(url, json=data, headers=headers)
387
+
388
+ if response.status_code == 200:
389
+ return response.content
390
+ return None
391
+ except Exception:
392
+ return None
393
+
394
+ def get_voices(self):
395
+ if not self.api_key:
396
+ return []
397
+
398
+ try:
399
+ url = "https://api.elevenlabs.io/v1/voices"
400
+ headers = {"xi-api-key": self.api_key}
401
+ response = requests.get(url, headers=headers)
402
+
403
+ if response.status_code == 200:
404
+ return response.json().get("voices", [])
405
+ return []
406
+ except Exception:
407
+ return []