File size: 5,580 Bytes
98e7f1e
330ba02
98e7f1e
 
330ba02
98e7f1e
 
 
 
 
 
330ba02
 
 
 
98e7f1e
1335812
 
 
98e7f1e
 
 
 
 
 
2ac826a
98e7f1e
 
 
 
2ac826a
98e7f1e
2ac826a
 
98e7f1e
 
 
 
 
 
 
 
 
 
 
 
 
330ba02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98e7f1e
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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()