Nymbo commited on
Commit
b003192
Β·
verified Β·
1 Parent(s): a499d04

Update ui_components.py

Browse files
Files changed (1) hide show
  1. ui_components.py +54 -36
ui_components.py CHANGED
@@ -9,16 +9,11 @@ import logging
9
  import traceback
10
  from openai import OpenAI
11
 
12
- from config import AppConfig, CUSTOM_CSS, HF_HUB_AVAILABLE
13
  from chat_handler import ChatHandler
14
  from server_manager import ServerManager
15
  from mcp_client import UniversalMCPClient
16
 
17
- # Import HuggingFace Hub for login functionality
18
- if HF_HUB_AVAILABLE:
19
- from huggingface_hub import login, logout, whoami
20
- from huggingface_hub.utils import HfHubHTTPError
21
-
22
  logger = logging.getLogger(__name__)
23
 
24
  class UIComponents:
@@ -78,8 +73,8 @@ class UIComponents:
78
  with gr.Sidebar(elem_id="main-sidebar"):
79
  gr.Markdown("# πŸ€— gpt.gradio.app")
80
 
81
- # HuggingFace Login Section
82
- self._create_login_section()
83
 
84
  # Provider and Model Selection with defaults
85
  self._create_provider_model_selection()
@@ -91,7 +86,7 @@ class UIComponents:
91
  with gr.Accordion("πŸ“š Guide & Info", open=False):
92
  gr.Markdown("""
93
  ## 🎯 How To Use
94
- 1. **Login**: Login with your HuggingFace account for API access
95
  2. **Add MCP Servers**: Connect to various AI tools on πŸ€—Hub
96
  3. **Enable/Disable Servers**: Use checkboxes to control which servers are active
97
  4. **Chat**: Interact with GPT-OSS and use connected MCP Servers
@@ -103,13 +98,21 @@ class UIComponents:
103
  - **Media Support**: Automatic embedding of media -- images, audio, and video etc
104
  """)
105
 
106
- def _create_login_section(self):
107
- """Create HuggingFace OAuth login section"""
108
  with gr.Group(elem_classes="login-section"):
109
- self.login_button = gr.LoginButton(
110
- value="Sign in for Inference",
111
- redirect_url="https://gradio-chat-gradio-app-hfips.hf.space/"
 
 
 
 
 
 
 
112
  )
 
113
 
114
  def _create_provider_model_selection(self):
115
  """Create provider and model selection dropdowns with defaults"""
@@ -232,24 +235,34 @@ class UIComponents:
232
  def _setup_event_handlers(self, chatbot: gr.Chatbot, demo: gr.Blocks):
233
  """Set up all event handlers"""
234
 
235
- # OAuth profile handler
236
- def handle_oauth_profile(profile: gr.OAuthProfile | None, token: gr.OAuthToken | None):
237
- if profile is None:
238
- return
239
-
240
- logger.info(f"πŸ‘€ OAuth profile received for user: {profile.name}")
241
-
242
- if token and token.token:
243
- logger.info("πŸ”‘ OAuth token received, updating HF client...")
244
- os.environ["HF_TOKEN"] = token.token
245
- try:
246
- self.mcp_client.hf_client = OpenAI(
247
- base_url="https://router.huggingface.co/v1",
248
- api_key=token.token
249
- )
250
- logger.info("βœ… HuggingFace Inference client updated with OAuth token")
251
- except Exception as e:
252
- logger.error(f"❌ Failed to update HF client: {e}")
 
 
 
 
 
 
 
 
 
 
253
 
254
  # Provider selection with auto-model loading
255
  def handle_provider_change(provider_id):
@@ -290,7 +303,7 @@ class UIComponents:
290
  if self.mcp_client.hf_client:
291
  return f"βœ… Ready! Using {active_params} active params, {context_length:,} token context"
292
  else:
293
- return "❌ Please login first"
294
 
295
  # Chat handlers
296
  def submit_message(message, history):
@@ -415,10 +428,15 @@ class UIComponents:
415
  label=f"Active Servers ({len(server_choices)} loaded)"
416
  )
417
 
418
- # Connect OAuth
 
 
 
 
 
419
  demo.load(
420
- fn=handle_oauth_profile,
421
- outputs=[]
422
  )
423
 
424
  # Connect provider/model dropdowns with auto-selection on load
 
9
  import traceback
10
  from openai import OpenAI
11
 
