broccoli0510 Claude Opus 5.5 commited on
Commit
82c0798
·
1 Parent(s): 0178299

Merge teacher's UI: tabs, adjustable settings, examples, server status

Browse files

Adds the chat settings (model, system prompt, max tokens, temperature),
example prompts, and a server status tab. /health and /metrics are not
exposed by the api02 gateway, so the status tab reports that instead of
failing. History trimming now accounts for the chosen max tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +163 -39
app.py CHANGED
@@ -1,7 +1,9 @@
1
  import os
2
  import re
 
3
 
4
  import gradio as gr
 
5
  from openai import OpenAI
6
 
7
  # ZeroGPU Space 啟動時要求至少有一個 @spaces.GPU 函式,否則會出現
@@ -17,7 +19,6 @@ try:
17
  except ImportError:
18
  pass
19
 
20
-
21
  # 7B 模型偶爾會混入簡體字,顯示前自動轉成繁體(台灣用語);套件不存在時直接顯示原文
22
  try:
23
  from opencc import OpenCC
@@ -32,37 +33,47 @@ except Exception:
32
  return text
33
 
34
 
 
 
 
35
  def _env(name, default=""):
36
  """讀環境變數並去掉前後空白;變數存在但為空值時,也改用預設值。"""
37
  return (os.getenv(name) or "").strip() or default
38
 
39
 
40
- # 讀取 Space 的環境變數;API Key 請設在 Space Settings → Variables and secrets 的 Secret(勿寫在程式碼裡)
41
  def _clean_url(value, default):
42
  """從設定值抽出第一個網址;可處理從聊天軟體複製來的 Markdown 連結,例如 [https://x/v1](https://x/v1)。"""
43
  m = re.search(r"https?://[^\s\[\]()<>\"']+", value or "")
44
  return m.group(0).rstrip("/") if m else default
45
 
46
 
47
- BASE_URL = _clean_url(_env("LLM_BASE_URL"), "https://api02.webinfo.tw/v1")
48
- API_KEY = _env("LLM_API_KEY")
 
 
49
  _RAW_KEY_LEN = len(os.getenv("LLM_API_KEY") or "") # 診斷用:只記長度,不記內容
