Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import gradio as gr
|
| 4 |
-
from google import genai #
|
| 5 |
-
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 6 |
from fastapi import FastAPI, HTTPException, Depends
|
| 7 |
from fastapi.security import OAuth2PasswordBearer
|
| 8 |
from pydantic import BaseModel
|
|
@@ -12,14 +12,14 @@ from supabase import create_client, Client
|
|
| 12 |
import jwt
|
| 13 |
from datetime import datetime, timedelta
|
| 14 |
|
| 15 |
-
# --- Configuration ---
|
| 16 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 17 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 18 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 19 |
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
|
| 20 |
JWT_SECRET = os.getenv("JWT_SECRET", "a-strong-secret-key-for-local-testing")
|
| 21 |
|
| 22 |
-
# --- Initialize Supabase Admin Client ---
|
| 23 |
try:
|
| 24 |
supabase_admin: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 25 |
print("Successfully created Supabase admin client.")
|
|
@@ -27,11 +27,8 @@ except Exception as e:
|
|
| 27 |
supabase_admin = None
|
| 28 |
print(f"Warning: Supabase service key invalid. User authentication will fail. Error: {e}")
|
| 29 |
|
| 30 |
-
# --- Tool Definitions (No changes here
|
| 31 |
-
# NOTE: In a real app, these would call your mock API. For this example, we keep the Supabase calls.
|
| 32 |
-
|
| 33 |
def get_ai_advisor_chat_history(supabase_user_client: Client, user_id: str):
|
| 34 |
-
"""Fetches the conversation history for the logged-in user."""
|
| 35 |
print(f"TOOL CALL: get_ai_advisor_chat_history for user '{user_id}' from Supabase")
|
| 36 |
try:
|
| 37 |
response = supabase_user_client.table('chat_history').select("*").eq('user_id', user_id).order('timestamp').limit(50).execute()
|
|
@@ -40,7 +37,6 @@ def get_ai_advisor_chat_history(supabase_user_client: Client, user_id: str):
|
|
| 40 |
return {"error": f"Database query failed: {str(e)}"}
|
| 41 |
|
| 42 |
def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str, user_message: str, assistant_message: str):
|
| 43 |
-
"""Saves the conversation turn to the database for the logged-in user."""
|
| 44 |
print(f"TOOL CALL: Saving chat turn for user '{user_id}' to Supabase")
|
| 45 |
try:
|
| 46 |
supabase_user_client.table('chat_history').insert([
|
|
@@ -51,7 +47,7 @@ def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str,
|
|
| 51 |
except Exception as e:
|
| 52 |
return {"error": f"Database insert failed: {str(e)}"}
|
| 53 |
|
| 54 |
-
# --- FastAPI Application with Authentication ---
|
| 55 |
app = FastAPI()
|
| 56 |
|
| 57 |
class LoginRequest(BaseModel):
|
|
@@ -62,7 +58,7 @@ class AgentRequest(BaseModel):
|
|
| 62 |
user_id: str
|
| 63 |
session_id: str = "default-session"
|
| 64 |
|
| 65 |
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
|
| 66 |
|
| 67 |
@app.post("/login")
|
| 68 |
async def login(request: LoginRequest):
|
|
@@ -75,7 +71,7 @@ async def login(request: LoginRequest):
|
|
| 75 |
|
| 76 |
@app.post("/agent/invoke")
|
| 77 |
async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
|
| 78 |
-
# 1. Authenticate
|
| 79 |
try:
|
| 80 |
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
|
| 81 |
user_id = decoded_token.get("sub")
|
|
@@ -83,50 +79,48 @@ async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2
|
|
| 83 |
raise HTTPException(status_code=401, detail="Invalid token or user mismatch.")
|
| 84 |
|
| 85 |
supabase_user_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 86 |
-
supabase_user_client.auth.set_session(access_token=token, refresh_token=token)
|
| 87 |
except jwt.PyJWTError as e:
|
| 88 |
raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
|
| 89 |
|
| 90 |
-
# 2. Define tools
|
| 91 |
def get_my_chat_history():
|
| 92 |
"""Fetches my most recent conversation history to provide context."""
|
| 93 |
return get_ai_advisor_chat_history(supabase_user_client, user_id)
|
| 94 |
|
| 95 |
tools_for_gemini = [get_my_chat_history]
|
| 96 |
-
|
| 97 |
-
# 3. Fetch history and run the Gemini agent
|
| 98 |
try:
|
| 99 |
-
|
| 100 |
-
client = genai.Client(api_key=GOOGLE_API_KEY)
|
| 101 |
|
| 102 |
history_data = get_my_chat_history()
|
| 103 |
-
|
| 104 |
-
# CHANGED: Build the conversation history in the new format
|
| 105 |
conversation_history = []
|
| 106 |
if isinstance(history_data, list):
|
| 107 |
for turn in history_data:
|
| 108 |
role = "user" if turn['role'] == 'user' else "model"
|
| 109 |
conversation_history.append({'role': role, 'parts': [{'text': turn['content']}]})
|
| 110 |
|
| 111 |
-
# Add the current user prompt
|
| 112 |
conversation_history.append({'role': 'user', 'parts': [{'text': request.prompt}]})
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
model =
|
|
|
|
|
|
|
| 116 |
response = model.generate_content(
|
| 117 |
conversation_history,
|
| 118 |
tools=tools_for_gemini,
|
| 119 |
-
safety_settings={
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
}
|
| 125 |
)
|
| 126 |
|
| 127 |
final_response_text = response.text
|
| 128 |
|
| 129 |
-
# 4. Save the new conversation turn
|
| 130 |
save_chat_turn(supabase_user_client, user_id, request.session_id, request.prompt, final_response_text)
|
| 131 |
|
| 132 |
return {"response": final_response_text}
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import gradio as gr
|
| 4 |
+
from google import genai # Correct modern library import
|
| 5 |
+
# REMOVED: from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 6 |
from fastapi import FastAPI, HTTPException, Depends
|
| 7 |
from fastapi.security import OAuth2PasswordBearer
|
| 8 |
from pydantic import BaseModel
|
|
|
|
| 12 |
import jwt
|
| 13 |
from datetime import datetime, timedelta
|
| 14 |
|
| 15 |
+
# --- Configuration (No changes here) ---
|
| 16 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 17 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 18 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 19 |
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
|
| 20 |
JWT_SECRET = os.getenv("JWT_SECRET", "a-strong-secret-key-for-local-testing")
|
| 21 |
|
| 22 |
+
# --- Initialize Supabase Admin Client (No changes here) ---
|
| 23 |
try:
|
| 24 |
supabase_admin: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 25 |
print("Successfully created Supabase admin client.")
|
|
|
|
| 27 |
supabase_admin = None
|
| 28 |
print(f"Warning: Supabase service key invalid. User authentication will fail. Error: {e}")
|
| 29 |
|
| 30 |
+
# --- Tool Definitions (No changes here) ---
|
|
|
|
|
|
|
| 31 |
def get_ai_advisor_chat_history(supabase_user_client: Client, user_id: str):
|
|
|
|
| 32 |
print(f"TOOL CALL: get_ai_advisor_chat_history for user '{user_id}' from Supabase")
|
| 33 |
try:
|
| 34 |
response = supabase_user_client.table('chat_history').select("*").eq('user_id', user_id).order('timestamp').limit(50).execute()
|
|
|
|
| 37 |
return {"error": f"Database query failed: {str(e)}"}
|
| 38 |
|
| 39 |
def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str, user_message: str, assistant_message: str):
|
|
|
|
| 40 |
print(f"TOOL CALL: Saving chat turn for user '{user_id}' to Supabase")
|
| 41 |
try:
|
| 42 |
supabase_user_client.table('chat_history').insert([
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
return {"error": f"Database insert failed: {str(e)}"}
|
| 49 |
|
| 50 |
+
# --- FastAPI Application with Authentication (No changes here) ---
|
| 51 |
app = FastAPI()
|
| 52 |
|
| 53 |
class LoginRequest(BaseModel):
|
|
|
|
| 58 |
user_id: str
|
| 59 |
session_id: str = "default-session"
|
| 60 |
|
| 61 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
|
| 62 |
|
| 63 |
@app.post("/login")
|
| 64 |
async def login(request: LoginRequest):
|
|
|
|
| 71 |
|
| 72 |
@app.post("/agent/invoke")
|
| 73 |
async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
|
| 74 |
+
# 1. Authenticate (No changes here)
|
| 75 |
try:
|
| 76 |
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
|
| 77 |
user_id = decoded_token.get("sub")
|
|
|
|
| 79 |
raise HTTPException(status_code=401, detail="Invalid token or user mismatch.")
|
| 80 |
|
| 81 |
supabase_user_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 82 |
+
supabase_user_client.auth.set_session(access_token=token, refresh_token=token)
|
| 83 |
except jwt.PyJWTError as e:
|
| 84 |
raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
|
| 85 |
|
| 86 |
+
# 2. Define tools (No changes here)
|
| 87 |
def get_my_chat_history():
|
| 88 |
"""Fetches my most recent conversation history to provide context."""
|
| 89 |
return get_ai_advisor_chat_history(supabase_user_client, user_id)
|
| 90 |
|
| 91 |
tools_for_gemini = [get_my_chat_history]
|
| 92 |
+
|
| 93 |
+
# 3. Fetch history and run the Gemini agent
|
| 94 |
try:
|
| 95 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
|
|
|
| 96 |
|
| 97 |
history_data = get_my_chat_history()
|
|
|
|
|
|
|
| 98 |
conversation_history = []
|
| 99 |
if isinstance(history_data, list):
|
| 100 |
for turn in history_data:
|
| 101 |
role = "user" if turn['role'] == 'user' else "model"
|
| 102 |
conversation_history.append({'role': role, 'parts': [{'text': turn['content']}]})
|
| 103 |
|
|
|
|
| 104 |
conversation_history.append({'role': 'user', 'parts': [{'text': request.prompt}]})
|
| 105 |
|
| 106 |
+
# Generate content using the modern client
|
| 107 |
+
model = genai.GenerativeModel('gemini-pro') # Correct way to init the model
|
| 108 |
+
|
| 109 |
+
# CHANGED: The safety_settings dictionary now uses strings
|
| 110 |
response = model.generate_content(
|
| 111 |
conversation_history,
|
| 112 |
tools=tools_for_gemini,
|
| 113 |
+
safety_settings={
|
| 114 |
+
'HARM_CATEGORY_DANGEROUS_CONTENT': 'BLOCK_NONE',
|
| 115 |
+
'HARM_CATEGORY_HARASSMENT': 'BLOCK_NONE',
|
| 116 |
+
'HARM_CATEGORY_HATE_SPEECH': 'BLOCK_NONE',
|
| 117 |
+
'HARM_CATEGORY_SEXUALLY_EXPLICIT': 'BLOCK_NONE',
|
| 118 |
}
|
| 119 |
)
|
| 120 |
|
| 121 |
final_response_text = response.text
|
| 122 |
|
| 123 |
+
# 4. Save the new conversation turn (No changes here)
|
| 124 |
save_chat_turn(supabase_user_client, user_id, request.session_id, request.prompt, final_response_text)
|
| 125 |
|
| 126 |
return {"response": final_response_text}
|