import gradio as gr import os from openai import OpenAI # --- Configuration --- # API key MUST be provided via an environment variable (e.g., GEMINI_API_KEY). DEFAULT_API_KEY = "" GEMINI_API_KEY_ENV_VAR = os.environ.get("GEMINI_API_KEY", DEFAULT_API_KEY) # Model configuration GEMINI_MODEL_NAME = "gemini-2.5-flash" GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/" def chatbot_query(message, history, rag_context): """ Handles the chat query, using the provided RAG context, and returns the updated history. History is managed as a list of dictionaries (type='messages'). """ # 1. Add the current user message to the history list history.append({"role": "user", "content": message}) final_api_key = GEMINI_API_KEY_ENV_VAR full_response = "The AI is currently unavailable." if not final_api_key: full_response = "ERROR: API Key is missing. Please ensure the 'GEMINI_API_KEY' environment variable is set." else: try: # Initialize the client using the Gemini base URL and the environment key client = OpenAI( base_url=GEMINI_API_BASE_URL, api_key=final_api_key, timeout=60.0 ) # Construct System Prompt using the RAG Context system_prompt = f""" You are an expert personal financial assistant. Your goal is to analyze the user's expenses and provide advice based on the context provided in the data box below. Be helpful, empathetic, and focus on practical recommendations. --- RAG/CONTEXT DATA --- {rag_context} ------------------------ Address the user's question based on this data. If the data is empty or irrelevant, provide general financial advice. """ # Prepare messages list for API call: System prompt + full conversation history messages = [{"role": "system", "content": system_prompt}] + history # API Call (Non-streaming) response = client.chat.completions.create( model=GEMINI_MODEL_NAME, messages=messages, temperature=0.7, stream=False ) full_response = response.choices[0].message.content except Exception as e: full_response = f"An API error occurred: {e}" # 2. Add the AI response to the history list history.append({"role": "assistant", "content": full_response}) # 3. Return the updated history list return history # --- Gradio UI Definition --- with gr.Blocks(title="Simple Personal Finance Chatbot") as demo: gr.Markdown("# 💬 Simple Personal Finance Chatbot (Gemini Powered)") gr.Markdown( """ Type your personal finance data (income, expenses, goals) into the **Context Box** below, then ask the chatbot a question based on that data. """ ) # RAG/Context Data Input rag_context = gr.Textbox( label="Context Box: Manually Add Your Financial Data (e.g., 'My salary is 1,00,000. My rent is 30,000 and my food spending is 15,000.')", lines=5, placeholder="Enter your financial data here. The AI will use this as context for its advice.", value="Monthly income: 85,000. Fixed expenses (rent, bills, SIP): 40,000. Discretionary spending: Food delivery: 10,000, Shopping: 8,000, Entertainment: 4,000. I want to save for a vacation next year." ) # Chatbot Interface - FIX: Setting type='messages' to address the user warning chatbot = gr.Chatbot( label="Financial Coach Chat", type='messages', height=350, avatar_images=[None, "https://storage.googleapis.com/huggingface-org/spaces/gradio-pr-bot/chatbot-avatar.png"] ) # Chat Input msg = gr.Textbox( label="Your Question", placeholder="e.g., Based on my data, where can I cut costs? Or, How much should I allocate to my vacation fund?" ) # Action Buttons with gr.Row(): clear_btn = gr.Button("Clear Chat") submit_btn = gr.Button("Ask the Coach", variant="primary") # Connect components # Submits the question, updates the chatbot history, and then clears the input box submit_event = submit_btn.click( fn=chatbot_query, inputs=[msg, chatbot, rag_context], outputs=[chatbot], queue=False ).then(lambda: "", None, msg, queue=False) # Clears the input box # Also bind to the Enter key press msg.submit( fn=chatbot_query, inputs=[msg, chatbot, rag_context], outputs=[chatbot], queue=False ).then(lambda: "", None, msg, queue=False) # Clear button action clear_btn.click(lambda: ([], ""), None, [chatbot, msg], queue=False)