NexusInstruments commited on
Commit
dc4bffb
Β·
verified Β·
1 Parent(s): d14a5d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -27
app.py CHANGED
@@ -2,30 +2,53 @@ 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():
@@ -38,21 +61,19 @@ def respond(
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),
@@ -64,29 +85,35 @@ def respond(
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(
78
- minimum=0.1,
79
- maximum=1.0,
80
- value=0.95,
81
- step=0.05,
82
- label="Top-p (nucleus sampling)",
83
  ),
 
 
 
 
 
 
 
 
84
  ],
85
  )
86
 
87
- with gr.Blocks() as demo:
88
  with gr.Sidebar():
 
89
  gr.LoginButton()
 
 
90
  chatbot.render()
91
 
92
  if __name__ == "__main__":
 
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
+ AVAILABLE_MODELS = [
6
+ "Qwen/Qwen2.5-72B-Instruct",
7
+ "meta-llama/Llama-3.1-8B-Instruct",
8
+ "openai/gpt-oss-20b",
9
+ "mistralai/Mistral-7B-Instruct-v0.3",
10
+ ]
11
 
12
+ DEFAULT_MODEL = AVAILABLE_MODELS[0]
13
+ DEFAULT_SYSTEM_MESSAGE = "You are a helpful, concise AI assistant."
14
 
15
+
16
+ def resolve_token(hf_token: gr.OAuthToken | None) -> str | None:
17
+ """Use Gradio OAuth token first, then fall back to HF_TOKEN for local runs."""
18
  if hf_token is not None and getattr(hf_token, "token", None):
19
  return hf_token.token
20
  env_token = os.getenv("HF_TOKEN", "").strip()
21
  return env_token or None
22
 
23
 
24
+ def _normalize_content(content: object) -> str:
25
+ """Flatten Gradio 6 content blocks into plain text for chat_completion."""
26
+ if isinstance(content, str):
27
+ return content
28
+ if isinstance(content, list):
29
+ parts: list[str] = []
30
+ for item in content:
31
+ if isinstance(item, str):
32
+ parts.append(item)
33
+ elif isinstance(item, dict) and "text" in item:
34
+ parts.append(str(item["text"]))
35
+ return "".join(parts)
36
+ return str(content) if content is not None else ""
37
+
38
+
39
  def respond(
40
  message: str,
41
  history: list[dict],
42
+ model_id: str,
43
  system_message: str,
44
  max_tokens: int,
45
  temperature: float,
46
  top_p: float,
47
  hf_token: gr.OAuthToken | None = None,
48
  ):
49
+ token = resolve_token(hf_token)
50
  if not token:
51
+ yield "πŸ”’ **Authentication required.** Sign in via the sidebar button (or set `HF_TOKEN` locally)."
52
  return
53
 
54
  if not message or not message.strip():
 
61
 
62
  for turn in history or []:
63
  if isinstance(turn, dict) and "role" in turn and "content" in turn:
64
+ role = str(turn["role"])
65
+ text = _normalize_content(turn["content"])
66
+ if text:
67
+ messages.append({"role": role, "content": text})
 
 
68
 
69
  messages.append({"role": "user", "content": message.strip()})
70
 
71
  try:
72
+ client = InferenceClient(token=token, model=model_id or DEFAULT_MODEL)
73
  response = ""
74
 
75
  for chunk in client.chat_completion(
76
+ messages=messages,
77
  max_tokens=int(max_tokens),
78
  stream=True,
79
  temperature=float(temperature),
 
85
  yield response
86
 
87
  except Exception as exc:
88
+ yield f"❌ **Inference error:** `{type(exc).__name__}: {exc}`"
89
 
90
 
91
  chatbot = gr.ChatInterface(
92
+ fn=respond,
 
93
  additional_inputs=[
94
+ gr.Dropdown(
95
+ choices=AVAILABLE_MODELS,
96
+ value=DEFAULT_MODEL,
97
+ allow_custom_value=True,
98
+ label="Model ID",
 
 
 
 
99
  ),
100
+ gr.Textbox(
101
+ value=DEFAULT_SYSTEM_MESSAGE,
102
+ label="System Message",
103
+ lines=3,
104
+ ),
105
+ gr.Slider(minimum=64, maximum=2048, value=512, step=32, label="Max new tokens"),
106
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
107
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
108
  ],
109
  )
110
 
111
+ with gr.Blocks(title="AI Chatbot") as demo:
112
  with gr.Sidebar():
113
+ gr.Markdown("## πŸ” Hugging Face Auth")
114
  gr.LoginButton()
115
+ gr.LogoutButton()
116
+
117
  chatbot.render()
118
 
119
  if __name__ == "__main__":