import os import re import time import gradio as gr import httpx from openai import OpenAI # ZeroGPU Space 啟動時要求至少有一個 @spaces.GPU 函式,否則會出現 # "Runtime error: No @spaces.GPU function detected during startup"。 # 本程式的運算都在遠端 LLM Server,不需要 GPU,所以只放一個空函式通過檢查。 # ⚠️ 請勿刪除這段。本機沒有安裝 spaces 套件時會自動略過。 try: import spaces @spaces.GPU def _zerogpu_placeholder(): pass except ImportError: pass # 7B 模型偶爾會混入簡體字,顯示前自動轉成繁體(台灣用語);套件不存在時直接顯示原文 try: from opencc import OpenCC _cc = OpenCC("s2twp") def _to_tw(text): # OpenCC 常把「了」誤轉成「瞭」(例如「宣告瞭」),轉回「了」(「了解」在台灣也是標準寫法) return _cc.convert(text).replace("瞭", "了") except Exception: def _to_tw(text): return text # Gradio 6 前端的 Prism 載入 cpp 語法時沒有先載入它依賴的 c 語法,會丟出 TypeError, # 導致 ```cpp 程式碼區塊整段顯示成空白。把 C++ 系列的語言標籤改成 c(上色效果幾乎相同)。 _CPP_FENCE = re.compile(r"^([ \t]*(?:```|~~~)[ \t]*)(?:c\+\+|cpp|cxx|cc|hpp|hxx|h)(?=[ \t]*$|\s)", re.IGNORECASE | re.MULTILINE) def _fix_code_fences(text): return _CPP_FENCE.sub(r"\1c", text) # --------------------------------------------------------------------------- # 設定 # --------------------------------------------------------------------------- def _env(name, default=""): """讀環境變數並去掉前後空白;變數存在但為空值時,也改用預設值。""" return (os.getenv(name) or "").strip() or default def _clean_url(value, default): """從設定值抽出第一個網址;可處理從聊天軟體複製來的 Markdown 連結,例如 [https://x/v1](https://x/v1)。""" m = re.search(r"https?://[^\s\[\]()<>\"']+", value or "") return m.group(0).rstrip("/") if m else default # API Key 請設在 Space Settings → Variables and secrets 的 Secret(勿寫在程式碼裡) LLM_BASE_URL = _clean_url(_env("LLM_BASE_URL"), "https://api02.webinfo.tw/v1") LLM_API_KEY = _env("LLM_API_KEY") LLM_MODEL = _env("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ") _RAW_KEY_LEN = len(os.getenv("LLM_API_KEY") or "") # 診斷用:只記長度,不記內容 # vLLM 的 /health 與 /metrics 在伺服器根目錄,不在 /v1 底下 SERVER_ROOT = LLM_BASE_URL.removesuffix("/v1") GPU_DESCRIPTION = "NVIDIA GeForce RTX 2080 Ti,11 GB VRAM" DEFAULT_SYSTEM_PROMPT = ( "你是一位樂於助人的程式設計助理,對象是台灣的大學生。" "請一律使用「繁體中文(台灣用語)」回答,絕對不要使用簡體字。" "清楚說明概念與錯誤原因,撰寫正確且易讀的程式碼,並指出錯誤或邊界情況。" "程式碼請放在附上語言名稱的 fenced code block 中。" ) # 模型上下文上限為 4096 tokens,需扣掉回答長度;以「1 個字元 ≈ 1 個 token」保守估算 CONTEXT_LIMIT = 4096 CONTEXT_RESERVE = 300 # 系統提示詞與格式的額外開銷 client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY or "missing-key", timeout=120) # --------------------------------------------------------------------------- # 對話 # --------------------------------------------------------------------------- def _text(content): """Gradio 6 的訊息內容可能是字串,也可能是 [{"type": "text", "text": ...}] 列表。""" if isinstance(content, str): return content if isinstance(content, list): return "".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content) return str(content or "") def _history_to_messages(history, budget_chars): """同時支援 Gradio 6 的 dict 格式與舊版的 (user, assistant) tuple 格式,並截短到預算內。""" msgs = [] for item in history or []: if isinstance(item, dict): if item.get("role") in ("user", "assistant"): msgs.append({"role": item["role"], "content": _text(item.get("content"))}) else: human, assistant = item if human: msgs.append({"role": "user", "content": _text(human)}) if assistant: msgs.append({"role": "assistant", "content": _text(assistant)}) # 從最舊的訊息開始捨棄,直到長度在預算內;對話必須以 user 開頭 while msgs and sum(len(m["content"]) for m in msgs) > budget_chars: msgs.pop(0) while msgs and msgs[0]["role"] != "user": msgs.pop(0) return msgs def respond(message, history, model, system_prompt, max_tokens, temperature): if not LLM_API_KEY: yield ( "⚠️ 尚未設定 LLM_API_KEY。請到 Space Settings → Variables and secrets 按 New secret," "Name 填 `LLM_API_KEY`、Value 貼上老師給的 Key,存檔後重啟 Space。\n\n" f"診斷:LLM_API_KEY 原始長度 = {_RAW_KEY_LEN}(正確應為 64);BASE_URL = `{LLM_BASE_URL}`" ) return max_tokens = int(max_tokens or 512) system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT message = _text(message) budget = CONTEXT_LIMIT - max_tokens - CONTEXT_RESERVE - len(system_prompt) - len(message) messages = [{"role": "system", "content": system_prompt}] messages += _history_to_messages(history, max(budget, 0)) messages.append({"role": "user", "content": message}) model = model or LLM_MODEL try: stream = client.chat.completions.create( model=model, messages=messages, max_tokens=max_tokens, temperature=float(temperature if temperature is not None else 0.2), stream=True, ) partial = "" for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: partial += chunk.choices[0].delta.content yield _fix_code_fences(_to_tw(partial)) if not partial: yield "(模型沒有回傳內容,請再試一次)" except Exception as e: yield f"連線錯誤或後端異常:{type(e).__name__}: {e}\n\n(BASE_URL = {LLM_BASE_URL},MODEL = {model})" # --------------------------------------------------------------------------- # 伺服器狀態 # --------------------------------------------------------------------------- def read_metrics(text): """回傳每個 vLLM 指標的最新值,以指標名稱為 key。""" values = {} for line in text.splitlines(): if line.startswith("#") or not line.strip(): continue name = line.split("{", 1)[0].split(" ", 1)[0] try: values[name] = float(line.rsplit(" ", 1)[1]) except ValueError: continue return values def server_status(): headers = {"Authorization": f"Bearer {LLM_API_KEY}"} lines = [f"**GPU**:{GPU_DESCRIPTION}(設定值,vLLM 不回報實際 VRAM 用量)", ""] notes = [] try: with httpx.Client(timeout=10) as http: lines += ["| 項目 | 狀態 |", "| --- | --- |"] # 1. 模型清單(同時當作 API 連線與回應時間檢查) start = time.perf_counter() models = http.get(f"{LLM_BASE_URL}/models", headers=headers) latency_ms = (time.perf_counter() - start) * 1000 if models.status_code == 200: served = models.json().get("data", []) served_ids = [m["id"] for m in served] lines.append("| API 連線 | ✅ 正常 |") lines.append(f"| API 回應時間 | {latency_ms:.0f} ms |") 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 |") elif models.status_code == 401: lines.append("| API 連線 | ❌ 金鑰錯誤(HTTP 401),請檢查 LLM_API_KEY |") else: lines.append(f"| API 連線 | ❌ 異常(HTTP {models.status_code}) |") # 2. 健康檢查 health = http.get(f"{SERVER_ROOT}/health") if health.status_code == 200: lines.append("| 服務健康檢查 | ✅ 正常 |") elif health.status_code == 404: lines.append("| 服務健康檢查 | ➖ 伺服器未對外開放 /health |") else: lines.append(f"| 服務健康檢查 | ❌ 異常(HTTP {health.status_code}) |") # 3. vLLM 即時指標 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} |") else: lines.append("| KV cache / 請求數 | ➖ 伺服器未對外開放 /metrics |") notes.append( "ℹ️ 伺服器的閘道目前只轉發 `/v1` 底下的 API,`/health` 與 `/metrics` 沒有對外開放," "因此無法顯示 KV cache 使用率與請求數。若需要這些資料,需請老師在伺服器端開放。" ) except httpx.HTTPError as e: lines.append(f"**無法連線到 LLM 伺服器**:{type(e).__name__}: {e}") except Exception as e: lines.append(f"**檢查失敗**:{type(e).__name__}: {e}") lines.append("") for note in notes: lines += [note, ""] # Space 主機使用 UTC,轉成台灣時間(UTC+8)顯示 tw_now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + 8 * 3600)) lines.append(f"檢查時間:{tw_now}(台灣時間)") return "\n".join(lines) # --------------------------------------------------------------------------- # 介面 # --------------------------------------------------------------------------- with gr.Blocks(title="程式設計小幫手") as demo: with gr.Tab("對話"): gr.ChatInterface( fn=respond, title="程式設計小幫手", description="貼上你的 C++ / Python 程式碼與錯誤訊息,或提出程式設計相關的問題。回答由實驗室自架的開源大型語言模型產生。", 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 程式出現 IndexError,為什麼?\n```python\nnums = [1, 2, 3]\nfor i in range(len(nums) + 1):\n print(nums[i])\n```"], ["這段 C++ 編譯不過,錯在哪裡?\n```c\n#include \nint main() {\n std::cout << \"hi\" << std::endl\n return 0;\n}\n```"], ["寫一個 Python 函式,判斷字串是否為回文。"], ["請說明 C++ 的指標(pointer)和參照(reference)的差別。"], ], 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()