ilang-ai commited on
Commit
c5249c3
·
1 Parent(s): a1c8ad4

Phase 1: 去 Gemini,AI 改走 OpenAI 兼容 provider(默认硅基流动)

Browse files

- 新增 modules/ai_provider.py:OpenAI兼容抽象层,文本+视觉容错链+600px压缩+懒加载,
任何 OpenAI 兼容供应商(SiliconFlow/OpenAI/DeepSeek/本地vLLM)都能接
- chat.py 去 google-generativeai/SAFETY_SETTINGS/_safe_text,7个函数走 provider,保留 .ilang prompt 与全部行为
- config.py:Gemini → AI_API_KEY/AI_BASE_URL/AI_MODEL/AI_VISION_MODELS(env)
- bot.py 启动AI测试改走 provider;requirements 换 openai+Pillow
- 实测:中英双语聊天 + 判spam(广告→True/闲聊→False)均正确

Files changed (5) hide show
  1. bot.py +4 -8
  2. config.py +10 -3
  3. modules/ai_provider.py +150 -0
  4. modules/chat.py +20 -65
  5. requirements.txt +2 -1
bot.py CHANGED
@@ -487,14 +487,10 @@ def main():
487
  # Polling mode: run AI test first, then start
488
  async def _test_ai():
489
  try:
