AI & Machine Learning Topic
Comprehensive guide on integrating Gemini API and OpenAI API into your applications:
Gemini AI API Integration
1. Setup and Installation
bash
pip install google-generativeai
2. Basic Integration
python
import google.generativeai as genai
import os
# Configure API Key
def setup_gemini(api_key):
genai.configure(api_key=api_key)
return genai
# Initialize Gemini
gemini = setup_gemini("your-gemini-api-key-here")
def chat_with_gemini(prompt, model="gemini-pro"):
"""Basic chat completion with Gemini"""
try:
model = genai.GenerativeModel(model)
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"Error: {str(e)}"
# Usage
response = chat_with_gemini("Explain quantum computing in simple terms")
print(response)
3. Advanced Gemini Features
python
def gemini_advanced_chat(messages, model="gemini-pro"):
"""Advanced chat with conversation history"""
model = genai.GenerativeModel(model)
# Start chat session
chat = model.start_chat(history=[])
responses = []
for message in messages:
response = chat.send_message(message)
responses.append(response.text)
return responses, chat.history
def gemini_multimodal(image_path, prompt, model="gemini-pro-vision"):
"""Handle image + text inputs"""
try:
import PIL.Image
# Load image
img = PIL.Image.open(image_path)
model = genai.GenerativeModel(model)
response = model.generate_content([prompt, img])
return response.text
except Exception as e:
return f"Error: {str(e)}"
# Example usage
messages = [
"Hello, how are you?",
"What's the weather like?",
"Can you help me with programming?"
]
responses, history = gemini_advanced_chat(messages)
OpenAI API Integration
1. Setup and Installation
bash
pip install openai
2. Basic Integration
python
from openai import OpenAI
import os
# Initialize client
client = OpenAI(api_key="your-openai-api-key-here")
def chat_with_gpt(messages, model="gpt-3.5-turbo", temperature=0.7):
"""Basic chat completion with OpenAI"""
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=1000
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
# Usage
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain machine learning in simple terms"}
]
response = chat_with_gpt(messages)
print(response)
3. Advanced OpenAI Features
python
def openai_advanced_completion(
prompt,
model="gpt-4",
temperature=0.7,
max_tokens=1500,
stream=False
):
"""Advanced completion with various parameters"""
try:
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=max_tokens,
stream=stream
)
if stream:
# Handle streaming response
full_response = ""
for chunk in response:
if chunk.choices[0].delta.content is not None:
full_response += chunk.choices[0].delta.content
return full_response
else:
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
def openai_image_generation(prompt, size="1024x1024", quality="standard"):
"""Generate images using DALL-E"""
try:
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size=size,
quality=quality,
n=1,
)
return response.data[0].url
except Exception as e:
return f"Error: {str(e)}"
Unified API Wrapper
1. Create a Unified Interface
python
from abc import ABC, abstractmethod
from typing import List, Dict, Any
import google.generativeai as genai
from openai import OpenAI
class AIProvider(ABC):
"""Abstract base class for AI providers"""
@abstractmethod
def chat_completion(self, messages: List[Dict], **kwargs) -> str:
pass
@abstractmethod
def get_available_models(self) -> List[str]:
pass
class GeminiProvider(AIProvider):
def __init__(self, api_key: str):
genai.configure(api_key=api_key)
self.client = genai
def chat_completion(self, messages: List[Dict], model: str = "gemini-pro", **kwargs) -> str:
try:
# Convert messages format for Gemini
prompt = self._format_messages(messages)
ai_model = self.client.GenerativeModel(model)
response = ai_model.generate_content(prompt)
return response.text
except Exception as e:
return f"Gemini Error: {str(e)}"
def get_available_models(self) -> List[str]:
return ["gemini-pro", "gemini-pro-vision"]
def _format_messages(self, messages: List[Dict]) -> str:
"""Convert OpenAI-style messages to Gemini prompt"""
formatted = ""
for msg in messages:
role = msg["role"]
content = msg["content"]
formatted += f"{role}: {content}\n"
return formatted
class OpenAIProvider(AIProvider):
def __init__(self, api_key: str):
self.client = OpenAI(api_key=api_key)
def chat_completion(self, messages: List[Dict], model: str = "gpt-3.5-turbo", **kwargs) -> str:
try:
response = self.client.chat.completions.create(
model=model,
messages=messages,
**kwargs
)
return response.choices[0].message.content
except Exception as e:
return f"OpenAI Error: {str(e)}"
def get_available_models(self) -> List[str]:
return ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"]
class UnifiedAIClient:
"""Unified client for multiple AI providers"""
def __init__(self):
self.providers = {}
def add_provider(self, name: str, provider: AIProvider):
self.providers[name] = provider
def chat_completion(self, provider_name: str, messages: List[Dict], **kwargs) -> str:
if provider_name not in self.providers:
raise ValueError(f"Provider {provider_name} not found")
return self.providers[provider_name].chat_completion(messages, **kwargs)
def get_available_providers(self) -> List[str]:
return list(self.providers.keys())
2. Usage Example
python
# Initialize unified client
ai_client = UnifiedAIClient()
# Add providers
ai_client.add_provider("gemini", GeminiProvider("your-gemini-key"))
ai_client.add_provider("openai", OpenAIProvider("your-openai-key"))
# Use different providers
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the capital of France?"}
]
# Get response from Gemini
gemini_response = ai_client.chat_completion("gemini", messages)
print(f"Gemini: {gemini_response}")
# Get response from OpenAI
openai_response = ai_client.chat_completion("openai", messages, model="gpt-3.5-turbo")
print(f"OpenAI: {openai_response}")
Web Application Integration (Flask)
python
from flask import Flask, request, jsonify, render_template
import os
app = Flask(__name__)
# Initialize AI clients
gemini_provider = GeminiProvider(os.getenv('GEMINI_API_KEY'))
openai_provider = OpenAIProvider(os.getenv('OPENAI_API_KEY'))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/chat', methods=['POST'])
def chat():
data = request.json
provider = data.get('provider', 'gemini')
message = data.get('message', '')
model = data.get('model', 'gemini-pro')
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message}
]
try:
if provider == 'gemini':
response = gemini_provider.chat_completion(messages, model=model)
elif provider == 'openai':
response = openai_provider.chat_completion(messages, model=model)
else:
return jsonify({'error': 'Invalid provider'}), 400
return jsonify({'response': response, 'provider': provider})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/providers', methods=['GET'])
def get_providers():
providers = {
'gemini': gemini_provider.get_available_models(),
'openai': openai_provider.get_available_models()
}
return jsonify(providers)
if __name__ == '__main__':
app.run(debug=True)
Frontend Integration (HTML + JavaScript)
html
<!DOCTYPE html>
<html>
<head>
<title>AI Chat Interface</title>
<style>
.chat-container { max-width: 800px; margin: 0 auto; padding: 20px; }
.message { margin: 10px 0; padding: 10px; border-radius: 5px; }
.user { background: #e3f2fd; text-align: right; }
.assistant { background: #f5f5f5; }
.provider-badge { font-size: 0.8em; color: #666; }
</style>
</head>
<body>
<div class="chat-container">
<h1>AI Chat Interface</h1>
<div>
<select id="providerSelect">
<option value="gemini">Gemini</option>
<option value="openai">OpenAI</option>
</select>
<select id="modelSelect">
<option value="gemini-pro">Gemini Pro</option>
<option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
</select>
</div>
<div id="chatMessages"></div>
<div>
<input type="text" id="messageInput" placeholder="Type your message..." style="width: 70%;">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
async function sendMessage() {
const message = document.getElementById('messageInput').value;
const provider = document.getElementById('providerSelect').value;
const model = document.getElementById('modelSelect').value;
if (!message) return;
// Add user message to chat
addMessage('user', message, provider);
document.getElementById('messageInput').value = '';
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ provider, message, model })
});
const data = await response.json();
if (data.response) {
addMessage('assistant', data.response, provider);
} else {
addMessage('assistant', `Error: ${data.error}`, provider);
}
} catch (error) {
addMessage('assistant', `Network error: ${error.message}`, provider);
}
}
function addMessage(role, content, provider) {
const messagesDiv = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}`;
messageDiv.innerHTML = `
<div>${content}</div>
<div class="provider-badge">${provider.toUpperCase()}</div>
`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
// Update models when provider changes
document.getElementById('providerSelect').addEventListener('change', async function() {
const provider = this.value;
const response = await fetch('/api/providers');
const providers = await response.json();
const modelSelect = document.getElementById('modelSelect');
modelSelect.innerHTML = '';
providers[provider].forEach(model => {
const option = document.createElement('option');
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
});
});
// Enter key to send message
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
Environment Configuration
Create a .env file:
env
GEMINI_API_KEY=your_actual_gemini_api_key OPENAI_API_KEY=your_actual_openai_api_key
Error Handling and Best Practices
python
import logging
from tenacity import retry, stop_after_attempt, wait_exponential
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class RobustAIClient:
def __init__(self, gemini_key, openai_key):
self.gemini = GeminiProvider(gemini_key)
self.openai = OpenAIProvider(openai_key)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def get_response_with_fallback(self, messages, primary_provider="gemini", fallback_provider="openai"):
"""Get response with automatic fallback"""
try:
if primary_provider == "gemini":
return self.gemini.chat_completion(messages)
else:
return self.openai.chat_completion(messages)
except Exception as e:
logger.warning(f"Primary provider {primary_provider} failed: {e}")
# Fallback to secondary provider
try:
if fallback_provider == "gemini":
return self.gemini.chat_completion(messages)
else:
return self.openai.chat_completion(messages)
except Exception as e2:
logger.error(f"All providers failed: {e2}")
return "Sorry, I'm unable to respond at the moment."
This comprehensive guide shows you how to:
-
Integrate both Gemini and OpenAI APIs individually
-
Create a unified interface for multiple providers
-
Build web applications with Flask
-
Create interactive frontends
-
Implement error handling and best practices
Choose the approach that best fits your application's needs!
Comments (0)
No comments yet. Be the first to comment!