-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodel_mapper.py
More file actions
87 lines (73 loc) · 2.74 KB
/
Copy pathmodel_mapper.py
File metadata and controls
87 lines (73 loc) · 2.74 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
"""模型名称映射器 — 按供应商作用域解析模型名."""
from __future__ import annotations
import fnmatch
import logging
import re
from ..config.schema import ModelMappingRule
logger = logging.getLogger(__name__)
_DEFAULT_TARGET = "glm-5.1"
_VENDOR_ALIASES = {
"zhipu": "fallback",
"fallback": "fallback",
"antigravity": "antigravity",
"copilot": "copilot",
"minimax": "minimax",
"kimi": "kimi",
"doubao": "doubao",
"xiaomi": "xiaomi",
"alibaba": "alibaba",
}
class ModelMapper:
"""将请求模型名映射到目标供应商模型名."""
def __init__(self, rules: list[ModelMappingRule]) -> None:
self._rules = rules
# 预编译正则表达式
self._compiled: dict[str, re.Pattern] = {}
for rule in rules:
if rule.is_regex:
self._compiled[rule.pattern] = re.compile(rule.pattern)
@staticmethod
def _normalize_vendor(vendor: str) -> str:
normalized = vendor.strip().lower()
return _VENDOR_ALIASES.get(normalized, normalized)
def _rule_applies_to_vendor(self, rule: ModelMappingRule, vendor: str) -> bool:
if not rule.vendors:
# 向后兼容:历史规则默认只服务 fallback/zhipu
return vendor == "fallback"
normalized = {self._normalize_vendor(name) for name in rule.vendors}
return vendor in normalized
def map(
self, model: str, vendor: str = "fallback", default: str | None = None
) -> str:
"""将源模型名映射为目标模型名.
优先级:精确匹配 > 通配符/正则匹配 > default/_DEFAULT_TARGET。
"""
display_name = vendor.strip().lower()
match_key = self._normalize_vendor(vendor)
# 1. 精确匹配
for rule in self._rules:
if not self._rule_applies_to_vendor(rule, match_key):
continue
if not rule.is_regex and "*" not in rule.pattern:
if rule.pattern == model:
return rule.target
# 2. 通配符/正则匹配
for rule in self._rules:
if not self._rule_applies_to_vendor(rule, match_key):
continue
if rule.is_regex:
compiled = self._compiled[rule.pattern]
if compiled.fullmatch(model):
return rule.target
elif "*" in rule.pattern:
if fnmatch.fnmatch(model, rule.pattern):
return rule.target
# 3. 默认值
fallback_target = default or _DEFAULT_TARGET
logger.debug(
"Model unmapped: %s -> %s (vendor=%s default)",
model,
fallback_target,
display_name,
)
return fallback_target