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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
from fastapi import FastAPI, HTTPException, Depends
|
| 6 |
+
from fastapi.security import OAuth2PasswordBearer
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from typing import List, Dict, Any
|
| 9 |
+
import uvicorn
|
| 10 |
+
from supabase import create_client, Client
|
| 11 |
+
import jwt # You'll need to add 'PyJWT' to requirements.txt
|
| 12 |
+
from datetime import datetime, timedelta
|
| 13 |
+
|
| 14 |
+
# --- Configuration ---
|
| 15 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 16 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 17 |
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY") # This is the public 'anon' key
|
| 18 |
+
# NEW: Add the service_role key to your HF Space secrets
|
| 19 |
+
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
|
| 20 |
+
# NEW: A secret for signing our own JWTs
|
| 21 |
+
JWT_SECRET = os.getenv("JWT_SECRET", "a-strong-secret-key-for-local-testing")
|
| 22 |
+
|
| 23 |
+
# --- Initialize Supabase Admin Client (for user authentication) ---
|
| 24 |
+
try:
|
| 25 |
+
# We use the service key to create an admin client that can manage users
|
| 26 |
+
supabase_admin: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 27 |
+
print("Successfully created Supabase admin client.")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
supabase_admin = None
|
| 30 |
+
print(f"Warning: Supabase service key invalid. User authentication will fail. Error: {e}")
|
| 31 |
+
|
| 32 |
+
# --- Tool Definitions (Unchanged, but now they will use a user-specific client) ---
|
| 33 |
+
# We will create the supabase client on-the-fly for each request using the user's token.
|
| 34 |
+
# So we don't need a global client here. The tool functions will accept the client as an argument.
|
| 35 |
+
|
| 36 |
+
def get_ai_advisor_chat_history(supabase_user_client: Client, user_id: str):
|
| 37 |
+
"""Fetches the conversation history for the logged-in user."""
|
| 38 |
+
print(f"TOOL CALL: get_ai_advisor_chat_history for user '{user_id}' from Supabase")
|
| 39 |
+
try:
|
| 40 |
+
response = supabase_user_client.table('chat_history').select("*").eq('user_id', user_id).order('timestamp').limit(50).execute()
|
| 41 |
+
return response.data
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return {"error": f"Database query failed: {str(e)}"}
|
| 44 |
+
|
| 45 |
+
def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str, user_message: str, assistant_message: str):
|
| 46 |
+
"""Saves the conversation turn to the database for the logged-in user."""
|
| 47 |
+
print(f"TOOL CALL: Saving chat turn for user '{user_id}' to Supabase")
|
| 48 |
+
try:
|
| 49 |
+
supabase_user_client.table('chat_history').insert([
|
| 50 |
+
{"user_id": user_id, "session_id": session_id, "role": "user", "content": user_message},
|
| 51 |
+
{"user_id": user_id, "session_id": session_id, "role": "assistant", "content": assistant_message}
|
| 52 |
+
]).execute()
|
| 53 |
+
return {"status": "success"}
|
| 54 |
+
except Exception as e:
|
| 55 |
+
return {"error": f"Database insert failed: {str(e)}"}
|
| 56 |
+
|
| 57 |
+
# --- FastAPI Application with Authentication ---
|
| 58 |
+
app = FastAPI()
|
| 59 |
+
|
| 60 |
+
class LoginRequest(BaseModel):
|
| 61 |
+
# In a real app, this would be email/password. Here we use a simple user_id.
|
| 62 |
+
user_id: str
|
| 63 |
+
|
| 64 |
+
class AgentRequest(BaseModel):
|
| 65 |
+
prompt: str
|
| 66 |
+
user_id: str
|
| 67 |
+
session_id: str = "default-session"
|
| 68 |
+
# We no longer need to pass history, as it will be fetched by the tool
|
| 69 |
+
# based on the authenticated user.
|
| 70 |
+
|
| 71 |
+
# This is our security scheme
|
| 72 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
| 73 |
+
|
| 74 |
+
@app.post("/login")
|
| 75 |
+
async def login(request: LoginRequest):
|
| 76 |
+
"""
|
| 77 |
+
Simulates a login. Creates a custom JWT that Supabase will trust.
|
| 78 |
+
This endpoint uses the ADMIN client to generate a token for a user.
|
| 79 |
+
"""
|
| 80 |
+
if not supabase_admin:
|
| 81 |
+
raise HTTPException(status_code=500, detail="Authentication service is not configured.")
|
| 82 |
+
|
| 83 |
+
# In a real app, you would verify a password here.
|
| 84 |
+
# For this demo, we'll just create a token for the given user_id.
|
| 85 |
+
user_id = request.user_id
|
| 86 |
+
|
| 87 |
+
# Create a custom JWT token that Supabase can understand.
|
| 88 |
+
# This token asserts the user's identity.
|
| 89 |
+
payload = {
|
| 90 |
+
"sub": user_id, # The user's UUID
|
| 91 |
+
"aud": "authenticated",
|
| 92 |
+
"exp": datetime.utcnow() + timedelta(hours=1), # Token expires in 1 hour
|
| 93 |
+
"role": "authenticated",
|
| 94 |
+
}
|
| 95 |
+
access_token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
|
| 96 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@app.post("/agent/invoke")
|
| 100 |
+
async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
|
| 101 |
+
"""
|
| 102 |
+
This endpoint is now secure. It requires a valid token.
|
| 103 |
+
"""
|
| 104 |
+
# 1. Authenticate the user and create a user-specific Supabase client
|
| 105 |
+
try:
|
| 106 |
+
# Decode the token to get the user_id
|
| 107 |
+
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
|
| 108 |
+
user_id = decoded_token.get("sub")
|
| 109 |
+
if not user_id or user_id != request.user_id:
|
| 110 |
+
raise HTTPException(status_code=401, detail="Invalid token or user mismatch.")
|
| 111 |
+
|
| 112 |
+
# Create a Supabase client that is authenticated as THIS user
|
| 113 |
+
supabase_user_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 114 |
+
supabase_user_client.auth.set_session(access_token=token, refresh_token="dummy") # Important!
|
| 115 |
+
|
| 116 |
+
except jwt.PyJWTError as e:
|
| 117 |
+
raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
|
| 118 |
+
|
| 119 |
+
# 2. Define tools that can access the user-specific client
|
| 120 |
+
# We define them here so they have access to the authenticated client and user_id
|
| 121 |
+
|
| 122 |
+
def get_my_chat_history():
|
| 123 |
+
"""Fetches my most recent conversation history."""
|
| 124 |
+
return get_ai_advisor_chat_history(supabase_user_client, user_id)
|
| 125 |
+
|
| 126 |
+
# The Gemini model itself doesn't need to know the user_id, it just calls the tool.
|
| 127 |
+
# We handle passing the id inside the function definition.
|
| 128 |
+
tools_for_gemini = [get_my_chat_history]
|
| 129 |
+
|
| 130 |
+
# 3. Fetch history and run the Gemini agent
|
| 131 |
+
try:
|
| 132 |
+
# Fetch the user's history to provide context to the model
|
| 133 |
+
history_data = get_my_chat_history()
|
| 134 |
+
chat_history = []
|
| 135 |
+
if isinstance(history_data, list):
|
| 136 |
+
for turn in history_data:
|
| 137 |
+
chat_history.append({"role": turn['role'], "parts": [turn['content']]})
|
| 138 |
+
|
| 139 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 140 |
+
model = genai.GenerativeModel(model_name='gemini-pro', tools=tools_for_gemini)
|
| 141 |
+
chat = model.start_chat(history=chat_history)
|
| 142 |
+
|
| 143 |
+
response = chat.send_message(request.prompt)
|
| 144 |
+
final_response_text = " ".join([part.text for part in response.parts if hasattr(part, 'text')])
|
| 145 |
+
|
| 146 |
+
# 4. Save the new conversation turn to the database
|
| 147 |
+
save_chat_turn(supabase_user_client, user_id, request.session_id, request.prompt, final_response_text)
|
| 148 |
+
|
| 149 |
+
return {"response": final_response_text}
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"Error in agent invocation: {e}")
|
| 153 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# --- Gradio UI (The Face) ---
|
| 157 |
+
# The UI needs to be updated to handle the login flow.
|
| 158 |
+
|
| 159 |
+
with gr.Blocks() as demo:
|
| 160 |
+
gr.Markdown("# 💎 Secure, Multi-User AI Agent")
|
| 161 |
+
gr.Markdown("First, 'log in' with a User ID (e.g., 'user-a', 'user-b'). This will generate a secure token. Then, you can chat with the agent, and your conversation will be saved securely to your own user record in Supabase.")
|
| 162 |
+
|
| 163 |
+
# State variables to hold session info
|
| 164 |
+
user_id_state = gr.State("")
|
| 165 |
+
token_state = gr.State("")
|
| 166 |
+
session_id_state = gr.State("session-" + os.urandom(8).hex())
|
| 167 |
+
|
| 168 |
+
with gr.Row():
|
| 169 |
+
user_id_input = gr.Textbox(label="Enter a User ID to Log In", placeholder="e.g., user-a")
|
| 170 |
+
login_button = gr.Button("Login")
|
| 171 |
+
login_status = gr.Markdown("")
|
| 172 |
+
|
| 173 |
+
chatbot = gr.Chatbot(label="Agent Chat", visible=False)
|
| 174 |
+
msg_input = gr.Textbox(label="Your Message", visible=False)
|
| 175 |
+
clear_button = gr.Button("Clear Chat", visible=False)
|
| 176 |
+
|
| 177 |
+
def login_fn(user_id):
|
| 178 |
+
if not user_id:
|
| 179 |
+
return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>"), user_id_state: ""}
|
| 180 |
+
try:
|
| 181 |
+
# Call our own FastAPI /login endpoint
|
| 182 |
+
response = requests.post("http://127.0.0.1:7860/login", json={"user_id": user_id})
|
| 183 |
+
if response.status_code == 200:
|
| 184 |
+
token = response.json()["access_token"]
|
| 185 |
+
status_html = f"<p style='color:green;'>Logged in as: {user_id}</p>"
|
| 186 |
+
# After successful login, show the chat interface
|
| 187 |
+
return {
|
| 188 |
+
login_status: gr.update(value=status_html),
|
| 189 |
+
user_id_state: user_id,
|
| 190 |
+
token_state: token,
|
| 191 |
+
chatbot: gr.update(visible=True),
|
| 192 |
+
msg_input: gr.update(visible=True),
|
| 193 |
+
clear_button: gr.update(visible=True),
|
| 194 |
+
}
|
| 195 |
+
else:
|
| 196 |
+
return {login_status: gr.update(value=f"<p style='color:red;'>Login failed: {response.text}</p>"), user_id_state: ""}
|
| 197 |
+
except requests.RequestException as e:
|
| 198 |
+
return {login_status: gr.update(value=f"<p style='color:red;'>Error connecting to backend: {e}</p>"), user_id_state: ""}
|
| 199 |
+
|
| 200 |
+
def chat_fn(message, chat_history, user_id, token, session_id):
|
| 201 |
+
if not token:
|
| 202 |
+
chat_history.append((message, "Error: You are not logged in. Please enter a User ID and click Login."))
|
| 203 |
+
return "", chat_history
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 207 |
+
payload = {"prompt": message, "user_id": user_id, "session_id": session_id}
|
| 208 |
+
response = requests.post("http://127.0.0.1:7860/agent/invoke", json=payload, headers=headers)
|
| 209 |
+
|
| 210 |
+
if response.status_code == 200:
|
| 211 |
+
bot_message = response.json()["response"]
|
| 212 |
+
else:
|
| 213 |
+
bot_message = f"Error from agent: {response.text}"
|
| 214 |
+
except requests.RequestException as e:
|
| 215 |
+
bot_message = f"Error connecting to agent: {e}"
|
| 216 |
+
|
| 217 |
+
chat_history.append((message, bot_message))
|
| 218 |
+
return "", chat_history
|
| 219 |
+
|
| 220 |
+
login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input, clear_button])
|
| 221 |
+
msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
|
| 222 |
+
clear_button.click(lambda: None, None, chatbot, queue=False)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# Mount the Gradio app onto the FastAPI server
|
| 226 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|