htchu Claude Haiku 5.5 commited on
Commit
330ba02
·
1 Parent(s): 1335812

Add vLLM server status tab to Coder Helper

Browse files

Split the UI into a 對話 tab and a 伺服器狀態 tab. The status tab checks
/health, lists served models and their context length from /v1/models,
and reads KV cache usage and request counts from vLLM's /metrics. It
shows the RTX 2080 Ti 11 GB as a configured reference value, since vLLM
does not report real VRAM usage.

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

Files changed (2) hide show
  1. app.py +88 -17
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,12 +1,18 @@
1
  import os
 
2
 
3
  import gradio as gr
 
4
  from openai import OpenAI
5
 
6
  LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api02.webinfo.tw/v1")
7
  LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
8
  LLM_MODEL = os.environ.get("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
9
 
 
 
 
 
10
  DEFAULT_SYSTEM_PROMPT = (
11
  "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答,"
12
  "清楚說明概念,撰寫正確且易讀的程式碼,並指出錯誤或邊界情況。"
@@ -39,23 +45,88 @@ def respond(message, history, model, system_prompt, max_tokens, temperature):
39
  yield partial
40
 
41
 
42
- demo = gr.ChatInterface(
43
- fn=respond,
44
- title="程式設計小幫手",
45
- description="提出程式設計相關的問題,回答由自架的開源大型語言模型產生。",
46
- additional_inputs=[
47
- gr.Dropdown(choices=[LLM_MODEL], value=LLM_MODEL, allow_custom_value=True, label="模型"),
48
- gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="系統提示詞", lines=3),
49
- gr.Slider(minimum=32, maximum=2048, value=512, step=32, label="最大輸出 token 數"),
50
- gr.Slider(minimum=0.0, maximum=1.5, value=0.2, step=0.1, label="溫度"),
51
- ],
52
- examples=[
53
- ["寫一個 Python 函式,判斷字串是否為回文。"],
54
- ["為什麼 JavaScript 的 `for (var i...)` 迴圈搭配 setTimeout 每次都印出同一個數字?"],
55
- ["請說明行程(process)和執行緒(thread)的差別。"],
56
- ],
57
- cache_examples=False,
58
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  if __name__ == "__main__":
61
  demo.launch()
 
1
  import os
2
+ import time
3
 
4
  import gradio as gr
5
+ import httpx
6
  from openai import OpenAI
7
 
8
  LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api02.webinfo.tw/v1")
9
  LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
10
  LLM_MODEL = os.environ.get("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
11
 
12
+ # vLLM serves /health and /metrics at the server root, not under /v1
13
+ SERVER_ROOT = LLM_BASE_URL.rstrip("/").removesuffix("/v1")
14
+ GPU_DESCRIPTION = "NVIDIA GeForce RTX 2080 Ti,11 GB VRAM"
15
+
16
  DEFAULT_SYSTEM_PROMPT = (
17
  "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答,"
18
  "清楚說明概念,撰寫正確且易讀的程式碼,並指出錯誤或邊界情況。"
 
45
  yield partial
46
 
47
 
48
+ def read_metrics(text):
49
+ """Return the latest value of each vLLM metric line, keyed by metric name."""
50
+ values = {}
51
+ for line in text.splitlines():
52
+ if line.startswith("#") or not line.strip():
53
+ continue
54
+ name = line.split("{", 1)[0].split(" ", 1)[0]
55
+ values[name] = float(line.rsplit(" ", 1)[1])
56
+ return values
57
+
58
+
59
+ def server_status():
60
+ headers = {"Authorization": f"Bearer {LLM_API_KEY}"}
61
+ lines = [f"**GPU**:{GPU_DESCRIPTION}(設定值,vLLM 不回報實際 VRAM 用量)", ""]
62
+
63
+ try:
64
+ with httpx.Client(timeout=5) as http:
65
+ start = time.perf_counter()
66
+ health = http.get(f"{SERVER_ROOT}/health")
67
+ latency_ms = (time.perf_counter() - start) * 1000
68
+ lines.append("| 項目 | 狀態 |")
69
+ lines.append("| --- | --- |")
70
+ lines.append(
71
+ f"| 服務健康檢查 | {'正常' if health.status_code == 200 else f'異常 (HTTP {health.status_code})'} |"
72
+ )
73
+ lines.append(f"| 健康檢查回應時間 | {latency_ms:.0f} ms |")
74
+
75
+ models = http.get(f"{LLM_BASE_URL}/models", headers=headers)
76
+ models.raise_for_status()
77
+ served = models.json()["data"]
78
+ served_ids = [m["id"] for m in served]
79
+ lines.append(f"| 已載入模型 | {', '.join(served_ids) or '無'} |")
80
+ lines.append(f"| 設定的模型是否已載入 | {'是' if LLM_MODEL in served_ids else '否'} |")
81
+ for m in served:
82
+ if "max_model_len" in m:
83
+ lines.append(f"| {m['id']} 最大上下文長度 | {m['max_model_len']} tokens |")
84
+
85
+ metrics = http.get(f"{SERVER_ROOT}/metrics")
86
+ if metrics.status_code == 200:
87
+ values = read_metrics(metrics.text)
88
+ cache = values.get("vllm:gpu_cache_usage_perc", values.get("vllm:kv_cache_usage_perc"))
89
+ if cache is not None:
90
+ lines.append(f"| KV cache 使用率 | {cache * 100:.1f}% |")
91
+ if "vllm:num_requests_running" in values:
92
+ lines.append(f"| 執行中請求 | {values['vllm:num_requests_running']:.0f} |")
93
+ if "vllm:num_requests_waiting" in values:
94
+ lines.append(f"| 排隊中請求 | {values['vllm:num_requests_waiting']:.0f} |")
95
+ except httpx.HTTPError as e:
96
+ lines.append(f"**無法連線到 vLLM 伺服器**:{e}")
97
+ except Exception as e:
98
+ lines.append(f"**檢查失敗**:{e}")
99
+
100
+ lines.append("")
101
+ lines.append(f"檢查時間:{time.strftime('%Y-%m-%d %H:%M:%S')}")
102
+ return "\n".join(lines)
103
+
104
+
105
+ with gr.Blocks(title="程式設計小幫手") as demo:
106
+ with gr.Tab("對話"):
107
+ gr.ChatInterface(
108
+ fn=respond,
109
+ title="程式設計小幫手",
110
+ description="提出程式設計相關的問題,回答由自架的開源大型語言模型產生。",
111
+ additional_inputs=[
112
+ gr.Dropdown(choices=[LLM_MODEL], value=LLM_MODEL, allow_custom_value=True, label="模型"),
113
+ gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="系統提示詞", lines=3),
114
+ gr.Slider(minimum=32, maximum=2048, value=512, step=32, label="最大輸出 token 數"),
115
+ gr.Slider(minimum=0.0, maximum=1.5, value=0.2, step=0.1, label="溫度"),
116
+ ],
117
+ examples=[
118
+ ["寫一個 Python 函式,判斷字串是否為回文。"],
119
+ ["為什麼 JavaScript 的 `for (var i...)` 迴圈搭配 setTimeout 每次都印出同一個數字?"],
120
+ ["請說明行程(process)和執行緒(thread)的差別。"],
121
+ ],
122
+ cache_examples=False,
123
+ )
124
+
125
+ with gr.Tab("伺服器狀態"):
126
+ status = gr.Markdown()
127
+ refresh = gr.Button("重新檢查")
128
+ refresh.click(server_status, outputs=status)
129
+ demo.load(server_status, outputs=status)
130
 
131
  if __name__ == "__main__":
132
  demo.launch()
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  gradio==6.31.0
2
  openai
 
 
1
  gradio==6.31.0
2
  openai
3
+ httpx