-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathwashin_llm.py
More file actions
220 lines (180 loc) · 6.21 KB
/
Copy pathwashin_llm.py
File metadata and controls
220 lines (180 loc) · 6.21 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""Washin 統一 LLM Gateway — ClawAPI 優先,直打 Gemini fallback。
三個 Python 專案共用此模組(prnews、trump-code、jp-headline)。
在 VPS 上走 localhost:3000 打 ClawAPI(零延遲),
ClawAPI 不可用時自動 fallback 到直打 Gemini API。
用法:
from washin_llm import call_llm
result = call_llm("翻譯以下內容:...", strategy="fast")
print(result["text"])
"""
from __future__ import annotations
import json
import logging
import os
import time
from typing import Any
import requests
logger = logging.getLogger(__name__)
# ClawAPI 端點(同台 VPS 走 localhost)
CLAWAPI_URL = os.environ.get("CLAWAPI_URL", "http://localhost:3000")
CLAWAPI_KEY = os.environ.get("CLAWAPI_KEY", "")
# Gemini 直打 fallback
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
GEMINI_API_KEYS_EXTRA = os.environ.get("GEMINI_API_KEYS_EXTRA", "")
_GEMINI_FLASH_URL = (
"https://generativelanguage.googleapis.com/v1beta"
"/models/{model}:generateContent"
)
# 熔斷器:連續 N 次 ClawAPI 失敗就暫時跳過
_claw_fail_count = 0
_claw_circuit_open_until = 0.0
_CLAW_CIRCUIT_THRESHOLD = 3
_CLAW_CIRCUIT_WAIT = 60 # 秒
def _get_gemini_keys() -> list[str]:
"""取得所有 Gemini API key。"""
keys = [GEMINI_API_KEY] if GEMINI_API_KEY else []
if GEMINI_API_KEYS_EXTRA:
keys.extend(k.strip() for k in GEMINI_API_KEYS_EXTRA.split(",") if k.strip())
return keys
_gemini_key_idx = 0
def _next_gemini_key() -> str:
"""輪流取 Gemini key。"""
global _gemini_key_idx
keys = _get_gemini_keys()
if not keys:
raise RuntimeError("沒有可用的 GEMINI_API_KEY")
_gemini_key_idx = (_gemini_key_idx + 1) % len(keys)
return keys[_gemini_key_idx]
def _call_clawapi(
prompt: str,
*,
system: str = "",
strategy: str = "fast",
max_tokens: int = 2000,
temperature: float = 0.3,
timeout: int = 60,
) -> dict[str, Any] | None:
"""嘗試透過 ClawAPI 呼叫 LLM。失敗回傳 None。"""
global _claw_fail_count, _claw_circuit_open_until
# 熔斷器檢查
if time.time() < _claw_circuit_open_until:
return None
try:
headers: dict[str, str] = {"Content-Type": "application/json"}
if CLAWAPI_KEY:
headers["Authorization"] = f"Bearer {CLAWAPI_KEY}"
body: dict[str, Any] = {
"prompt": prompt,
"strategy": strategy,
"max_tokens": max_tokens,
"temperature": temperature,
}
if system:
body["system"] = system
resp = requests.post(
f"{CLAWAPI_URL}/api/v2/llm",
json=body,
headers=headers,
timeout=timeout,
)
if resp.status_code == 200:
data = resp.json()
_claw_fail_count = 0 # 重置熔斷
return {
"text": data.get("text", data.get("result", "")),
"model": data.get("model", "clawapi"),
"source": "clawapi",
"tokens": data.get("tokens_used", 0),
}
logger.warning("ClawAPI LLM %d: %s", resp.status_code, resp.text[:100])
_claw_fail_count += 1
except Exception as e:
logger.warning("ClawAPI LLM 連線失敗: %s", e)
_claw_fail_count += 1
# 達到熔斷閾值
if _claw_fail_count >= _CLAW_CIRCUIT_THRESHOLD:
_claw_circuit_open_until = time.time() + _CLAW_CIRCUIT_WAIT
logger.warning("ClawAPI 熔斷 %d 秒", _CLAW_CIRCUIT_WAIT)
return None
def _call_gemini_direct(
prompt: str,
*,
model: str = "gemini-2.5-flash",
max_tokens: int = 2000,
temperature: float = 0.3,
timeout: int = 45,
) -> dict[str, Any]:
"""直打 Gemini API(fallback)。"""
keys = _get_gemini_keys()
if not keys:
raise RuntimeError("沒有可用的 GEMINI_API_KEY,且 ClawAPI 不可用")
last_error = ""
for _ in range(len(keys)):
key = _next_gemini_key()
url = _GEMINI_FLASH_URL.format(model=model) + f"?key={key}"
body = {
"contents": [{"parts": [{"text": prompt}]}],
"generationConfig": {
"maxOutputTokens": max_tokens,
"temperature": temperature,
},
}
try:
resp = requests.post(url, json=body, timeout=timeout)
if resp.status_code == 429:
logger.warning("Gemini 429,換 key 重試")
continue
if resp.status_code == 200:
data = resp.json()
text = (
data.get("candidates", [{}])[0]
.get("content", {})
.get("parts", [{}])[0]
.get("text", "")
)
return {
"text": text,
"model": model,
"source": "gemini-direct",
"tokens": data.get("usageMetadata", {}).get("totalTokenCount", 0),
}
last_error = f"HTTP {resp.status_code}: {resp.text[:100]}"
logger.warning("Gemini 錯誤: %s", last_error)
except Exception as e:
last_error = str(e)
logger.warning("Gemini 連線失敗: %s", e)
raise RuntimeError(f"Gemini 所有 key 都失敗: {last_error}")
def call_llm(
prompt: str,
*,
system: str = "",
strategy: str = "fast",
model: str = "gemini-2.5-flash",
max_tokens: int = 2000,
temperature: float = 0.3,
timeout: int = 60,
) -> dict[str, Any]:
"""統一 LLM 呼叫入口。
優先走 ClawAPI(同台 VPS localhost,多供應商 fallback),
ClawAPI 不可用時 fallback 到直打 Gemini API。
回傳:{"text": str, "model": str, "source": "clawapi"|"gemini-direct", "tokens": int}
"""
# 第一層:ClawAPI
result = _call_clawapi(
prompt,
system=system,
strategy=strategy,
max_tokens=max_tokens,
temperature=temperature,
timeout=timeout,
)
if result and result.get("text"):
return result
# 第二層:Gemini 直打
return _call_gemini_direct(
prompt,
model=model,
max_tokens=max_tokens,
temperature=temperature,
timeout=min(timeout, 45),
)