File size: 5,133 Bytes
cc4d793
 
 
 
4322b7b
cc4d793
4322b7b
6fd6f8e
6ade485
cc4d793
b19aaae
cc4d793
 
 
4322b7b
cc4d793
6fd6f8e
 
cc4d793
 
6fd6f8e
 
 
6ade485
6fd6f8e
4322b7b
cc4d793
6fd6f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4322b7b
6fd6f8e
 
4322b7b
6fd6f8e
4322b7b
cc4d793
 
 
 
4322b7b
 
cc4d793
 
4322b7b
 
cc4d793
 
 
4322b7b
 
 
 
 
 
cc4d793
4322b7b
6fd6f8e
4322b7b
 
6fd6f8e
4322b7b
 
cc4d793
 
4322b7b
 
 
 
cc4d793
4322b7b
 
 
 
 
 
 
6fd6f8e
 
 
4322b7b
 
 
 
6fd6f8e
4322b7b
6fd6f8e
4322b7b
 
 
 
 
6fd6f8e
4322b7b
6fd6f8e
4322b7b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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)