File size: 20,516 Bytes
1521ce5 | 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | from __future__ import annotations
"""
统一 LLM 调用模块
================
仿照 mify_client.py 的调用方式,通过 Mify API 代理调用闭源模型。
支持模型:
- gpt-5.5 (Azure OpenAI)
- gemini-3.1-pro-preview-pt (Vertex AI)
所有数据构造脚本通过 get_llm() 获取实例,通过 .generate() / .generate_json() 调用。
"""
import json
import time
import logging
import os
from abc import ABC, abstractmethod
from typing import Optional
from openai import OpenAI
try:
import anthropic
_ANTHROPIC_AVAILABLE = True
except ImportError:
anthropic = None
_ANTHROPIC_AVAILABLE = False
logger = logging.getLogger(__name__)
# ==================== Mify API 配置 ====================
MIFY_API_KEY = os.getenv("MIFY_API_KEY", "")
MIFY_BASE_URL = os.getenv("MIFY_BASE_URL", "https://api.llm.mioffice.cn/v1")
# Claude 模型走单独的 Anthropic-compatible endpoint
MIFY_ANTHROPIC_BASE_URL = os.getenv("MIFY_ANTHROPIC_BASE_URL", "https://api.llm.mioffice.cn/anthropic")
# 模型名称 -> Provider ID 映射 (OpenAI-compatible models 才需要)
# 注: 不在此表的模型不发 provider header (如 ppio/pa/gpt-5.5, 名字自带路由, 带 header 会 400).
MODEL_PROVIDER = {
"gpt-5.4": "azure_openai",
"gemini-3.1-pro-preview-pt": "vertex_ai",
"gemini-3-pro-preview-pt": "vertex_ai",
"glm-5.2": "zhipuai",
}
# Claude 系列走 Anthropic SDK + Mify /anthropic endpoint
ANTHROPIC_MODELS = {
"ppio/pa/claude-opus-4-7",
"ppio/pa/claude-sonnet-4-6",
"ppio/pa/claude-haiku-4-5",
}
# Reasoning / 受限模型: 不接受 temperature 参数 (会返回 400)
# - gpt-5.x (azure_openai 路由) 系列 是 reasoning 模型, 拒绝 temperature
# - claude-opus-4-7 (deprecated temperature)
# 注: ppio/pa/gpt-5.5 实测接受 temperature, 故不在此名单.
MODELS_NO_TEMPERATURE = {
"gpt-5.4",
"gpt-5.2",
"o3",
"ppio/pa/claude-opus-4-7",
}
# 模型的上下文窗口大小
MODEL_MAX_LENGTH = {
"ppio/pa/gpt-5.5": 272000,
"gemini-3.1-pro-preview-pt": 900000,
"ppio/pa/claude-opus-4-7": 200000,
"ppio/pa/claude-sonnet-4-6": 200000,
"glm-5.2": 200000,
}
# 模型简短别名(文件命名用)
MODEL_ALIAS = {
"ppio/pa/gpt-5.5": "gpt5.5",
"gemini-3.1-pro-preview-pt": "gemini3.1pro",
"ppio/pa/claude-opus-4-7": "claude-opus-4.7",
"ppio/pa/claude-sonnet-4-6": "claude-sonnet-4.6",
"glm-5.2": "glm5.2",
}
# ==================== Content-filter 检测 ====================
class ContentFilterError(Exception):
"""模型 backend 拒绝该 prompt (Azure content filter / Anthropic safety / etc).
Deterministic, 不重试 — 由上层 fallback chain 接管."""
_CONTENT_FILTER_PATTERNS = (
"content management policy", # Azure OpenAI
"response was filtered", # Azure OpenAI
"ResponsibleAIPolicyViolation", # Azure
"content filtering", # Generic
"safety filter", # Gemini
"safety_violation", # Gemini
"blocked by safety", # Anthropic
"content_policy_violation", # OpenAI moderation
)
def _is_content_filter_error(msg: str) -> bool:
if not msg:
return False
low = msg.lower()
return any(p.lower() in low for p in _CONTENT_FILTER_PATTERNS)
# ==================== 抽象接口 ====================
class LLMInterface(ABC):
@abstractmethod
def generate(
self,
messages: list[dict],
n: int = 1,
temperature: float = 0.7,
max_tokens: int = 2048,
) -> list[str]:
...
def generate_json(
self,
messages: list[dict],
temperature: float = 0.7,
max_tokens: int = 2048,
retries: int = 3,
) -> dict:
for attempt in range(retries):
results = self.generate(
messages, n=1, temperature=temperature, max_tokens=max_tokens
)
text = results[0].strip()
# 清洗 markdown code block
if text.startswith("```json"):
text = text[7:]
if text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
try:
return json.loads(text)
except json.JSONDecodeError:
logger.warning(
f"JSON parse failed (attempt {attempt + 1}/{retries}): {text[:200]}"
)
if attempt < retries - 1:
time.sleep(1)
raise ValueError(f"Failed to parse JSON after {retries} attempts")
# ==================== Mify API 调用实现 ====================
class MifyLLM(LLMInterface):
"""通过 Mify API 代理调用闭源模型 (GPT / Gemini / Claude 等).
自动按模型名分发:
- Claude 系列 (ANTHROPIC_MODELS): Anthropic SDK + /anthropic endpoint
- 其他: OpenAI SDK + /v1 endpoint
"""
def __init__(
self,
model: str,
api_key: str = MIFY_API_KEY,
base_url: str = MIFY_BASE_URL,
anthropic_base_url: str = MIFY_ANTHROPIC_BASE_URL,
max_retries: int = 3,
retry_delay: int = 5,
request_interval: float = 1.0,
):
self.model = model
self.api_key = api_key
self.base_url = base_url
self.anthropic_base_url = anthropic_base_url
self.max_retries = max_retries
self.retry_delay = retry_delay
self.request_interval = request_interval
self.is_anthropic = model in ANTHROPIC_MODELS
if self.is_anthropic:
if not _ANTHROPIC_AVAILABLE:
raise RuntimeError(
f"Model {model} requires the 'anthropic' package. Install via `pip install anthropic`."
)
self.anthropic_client = anthropic.Anthropic(
api_key=api_key, base_url=anthropic_base_url,
)
self.client = None
else:
# 只有在 MODEL_PROVIDER 显式配置时才发 provider header.
# 名字自带路由的模型 (如 ppio/pa/gpt-5.5) 不能带 header, 否则网关 400.
provider_id = MODEL_PROVIDER.get(model)
headers = {"X-Model-Provider-Id": provider_id} if provider_id else {}
self.client = OpenAI(
api_key=api_key,
base_url=base_url,
default_headers=headers,
)
self.anthropic_client = None
def _split_system(self, messages: list[dict]) -> tuple[Optional[str], list[dict]]:
"""Anthropic SDK 要求 system 走单独 kwarg, 这里把 system 消息抽出来."""
system_chunks: list[str] = []
rest: list[dict] = []
for m in messages:
if m.get("role") == "system":
system_chunks.append(m.get("content", ""))
else:
rest.append(m)
system = "\n".join(s for s in system_chunks if s) or None
return system, rest
def _call_once_openai(self, messages: list[dict], temperature: float, max_tokens: int) -> str | None:
kwargs = {
"model": self.model,
"messages": messages,
"max_completion_tokens": max_tokens,
"stream": False,
}
if self.model not in MODELS_NO_TEMPERATURE:
kwargs["temperature"] = temperature
for attempt in range(self.max_retries):
try:
response = self.client.chat.completions.create(**kwargs)
if response and response.choices:
content = response.choices[0].message.content
if content is not None:
return content
return None
except Exception as e:
msg = str(e)
# Content filter 是 deterministic 的, 重试无意义, 直接 raise 让 fallback 接管
if _is_content_filter_error(msg):
logger.warning(
f" Content-filter rejected by {self.model}, abort retries: {msg[:200]}"
)
raise ContentFilterError(msg) from e
logger.warning(
f" [Retry {attempt + 1}/{self.max_retries}] {type(e).__name__}: {msg[:200]}"
)
if attempt < self.max_retries - 1:
time.sleep(self.retry_delay * (attempt + 1))
return None
def _call_once_anthropic(self, messages: list[dict], temperature: float, max_tokens: int) -> str | None:
system, rest = self._split_system(messages)
kwargs = {
"model": self.model,
"messages": rest,
"max_tokens": max_tokens,
}
if self.model not in MODELS_NO_TEMPERATURE:
kwargs["temperature"] = temperature
if system:
kwargs["system"] = system
for attempt in range(self.max_retries):
try:
response = self.anthropic_client.messages.create(**kwargs)
if response.content:
parts = [c.text for c in response.content if getattr(c, "type", None) == "text"]
if parts:
return "\n".join(parts)
return None
except Exception as e:
msg = str(e)
if _is_content_filter_error(msg):
logger.warning(
f" Content-filter rejected by {self.model}, abort retries: {msg[:200]}"
)
raise ContentFilterError(msg) from e
logger.warning(
f" [Retry {attempt + 1}/{self.max_retries}] {type(e).__name__}: {msg[:200]}"
)
if attempt < self.max_retries - 1:
time.sleep(self.retry_delay * (attempt + 1))
return None
def _call_once(self, messages: list[dict], temperature: float, max_tokens: int) -> str | None:
"""单次 API 调用, 按模型分发到 OpenAI 或 Anthropic backend."""
if self.is_anthropic:
return self._call_once_anthropic(messages, temperature, max_tokens)
return self._call_once_openai(messages, temperature, max_tokens)
def generate(
self,
messages: list[dict],
n: int = 1,
temperature: float = 0.7,
max_tokens: int = 2048,
) -> list[str]:
results = []
for i in range(n):
result = self._call_once(messages, temperature, max_tokens)
results.append(result or "")
if i < n - 1 and self.request_interval > 0:
time.sleep(self.request_interval)
return results
# ==================== 直接 OpenAI API (非 Mify) ====================
class DirectOpenAILLM(LLMInterface):
"""直接调用 OpenAI 官方 API (非代理)。"""
def __init__(self, model: str, api_key: Optional[str] = None, base_url: Optional[str] = None):
kwargs = {}
if api_key:
kwargs["api_key"] = api_key
if base_url:
kwargs["base_url"] = base_url
self.client = OpenAI(**kwargs)
self.model = model
def generate(
self,
messages: list[dict],
n: int = 1,
temperature: float = 0.7,
max_tokens: int = 2048,
) -> list[str]:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
n=n,
temperature=temperature,
max_tokens=max_tokens,
)
return [choice.message.content or "" for choice in response.choices]
# ==================== vLLM (本地部署) ====================
class VLLMLLM(LLMInterface):
"""通过 vLLM 的 OpenAI-compatible API 调用本地模型。"""
def __init__(self, model: str, base_url: str, api_key: str = "EMPTY"):
self.client = OpenAI(base_url=base_url, api_key=api_key)
self.model = model
def generate(
self,
messages: list[dict],
n: int = 1,
temperature: float = 0.7,
max_tokens: int = 2048,
) -> list[str]:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
n=n,
temperature=temperature,
max_tokens=max_tokens,
)
return [choice.message.content or "" for choice in response.choices]
# ==================== Fallback 链 ====================
class FallbackLLM(LLMInterface):
"""串行尝试多个 backend, 任一成功就返回. 用于绕过 Azure content filter
等 deterministic 拒绝: gpt-5.5 命中 ContentFilterError -> gemini -> claude.
顺序按构造时传入的 backends 排序. 只有 primary 失败才付出 fallback 成本.
"""
def __init__(self, backends: list[LLMInterface]):
if not backends:
raise ValueError("FallbackLLM requires at least one backend")
self.backends = backends
def generate(
self,
messages: list[dict],
n: int = 1,
temperature: float = 0.7,
max_tokens: int = 2048,
) -> list[str]:
last_error: Optional[Exception] = None
for i, backend in enumerate(self.backends):
tag = getattr(backend, "model", type(backend).__name__)
try:
results = backend.generate(messages, n=n, temperature=temperature, max_tokens=max_tokens)
# 全空才算失败 (单个空字符串视为这次没拿到内容, 但若有 n>1 部分成功仍算 OK)
if results and any(r for r in results):
if i > 0:
logger.info(f"FallbackLLM: succeeded via fallback backend [{i}] {tag}")
return results
logger.warning(f"FallbackLLM: backend [{i}] {tag} returned empty, trying next")
except ContentFilterError as e:
last_error = e
logger.info(f"FallbackLLM: backend [{i}] {tag} hit content filter, trying next")
except Exception as e:
last_error = e
logger.warning(f"FallbackLLM: backend [{i}] {tag} raised {type(e).__name__}: {str(e)[:200]}")
# 全部 backend 都失败
if last_error is not None:
raise last_error
return [""] * n
# ==================== 工厂函数 ====================
def get_llm(
provider: str,
model: str,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
) -> LLMInterface:
"""
根据 provider 创建 LLM 实例.
Args:
provider: "mify" | "openai" | "vllm"
- mify: 通过 Mify 代理调用 GPT/Gemini/Claude (默认推荐)
- openai: 直接调用 OpenAI 官方 API
- vllm: 调用本地 vLLM 服务
model: 模型名 (如 "gpt-5.5"). 支持 fallback 链, 用逗号分隔多个模型,
primary 命中 content filter 时自动顺移到下一个,
例如 "gpt-5.5,gemini-3.1-pro-preview-pt".
api_key: API 密钥 (mify 模式下可不传, 使用默认)
base_url: API 地址 (vllm 模式必传)
"""
# 解析逗号分隔的 fallback 链
model_names = [m.strip() for m in model.split(",") if m.strip()]
if not model_names:
raise ValueError(f"empty model spec: {model!r}")
def make_one(name: str) -> LLMInterface:
if provider == "mify":
return MifyLLM(
model=name,
api_key=api_key or MIFY_API_KEY,
base_url=base_url or MIFY_BASE_URL,
)
elif provider == "openai":
return DirectOpenAILLM(model=name, api_key=api_key, base_url=base_url)
elif provider == "vllm":
if not base_url:
raise ValueError("base_url required for vllm provider")
return VLLMLLM(model=name, base_url=base_url, api_key=api_key or "EMPTY")
else:
raise ValueError(f"Unknown provider: {provider}. Use 'mify', 'openai', or 'vllm'.")
if len(model_names) == 1:
return make_one(model_names[0])
backends = [make_one(n) for n in model_names]
logger.info(f"get_llm: built FallbackLLM chain {model_names}")
return FallbackLLM(backends)
# ==================== 便捷函数 (兼容 mify_client.py 风格) ====================
def _split_system_for_anthropic(messages: list[dict]) -> tuple[Optional[str], list[dict]]:
system_chunks: list[str] = []
rest: list[dict] = []
for m in messages:
if m.get("role") == "system":
system_chunks.append(m.get("content", ""))
else:
rest.append(m)
system = "\n".join(s for s in system_chunks if s) or None
return system, rest
def _call_anthropic_direct(
model_name: str,
messages: list[dict],
max_tokens: int,
temperature: float,
max_retries: int,
retry_delay: int,
) -> str | None:
if not _ANTHROPIC_AVAILABLE:
raise RuntimeError(
f"Model {model_name} requires the 'anthropic' package. Install via `pip install anthropic`."
)
client = anthropic.Anthropic(api_key=MIFY_API_KEY, base_url=MIFY_ANTHROPIC_BASE_URL)
system, rest = _split_system_for_anthropic(messages)
kwargs = {
"model": model_name,
"messages": rest,
"max_tokens": max_tokens,
}
if model_name not in MODELS_NO_TEMPERATURE:
kwargs["temperature"] = temperature
if system:
kwargs["system"] = system
for attempt in range(max_retries):
try:
response = client.messages.create(**kwargs)
if response.content:
parts = [c.text for c in response.content if getattr(c, "type", None) == "text"]
if parts:
return "\n".join(parts)
return None
except Exception as e:
logger.warning(
f" [Retry {attempt + 1}/{max_retries}] {type(e).__name__}: {str(e)[:200]}"
)
if attempt < max_retries - 1:
import random
# 指数退避 + 随机抖动,避免多 worker 同时重试撞车
backoff = retry_delay * (2 ** attempt) + random.uniform(0, 2)
time.sleep(backoff)
return None
def call_model(
model_name: str,
messages: list[dict],
max_tokens: int = 4096,
temperature: float = 0,
max_retries: int = 3,
retry_delay: int = 5,
) -> str | None:
"""
兼容 mify_client.py 的 call_model() 接口.
自动按模型分发: Claude 走 Anthropic SDK + /anthropic, 其他走 OpenAI SDK + /v1.
"""
if model_name in ANTHROPIC_MODELS:
return _call_anthropic_direct(
model_name, messages, max_tokens, temperature, max_retries, retry_delay,
)
# 只有在 MODEL_PROVIDER 显式配置时才发 provider header.
# 名字自带路由的模型 (如 ppio/pa/gpt-5.5) 不能带 header, 否则网关 400.
provider_id = MODEL_PROVIDER.get(model_name)
headers = {"X-Model-Provider-Id": provider_id} if provider_id else {}
client = OpenAI(
api_key=MIFY_API_KEY,
base_url=MIFY_BASE_URL,
default_headers=headers,
)
kwargs = {
"model": model_name,
"messages": messages,
"max_completion_tokens": max_tokens,
"stream": False,
}
if model_name not in MODELS_NO_TEMPERATURE:
kwargs["temperature"] = temperature
for attempt in range(max_retries):
try:
response = client.chat.completions.create(**kwargs)
if response and response.choices:
content = response.choices[0].message.content
if content is not None:
return content
return None
except Exception as e:
logger.warning(
f" [Retry {attempt + 1}/{max_retries}] {type(e).__name__}: {str(e)[:200]}"
)
if attempt < max_retries - 1:
import random
backoff = retry_delay * (2 ** attempt) + random.uniform(0, 2)
time.sleep(backoff)
return None
def get_model_alias(model_name: str) -> str:
return MODEL_ALIAS.get(model_name, model_name.replace("/", "_").replace(":", "_"))
def get_model_max_length(model_name: str) -> int:
return MODEL_MAX_LENGTH.get(model_name, 32768)
|