Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
-
import requests
|
| 3 |
import gradio as gr
|
| 4 |
from google import 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
|
| 12 |
from datetime import datetime, timedelta
|
|
@@ -14,11 +9,11 @@ from datetime import datetime, timedelta
|
|
| 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")
|
| 18 |
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
|
| 19 |
JWT_SECRET = os.getenv("JWT_SECRET", "a-strong-secret-key-for-local-testing")
|
| 20 |
|
| 21 |
-
# --- Initialize Supabase Admin Client ---
|
| 22 |
try:
|
| 23 |
supabase_admin: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 24 |
print("Successfully created Supabase admin client.")
|
|
@@ -46,17 +41,26 @@ def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str,
|
|
| 46 |
except Exception as e:
|
| 47 |
return {"error": f"Database insert failed: {str(e)}"}
|
| 48 |
|
| 49 |
-
# --- Core Agent Logic (
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
|
| 53 |
if not decoded_token.get("sub") or decoded_token.get("sub") != user_id:
|
| 54 |
-
raise
|
| 55 |
|
| 56 |
supabase_user_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 57 |
supabase_user_client.auth.set_session(access_token=token, refresh_token=token)
|
| 58 |
except jwt.PyJWTError as e:
|
| 59 |
-
raise
|
| 60 |
|
| 61 |
def get_my_chat_history():
|
| 62 |
return get_ai_advisor_chat_history(supabase_user_client, user_id)
|
|
@@ -84,35 +88,8 @@ async def _run_agent_logic(prompt: str, user_id: str, session_id: str, token: st
|
|
| 84 |
return final_response_text
|
| 85 |
except Exception as e:
|
| 86 |
print(f"Error in agent invocation: {e}")
|
| 87 |
-
# Return error as a string to be displayed in chat
|
| 88 |
return f"An error occurred while processing your request: {e}"
|
| 89 |
|
| 90 |
-
# --- FastAPI Endpoints ---
|
| 91 |
-
app = FastAPI()
|
| 92 |
-
|
| 93 |
-
class LoginRequest(BaseModel):
|
| 94 |
-
user_id: str
|
| 95 |
-
|
| 96 |
-
class AgentRequest(BaseModel):
|
| 97 |
-
prompt: str
|
| 98 |
-
user_id: str
|
| 99 |
-
session_id: str = "default-session"
|
| 100 |
-
|
| 101 |
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
|
| 102 |
-
|
| 103 |
-
@app.post("/login")
|
| 104 |
-
async def login(request: LoginRequest):
|
| 105 |
-
if not supabase_admin: raise HTTPException(status_code=500, detail="Auth service not configured.")
|
| 106 |
-
user_id = request.user_id
|
| 107 |
-
payload = { "sub": user_id, "aud": "authenticated", "exp": datetime.utcnow() + timedelta(hours=1), "role": "authenticated" }
|
| 108 |
-
access_token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
|
| 109 |
-
return {"access_token": access_token, "token_type": "bearer"}
|
| 110 |
-
|
| 111 |
-
@app.post("/agent/invoke")
|
| 112 |
-
async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
|
| 113 |
-
response_text = await _run_agent_logic(request.prompt, request.user_id, request.session_id, token)
|
| 114 |
-
return {"response": response_text}
|
| 115 |
-
|
| 116 |
# --- Gradio UI ---
|
| 117 |
with gr.Blocks() as demo:
|
| 118 |
gr.Markdown("# 💎 Secure, Multi-User AI Agent (Live)")
|
|
@@ -130,14 +107,11 @@ with gr.Blocks() as demo:
|
|
| 130 |
chatbot = gr.Chatbot(label="Agent Chat", visible=False, height=500)
|
| 131 |
msg_input = gr.Textbox(label="Your Message", visible=False, show_label=False, placeholder="Type your message here...")
|
| 132 |
|
| 133 |
-
|
| 134 |
-
async def login_fn(user_id):
|
| 135 |
if not user_id:
|
| 136 |
return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>")}
|
| 137 |
try:
|
| 138 |
-
|
| 139 |
-
token_data = await login(LoginRequest(user_id=user_id))
|
| 140 |
-
token = token_data["access_token"]
|
| 141 |
status_html = f"<p style='color:green;'>Logged in as: {user_id}. You can start chatting.</p>"
|
| 142 |
return {
|
| 143 |
login_status: gr.update(value=status_html), user_id_state: user_id, token_state: token,
|
|
@@ -146,14 +120,12 @@ with gr.Blocks() as demo:
|
|
| 146 |
except Exception as e:
|
| 147 |
return {login_status: gr.update(value=f"<p style='color:red;'>Login failed: {e}</p>")}
|
| 148 |
|
| 149 |
-
|
| 150 |
-
async def chat_fn(message, chat_history, user_id, token, session_id):
|
| 151 |
if not token:
|
| 152 |
chat_history.append((message, "Error: You are not logged in."))
|
| 153 |
return "", chat_history
|
| 154 |
|
| 155 |
-
|
| 156 |
-
bot_message = await _run_agent_logic(message, user_id, session_id, token)
|
| 157 |
|
| 158 |
chat_history.append((message, bot_message))
|
| 159 |
return "", chat_history
|
|
@@ -161,7 +133,5 @@ with gr.Blocks() as demo:
|
|
| 161 |
login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input])
|
| 162 |
msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
if __name__ == "__main__":
|
| 167 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from google import genai
|
|
|
|
|
|
|
|
|
|
| 4 |
from typing import List, Dict, Any
|
|
|
|
| 5 |
from supabase import create_client, Client
|
| 6 |
import jwt
|
| 7 |
from datetime import datetime, timedelta
|
|
|
|
| 9 |
# --- Configuration ---
|
| 10 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 12 |
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY") # This is the public 'anon' key
|
| 13 |
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
|
| 14 |
JWT_SECRET = os.getenv("JWT_SECRET", "a-strong-secret-key-for-local-testing")
|
| 15 |
|
| 16 |
+
# --- Initialize Supabase Admin Client (for user authentication) ---
|
| 17 |
try:
|
| 18 |
supabase_admin: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 19 |
print("Successfully created Supabase admin client.")
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
return {"error": f"Database insert failed: {str(e)}"}
|
| 43 |
|
| 44 |
+
# --- Core Agent & Auth Logic (No FastAPI dependencies) ---
|
| 45 |
+
def perform_login(user_id: str):
|
| 46 |
+
"""Generates a secure JWT for a given user ID."""
|
| 47 |
+
if not supabase_admin:
|
| 48 |
+
raise Exception("Authentication service is not configured.")
|
| 49 |
+
payload = { "sub": user_id, "aud": "authenticated", "exp": datetime.utcnow() + timedelta(hours=1), "role": "authenticated" }
|
| 50 |
+
access_token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
|
| 51 |
+
return access_token
|
| 52 |
+
|
| 53 |
+
def run_agent_logic(prompt: str, user_id: str, session_id: str, token: str):
|
| 54 |
+
"""The main logic for the agent, now a simple callable function."""
|
| 55 |
try:
|
| 56 |
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
|
| 57 |
if not decoded_token.get("sub") or decoded_token.get("sub") != user_id:
|
| 58 |
+
raise Exception("Invalid token or user mismatch.")
|
| 59 |
|
| 60 |
supabase_user_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 61 |
supabase_user_client.auth.set_session(access_token=token, refresh_token=token)
|
| 62 |
except jwt.PyJWTError as e:
|
| 63 |
+
raise Exception(f"Invalid token: {e}")
|
| 64 |
|
| 65 |
def get_my_chat_history():
|
| 66 |
return get_ai_advisor_chat_history(supabase_user_client, user_id)
|
|
|
|
| 88 |
return final_response_text
|
| 89 |
except Exception as e:
|
| 90 |
print(f"Error in agent invocation: {e}")
|
|
|
|
| 91 |
return f"An error occurred while processing your request: {e}"
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
# --- Gradio UI ---
|
| 94 |
with gr.Blocks() as demo:
|
| 95 |
gr.Markdown("# 💎 Secure, Multi-User AI Agent (Live)")
|
|
|
|
| 107 |
chatbot = gr.Chatbot(label="Agent Chat", visible=False, height=500)
|
| 108 |
msg_input = gr.Textbox(label="Your Message", visible=False, show_label=False, placeholder="Type your message here...")
|
| 109 |
|
| 110 |
+
def login_fn(user_id):
|
|
|
|
| 111 |
if not user_id:
|
| 112 |
return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>")}
|
| 113 |
try:
|
| 114 |
+
token = perform_login(user_id)
|
|
|
|
|
|
|
| 115 |
status_html = f"<p style='color:green;'>Logged in as: {user_id}. You can start chatting.</p>"
|
| 116 |
return {
|
| 117 |
login_status: gr.update(value=status_html), user_id_state: user_id, token_state: token,
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
return {login_status: gr.update(value=f"<p style='color:red;'>Login failed: {e}</p>")}
|
| 122 |
|
| 123 |
+
def chat_fn(message, chat_history, user_id, token, session_id):
|
|
|
|
| 124 |
if not token:
|
| 125 |
chat_history.append((message, "Error: You are not logged in."))
|
| 126 |
return "", chat_history
|
| 127 |
|
| 128 |
+
bot_message = run_agent_logic(message, user_id, session_id, token)
|
|
|
|
| 129 |
|
| 130 |
chat_history.append((message, bot_message))
|
| 131 |
return "", chat_history
|
|
|
|
| 133 |
login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input])
|
| 134 |
msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
|
| 135 |
|
| 136 |
+
# The standard way to launch a Gradio app on Hugging Face
|
| 137 |
+
demo.launch()
|
|
|
|
|
|