NexusInstruments commited on
Commit
d14a5d3
·
verified ·
1 Parent(s): 76febd5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -34
app.py CHANGED
@@ -1,52 +1,77 @@
 
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(
@@ -64,6 +89,5 @@ with gr.Blocks() as demo:
64
  gr.LoginButton()
65
  chatbot.render()
66
 
67
-
68
  if __name__ == "__main__":
69
- demo.launch()
 
1
+ import os
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
+ DEFAULT_MODEL = "openai/gpt-oss-20b"
6
+ DEFAULT_SYSTEM_MESSAGE = "You are a friendly Chatbot."
7
+
8
+
9
+ def get_token(hf_token: gr.OAuthToken | None) -> str | None:
10
+ """Resolve token from Gradio OAuth first, then HF_TOKEN for local runs."""
11
+ if hf_token is not None and getattr(hf_token, "token", None):
12
+ return hf_token.token
13
+ env_token = os.getenv("HF_TOKEN", "").strip()
14
+ return env_token or None
15
+
16
 
17
  def respond(
18
+ message: str,
19
+ history: list[dict],
20
+ system_message: str,
21
+ max_tokens: int,
22
+ temperature: float,
23
+ top_p: float,
24
+ hf_token: gr.OAuthToken | None = None,
25
  ):
26
+ token = get_token(hf_token)
27
+ if not token:
28
+ yield "🔒 Please log in using the sidebar button (or set `HF_TOKEN` locally)."
29
+ return
30
 
31
+ if not message or not message.strip():
32
+ yield "⚠️ Please enter a message."
33
+ return
34
 
35
+ messages: list[dict[str, str]] = []
36
+ if system_message and system_message.strip():
37
+ messages.append({"role": "system", "content": system_message.strip()})
38
 
39
+ for turn in history or []:
40
+ if isinstance(turn, dict) and "role" in turn and "content" in turn:
41
+ content = turn["content"]
42
+ if isinstance(content, list):
43
+ content = "".join(
44
+ part.get("text", "") for part in content if isinstance(part, dict)
45
+ )
46
+ messages.append({"role": turn["role"], "content": str(content)})
47
 
48
+ messages.append({"role": "user", "content": message.strip()})
49
 
50
+ try:
51
+ client = InferenceClient(token=token, model=DEFAULT_MODEL)
52
+ response = ""
 
 
 
 
 
 
 
 
53
 
54
+ for chunk in client.chat_completion(
55
+ messages,
56
+ max_tokens=int(max_tokens),
57
+ stream=True,
58
+ temperature=float(temperature),
59
+ top_p=float(top_p),
60
+ ):
61
+ choices = getattr(chunk, "choices", None)
62
+ if choices and choices[0].delta and choices[0].delta.content:
63
+ response += choices[0].delta.content
64
+ yield response
65
+
66
+ except Exception as exc:
67
+ yield f"❌ **Error:** `{type(exc).__name__}: {exc}`"
68
 
69
 
 
 
 
70
  chatbot = gr.ChatInterface(
71
  respond,
72
+ type="messages",
73
  additional_inputs=[
74
+ gr.Textbox(value=DEFAULT_SYSTEM_MESSAGE, label="System message"),
75
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
76
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
77
  gr.Slider(
 
89
  gr.LoginButton()
90
  chatbot.render()
91
 
 
92
  if __name__ == "__main__":
93
+ demo.queue(default_concurrency_limit=20).launch()