50
- DEFAULT_MODEL = _env("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
51
 
52
- client = OpenAI(base_url=BASE_URL, api_key=API_KEY or "missing-key", timeout=120)
 
 
53
 
54
- SYSTEM_PROMPT = (
55
  "你是一位樂於助人的程式設計助理,對象是台灣的大學生。"
56
- "請一律使用「繁體中文(台灣用語)」回答,絕對不要使用簡體字"
57
- "(例如要寫「從、對於、程式、這個、輸出」,不要寫「从、对于、程序、这个、输出」)。"
58
- "清楚說明概念與錯誤原因;程式碼與關鍵字保持英文,並放在 Markdown 程式碼區塊中。"
59
  )
60
 
61
- # 模型上下文上限為 4096 tokens:保留 512 給回答,對話歷史超過約 6000 字元時從最舊的開始捨棄
62
- MAX_TOKENS = 512
63
- MAX_HISTORY_CHARS = 6000
 
 
64
 
65
 
 
 
 
66
  def _text(content):
67
  """Gradio 6 的訊息內容可能是字串,也可能是 [{"type": "text", "text": ...}] 列表。"""
68
  if isinstance(content, str):
@@ -72,8 +83,8 @@ def _text(content):
72
  return str(content or "")
73
 
74
 
75
- def _history_to_messages(history):
76
- """同時支援 Gradio 6 的 dict 格式與舊版的 (user, assistant) tuple 格式。"""
77
  msgs = []
78
  for item in history or []:
79
  if isinstance(item, dict):
@@ -85,51 +96,164 @@ def _history_to_messages(history):
85
  msgs.append({"role": "user", "content": _text(human)})
86
  if assistant:
87
  msgs.append({"role": "assistant", "content": _text(assistant)})
88
- # 從最舊的訊息開始捨棄,直到長度在上限內
89
- while msgs and sum(len(m["content"]) for m in msgs) > MAX_HISTORY_CHARS:
90
  msgs.pop(0)
91
- # 對話必須以 user 開頭
92
  while msgs and msgs[0]["role"] != "user":
93
  msgs.pop(0)
94
  return msgs
95
 
96
 
97
- def predict(message, history):
98
- if not API_KEY:
99
  yield (
100
  "⚠️ 尚未設定 LLM_API_KEY。請到 Space Settings → Variables and secrets 按 New secret,"
101
  "Name 填 `LLM_API_KEY`、Value 貼上老師給的 Key,存檔後重啟 Space。\n\n"
102
- f"診斷:LLM_API_KEY 原始長度 = {_RAW_KEY_LEN}(正確應為 64);BASE_URL = `{BASE_URL}`"
103
  )
104
  return
105
 
106
- messages =[{"role": "system", "content": SYSTEM_PROMPT}]
107
- messages += _history_to_messages(history)
108
- messages.append({"role": "user", "content": _text(message)})
 
 
 
 
 
109
 
 
110
  try:
111
- response = client.chat.completions.create(
112
- model=DEFAULT_MODEL,
113
  messages=messages,
114
- max_tokens=MAX_TOKENS,
115
- temperature=0.2,
116
  stream=True,
117
  )
118
- partial_message = ""
119
- for chunk in response:
120
  if chunk.choices and chunk.choices[0].delta.content:
121
- partial_message += chunk.choices[0].delta.content
122
- yield _to_tw(partial_message)
123
- if not partial_message:
124
  yield "(模型沒有回傳內容,請再試一次)"
125
  except Exception as e:
126
- yield f"連線錯誤或後端異常:{type(e).__name__}: {e}\n\n(BASE_URL = {BASE_URL},MODEL = {DEFAULT_MODEL})"
127
 
128
 
129
- demo = gr.ChatInterface(
130
- fn=predict,
131
- title="程式設計小幫手",
132
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  if __name__ == "__main__":
135
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
  import re
3
+ import time
4
 
5
  import gradio as gr
6
+ import httpx
7
  from openai import OpenAI
8
 
9
  # ZeroGPU Space 啟動時要求至少有一個 @spaces.GPU 函式,否則會出現
 
19
  except ImportError:
20
  pass
21
 
 
22
  # 7B 模型偶爾會混入簡體字,顯示前自動轉成繁體(台灣用語);套件不存在時直接顯示原文
23
  try:
24
  from opencc import OpenCC
 
33
  return text
34
 
35
 
36
+ # ---------------------------------------------------------------------------
37
+ # 設定
38
+ # ---------------------------------------------------------------------------
39
  def _env(name, default=""):
40
  """讀環境變數並去掉前後空白;變數存在但為空值時,也改用預設值。"""
41
  return (os.getenv(name) or "").strip() or default
42
 
43
 
 
44
  def _clean_url(value, default):
45
  """從設定值抽出第一個網址;可處理從聊天軟體複製來的 Markdown 連結,例如 [https://x/v1](https://x/v1)。"""
46
  m = re.search(r"https?://[^\s\[\]()<>\"']+", value or "")
47
  return m.group(0).rstrip("/") if m else default
48
 
49
 
50
+ # API Key 請設在 Space Settings → Variables and secrets 的 Secret(勿寫在程式碼裡)
51
+ LLM_BASE_URL = _clean_url(_env("LLM_BASE_URL"), "https://api02.webinfo.tw/v1")
52
+ LLM_API_KEY = _env("LLM_API_KEY")
53
+ LLM_MODEL = _env("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
54
  _RAW_KEY_LEN = len(os.getenv("LLM_API_KEY") or "") # 診斷用:只記長度,不記內容
 
55
 
56
+ # vLLM 的 /health 與 /metrics 在伺服器根目錄,不在 /v1 底下
57
+ SERVER_ROOT = LLM_BASE_URL.removesuffix("/v1")
58
+ GPU_DESCRIPTION = "NVIDIA GeForce RTX 2080 Ti,11 GB VRAM"
59
 
60
+ DEFAULT_SYSTEM_PROMPT = (
61
  "你是一位樂於助人的程式設計助理,對象是台灣的大學生。"
62
+ "請一律使用「繁體中文(台灣用語)」回答,絕對不要使用簡體字。"
63
+ "清楚說明概念與錯誤原因,撰寫正確且易讀的程式碼,並指出錯誤或邊界情況。"
64
+ "程式碼請放在附上語言名稱的 fenced code block 中。"
65
  )
66
 
67
+ # 模型上下文上限為 4096 tokens,需扣掉回答長度;以「1 個字元 ≈ 1 個 token」保守估算
68
+ CONTEXT_LIMIT = 4096
69
+ CONTEXT_RESERVE = 300 # 系統提示詞與格式的額外開銷
70
+
71
+ client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY or "missing-key", timeout=120)
72
 
73
 
74
+ # ---------------------------------------------------------------------------
75
+ # 對話
76
+ # ---------------------------------------------------------------------------
77
  def _text(content):
78
  """Gradio 6 的訊息內容可能是字串,也可能是 [{"type": "text", "text": ...}] 列表。"""
79
  if isinstance(content, str):
 
83
  return str(content or "")
84
 
85
 
86
+ def _history_to_messages(history, budget_chars):
87
+ """同時支援 Gradio 6 的 dict 格式與舊版的 (user, assistant) tuple 格式,並截短到預算內。"""
88
  msgs = []
89
  for item in history or []:
90
  if isinstance(item, dict):
 
96
  msgs.append({"role": "user", "content": _text(human)})
97
  if assistant:
98
  msgs.append({"role": "assistant", "content": _text(assistant)})
99
+ # 從最舊的訊息開始捨棄,直到長度在預算內;對話必須以 user 開頭
100
+ while msgs and sum(len(m["content"]) for m in msgs) > budget_chars:
101
  msgs.pop(0)
 
102
  while msgs and msgs[0]["role"] != "user":
103
  msgs.pop(0)
104
  return msgs
105
 
106
 
107
+ def respond(message, history, model, system_prompt, max_tokens, temperature):
108
+ if not LLM_API_KEY:
109
  yield (
110
  "⚠️ 尚未設定 LLM_API_KEY。請到 Space Settings → Variables and secrets 按 New secret,"
111
  "Name 填 `LLM_API_KEY`、Value 貼上老師給的 Key,存檔後重啟 Space。\n\n"
112
+ f"診斷:LLM_API_KEY 原始長度 = {_RAW_KEY_LEN}(正確應為 64);BASE_URL = `{LLM_BASE_URL}`"
113
  )
114
  return
115
 
116
+ max_tokens = int(max_tokens or 512)
117
+ system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT
118
+ message = _text(message)
119
+ budget = CONTEXT_LIMIT - max_tokens - CONTEXT_RESERVE - len(system_prompt) - len(message)
120
+
121
+ messages = [{"role": "system", "content": system_prompt}]
122
+ messages += _history_to_messages(history, max(budget, 0))
123
+ messages.append({"role": "user", "content": message})
124
 
125
+ model = model or LLM_MODEL
126
  try:
127
+ stream = client.chat.completions.create(
128
+ model=model,
129
  messages=messages,
130
+ max_tokens=max_tokens,
131
+ temperature=float(temperature if temperature is not None else 0.2),
132
  stream=True,
133
  )
134
+ partial = ""
135
+ for chunk in stream:
136
  if chunk.choices and chunk.choices[0].delta.content:
137
+ partial += chunk.choices[0].delta.content
138
+ yield _to_tw(partial)
139
+ if not partial:
140
  yield "(模型沒有回傳內容,請再試一次)"
141
  except Exception as e:
142
+ yield f"連線錯誤或後端異常:{type(e).__name__}: {e}\n\n(BASE_URL = {LLM_BASE_URL},MODEL = {model})"
143
 
144
 
145
+ # ---------------------------------------------------------------------------
146
+ # 伺服器狀態
147
+ # ---------------------------------------------------------------------------
148
+ def read_metrics(text):
149
+ """回傳每個 vLLM 指標的最新值,以指標名稱為 key。"""
150
+ values = {}
151
+ for line in text.splitlines():
152
+ if line.startswith("#") or not line.strip():
153
+ continue
154
+ name = line.split("{", 1)[0].split(" ", 1)[0]
155
+ try:
156
+ values[name] = float(line.rsplit(" ", 1)[1])
157
+ except ValueError:
158
+ continue
159
+ return values
160
+
161
+
162
+ def server_status():
163
+ headers = {"Authorization": f"Bearer {LLM_API_KEY}"}
164
+ lines = [f"**GPU**:{GPU_DESCRIPTION}(設定值,vLLM 不回報實際 VRAM 用量)", ""]
165
+ notes = []
166
+
167
+ try:
168
+ with httpx.Client(timeout=10) as http:
169
+ lines += ["| 項目 | 狀態 |", "| --- | --- |"]
170
+
171
+ # 1. 模型清單(同時當作 API 連線與回應時間檢查)
172
+ start = time.perf_counter()
173
+ models = http.get(f"{LLM_BASE_URL}/models", headers=headers)
174
+ latency_ms = (time.perf_counter() - start) * 1000
175
+ if models.status_code == 200:
176
+ served = models.json().get("data", [])
177
+ served_ids = [m["id"] for m in served]
178
+ lines.append("| API 連線 | ✅ 正常 |")
179
+ lines.append(f"| API 回應時間 | {latency_ms:.0f} ms |")
180
+ lines.append(f"| 已載入模型 | {', '.join(served_ids) or '無'} |")
181
+ lines.append(f"| 設定的模型是否已載入 | {'✅ 是' if LLM_MODEL in served_ids else '❌ 否'} |")
182
+ for m in served:
183
+ if "max_model_len" in m:
184
+ lines.append(f"| {m['id']} 最大上下文長度 | {m['max_model_len']} tokens |")
185
+ elif models.status_code == 401:
186
+ lines.append("| API 連線 | ❌ 金鑰錯誤(HTTP 401),請檢查 LLM_API_KEY |")
187
+ else:
188
+ lines.append(f"| API 連線 | ❌ 異常(HTTP {models.status_code}) |")
189
+
190
+ # 2. 健康檢查
191
+ health = http.get(f"{SERVER_ROOT}/health")
192
+ if health.status_code == 200:
193
+ lines.append("| 服務健康檢查 | ✅ 正常 |")
194
+ elif health.status_code == 404:
195
+ lines.append("| 服務健康檢查 | ➖ 伺服器未對外開放 /health |")
196
+ else:
197
+ lines.append(f"| 服務健康檢查 | ❌ 異常(HTTP {health.status_code}) |")
198
+
199
+ # 3. vLLM 即時指標
200
+ metrics = http.get(f"{SERVER_ROOT}/metrics")
201
+ if metrics.status_code == 200:
202
+ values = read_metrics(metrics.text)
203
+ cache = values.get("vllm:gpu_cache_usage_perc", values.get("vllm:kv_cache_usage_perc"))
204
+ if cache is not None:
205
+ lines.append(f"| KV cache 使用率 | {cache * 100:.1f}% |")
206
+ if "vllm:num_requests_running" in values:
207
+ lines.append(f"| 執行中請求 | {values['vllm:num_requests_running']:.0f} |")
208
+ if "vllm:num_requests_waiting" in values:
209
+ lines.append(f"| 排隊中請求 | {values['vllm:num_requests_waiting']:.0f} |")
210
+ else:
211
+ lines.append("| KV cache / 請求數 | ➖ 伺服器未對外開放 /metrics |")
212
+ notes.append(
213
+ "ℹ️ 伺服器的閘道目前只轉發 `/v1` 底下的 API,`/health` 與 `/metrics` 沒有對外開放,"
214
+ "因此無法顯示 KV cache 使用率與請求數。若需要這些資料,需請老師在伺服器端開放。"
215
+ )
216
+ except httpx.HTTPError as e:
217
+ lines.append(f"**無法連線到 LLM 伺服器**:{type(e).__name__}: {e}")
218
+ except Exception as e:
219
+ lines.append(f"**檢查失敗**:{type(e).__name__}: {e}")
220
+
221
+ lines.append("")
222
+ for note in notes:
223
+ lines += [note, ""]
224
+ lines.append(f"檢查時間:{time.strftime('%Y-%m-%d %H:%M:%S')}")
225
+ return "\n".join(lines)
226
+
227
+
228
+ # ---------------------------------------------------------------------------
229
+ # 介面
230
+ # ---------------------------------------------------------------------------
231
+ with gr.Blocks(title="程式設計小幫手") as demo:
232
+ with gr.Tab("對話"):
233
+ gr.ChatInterface(
234
+ fn=respond,
235
+ title="程式設計小幫手",
236
+ description="貼上你的 C++ / Python 程式碼與錯誤訊息,或提出程式設計相關的問題。回答由實驗室自架的開源大型語言模型產生。",
237
+ additional_inputs=[
238
+ gr.Dropdown(choices=[LLM_MODEL], value=LLM_MODEL, allow_custom_value=True, label="模型"),
239
+ gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="系統提示詞", lines=3),
240
+ gr.Slider(minimum=32, maximum=2048, value=512, step=32, label="最大輸出 token 數"),
241
+ gr.Slider(minimum=0.0, maximum=1.5, value=0.2, step=0.1, label="溫度"),
242
+ ],
243
+ examples=[
244
+ ["我的 Python 程式出現 IndexError,為什麼?\n```python\nnums = [1, 2, 3]\nfor i in range(len(nums) + 1):\n print(nums[i])\n```"],
245
+ ["這段 C++ 編譯不過,錯在哪裡?\n```cpp\n#include <iostream>\nint main() {\n std::cout << \"hi\" << std::endl\n return 0;\n}\n```"],
246
+ ["寫一個 Python 函式,判斷字串是否為回文。"],
247
+ ["請說明 C++ 的指標(pointer)和參照(reference)的差別。"],
248
+ ],
249
+ cache_examples=False,
250
+ )
251
+
252
+ with gr.Tab("伺服器狀態"):
253
+ status = gr.Markdown()
254
+ refresh = gr.Button("重新檢查")
255
+ refresh.click(server_status, outputs=status)
256
+ demo.load(server_status, outputs=status)
257
 
258
  if __name__ == "__main__":
259
+ demo.launch()