import gradio as gr import os from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM import torch import requests import json from datetime import datetime class FinanceAgent: def __init__(self): """Initialize the Finance Agent with a language model""" try: # Use a lightweight model that works well for text generation model_name = "microsoft/DialoGPT-medium" self.tokenizer = AutoTokenizer.from_pretrained(model_name) self.model = AutoModelForCausalLM.from_pretrained(model_name) # Add padding token if it doesn't exist if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.model.to(self.device) except Exception as e: print(f"Error initializing model: {e}") self.model = None self.tokenizer = None def get_finance_knowledge_base(self): """Finance knowledge base for common topics""" return { "stocks": { "definition": "Stocks represent ownership shares in a company", "key_points": [ "Stock prices fluctuate based on supply and demand", "Dividends provide regular income to shareholders", "Growth stocks focus on capital appreciation", "Value stocks are typically undervalued by the market", "Diversification reduces investment risk" ] }, "bonds": { "definition": "Bonds are debt securities issued by corporations or governments", "key_points": [ "Bonds pay fixed interest over time", "Government bonds are generally safer than corporate bonds", "Bond prices move inversely to interest rates", "Credit rating affects bond yields", "Bonds provide portfolio stability" ] }, "cryptocurrency": { "definition": "Digital currencies secured by cryptography", "key_points": [ "Bitcoin was the first cryptocurrency", "Blockchain technology ensures security", "High volatility characterizes crypto markets", "Regulatory uncertainty affects prices", "Limited supply drives scarcity value" ] }, "investing": { "definition": "Allocating money to generate returns over time", "key_points": [ "Start early to benefit from compound interest", "Diversify across asset classes", "Consider risk tolerance and time horizon", "Regular investing through dollar-cost averaging", "Rebalance portfolio periodically" ] }, "retirement": { "definition": "Planning for financial security after working years", "key_points": [ "401(k) plans offer tax advantages", "IRA accounts provide additional savings options", "Social Security provides base income", "Healthcare costs increase in retirement", "Estate planning protects beneficiaries" ] }, "budgeting": { "definition": "Planning and controlling personal expenses", "key_points": [ "Track income and expenses regularly", "Follow the 50/30/20 rule for allocation", "Build an emergency fund", "Automate savings and bill payments", "Review and adjust budget monthly" ] } } def generate_finance_response(self, user_input): """Generate a comprehensive finance response""" user_input_lower = user_input.lower() knowledge_base = self.get_finance_knowledge_base() # Find relevant topics relevant_topics = [] for topic, info in knowledge_base.items(): if topic in user_input_lower or any(keyword in user_input_lower for keyword in [topic]): relevant_topics.append((topic, info)) # Generate response if relevant_topics: response = f"## Finance Topic: {user_input}\n\n" for topic, info in relevant_topics: response += f"### {topic.title()}\n" response += f"**Definition:** {info['definition']}\n\n" response += "**Key Points:**\n" for point in info['key_points']: response += f"• {point}\n" response += "\n" else: # General finance advice response = f"## Finance Topic: {user_input}\n\n" response += self.generate_general_advice(user_input) # Add disclaimer response += "\n---\n" response += "*Disclaimer: This information is for educational purposes only and should not be considered as financial advice. Please consult with a qualified financial advisor for personalized guidance.*" return response def generate_general_advice(self, topic): """Generate general financial advice for unknown topics""" general_tips = [ "Consider your financial goals and risk tolerance", "Diversification is key to managing investment risk", "Start with fundamental analysis before making decisions", "Keep informed about market trends and economic indicators", "Consider consulting with financial professionals", "Maintain an emergency fund for unexpected expenses", "Regular review and adjustment of financial strategies is important" ] response = f"Here's some general guidance regarding '{topic}':\n\n" response += "**General Financial Principles:**\n" for tip in general_tips[:5]: # Show first 5 tips response += f"• {tip}\n" response += f"\n**Specific to '{topic}':**\n" response += f"• Research thoroughly before making any financial decisions related to {topic}\n" response += f"• Understand the risks and potential returns associated with {topic}\n" response += f"• Consider how {topic} fits into your overall financial portfolio\n" return response # Initialize the finance agent finance_agent = FinanceAgent() def process_finance_query(user_input, history): """Process user input and return finance advice""" if not user_input.strip(): return "Please enter a finance topic or question.", history try: # Generate response response = finance_agent.generate_finance_response(user_input) # Update history history.append([user_input, response]) return "", history except Exception as e: error_response = f"I apologize, but I encountered an error processing your request: {str(e)}\n\nPlease try rephrasing your question." history.append([user_input, error_response]) return "", history def clear_conversation(): """Clear the conversation history""" return [], "" # Create Gradio interface with gr.Blocks( theme=gr.themes.Soft(), title="Finance Agent", css=""" .container { max-width: 800px; margin: 0 auto; } .header { text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px; } """ ) as demo: gr.HTML("""

🏦 Finance Agent

Your AI-powered financial advisor for quick insights and guidance

""") with gr.Row(): with gr.Column(scale=1): gr.HTML("""

💡 How to Use:

""") gr.HTML("""

📈 Popular Topics:

Investing: Stocks, Bonds, ETFs

Planning: Retirement, Budgeting

Trading: Cryptocurrency, Options

Banking: Savings, Loans, Credit

""") with gr.Column(scale=2): chatbot = gr.Chatbot( height=500, show_label=False, container=True, bubble_full_width=False ) with gr.Row(): user_input = gr.Textbox( placeholder="Enter your finance topic or question (e.g., 'stocks', 'retirement planning', 'cryptocurrency')", show_label=False, container=False, scale=4 ) submit_btn = gr.Button("Ask Agent", variant="primary", scale=1) with gr.Row(): clear_btn = gr.Button("Clear Chat", variant="secondary") gr.HTML("
") # Spacer # Example questions gr.Examples( examples=[ ["What are stocks and how do they work?"], ["How should I start investing as a beginner?"], ["Explain cryptocurrency basics"], ["What's the best budgeting strategy?"], ["How to plan for retirement?"], ["What are the differences between stocks and bonds?"] ], inputs=user_input, label="Example Questions" ) # Event handlers submit_btn.click( process_finance_query, inputs=[user_input, chatbot], outputs=[user_input, chatbot] ) user_input.submit( process_finance_query, inputs=[user_input, chatbot], outputs=[user_input, chatbot] ) clear_btn.click( clear_conversation, outputs=[chatbot, user_input] ) gr.HTML("""

⚠️ Important Disclaimer: This AI agent provides educational information only. Always consult qualified financial advisors for personalized advice.

Built with ❤️ using Gradio and Hugging Face

""") # Launch configuration for Hugging Face Spaces if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, share=False )