Spaces:
Running
Running
Download app.py from htchu/coderhelper: direct link, hf CLI and curl.
- Browser
- Download file 5.58 kB
-
https://huggingface.co/spaces/htchu/coderhelper/resolve/main/app.py
- Command line
-
hf download hf://spaces/htchu/coderhelper/app.py
-
curl -L -o app.py https://huggingface.co/spaces/htchu/coderhelper/resolve/main/app.py
5.58 kB
| import os | |
| import time | |
| import gradio as gr | |
| import httpx | |
| from openai import OpenAI | |
| LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api02.webinfo.tw/v1") | |
| LLM_API_KEY = os.environ.get("LLM_API_KEY", "") | |
| LLM_MODEL = os.environ.get("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ") | |
| # vLLM serves /health and /metrics at the server root, not under /v1 | |
| SERVER_ROOT = LLM_BASE_URL.rstrip("/").removesuffix("/v1") | |
| GPU_DESCRIPTION = "NVIDIA GeForce RTX 2080 Ti,11 GB VRAM" | |
| DEFAULT_SYSTEM_PROMPT = ( | |
| "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答," | |
| "清楚說明概念,撰寫正確且易讀的程式碼,並指出錯誤或邊界情況。" | |
| "程式碼請放在附上語言名稱的 fenced code block 中。" | |
| ) | |
| client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY) | |
| def respond(message, history, model, system_prompt, max_tokens, temperature): | |
| messages = [{"role": "system", "content": system_prompt or DEFAULT_SYSTEM_PROMPT}] | |
| messages += [{"role": m["role"], "content": m["content"]} for m in history] | |
| messages.append({"role": "user", "content": message}) | |
| stream = client.chat.completions.create( | |
| model=model or LLM_MODEL, | |
| messages=messages, | |
| max_tokens=int(max_tokens or 512), | |
| temperature=float(temperature or 0.2), | |
| stream=True, | |
| ) | |
| partial = "" | |
| for chunk in stream: | |
| if not chunk.choices: | |
| continue | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| partial += delta | |
| yield partial | |
| def read_metrics(text): | |
| """Return the latest value of each vLLM metric line, keyed by metric name.""" | |
| values = {} | |
| for line in text.splitlines(): | |
| if line.startswith("#") or not line.strip(): | |
| continue | |
| name = line.split("{", 1)[0].split(" ", 1)[0] | |
| values[name] = float(line.rsplit(" ", 1)[1]) | |
| return values | |
| def server_status(): | |
| headers = {"Authorization": f"Bearer {LLM_API_KEY}"} | |
| lines = [f"**GPU**:{GPU_DESCRIPTION}(設定值,vLLM 不回報實際 VRAM 用量)", ""] | |
| try: | |
| with httpx.Client(timeout=5) as http: | |
| start = time.perf_counter() | |
| health = http.get(f"{SERVER_ROOT}/health") | |
| latency_ms = (time.perf_counter() - start) * 1000 | |
| lines.append("| 項目 | 狀態 |") | |
| lines.append("| --- | --- |") | |
| lines.append( | |
| f"| 服務健康檢查 | {'正常' if health.status_code == 200 else f'異常 (HTTP {health.status_code})'} |" | |
| ) | |
| lines.append(f"| 健康檢查回應時間 | {latency_ms:.0f} ms |") | |
| models = http.get(f"{LLM_BASE_URL}/models", headers=headers) | |
| models.raise_for_status() | |
| served = models.json()["data"] | |
| served_ids = [m["id"] for m in served] | |
| lines.append(f"| 已載入模型 | {', '.join(served_ids) or '無'} |") | |
| lines.append(f"| 設定的模型是否已載入 | {'是' if LLM_MODEL in served_ids else '否'} |") | |
| for m in served: | |
| if "max_model_len" in m: | |
| lines.append(f"| {m['id']} 最大上下文長度 | {m['max_model_len']} tokens |") | |
| metrics = http.get(f"{SERVER_ROOT}/metrics") | |
| if metrics.status_code == 200: | |
| values = read_metrics(metrics.text) | |
| cache = values.get("vllm:gpu_cache_usage_perc", values.get("vllm:kv_cache_usage_perc")) | |
| if cache is not None: | |
| lines.append(f"| KV cache 使用率 | {cache * 100:.1f}% |") | |
| if "vllm:num_requests_running" in values: | |
| lines.append(f"| 執行中請求 | {values['vllm:num_requests_running']:.0f} |") | |
| if "vllm:num_requests_waiting" in values: | |
| lines.append(f"| 排隊中請求 | {values['vllm:num_requests_waiting']:.0f} |") | |
| except httpx.HTTPError as e: | |
| lines.append(f"**無法連線到 vLLM 伺服器**:{e}") | |
| except Exception as e: | |
| lines.append(f"**檢查失敗**:{e}") | |
| lines.append("") | |
| lines.append(f"檢查時間:{time.strftime('%Y-%m-%d %H:%M:%S')}") | |
| return "\n".join(lines) | |
| with gr.Blocks(title="程式設計小幫手") as demo: | |
| with gr.Tab("對話"): | |
| gr.ChatInterface( | |
| fn=respond, | |
| title="程式設計小幫手", | |
| description="提出程式設計相關的問題,回答由自架的開源大型語言模型產生。", | |
| additional_inputs=[ | |
| gr.Dropdown(choices=[LLM_MODEL], value=LLM_MODEL, allow_custom_value=True, label="模型"), | |
| gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="系統提示詞", lines=3), | |
| gr.Slider(minimum=32, maximum=2048, value=512, step=32, label="最大輸出 token 數"), | |
| gr.Slider(minimum=0.0, maximum=1.5, value=0.2, step=0.1, label="溫度"), | |
| ], | |
| examples=[ | |
| ["寫一個 Python 函式,判斷字串是否為回文。"], | |
| ["為什麼 JavaScript 的 `for (var i...)` 迴圈搭配 setTimeout 每次都印出同一個數字?"], | |
| ["請說明行程(process)和執行緒(thread)的差別。"], | |
| ], | |
| cache_examples=False, | |
| ) | |
| with gr.Tab("伺服器狀態"): | |
| status = gr.Markdown() | |
| refresh = gr.Button("重新檢查") | |
| refresh.click(server_status, outputs=status) | |
| demo.load(server_status, outputs=status) | |
| if __name__ == "__main__": | |
| demo.launch() | |