| import google.generativeai as genai | |
| from typing import Dict, List, Optional | |
| import config | |
| class GeminiExplainer: | |
| """Alternative LLM explainer using Google Gemini""" | |
| def __init__(self): | |
| if config.GEMINI_API_KEY: | |
| genai.configure(api_key=config.GEMINI_API_KEY) | |
| self.model = genai.GenerativeModel(config.GEMINI_MODEL) | |
| self.enabled = True | |
| else: | |
| self.enabled = False | |
| def explain_recommendation( | |
| self, | |
| card: str, | |
| rewards: float, | |
| rewards_rate: str, | |
| merchant: str, | |
| category: str, | |
| amount: float, | |
| warnings: Optional[List[str]] = None, | |
| annual_potential: float = 0, | |
| alternatives: Optional[List[Dict]] = None | |
| ) -> str: | |
| """Generate explanation using Gemini""" | |
| if not self.enabled: | |
| return "Gemini explainer not configured" | |
| prompt = f"""You are a friendly financial advisor explaining credit card rewards to everyday consumers. | |
| Transaction Details: | |
| - Merchant: {merchant} | |
| - Category: {category} | |
| - Amount: ${amount:.2f} | |
| Recommended Card: {card} | |
| Rewards Earned: ${rewards:.2f} ({rewards_rate}) | |
| Annual Potential: ${annual_potential:.2f}/year | |
| Task: Explain in 2-3 simple sentences why this card is the best choice. Use friendly, conversational language. | |
| Focus on the tangible benefit (e.g., "That's like getting a free coffee every week!"). | |
| {"Warnings to mention: " + ", ".join(warnings) if warnings else ""} | |
| """ | |
| try: | |
| response = self.model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| return f"Gemini explanation unavailable: {str(e)}" | |
| def generate_spending_insights( | |
| self, | |
| user_id: str, | |
| total_spending: float, | |
| total_rewards: float, | |
| optimization_score: int, | |
| top_categories: List[Dict], | |
| recommendations_count: int | |
| ) -> str: | |
| """Generate personalized insights using Gemini""" | |
| if not self.enabled: | |
| return "Gemini insights not configured" | |
| prompt = f"""You are a financial coach reviewing a user's credit card rewards performance. | |
| User Stats: | |
| - Total Spending: ${total_spending:.2f} | |
| - Total Rewards: ${total_rewards:.2f} | |
| - Optimization Score: {optimization_score}/100 | |
| - Optimized Transactions: {recommendations_count} | |
| - Top Categories: {', '.join([c.get('category', 'Unknown') for c in top_categories[:3]])} | |
| Task: Provide 3 actionable insights in a friendly, motivating tone. Each insight should be 1 sentence. | |
| Focus on what they're doing well and one improvement opportunity. | |
| """ | |
| try: | |
| response = self.model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| return f"Gemini insights unavailable: {str(e)}" | |
| def get_gemini_explainer(): | |
| """Factory function to get Gemini explainer""" | |
| return GeminiExplainer() |