admin08077 commited on
Commit
5476612
·
verified ·
1 Parent(s): aaf0edc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -28
app.py CHANGED
@@ -1,25 +1,24 @@
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
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 (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,7 +26,7 @@ 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
  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:
@@ -47,7 +46,7 @@ def save_chat_turn(supabase_user_client: Client, user_id: str, session_id: str,
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):
@@ -71,7 +70,6 @@ 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")
@@ -83,17 +81,14 @@ async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2
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):
@@ -102,34 +97,24 @@ async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2
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}
127
-
128
  except Exception as e:
129
  print(f"Error in agent invocation: {e}")
130
  raise HTTPException(status_code=500, detail=str(e))
131
 
132
- # --- Gradio UI (The Face) - No changes needed here ---
133
  with gr.Blocks() as demo:
134
  gr.Markdown("# 💎 Secure, Multi-User AI Agent (Upgraded)")
135
  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.")
@@ -150,7 +135,8 @@ with gr.Blocks() as demo:
150
  if not user_id:
151
  return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>"), user_id_state: ""}
152
  try:
153
- response = requests.post("http://127.0.0.1:7860/login", json={"user_id": user_id})
 
154
  if response.status_code == 200:
155
  token = response.json()["access_token"]
156
  status_html = f"<p style='color:green;'>Logged in as: {user_id}. You can start chatting now.</p>"
@@ -170,7 +156,7 @@ with gr.Blocks() as demo:
170
  try:
171
  headers = {"Authorization": f"Bearer {token}"}
172
  payload = {"prompt": message, "user_id": user_id, "session_id": session_id}
173
- response = requests.post("http://127.0.0.1:7860/agent/invoke", json=payload, headers=headers)
174
 
175
  if response.status_code == 200:
176
  bot_message = response.json()["response"]
@@ -185,4 +171,8 @@ with gr.Blocks() as demo:
185
  login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input])
186
  msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
187
 
188
- app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
 
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 # Ensure uvicorn is imported
10
  from supabase import create_client, Client
11
  import jwt
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")
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.")
 
26
  supabase_admin = None
27
  print(f"Warning: Supabase service key invalid. User authentication will fail. Error: {e}")
28
 
29
+ # --- Tool Definitions ---
30
  def get_ai_advisor_chat_history(supabase_user_client: Client, user_id: str):
31
  print(f"TOOL CALL: get_ai_advisor_chat_history for user '{user_id}' from Supabase")
32
  try:
 
46
  except Exception as e:
47
  return {"error": f"Database insert failed: {str(e)}"}
48
 
49
+ # --- FastAPI Application ---
50
  app = FastAPI()
51
 
52
  class LoginRequest(BaseModel):
 
70
 
71
  @app.post("/agent/invoke")
72
  async def invoke_gemini_agent(request: AgentRequest, token: str = Depends(oauth2_scheme)):
 
73
  try:
74
  decoded_token = jwt.decode(token, JWT_SECRET, algorithms=["HS256"], audience="authenticated")
75
  user_id = decoded_token.get("sub")
 
81
  except jwt.PyJWTError as e:
82
  raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
83
 
 
84
  def get_my_chat_history():
85
  """Fetches my most recent conversation history to provide context."""
86
  return get_ai_advisor_chat_history(supabase_user_client, user_id)
87
 
88
  tools_for_gemini = [get_my_chat_history]
89
 
 
90
  try:
91
  genai.configure(api_key=GOOGLE_API_KEY)
 
92
  history_data = get_my_chat_history()
93
  conversation_history = []
94
  if isinstance(history_data, list):
 
97
  conversation_history.append({'role': role, 'parts': [{'text': turn['content']}]})
98
 
99
  conversation_history.append({'role': 'user', 'parts': [{'text': request.prompt}]})
 
 
 
100
 
101
+ model = genai.GenerativeModel('gemini-pro')
102
  response = model.generate_content(
103
  conversation_history,
104
  tools=tools_for_gemini,
105
  safety_settings={
106
+ 'HARM_CATEGORY_DANGEROUS_CONTENT': 'BLOCK_NONE', 'HARM_CATEGORY_HARASSMENT': 'BLOCK_NONE',
107
+ 'HARM_CATEGORY_HATE_SPEECH': 'BLOCK_NONE', 'HARM_CATEGORY_SEXUALLY_EXPLICIT': 'BLOCK_NONE',
 
 
108
  }
109
  )
 
110
  final_response_text = response.text
 
 
111
  save_chat_turn(supabase_user_client, user_id, request.session_id, request.prompt, final_response_text)
 
112
  return {"response": final_response_text}
 
113
  except Exception as e:
114
  print(f"Error in agent invocation: {e}")
115
  raise HTTPException(status_code=500, detail=str(e))
116
 
117
+ # --- Gradio UI ---
118
  with gr.Blocks() as demo:
119
  gr.Markdown("# 💎 Secure, Multi-User AI Agent (Upgraded)")
120
  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.")
 
135
  if not user_id:
136
  return {login_status: gr.update(value="<p style='color:red;'>Please enter a User ID.</p>"), user_id_state: ""}
137
  try:
138
+ # For HF Spaces, the app runs on a specific port, but we call it internally via its name
139
+ response = requests.post("http://localhost:7860/login", json={"user_id": user_id})
140
  if response.status_code == 200:
141
  token = response.json()["access_token"]
142
  status_html = f"<p style='color:green;'>Logged in as: {user_id}. You can start chatting now.</p>"
 
156
  try:
157
  headers = {"Authorization": f"Bearer {token}"}
158
  payload = {"prompt": message, "user_id": user_id, "session_id": session_id}
159
+ response = requests.post("http://localhost:7860/agent/invoke", json=payload, headers=headers)
160
 
161
  if response.status_code == 200:
162
  bot_message = response.json()["response"]
 
171
  login_button.click(login_fn, inputs=[user_id_input], outputs=[login_status, user_id_state, token_state, chatbot, msg_input])
172
  msg_input.submit(chat_fn, [msg_input, chatbot, user_id_state, token_state, session_id_state], [msg_input, chatbot])
173
 
174
+ app = gr.mount_gradio_app(app, demo, path="/")
175
+
176
+ # --- ADD THIS BLOCK AT THE VERY END ---
177
+ if __name__ == "__main__":
178
+ uvicorn.run(app, host="0.0.0.0", port=7860)