490
- from modules.chat import model, _safe_text
491
- r = await model.generate_content_async("Say hi in one word. JSON: {\"intent\":\"chat\",\"reply\":\"hi\"}", safety_settings=[
492
- {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
493
- {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
494
- {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
495
- {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
496
- ])
497
- text = _safe_text(r)
498
  if text:
499
  logger.info("AI startup test OK: " + text[:100])
500
  else:
 
487
  # Polling mode: run AI test first, then start
488
  async def _test_ai():
489
  try:
490
+ from modules import ai_provider
491
+ text = await ai_provider.generate_text(
492
+ "Say hi in one word. JSON: {\"intent\":\"chat\",\"reply\":\"hi\"}",
493
+ max_tokens=50)
 
 
 
 
494
  if text:
495
  logger.info("AI startup test OK: " + text[:100])
496
  else:
config.py CHANGED
@@ -3,9 +3,16 @@ import os
3
  # Telegram Bot
4
  BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
5
 
6
- # Gemini AI
7
- GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
8
- GEMINI_MODEL = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash")
 
 
 
 
 
 
 
9
 
10
  # Database
11
  DB_PATH = os.environ.get("DB_PATH", "/data/bot.db")
 
3
  # Telegram Bot
4
  BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
5
 
6
+ # AI provider — OpenAI-compatible (SiliconFlow / OpenAI / DeepSeek / local vLLM / any relay)
7
+ AI_API_KEY = os.environ.get("AI_API_KEY", "")
8
+ AI_BASE_URL = os.environ.get("AI_BASE_URL", "https://api.siliconflow.cn/v1")
9
+ AI_MODEL = os.environ.get("AI_MODEL", "deepseek-ai/DeepSeek-V4-Flash")
10
+ AI_VISION_MODELS = os.environ.get(
11
+ "AI_VISION_MODELS",
12
+ "Qwen/Qwen3-VL-30B-A3B-Instruct,Qwen/Qwen3-VL-32B-Instruct,Qwen/Qwen3-VL-8B-Instruct",
13
+ )
14
+ AI_AUDIO_MODEL = os.environ.get("AI_AUDIO_MODEL", "Qwen/Qwen3-Omni-30B-A3B-Instruct")
15
+ AI_IMAGE_MAX_WIDTH = int(os.environ.get("AI_IMAGE_MAX_WIDTH", "600"))
16
 
17
  # Database
18
  DB_PATH = os.environ.get("DB_PATH", "/data/bot.db")
modules/ai_provider.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI provider layer — OpenAI-compatible.
3
+
4
+ TelegramGuard talks to any OpenAI-compatible chat API: SiliconFlow (default),
5
+ OpenAI, DeepSeek, a local vLLM/Ollama, or any relay. Business code never imports
6
+ a vendor SDK — it calls generate_text / generate_vision / generate_audio here.
7
+
8
+ Config (all via env, see config.py):
9
+ AI_API_KEY — your key
10
+ AI_BASE_URL — endpoint (default https://api.siliconflow.cn/v1)
11
+ AI_MODEL — text model
12
+ AI_VISION_MODELS — comma-separated vision fallback chain (first fails -> next)
13
+ AI_AUDIO_MODEL — audio-capable model (optional; voice degrades gracefully)
14
+ AI_IMAGE_MAX_WIDTH — downscale images before upload (default 600)
15
+
16
+ Design: lazy client init (no network at import, no crash on missing key),
17
+ images downscaled before upload, vision falls back down the model chain.
18
+ """
19
+
20
+ import base64
21
+ import io
22
+ import logging
23
+
24
+ import config
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ try:
29
+ from openai import AsyncOpenAI
30
+ except ImportError:
31
+ AsyncOpenAI = None
32
+
33
+ try:
34
+ from PIL import Image
35
+ except ImportError:
36
+ Image = None
37
+
38
+
39
+ class AIError(Exception):
40
+ pass
41
+
42
+
43
+ _client = None
44
+
45
+
46
+ def _get_client():
47
+ global _client
48
+ if AsyncOpenAI is None:
49
+ raise AIError("openai package not installed (pip install openai)")
50
+ if _client is None:
51
+ key = getattr(config, "AI_API_KEY", "")
52
+ base = getattr(config, "AI_BASE_URL", "https://api.siliconflow.cn/v1")
53
+ if not key:
54
+ raise AIError("AI_API_KEY not set")
55
+ _client = AsyncOpenAI(api_key=key, base_url=base, timeout=90)
56
+ return _client
57
+
58
+
59
+ def _text_model():
60
+ return getattr(config, "AI_MODEL", "deepseek-ai/DeepSeek-V4-Flash")
61
+
62
+
63
+ def _vision_models():
64
+ raw = getattr(config, "AI_VISION_MODELS", "")
65
+ if raw:
66
+ return [m.strip() for m in raw.split(",") if m.strip()]
67
+ return [
68
+ "Qwen/Qwen3-VL-30B-A3B-Instruct",
69
+ "Qwen/Qwen3-VL-32B-Instruct",
70
+ "Qwen/Qwen3-VL-8B-Instruct",
71
+ ]
72
+
73
+
74
+ def _audio_model():
75
+ return getattr(config, "AI_AUDIO_MODEL", "Qwen/Qwen3-Omni-30B-A3B-Instruct")
76
+
77
+
78
+ def _compress(image_bytes):
79
+ max_w = getattr(config, "AI_IMAGE_MAX_WIDTH", 600)
80
+ if Image is None or not max_w:
81
+ return image_bytes
82
+ try:
83
+ img = Image.open(io.BytesIO(image_bytes))
84
+ if img.mode not in ("RGB", "L"):
85
+ img = img.convert("RGB")
86
+ if img.width > max_w:
87
+ h = max(1, int(img.height * max_w / img.width))
88
+ img = img.resize((max_w, h))
89
+ out = io.BytesIO()
90
+ img.save(out, format="JPEG", quality=85)
91
+ return out.getvalue()
92
+ except Exception as e:
93
+ logger.warning("image compress failed, using original: " + str(e))
94
+ return image_bytes
95
+
96
+
97
+ def _image_part(image_bytes):
98
+ b64 = base64.b64encode(_compress(image_bytes)).decode()
99
+ return {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b64}}
100
+
101
+
102
+ async def _chat(models, messages, max_tokens, temperature):
103
+ client = _get_client()
104
+ if isinstance(models, str):
105
+ models = [models]
106
+ last_err = None
107
+ for m in models:
108
+ try:
109
+ resp = await client.chat.completions.create(
110
+ model=m, messages=messages, max_tokens=max_tokens, temperature=temperature
111
+ )
112
+ txt = (resp.choices[0].message.content or "").strip()
113
+ if txt:
114
+ return txt
115
+ last_err = AIError("empty response")
116
+ except Exception as e:
117
+ last_err = e
118
+ logger.warning("[AI] model=%s failed: %s", m, e)
119
+ raise AIError("all models failed: " + str(last_err))
120
+
121
+
122
+ async def generate_text(prompt, system=None, max_tokens=800, temperature=0.7):
123
+ msgs = []
124
+ if system:
125
+ msgs.append({"role": "system", "content": system})
126
+ msgs.append({"role": "user", "content": prompt})
127
+ return await _chat(_text_model(), msgs, max_tokens, temperature)
128
+
129
+
130
+ async def generate_vision(prompt, image_bytes, system=None, max_tokens=800, temperature=0.4):
131
+ msgs = []
132
+ if system:
133
+ msgs.append({"role": "system", "content": system})
134
+ msgs.append({"role": "user", "content": [
135
+ {"type": "text", "text": prompt},
136
+ _image_part(image_bytes),
137
+ ]})
138
+ return await _chat(_vision_models(), msgs, max_tokens, temperature)
139
+
140
+
141
+ async def generate_audio(prompt, audio_bytes, fmt="ogg", system=None, max_tokens=800, temperature=0.7):
142
+ b64 = base64.b64encode(audio_bytes).decode()
143
+ msgs = []
144
+ if system:
145
+ msgs.append({"role": "system", "content": system})
146
+ msgs.append({"role": "user", "content": [
147
+ {"type": "text", "text": prompt},
148
+ {"type": "input_audio", "input_audio": {"data": b64, "format": fmt}},
149
+ ]})
150
+ return await _chat(_audio_model(), msgs, max_tokens, temperature)
modules/chat.py CHANGED
@@ -2,20 +2,12 @@ import json
2
  import logging
3
  import random
4
  import os
5
- import google.generativeai as genai
 
6
  import config
7
 
8
  logger = logging.getLogger(__name__)
9
 
10
- genai.configure(api_key=config.GEMINI_API_KEY)
11
-
12
- # Relax Gemini safety filters
13
- SAFETY_SETTINGS = [
14
- {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
15
- {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
16
- {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
17
- {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
18
- ]
19
 
20
  # Load prompts from .ilang files (prompts/ if exists, else prompts_demo/)
21
  def _load_prompt(name):
@@ -29,6 +21,7 @@ def _load_prompt(name):
29
  logger.warning("Prompt not found: " + name)
30
  return ""
31
 
 
32
  SYSTEM_PROMPT = _load_prompt("persona.ilang")
33
  ANTISPAM_TEXT_PROMPT = _load_prompt("antispam.ilang")
34
  VISION_PROMPT = _load_prompt("vision.ilang")
@@ -44,16 +37,6 @@ GROUP_WELCOME = (
44
  "Just give me admin permissions (delete messages + ban users)."
45
  )
46
 
47
- model = genai.GenerativeModel(
48
- config.GEMINI_MODEL,
49
- system_instruction=SYSTEM_PROMPT,
50
- safety_settings=SAFETY_SETTINGS
51
- )
52
- vision_model = genai.GenerativeModel(
53
- config.GEMINI_MODEL,
54
- safety_settings=SAFETY_SETTINGS
55
- )
56
-
57
 
58
  def _parse(raw):
59
  if not raw:
@@ -97,24 +80,6 @@ def _ctx(history, info):
97
  return "\n".join(parts)
98
 
99
 
100
- def _safe_text(response):
101
- """Safely extract text from Gemini response — r.text throws ValueError when blocked."""
102
- try:
103
- if response.text:
104
- return response.text.strip()
105
- except (ValueError, AttributeError):
106
- pass
107
- # Try extracting from candidates
108
- try:
109
- if response.candidates:
110
- for c in response.candidates:
111
- if hasattr(c, 'content') and c.content and c.content.parts:
112
- return c.content.parts[0].text.strip()
113
- except Exception:
114
- pass
115
- return ""
116
-
117
-
118
  def _deflect():
119
  lines = [
120
  "That's a tough one. What else can I help with?",
@@ -128,19 +93,8 @@ async def ai_text(text, history=None, context_info=""):
128
  try:
129
  c = _ctx(history, context_info)
130
  prompt = c + "\nuser: " + text if c else "user: " + text
131
- r = await model.generate_content_async(prompt, safety_settings=SAFETY_SETTINGS)
132
- raw = _safe_text(r)
133
  if not raw:
134
- feedback = ""
135
- if hasattr(r, 'prompt_feedback'):
136
- feedback = str(r.prompt_feedback)
137
- if hasattr(r, 'candidates') and r.candidates:
138
- for cand in r.candidates:
139
- if hasattr(cand, 'finish_reason'):
140
- feedback += " finish:" + str(cand.finish_reason)
141
- if hasattr(cand, 'safety_ratings'):
142
- feedback += " safety:" + str(cand.safety_ratings)
143
- logger.warning("AI empty response. feedback=" + feedback + " prompt_len=" + str(len(prompt)))
144
  return ("chat", None, _deflect())
145
  logger.info("AI raw[" + str(len(raw)) + "]: " + raw[:200])
146
  return _parse(raw)
@@ -155,8 +109,8 @@ async def ai_vision(image_bytes, caption="", history=None, context_info=""):
155
  prompt = VISION_PROMPT + "\n" + c
156
  if caption:
157
  prompt += "\nuser: " + caption
158
- r = await vision_model.generate_content_async([prompt, {"mime_type": "image/jpeg", "data": image_bytes}], safety_settings=SAFETY_SETTINGS)
159
- return _parse(_safe_text(r))
160
  except Exception as e:
161
  logger.warning("AI vision: " + str(e))
162
  return ("chat", None, "Couldn't read that image. Try another one?")
@@ -165,9 +119,12 @@ async def ai_vision(image_bytes, caption="", history=None, context_info=""):
165
  async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_info=""):
166
  try:
167
  c = _ctx(history, context_info)
168
- prompt = SYSTEM_PROMPT + "\n" + c + "\nUser sent a voice message:"
169
- r = await vision_model.generate_content_async([prompt, {"mime_type": mime_type, "data": audio_bytes}], safety_settings=SAFETY_SETTINGS)
170
- return _parse(_safe_text(r))
 
 
 
171
  except Exception as e:
172
  logger.warning("AI voice: " + str(e))
173
  return ("chat", None, "Didn't catch that. Try again or type it out.")
@@ -176,9 +133,8 @@ async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_inf
176
  async def ai_judge_group_message(text):
177
  try:
178
  prompt = ANTISPAM_TEXT_PROMPT + "\n\nMessage content: " + text[:1000]
179
- r = await vision_model.generate_content_async(prompt, safety_settings=SAFETY_SETTINGS)
180
- result = (_safe_text(r) or "ok").lower()
181
- return "spam" in result
182
  except Exception:
183
  return False
184
 
@@ -188,9 +144,8 @@ async def ai_judge_group_image(image_bytes, caption=""):
188
  prompt = ANTISPAM_TEXT_PROMPT + "\n\nJudge this image. Reply ONLY: spam or ok."
189
  if caption:
190
  prompt += "\nCaption: " + caption[:500]
191
- r = await vision_model.generate_content_async([prompt, {"mime_type": "image/jpeg", "data": image_bytes}], safety_settings=SAFETY_SETTINGS)
192
- result = (_safe_text(r) or "ok").lower()
193
- return "spam" in result
194
  except Exception:
195
  return False
196
 
@@ -203,8 +158,8 @@ async def ai_group_vision(image_bytes, caption="", history=None):
203
  prompt += "\nuser: " + caption
204
  else:
205
  prompt += "\nuser: [shared an image]"
206
- r = await vision_model.generate_content_async([prompt, {"mime_type": "image/jpeg", "data": image_bytes}], safety_settings=SAFETY_SETTINGS)
207
- raw = _safe_text(r)
208
  if not raw:
209
  return _deflect()
210
  intent, device, reply = _parse(raw)
@@ -219,8 +174,8 @@ async def ai_group_reply(text, history=None):
219
  try:
220
  ctx = _ctx(history, "GROUP_CHAT: You were @mentioned in a group. Reply directly, 1-2 sentences.")
221
  prompt = ctx + "\nuser: " + text
222
- r = await model.generate_content_async(prompt, safety_settings=SAFETY_SETTINGS)
223
- raw = _safe_text(r)
224
  if not raw:
225
  return _deflect()
226
  intent, device, reply = _parse(raw)
 
2
  import logging
3
  import random
4
  import os
5
+
6
+ from modules import ai_provider
7
  import config
8
 
9
  logger = logging.getLogger(__name__)
10
 
 
 
 
 
 
 
 
 
 
11
 
12
  # Load prompts from .ilang files (prompts/ if exists, else prompts_demo/)
13
  def _load_prompt(name):
 
21
  logger.warning("Prompt not found: " + name)
22
  return ""
23
 
24
+
25
  SYSTEM_PROMPT = _load_prompt("persona.ilang")
26
  ANTISPAM_TEXT_PROMPT = _load_prompt("antispam.ilang")
27
  VISION_PROMPT = _load_prompt("vision.ilang")
 
37
  "Just give me admin permissions (delete messages + ban users)."
38
  )
39
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  def _parse(raw):
42
  if not raw:
 
80
  return "\n".join(parts)
81
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  def _deflect():
84
  lines = [
85
  "That's a tough one. What else can I help with?",
 
93
  try:
94
  c = _ctx(history, context_info)
95
  prompt = c + "\nuser: " + text if c else "user: " + text
96
+ raw = await ai_provider.generate_text(prompt, system=SYSTEM_PROMPT)
 
97
  if not raw:
 
 
 
 
 
 
 
 
 
 
98
  return ("chat", None, _deflect())
99
  logger.info("AI raw[" + str(len(raw)) + "]: " + raw[:200])
100
  return _parse(raw)
 
109
  prompt = VISION_PROMPT + "\n" + c
110
  if caption:
111
  prompt += "\nuser: " + caption
112
+ raw = await ai_provider.generate_vision(prompt, image_bytes, system=SYSTEM_PROMPT)
113
+ return _parse(raw)
114
  except Exception as e:
115
  logger.warning("AI vision: " + str(e))
116
  return ("chat", None, "Couldn't read that image. Try another one?")
 
119
  async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_info=""):
120
  try:
121
  c = _ctx(history, context_info)
122
+ prompt = c + "\nUser sent a voice message:" if c else "User sent a voice message:"
123
+ fmt = "ogg"
124
+ if "/" in mime_type:
125
+ fmt = mime_type.split("/", 1)[1].split(";")[0] or "ogg"
126
+ raw = await ai_provider.generate_audio(prompt, audio_bytes, fmt=fmt, system=SYSTEM_PROMPT)
127
+ return _parse(raw)
128
  except Exception as e:
129
  logger.warning("AI voice: " + str(e))
130
  return ("chat", None, "Didn't catch that. Try again or type it out.")
 
133
  async def ai_judge_group_message(text):
134
  try:
135
  prompt = ANTISPAM_TEXT_PROMPT + "\n\nMessage content: " + text[:1000]
136
+ raw = await ai_provider.generate_text(prompt, max_tokens=8, temperature=0.0)
137
+ return "spam" in (raw or "ok").lower()
 
138
  except Exception:
139
  return False
140
 
 
144
  prompt = ANTISPAM_TEXT_PROMPT + "\n\nJudge this image. Reply ONLY: spam or ok."
145
  if caption:
146
  prompt += "\nCaption: " + caption[:500]
147
+ raw = await ai_provider.generate_vision(prompt, image_bytes, max_tokens=8, temperature=0.0)
148
+ return "spam" in (raw or "ok").lower()
 
149
  except Exception:
150
  return False
151
 
 
158
  prompt += "\nuser: " + caption
159
  else:
160
  prompt += "\nuser: [shared an image]"
161
+ raw = await ai_provider.generate_vision(prompt, image_bytes, system=SYSTEM_PROMPT)
162
+ raw = (raw or "").strip()
163
  if not raw:
164
  return _deflect()
165
  intent, device, reply = _parse(raw)
 
174
  try:
175
  ctx = _ctx(history, "GROUP_CHAT: You were @mentioned in a group. Reply directly, 1-2 sentences.")
176
  prompt = ctx + "\nuser: " + text
177
+ raw = await ai_provider.generate_text(prompt, system=SYSTEM_PROMPT)
178
+ raw = (raw or "").strip()
179
  if not raw:
180
  return _deflect()
181
  intent, device, reply = _parse(raw)
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  python-telegram-bot[job-queue]>=21.0
2
- google-generativeai==0.8.4
 
3
  aiosqlite>=0.20.0
 
1
  python-telegram-bot[job-queue]>=21.0
2
+ openai>=1.40
3
+ Pillow>=10.0
4
  aiosqlite>=0.20.0