Spaces:
Sleeping
Sleeping
Commit ·
cce5088
1
Parent(s): fbd1921
Restore ZeroGPU placeholder and fixes; use api02 endpoint
Browse filesRe-add the @spaces.GPU placeholder (startup check), Gradio 6 history
handling, empty-env fallback, and history trimming for the 4096-token
context. API key is read from the LLM_API_KEY Space secret only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
app.py
CHANGED
|
@@ -1,41 +1,109 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=120)
|
| 11 |
|
| 12 |
def predict(message, history):
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
try:
|
| 20 |
response = client.chat.completions.create(
|
| 21 |
model=DEFAULT_MODEL,
|
| 22 |
messages=messages,
|
| 23 |
-
max_tokens=
|
| 24 |
temperature=0.2,
|
| 25 |
-
stream=True
|
| 26 |
)
|
| 27 |
partial_message = ""
|
| 28 |
for chunk in response:
|
| 29 |
-
if chunk.choices[0].delta.content:
|
| 30 |
partial_message += chunk.choices[0].delta.content
|
| 31 |
yield partial_message
|
|
|
|
|
|
|
| 32 |
except Exception as e:
|
| 33 |
-
yield f"連線錯誤或後端異常:{
|
|
|
|
| 34 |
|
| 35 |
demo = gr.ChatInterface(
|
| 36 |
fn=predict,
|
| 37 |
-
title="程式設計小幫手"
|
| 38 |
)
|
| 39 |
|
| 40 |
if __name__ == "__main__":
|
| 41 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
+
|
| 3 |
import gradio as gr
|
| 4 |
from openai import OpenAI
|
| 5 |
|
| 6 |
+
# ZeroGPU Space 啟動時要求至少有一個 @spaces.GPU 函式,否則會出現
|
| 7 |
+
# "Runtime error: No @spaces.GPU function detected during startup"。
|
| 8 |
+
# 本程式的運算都在遠端 LLM Server,不需要 GPU,所以只放一個空函式通過檢查。
|
| 9 |
+
# ⚠️ 請勿刪除這段。本機沒有安裝 spaces 套件時會自動略過。
|
| 10 |
+
try:
|
| 11 |
+
import spaces
|
| 12 |
+
|
| 13 |
+
@spaces.GPU
|
| 14 |
+
def _zerogpu_placeholder():
|
| 15 |
+
pass
|
| 16 |
+
except ImportError:
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _env(name, default=""):
|
| 21 |
+
"""讀環境變數並去掉前後空白;變數存在但為空值時,也改用預設值。"""
|
| 22 |
+
return (os.getenv(name) or "").strip() or default
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# 讀取 Space 的環境變數;API Key 請設在 Space Settings → Variables and secrets 的 Secret(勿寫在程式碼裡)
|
| 26 |
+
BASE_URL = _env("LLM_BASE_URL", "https://api02.webinfo.tw/v1")
|
| 27 |
+
API_KEY = _env("LLM_API_KEY")
|
| 28 |
+
_RAW_KEY_LEN = len(os.getenv("LLM_API_KEY") or "") # 診斷用:只記長度,不記內容
|
| 29 |
+
DEFAULT_MODEL = _env("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
|
| 30 |
+
|
| 31 |
+
client = OpenAI(base_url=BASE_URL, api_key=API_KEY or "missing-key", timeout=120)
|
| 32 |
+
|
| 33 |
+
SYSTEM_PROMPT = "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答,清楚說明概念與錯誤原因。"
|
| 34 |
+
|
| 35 |
+
# 模型上下文上限為 4096 tokens:保留 512 給回答,對話歷史超過約 6000 字元時從最舊的開始捨棄
|
| 36 |
+
MAX_TOKENS = 512
|
| 37 |
+
MAX_HISTORY_CHARS = 6000
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _text(content):
|
| 41 |
+
"""Gradio 6 的訊息內容可能是字串,也可能是 [{"type": "text", "text": ...}] 列表。"""
|
| 42 |
+
if isinstance(content, str):
|
| 43 |
+
return content
|
| 44 |
+
if isinstance(content, list):
|
| 45 |
+
return "".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content)
|
| 46 |
+
return str(content or "")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _history_to_messages(history):
|
| 50 |
+
"""同時支援 Gradio 6 的 dict 格式與舊版的 (user, assistant) tuple 格式。"""
|
| 51 |
+
msgs = []
|
| 52 |
+
for item in history or []:
|
| 53 |
+
if isinstance(item, dict):
|
| 54 |
+
if item.get("role") in ("user", "assistant"):
|
| 55 |
+
msgs.append({"role": item["role"], "content": _text(item.get("content"))})
|
| 56 |
+
else:
|
| 57 |
+
human, assistant = item
|
| 58 |
+
if human:
|
| 59 |
+
msgs.append({"role": "user", "content": _text(human)})
|
| 60 |
+
if assistant:
|
| 61 |
+
msgs.append({"role": "assistant", "content": _text(assistant)})
|
| 62 |
+
# 從最舊的訊息開始捨棄,直到長度在上限內
|
| 63 |
+
while msgs and sum(len(m["content"]) for m in msgs) > MAX_HISTORY_CHARS:
|
| 64 |
+
msgs.pop(0)
|
| 65 |
+
# 對話必須以 user 開頭
|
| 66 |
+
while msgs and msgs[0]["role"] != "user":
|
| 67 |
+
msgs.pop(0)
|
| 68 |
+
return msgs
|
| 69 |
|
|
|
|
| 70 |
|
| 71 |
def predict(message, history):
|
| 72 |
+
if not API_KEY:
|
| 73 |
+
yield (
|
| 74 |
+
"⚠️ 尚未設定 LLM_API_KEY。請到 Space Settings → Variables and secrets 按 New secret,"
|
| 75 |
+
"Name 填 `LLM_API_KEY`、Value 貼上老師給的 Key,存檔後重啟 Space。\n\n"
|
| 76 |
+
f"診斷:LLM_API_KEY 原始長度 = {_RAW_KEY_LEN}(正確應為 64);BASE_URL = `{BASE_URL}`"
|
| 77 |
+
)
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
messages =[{"role": "system", "content": SYSTEM_PROMPT}]
|
| 81 |
+
messages += _history_to_messages(history)
|
| 82 |
+
messages.append({"role": "user", "content": _text(message)})
|
| 83 |
+
|
| 84 |
try:
|
| 85 |
response = client.chat.completions.create(
|
| 86 |
model=DEFAULT_MODEL,
|
| 87 |
messages=messages,
|
| 88 |
+
max_tokens=MAX_TOKENS,
|
| 89 |
temperature=0.2,
|
| 90 |
+
stream=True,
|
| 91 |
)
|
| 92 |
partial_message = ""
|
| 93 |
for chunk in response:
|
| 94 |
+
if chunk.choices and chunk.choices[0].delta.content:
|
| 95 |
partial_message += chunk.choices[0].delta.content
|
| 96 |
yield partial_message
|
| 97 |
+
if not partial_message:
|
| 98 |
+
yield "(模型沒有回傳內容,請再試一次)"
|
| 99 |
except Exception as e:
|
| 100 |
+
yield f"連線錯誤或後端異常:{type(e).__name__}: {e}\n\n(BASE_URL = {BASE_URL},MODEL = {DEFAULT_MODEL})"
|
| 101 |
+
|
| 102 |
|
| 103 |
demo = gr.ChatInterface(
|
| 104 |
fn=predict,
|
| 105 |
+
title="程式設計小幫手",
|
| 106 |
)
|
| 107 |
|
| 108 |
if __name__ == "__main__":
|
| 109 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|