broccoli0510 commited on
Commit
fbd1921
·
verified ·
1 Parent(s): 0a4ab83

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -56
app.py CHANGED
@@ -2,64 +2,20 @@ import os
2
  import gradio as gr
3
  from openai import OpenAI
4
 
5
- def _env(name, default=""):
6
- """讀環境變數並去掉前後空白;變數存在但是空值時,也改用預設值。"""
7
- return (os.getenv(name) or "").strip() or default
8
-
9
-
10
- BASE_URL = _env("LLM_BASE_URL", "https://api01.webinfo.tw/v1")
11
- API_KEY = _env("LLM_API_KEY")
12
- DEFAULT_MODEL = _env("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
13
- _RAW_KEY_LEN = len(os.getenv("LLM_API_KEY") or "") # 診斷用:只記長度,不記內容
14
-
15
- client = OpenAI(base_url=BASE_URL, api_key=API_KEY or "missing-key", timeout=120)
16
-
17
- # ZeroGPU Space 啟動時要求至少有一個 @spaces.GPU 函式,否則會出現 Runtime Error。
18
- # 本程式的運算都在遠端 LLM Server,不需要 GPU,所以只放一個空函式通過檢查。
19
- # 本機沒有安裝 spaces 套件時會自動略過。
20
- try:
21
- import spaces
22
-
23
- @spaces.GPU
24
- def _zerogpu_placeholder():
25
- pass
26
- except ImportError:
27
- pass
28
-
29
- def _text(content):
30
- """Gradio 6 的訊息內容可能是字串,也可能是 [{"type": "text", "text": ...}] 列表。"""
31
- if isinstance(content, str):
32
- return content
33
- if isinstance(content, list):
34
- return "".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content)
35
- return str(content or "")
36
 
 
37
 
38
  def predict(message, history):
39
- if not API_KEY:
40
- # 只列出名稱(不顯示值),幫忙找出名稱打錯的情況
41
- similar = [k for k in os.environ if "KEY" in k.upper() or "LLM" in k.upper()]
42
- yield (
43
- "⚠️ 尚未設定 LLM_API_KEY,請到 Space Settings → Variables and secrets 新增 Secret,"
44
- "名稱必須完全是 `LLM_API_KEY`,新增後要重啟 Space。\n\n"
45
- f"目前偵測到的相似環境變數名稱:{', '.join(f'`{k!r}`' for k in similar) or '(無)'}\n\n"
46
- f"診斷:LLM_API_KEY 原始長度 = {_RAW_KEY_LEN}(正確的 Key 應為 64);"
47
- f"BASE_URL = `{BASE_URL}`;MODEL = `{DEFAULT_MODEL}`"
48
- )
49
- return
50
-
51
- # 將歷史訊息轉換為 OpenAI API 格式(同時支援 Gradio 6 的 dict 格式與舊版的 tuple 格式)
52
- messages = [{"role": "system", "content": "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答。"}]
53
- for item in history:
54
- if isinstance(item, dict):
55
- messages.append({"role": item["role"], "content": _text(item["content"])})
56
- else:
57
- human, assistant = item
58
- messages.append({"role": "user", "content": _text(human)})
59
- if assistant:
60
- messages.append({"role": "assistant", "content": _text(assistant)})
61
- messages.append({"role": "user", "content": _text(message)})
62
-
63
  try:
64
  response = client.chat.completions.create(
65
  model=DEFAULT_MODEL,
@@ -70,7 +26,7 @@ def predict(message, history):
70
  )
71
  partial_message = ""
72
  for chunk in response:
73
- if chunk.choices and chunk.choices[0].delta.content:
74
  partial_message += chunk.choices[0].delta.content
75
  yield partial_message
76
  except Exception as e:
 
2
  import gradio as gr
3
  from openai import OpenAI
4
 
5
+ # 優先讀取環境變數,若無則使用老師指定的 api02 正確端點與金鑰
6
+ BASE_URL = os.getenv("LLM_BASE_URL", "https://api02.webinfo.tw/v1")
7
+ API_KEY = os.getenv("LLM_API_KEY", "cc4de1d6fd66357051be5f62823d2ef7823850a14cf37cb45ab573dac3f8df09")
8
+ DEFAULT_MODEL = os.getenv("LLM_MODEL", "Qwen/Qwen2.5-Coder-7B-Instruct-AWQ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=120)
11
 
12
  def predict(message, history):
13
+ messages = [{"role": "system", "content": "你是一位樂於助人的程式設計助理。請一律使用繁體中文回答,清楚說明概念與錯誤原因。"}]
14
+ for human, assistant in history:
15
+ messages.append({"role": "user", "content": human})
16
+ messages.append({"role": "assistant", "content": assistant})
17
+ messages.append({"role": "user", "content": message})
18
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
  response = client.chat.completions.create(
21
  model=DEFAULT_MODEL,
 
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: