NexusInstruments commited on
Commit
2daa659
·
verified ·
1 Parent(s): e52b90c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -29
app.py CHANGED
@@ -1,52 +1,81 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
 
 
 
4
 
5
  def respond(
6
- message,
7
  history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
  hf_token: gr.OAuthToken,
13
  ):
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
 
 
22
 
23
  messages.append({"role": "user", "content": message})
24
 
25
- response = ""
 
 
 
 
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
  chatbot = gr.ChatInterface(
47
  respond,
 
48
  additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
 
 
 
 
50
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
  gr.Slider(
@@ -61,9 +90,11 @@ chatbot = gr.ChatInterface(
61
 
62
  with gr.Blocks() as demo:
63
  with gr.Sidebar():
 
64
  gr.LoginButton()
65
- chatbot.render()
66
 
 
67
 
68
  if __name__ == "__main__":
69
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
+ DEFAULT_MODEL = "openai/gpt-oss-20b"
5
+ DEFAULT_SYSTEM_MESSAGE = "You are a friendly Chatbot."
6
+
7
 
8
  def respond(
9
+ message: str,
10
  history: list[dict[str, str]],
11
+ system_message: str,
12
+ max_tokens: int,
13
+ temperature: float,
14
+ top_p: float,
15
  hf_token: gr.OAuthToken,
16
  ):
17
  """
18
+ Chat completion handler with streaming, safe auth checks,
19
+ and graceful error handling.
20
  """
21
+ # --- Auth guard ---------------------------------------------------------
22
+ if hf_token is None or not hf_token.token:
23
+ yield "🔒 **Authentication required.** Please log in using the sidebar button."
24
+ return
25
+
26
+ if not message or not message.strip():
27
+ yield "⚠️ Please enter a message before sending."
28
+ return
29
 
30
+ # --- Build messages -----------------------------------------------------
31
+ messages = []
32
+ if system_message and system_message.strip():
33
+ messages.append({"role": "system", "content": system_message})
34
 
35
+ for entry in history or []:
36
+ # Defensive normalisation: handle both dict and legacy tuple formats.
37
+ if isinstance(entry, dict) and "role" in entry and "content" in entry:
38
+ messages.append(entry)
39
+ elif isinstance(entry, (list, tuple)) and len(entry) >= 2:
40
+ user_msg, assistant_msg = str(entry[0]), str(entry[1])
41
+ messages.append({"role": "user", "content": user_msg})
42
+ if assistant_msg:
43
+ messages.append({"role": "assistant", "content": assistant_msg})
44
 
45
  messages.append({"role": "user", "content": message})
46
 
47
+ # --- Stream inference ---------------------------------------------------
48
+ try:
49
+ client = InferenceClient(token=hf_token.token, model=DEFAULT_MODEL)
50
+ stream = client.chat_completion(
51
+ messages,
52
+ max_tokens=max_tokens,
53
+ stream=True,
54
+ temperature=temperature,
55
+ top_p=top_p,
56
+ )
57
 
58
+ response = ""
59
+ for chunk in stream:
60
+ choices = chunk.choices
61
+ if choices and choices[0].delta and choices[0].delta.content:
62
+ response += choices[0].delta.content
63
+ yield response
 
 
 
 
 
64
 
65
+ except Exception as e:
66
+ yield f"❌ **Inference error:** `{type(e).__name__}: {e}`"
67
 
68
 
69
+ # --- UI -------------------------------------------------------------------
 
 
70
  chatbot = gr.ChatInterface(
71
  respond,
72
+ type="messages", # Enforce the new {role, content} format
73
  additional_inputs=[
74
+ gr.Textbox(
75
+ value=DEFAULT_SYSTEM_MESSAGE,
76
+ label="System message",
77
+ placeholder="You are a helpful assistant...",
78
+ ),
79
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
80
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
81
  gr.Slider(
 
90
 
91
  with gr.Blocks() as demo:
92
  with gr.Sidebar():
93
+ gr.Markdown("## 🔐 Authentication")
94
  gr.LoginButton()
95
+ gr.LogoutButton()
96
 
97
+ chatbot.render()
98
 
99
  if __name__ == "__main__":
100
+ demo.queue(default_concurrency_limit=20).launch()