智谱AI 外部 API 調用完整指南:模型命名坑 · 推理 token 消耗問題 · 優先級鏈設計 · GCP SM 密鑰管理
Thomas 有一套每日郵件摘要系統(GitHub Actions + Python),需要對 7 個家庭 Gmail 帳號 + QQ 郵箱的郵件進行分類(legal / finance / property / medical / church / education / family / skip)。
舊版用純 Python 關鍵詞規則分類,效果差。目標是用 AI 分類,提升準確率。
glm-4-5 或 glm-4-5-flash,全部回傳 400 Bad Request(模型不存在)。reasoning_content,content 沒 token 可用,回傳空字串。glm-5-turbo,max_tokens 設 600,從 choices[0]['message']['content'] 取結果,忽略 reasoning_content。| 模型 ID | 類型 | 適用場景 | 此 key 狀態 |
|---|---|---|---|
| glm-5-turbo | 推理模型(GLM 5) | 複雜分類、推理任務 | ✅ 可用 |
| glm-4-flash | 快速模型(GLM 4) | 批量分類、高頻調用 | ✅ 可用 |
| glm-z1-flash | 推理模型(Z1 系列) | 推理任務(回應帶 <think> 前綴) | ✅ 可用 |
| glm-4-plus / glm-4-long 等 | 進階模型 | 長文、高品質 | ❌ 余额不足 |
| glm-4-5 / glm-4-5-flash | — | — | ❌ 400 不存在 |
import urllib.request, json
KEY = 'your-api-key-here' # 從 GCP SM 讀取,不要硬編碼
body = json.dumps({
'model': 'glm-5-turbo', # ← 正確模型名
'messages': [{'role': 'user', 'content': '你好'}],
'max_tokens': 600 # ← 推理模型必須足夠大
}).encode()
req = urllib.request.Request(
'https://open.bigmodel.cn/api/paas/v4/chat/completions',
data=body,
headers={
'Authorization': f'Bearer {KEY}',
'Content-Type': 'application/json'
},
method='POST'
)
with urllib.request.urlopen(req, timeout=30) as r:
res = json.loads(r.read())
# 回應結構
content = res['choices'][0]['message']['content'] # 實際答案
reasoning = res['choices'][0]['message'].get('reasoning_content', '') # 推理過程(可忽略)
print(content)
GLM_API_KEY = os.environ.get('GLM_API_KEY', '')
def glm_classify(emails_batch):
if not GLM_API_KEY or not emails_batch:
return {}
items = '\n'.join(
f'{i+1}. 主題:{e["subject"][:80]} | 寄件:{e["from"][:40]}'
for i, e in enumerate(emails_batch)
)
prompt = (
'你是 Thomas Tang(紐西蘭)的郵件分類助手。\n'
'類別:legal/finance/property/medical/church/education/family/skip\n'
f'{items}\n只輸出 JSON,如 {"{"}"1":"legal","2":"skip"{"}"}'
)
try:
body = json.dumps({
'model': 'glm-5-turbo', # ← 必須是這個名稱
'messages': [{'role': 'user', 'content': prompt}],
'max_tokens': 600 # ← 推理模型需要足夠空間
}).encode()
req = urllib.request.Request(
'https://open.bigmodel.cn/api/paas/v4/chat/completions',
data=body,
headers={
'Authorization': f'Bearer {GLM_API_KEY}',
'Content-Type': 'application/json'
},
method='POST'
)
with urllib.request.urlopen(req, timeout=30) as r:
content = json.loads(r.read())['choices'][0]['message']['content'].strip()
m = re.search(r'\{[^}]+\}', content)
return json.loads(m.group()) if m else {}
except Exception as e:
print(f'GLM error: {e}')
return {} # 失敗時回傳空 dict,由規則分類接管
# 命名規範:服務-版本-用途(要特徵鮮明)
echo -n "your-api-key" | gcloud secrets create zhipu-GLM5Turbo-apikey \
--project=nvda-strategy --data-file=-
# 驗證
gcloud secrets versions access latest --secret=zhipu-GLM5Turbo-apikey --project=nvda-strategy
gh secret set GLM_API_KEY \
--repo thomastangnz-commits/downloads-config \
--body "your-api-key"
env:
GLM_API_KEY: ${{ secrets.GLM_API_KEY }}
GLM_API_KEY = os.environ.get('GLM_API_KEY', '')
# 注意:用 .get() 讓它在沒有 key 時 gracefully fallback
登入 open.bigmodel.cn → 控制台 → 用量統計,查看各模型的消耗和剩餘配額。也可以下載 PDF 模型清單(已存於 G 盤:G:/我的云端硬盘/软件工具/GLM_API_模型清单.pdf)
glm-5-turbo 和 glm-z1 系列都是推理模型(類似 OpenAI o1),回應結構與普通模型不同:
{
"choices": [{
"message": {
"content": "legal", // ← 你要的答案在這裡
"reasoning_content": "1. 分析主題...\n...", // ← 推理過程,可忽略
"role": "assistant"
}
}],
"usage": {
"completion_tokens": 200,
"completion_tokens_details": {
"reasoning_tokens": 180 // ← 大部分 token 用於推理
},
"prompt_tokens": 50
}
}