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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import anthropic
|
| 5 |
+
import requests
|
| 6 |
+
from typing import Dict, Any, List, Optional
|
| 7 |
+
|
| 8 |
+
# Initialize the environment variables for different providers
|
| 9 |
+
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
| 10 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 12 |
+
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
|
| 13 |
+
|
| 14 |
+
class AIProviderManager:
|
| 15 |
+
"""Manager for multiple AI providers"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.providers = {}
|
| 19 |
+
self.initialize_providers()
|
| 20 |
+
|
| 21 |
+
def initialize_providers(self):
|
| 22 |
+
"""Initialize available AI providers"""
|
| 23 |
+
# Initialize Anthropic (Claude)
|
| 24 |
+
if ANTHROPIC_API_KEY:
|
| 25 |
+
try:
|
| 26 |
+
self.providers["claude"] = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
| 27 |
+
st.sidebar.success("🟢 Claude AI connected")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
st.sidebar.error(f"🔴 Error initializing Claude: {str(e)}")
|
| 30 |
+
|
| 31 |
+
# Initialize OpenAI if available
|
| 32 |
+
if OPENAI_API_KEY:
|
| 33 |
+
try:
|
| 34 |
+
import openai
|
| 35 |
+
openai.api_key = OPENAI_API_KEY
|
| 36 |
+
self.providers["openai"] = True
|
| 37 |
+
st.sidebar.success("🟢 OpenAI connected")
|
| 38 |
+
except ImportError:
|
| 39 |
+
st.sidebar.warning("⚠️ OpenAI SDK not installed. Run 'pip install openai'")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
st.sidebar.error(f"🔴 Error initializing OpenAI: {str(e)}")
|
| 42 |
+
|
| 43 |
+
# Initialize DeepSeek if available
|
| 44 |
+
if DEEPSEEK_API_KEY:
|
| 45 |
+
try:
|
| 46 |
+
import openai as deepseek_client
|
| 47 |
+
self.providers["deepseek"] = {
|
| 48 |
+
"client": deepseek_client,
|
| 49 |
+
"base_url": "https://api.deepseek.com"
|
| 50 |
+
}
|
| 51 |
+
st.sidebar.success("🟢 DeepSeek AI connected")
|
| 52 |
+
except ImportError:
|
| 53 |
+
st.sidebar.warning("⚠️ OpenAI SDK needed for DeepSeek. Run 'pip install openai'")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
st.sidebar.error(f"🔴 Error initializing DeepSeek: {str(e)}")
|
| 56 |
+
|
| 57 |
+
# Initialize Perplexity if available
|
| 58 |
+
if PERPLEXITY_API_KEY:
|
| 59 |
+
self.providers["perplexity"] = True
|
| 60 |
+
st.sidebar.success("🟢 Perplexity API connected")
|
| 61 |
+
|
| 62 |
+
def get_available_models(self):
|
| 63 |
+
"""Get all available models across providers"""
|
| 64 |
+
models = {}
|
| 65 |
+
|
| 66 |
+
# Claude models
|
| 67 |
+
if "claude" in self.providers:
|
| 68 |
+
models.update({
|
| 69 |
+
"claude-3-sonnet-20250219": "Claude 3 Sonnet",
|
| 70 |
+
"claude-3-haiku-20250319": "Claude 3 Haiku",
|
| 71 |
+
"claude-3-opus-20250229": "Claude 3 Opus"
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# OpenAI models
|
| 75 |
+
if "openai" in self.providers:
|
| 76 |
+
models.update({
|
| 77 |
+
"gpt-4": "GPT-4",
|
| 78 |
+
"gpt-4-turbo": "GPT-4 Turbo",
|
| 79 |
+
"gpt-3.5-turbo": "GPT-3.5 Turbo"
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
# DeepSeek models
|
| 83 |
+
if "deepseek" in self.providers:
|
| 84 |
+
models.update({
|
| 85 |
+
"deepseek-chat": "DeepSeek Chat",
|
| 86 |
+
"deepseek-coder": "DeepSeek Coder"
|
| 87 |
+
})
|
| 88 |
+
|
| 89 |
+
return models
|
| 90 |
+
|
| 91 |
+
def generate_text(self, prompt: str, model: str, system_prompt: str = None, temperature: float = 0.7, max_tokens: int = 1000):
|
| 92 |
+
"""Generate text using the specified model"""
|
| 93 |
+
# Check if the specified model is available
|
| 94 |
+
if model.startswith("claude") and "claude" in self.providers:
|
| 95 |
+
return self._generate_with_claude(prompt, model, system_prompt, temperature, max_tokens)
|
| 96 |
+
|
| 97 |
+
elif model.startswith("gpt") and "openai" in self.providers:
|
| 98 |
+
return self._generate_with_openai(prompt, model, system_prompt, temperature, max_tokens)
|
| 99 |
+
|
| 100 |
+
elif model.startswith("deepseek") and "deepseek" in self.providers:
|
| 101 |
+
return self._generate_with_deepseek(prompt, model, system_prompt, temperature, max_tokens)
|
| 102 |
+
|
| 103 |
+
else:
|
| 104 |
+
# Fallback to Claude if available
|
| 105 |
+
if "claude" in self.providers:
|
| 106 |
+
st.warning(f"Model {model} not available. Falling back to Claude 3 Sonnet.")
|
| 107 |
+
return self._generate_with_claude(
|
| 108 |
+
prompt,
|
| 109 |
+
"claude-3-sonnet-20250219",
|
| 110 |
+
system_prompt,
|
| 111 |
+
temperature,
|
| 112 |
+
max_tokens
|
| 113 |
+
)
|
| 114 |
+
else:
|
| 115 |
+
raise ValueError(f"No AI provider available for model: {model}")
|
| 116 |
+
|
| 117 |
+
def _generate_with_claude(self, prompt: str, model: str, system_prompt: str = None, temperature: float = 0.7, max_tokens: int = 1000):
|
| 118 |
+
"""Generate text using Claude"""
|
| 119 |
+
client = self.providers["claude"]
|
| 120 |
+
|
| 121 |
+
messages = [{"role": "user", "content": prompt}]
|
| 122 |
+
|
| 123 |
+
response = client.messages.create(
|
| 124 |
+
model=model,
|
| 125 |
+
max_tokens=max_tokens,
|
| 126 |
+
temperature=temperature,
|
| 127 |
+
system=system_prompt if system_prompt else "You are a helpful assistant.",
|
| 128 |
+
messages=messages
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return response.content[0].text
|
| 132 |
+
|
| 133 |
+
def _generate_with_openai(self, prompt: str, model: str, system_prompt: str = None, temperature: float = 0.7, max_tokens: int = 1000):
|
| 134 |
+
"""Generate text using OpenAI"""
|
| 135 |
+
import openai
|
| 136 |
+
|
| 137 |
+
messages = []
|
| 138 |
+
if system_prompt:
|
| 139 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 140 |
+
|
| 141 |
+
messages.append({"role": "user", "content": prompt})
|
| 142 |
+
|
| 143 |
+
response = openai.chat.completions.create(
|
| 144 |
+
model=model,
|
| 145 |
+
messages=messages,
|
| 146 |
+
temperature=temperature,
|
| 147 |
+
max_tokens=max_tokens
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
return response.choices[0].message.content
|
| 151 |
+
|
| 152 |
+
def _generate_with_deepseek(self, prompt: str, model: str, system_prompt: str = None, temperature: float = 0.7, max_tokens: int = 1000):
|
| 153 |
+
"""Generate text using DeepSeek"""
|
| 154 |
+
import openai as deepseek
|
| 155 |
+
|
| 156 |
+
deepseek.api_key = DEEPSEEK_API_KEY
|
| 157 |
+
deepseek.base_url = "https://api.deepseek.com"
|
| 158 |
+
|
| 159 |
+
messages = []
|
| 160 |
+
if system_prompt:
|
| 161 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 162 |
+
|
| 163 |
+
messages.append({"role": "user", "content": prompt})
|
| 164 |
+
|
| 165 |
+
response = deepseek.chat.completions.create(
|
| 166 |
+
model="deepseek-chat" if model == "deepseek-chat" else "deepseek-coder",
|
| 167 |
+
messages=messages,
|
| 168 |
+
temperature=temperature,
|
| 169 |
+
max_tokens=max_tokens
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
return response.choices[0].message.content
|
| 173 |
+
|
| 174 |
+
def web_search(self, query: str) -> List[Dict[str, Any]]:
|
| 175 |
+
"""Perform a web search using Perplexity API"""
|
| 176 |
+
if "perplexity" not in self.providers or not PERPLEXITY_API_KEY:
|
| 177 |
+
raise ValueError("Perplexity API not available")
|
| 178 |
+
|
| 179 |
+
headers = {
|
| 180 |
+
"Authorization": f"Bearer {PERPLEXITY_API_KEY}",
|
| 181 |
+
"Content-Type": "application/json"
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
data = {
|
| 185 |
+
"query": query,
|
| 186 |
+
"max_results": 5
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
response = requests.post(
|
| 191 |
+
"https://api.perplexity.ai/search",
|
| 192 |
+
headers=headers,
|
| 193 |
+
json=data
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
if response.status_code == 200:
|
| 197 |
+
results = response.json()
|
| 198 |
+
return results.get("results", [])
|
| 199 |
+
else:
|
| 200 |
+
st.error(f"Error in web search: {response.status_code} - {response.text}")
|
| 201 |
+
return []
|
| 202 |
+
except Exception as e:
|
| 203 |
+
st.error(f"Error performing web search: {str(e)}")
|
| 204 |
+
return []
|
| 205 |
+
|
| 206 |
+
def enhance_with_web_search(self, slide_content: Dict[str, Any], search_query: str = None) -> Dict[str, Any]:
|
| 207 |
+
"""Enhance slide content with web search results"""
|
| 208 |
+
if "perplexity" not in self.providers or not PERPLEXITY_API_KEY:
|
| 209 |
+
st.warning("Web search enhancement not available (Perplexity API key required)")
|
| 210 |
+
return slide_content
|
| 211 |
+
|
| 212 |
+
# Use slide title if no search query provided
|
| 213 |
+
if not search_query:
|
| 214 |
+
title = slide_content.get("title", "")
|
| 215 |
+
search_query = f"latest information about {title}"
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
with st.spinner(f"Searching the web for: {search_query}"):
|
| 219 |
+
results = self.web_search(search_query)
|
| 220 |
+
|
| 221 |
+
if not results:
|
| 222 |
+
st.warning("No search results found")
|
| 223 |
+
return slide_content
|
| 224 |
+
|
| 225 |
+
# Compile search results
|
| 226 |
+
search_content = "Web search results:\n\n"
|
| 227 |
+
for i, result in enumerate(results, 1):
|
| 228 |
+
title = result.get("title", "No title")
|
| 229 |
+
snippet = result.get("snippet", "No snippet")
|
| 230 |
+
url = result.get("url", "No URL")
|
| 231 |
+
|
| 232 |
+
search_content += f"{i}. {title}\n"
|
| 233 |
+
search_content += f" {snippet}\n"
|
| 234 |
+
search_content += f" Source: {url}\n\n"
|
| 235 |
+
|
| 236 |
+
# Create an enrichment prompt
|
| 237 |
+
prompt = f"""
|
| 238 |
+
You are an expert presentation content creator.
|
| 239 |
+
|
| 240 |
+
Current slide:
|
| 241 |
+
Title: {slide_content.get('title', 'No title')}
|
| 242 |
+
Content: {slide_content.get('content', [])}
|
| 243 |
+
|
| 244 |
+
I have gathered recent information about this topic. Please use this information to enhance the slide content:
|
| 245 |
+
|
| 246 |
+
{search_content}
|
| 247 |
+
|
| 248 |
+
Please provide:
|
| 249 |
+
1. An updated slide title (if needed)
|
| 250 |
+
2. Enhanced content points that incorporate the latest information
|
| 251 |
+
3. A note about the sources of this information
|
| 252 |
+
|
| 253 |
+
Return your response as JSON with the following structure:
|
| 254 |
+
{{
|
| 255 |
+
"title": "Enhanced title",
|
| 256 |
+
"content": ["Point 1", "Point 2", "Point 3"],
|
| 257 |
+
"notes": "Notes including source information"
|
| 258 |
+
}}
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
# Generate enhanced content
|
| 262 |
+
response = self.generate_text(
|
| 263 |
+
prompt=prompt,
|
| 264 |
+
model="claude-3-sonnet-20250219" if "claude" in self.providers else "gpt-4" if "openai" in self.providers else "deepseek-chat",
|
| 265 |
+
system_prompt="You are an expert at enhancing presentation content with the latest information. Always respond with valid JSON.",
|
| 266 |
+
temperature=0.5,
|
| 267 |
+
max_tokens=2000
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Extract the JSON from the response
|
| 271 |
+
try:
|
| 272 |
+
# Find JSON in the text
|
| 273 |
+
json_start = response.find("{")
|
| 274 |
+
json_end = response.rfind("}") + 1
|
| 275 |
+
|
| 276 |
+
if json_start >= 0 and json_end > 0:
|
| 277 |
+
json_str = response[json_start:json_end]
|
| 278 |
+
enhanced_content = json.loads(json_str)
|
| 279 |
+
|
| 280 |
+
# Update the slide content
|
| 281 |
+
slide_content["title"] = enhanced_content.get("title", slide_content.get("title", ""))
|
| 282 |
+
slide_content["content"] = enhanced_content.get("content", slide_content.get("content", []))
|
| 283 |
+
|
| 284 |
+
# Append to existing notes
|
| 285 |
+
existing_notes = slide_content.get("notes", "")
|
| 286 |
+
new_notes = enhanced_content.get("notes", "")
|
| 287 |
+
slide_content["notes"] = f"{existing_notes}\n\n{new_notes}".strip()
|
| 288 |
+
|
| 289 |
+
# Add source information
|
| 290 |
+
slide_content["source_info"] = {
|
| 291 |
+
"search_query": search_query,
|
| 292 |
+
"results_count": len(results),
|
| 293 |
+
"timestamp": "March 2025"
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
st.success("Slide enhanced with latest web information!")
|
| 297 |
+
else:
|
| 298 |
+
st.error("Could not extract JSON from AI response")
|
| 299 |
+
except Exception as e:
|
| 300 |
+
st.error(f"Error processing AI response: {str(e)}")
|
| 301 |
+
|
| 302 |
+
except Exception as e:
|
| 303 |
+
st.error(f"Error enhancing content with web search: {str(e)}")
|
| 304 |
+
|
| 305 |
+
return slide_content
|
| 306 |
+
|
| 307 |
+
def generate_image_description(self, slide_content: Dict[str, Any]) -> str:
|
| 308 |
+
"""Generate an optimized description for image generation"""
|
| 309 |
+
if not "claude" in self.providers and not "openai" in self.providers:
|
| 310 |
+
return ""
|
| 311 |
+
|
| 312 |
+
title = slide_content.get('title', '')
|
| 313 |
+
|
| 314 |
+
if isinstance(slide_content.get('content', []), list):
|
| 315 |
+
content_text = " ".join(slide_content.get('content', []))[:500] # Limit length
|
| 316 |
+
else:
|
| 317 |
+
content_text = str(slide_content.get('content', ''))[:500]
|
| 318 |
+
|
| 319 |
+
prompt = f"""
|
| 320 |
+
You are an expert at creating image generation prompts.
|
| 321 |
+
|
| 322 |
+
I need a detailed visual description for a presentation slide with the following content:
|
| 323 |
+
|
| 324 |
+
Title: {title}
|
| 325 |
+
Content: {content_text}
|
| 326 |
+
|
| 327 |
+
Please create a detailed description (under a single paragraph of 50 words or less) that would help an AI image generator create an appropriate, professional, metaphorical image for this slide.
|
| 328 |
+
|
| 329 |
+
Focus on imagery that would work well in a business presentation context - prefer abstract, conceptual, or metaphorical imagery over literal representations.
|
| 330 |
+
Specify style (photorealistic, illustration, 3D render), color scheme, and composition.
|
| 331 |
+
|
| 332 |
+
ONLY provide the description itself with no explanations, introductions, or extra text.
|
| 333 |
+
"""
|
| 334 |
+
|
| 335 |
+
try:
|
| 336 |
+
# Choose the model based on availability
|
| 337 |
+
model = "claude-3-haiku-20250319" if "claude" in self.providers else "gpt-3.5-turbo"
|
| 338 |
+
|
| 339 |
+
response = self.generate_text(
|
| 340 |
+
prompt=prompt,
|
| 341 |
+
model=model,
|
| 342 |
+
system_prompt="You are an expert at creating image generation prompts for business presentations.",
|
| 343 |
+
temperature=0.7,
|
| 344 |
+
max_tokens=200
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# Clean up the response
|
| 348 |
+
description = response.strip()
|
| 349 |
+
|
| 350 |
+
return description
|
| 351 |
+
except Exception as e:
|
| 352 |
+
st.error(f"Error generating image description: {str(e)}")
|
| 353 |
+
return f"An image representing {title}"
|
| 354 |
+
|
| 355 |
+
# Initialize the AI provider manager
|
| 356 |
+
def get_ai_manager():
|
| 357 |
+
"""Get or create the AI provider manager"""
|
| 358 |
+
if 'ai_manager' not in st.session_state:
|
| 359 |
+
st.session_state.ai_manager = AIProviderManager()
|
| 360 |
+
|
| 361 |
+
return st.session_state.ai_manager
|