12
+ from config import AppConfig, CUSTOM_CSS
13
  from chat_handler import ChatHandler
14
  from server_manager import ServerManager
15
  from mcp_client import UniversalMCPClient
16
 
 
 
 
 
 
17
  logger = logging.getLogger(__name__)
18
 
19
  class UIComponents:
 
73
  with gr.Sidebar(elem_id="main-sidebar"):
74
  gr.Markdown("# πŸ€— gpt.gradio.app")
75
 
76
+ # API key management section
77
+ self._create_api_key_section()
78
 
79
  # Provider and Model Selection with defaults
80
  self._create_provider_model_selection()
 
86
  with gr.Accordion("πŸ“š Guide & Info", open=False):
87
  gr.Markdown("""
88
  ## 🎯 How To Use
89
+ 1. **Add Your API Key**: Paste a valid Hugging Face Inference API token
90
  2. **Add MCP Servers**: Connect to various AI tools on πŸ€—Hub
91
  3. **Enable/Disable Servers**: Use checkboxes to control which servers are active
92
  4. **Chat**: Interact with GPT-OSS and use connected MCP Servers
 
98
  - **Media Support**: Automatic embedding of media -- images, audio, and video etc
99
  """)
100
 
101
+ def _create_api_key_section(self):
102
+ """Create secret input section for Hugging Face API keys"""
103
  with gr.Group(elem_classes="login-section"):
104
+ gr.Markdown("""
105
+ **πŸ” Hugging Face Inference Token**
106
+
107
+ Paste your API token below. It stays in your browser session only and is not stored.
108
+ """)
109
+ self.api_key_box = gr.Textbox(
110
+ label="HF API Token",
111
+ placeholder="hf_...",
112
+ type="password",
113
+ value=os.getenv("HF_TOKEN", "")
114
  )
115
+ self.api_key_status = gr.Markdown("", visible=False, container=True)
116
 
117
  def _create_provider_model_selection(self):
118
  """Create provider and model selection dropdowns with defaults"""
 
235
  def _setup_event_handlers(self, chatbot: gr.Chatbot, demo: gr.Blocks):
236
  """Set up all event handlers"""
237
 
238
+ def handle_api_key_update(api_key: str):
239
+ """Persist user-provided API key for the current session"""
240
+ if not api_key:
241
+ os.environ.pop("HF_TOKEN", None)
242
+ AppConfig.HF_TOKEN = None
243
+ self.mcp_client.hf_client = None
244
+ return gr.Markdown("⚠️ API token cleared. Add a token to enable calls.", visible=True)
245
+
246
+ token = api_key.strip()
247
+ os.environ["HF_TOKEN"] = token
248
+ AppConfig.HF_TOKEN = token
249
+
250
+ try:
251
+ self.mcp_client.hf_client = OpenAI(
252
+ base_url="https://router.huggingface.co/v1",
253
+ api_key=token
254
+ )
255
+ logger.info("βœ… HuggingFace client configured from pasted token")
256
+ return gr.Markdown("βœ… API token saved for this session.", visible=True)
257
+ except Exception as exc:
258
+ logger.error(f"❌ Failed to configure HF client with provided token: {exc}")
259
+ return gr.Markdown("❌ Invalid token. Please verify and try again.", visible=True)
260
+
261
+ def initialize_api_key_status():
262
+ token_present = bool(os.getenv("HF_TOKEN"))
263
+ if token_present:
264
+ return gr.Markdown("βœ… API token detected from environment.", visible=True)
265
+ return gr.Markdown("", visible=False)
266
 
267
  # Provider selection with auto-model loading
268
  def handle_provider_change(provider_id):
 
303
  if self.mcp_client.hf_client:
304
  return f"βœ… Ready! Using {active_params} active params, {context_length:,} token context"
305
  else:
306
+ return "❌ Please add your Hugging Face API token"
307
 
308
  # Chat handlers
309
  def submit_message(message, history):
 
428
  label=f"Active Servers ({len(server_choices)} loaded)"
429
  )
430
 
431
+ self.api_key_box.input(
432
+ handle_api_key_update,
433
+ inputs=[self.api_key_box],
434
+ outputs=[self.api_key_status]
435
+ )
436
+
437
  demo.load(
438
+ fn=initialize_api_key_status,
439
+ outputs=[self.api_key_status]
440
  )
441
 
442
  # Connect provider/model dropdowns with auto-selection on load