admin08077 commited on
Commit
29fc612
·
verified ·
1 Parent(s): 2f0b483

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -84
app.py CHANGED
@@ -1,37 +1,34 @@
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."""
@@ -58,91 +55,77 @@ def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str,
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
 
@@ -152,15 +135,11 @@ async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2
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())
@@ -170,27 +149,20 @@ with gr.Blocks() as demo:
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: ""}
@@ -199,9 +171,8 @@ with gr.Blocks() as demo:
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}
@@ -217,10 +188,7 @@ with gr.Blocks() as demo:
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="/")
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ from google import genai # CHANGED: Modern library import
5
+ from google.generativeai.types import HarmCategory, HarmBlockThreshold # For safety settings
6
  from fastapi import FastAPI, HTTPException, Depends
7
  from fastapi.security import OAuth2PasswordBearer
8
  from pydantic import BaseModel
9
  from typing import List, Dict, Any
10
  import uvicorn
11
  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.")
26
  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, these are still correct) ---
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."""
 
55
  app = FastAPI()
56
 
57
  class LoginRequest(BaseModel):
 
58
  user_id: str
59
 
60
  class AgentRequest(BaseModel):
61
  prompt: str
62
  user_id: str
63
  session_id: str = "default-session"
 
 
64
 
65
+ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") # Corrected tokenUrl
 
66
 
67
  @app.post("/login")
68
  async def login(request: LoginRequest):
 
 
 
 
69
  if not supabase_admin:
70
  raise HTTPException(status_code=500, detail="Authentication service is not configured.")
 
 
 
71
  user_id = request.user_id
72
+ payload = { "sub": user_id, "aud": "authenticated", "exp": datetime.utcnow() + timedelta(hours=1), "role": "authenticated", }
 
 
 
 
 
 
 
 
73
  access_token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
74
  return {"access_token": access_token, "token_type": "bearer"}
75
 
 
76
  @app.post("/agent/invoke")
77
  async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
78
+ # 1. Authenticate and create user-specific Supabase client
 
 
 
79
  try:
 
80
  decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
81
  user_id = decoded_token.get("sub")
82
  if not user_id or user_id != request.user_id:
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) # Use token for both
 
87
  except jwt.PyJWTError as e:
88
  raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
89
 
90
+ # 2. Define tools available for this specific request
 
 
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 using the MODERN library structure
98
  try:
99
+ # CHANGED: Initialize the modern client
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
+ # CHANGED: Call the model with the full history
115
+ model = client.models.get('gemini-pro')
116
+ response = model.generate_content(
117
+ conversation_history,
118
+ tools=tools_for_gemini,
119
+ safety_settings={ # Added safety settings for robustness
120
+ HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
121
+ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
122
+ HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
123
+ HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
124
+ }
125
+ )
126
+
127
+ final_response_text = response.text
128
 
 
 
 
129
  # 4. Save the new conversation turn to the database
130
  save_chat_turn(supabase_user_client, user_id, request.session_id, request.prompt, final_response_text)
131
 
 
135
  print(f"Error in agent invocation: {e}")
136
  raise HTTPException(status_code=500, detail=str(e))
137
 
138
+ # --- Gradio UI (The Face) - No changes needed here ---
139
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
140
+ gr.Markdown("# 💎 Secure, Multi-User AI Agent (Upgraded)")
 
 
 
141
  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.")
142
 
 
143
  user_id_state = gr.State("")
144
  token_state = gr.State("")
145
  session_id_state = gr.State("session-" + os.urandom(8).hex())
 
149
  login_button = gr.Button("Login")
150
  login_status = gr.Markdown("")
151
 
152
+ chatbot = gr.Chatbot(label="Agent Chat", visible=False, height=500)
153
+ msg_input = gr.Textbox(label="Your Message", visible=False, show_label=False, placeholder="Type your message here...")
 
154
 
155
  def login_fn(user_id):
156
  if not user_id:
157
  return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>"), user_id_state: ""}
158
  try:
 
159
  response = requests.post("http://127.0.0.1:7860/login", json={"user_id": user_id})
160
  if response.status_code == 200:
161
  token = response.json()["access_token"]
162
+ status_html = f"<p style='color:green;'>Logged in as: {user_id}. You can start chatting now.</p>"
 
163
  return {
164
+ login_status: gr.update(value=status_html), user_id_state: user_id, token_state: token,
165
+ chatbot: gr.update(visible=True), msg_input: gr.update(visible=True),
 
 
 
 
166
  }
167
  else:
168
  return {login_status: gr.update(value=f"<p style='color:red;'>Login failed: {response.text}</p>"), user_id_state: ""}
 
171
 
172
  def chat_fn(message, chat_history, user_id, token, session_id):
173
  if not token:
174
+ chat_history.append((message, "Error: You are not logged in."))
175
  return "", chat_history
 
176
  try:
177
  headers = {"Authorization": f"Bearer {token}"}
178
  payload = {"prompt": message, "user_id": user_id, "session_id": session_id}
 
188
  chat_history.append((message, bot_message))
189
  return "", chat_history
190
 
191
+ login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input])
192
  msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
 
 
193
 
 
194
  app = gr.mount_gradio_app(app, demo, path="/")