llm_models.py
8.01 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
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
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Any
logger = logging.getLogger(__name__)
DASHSCOPE_CLIENT = "dashscope"
OPENAI_COMPATIBLE_CLIENT = "openai_compatible"
DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
SUPPORTED_CHAT_MODELS = tuple(
dict.fromkeys(
(
"qwen3.7-plus",
"qwen3.6-plus",
"qwen3.5-plus",
"qwen-plus",
"qwen3.6-flash",
"qwen3.5-flash",
"qwen-flash",
"deepseek-v4.1-flash",
"deepseek-v4-pro",
"deepseek-v3.2",
)
)
)
@dataclass(frozen=True)
class ChatModelProfile:
name: str
client: str = DASHSCOPE_CLIENT
multimodal: bool = False
supports_enable_thinking: bool = False
temperature: float | None = 0.5
_CHAT_MODEL_PROFILES: dict[str, ChatModelProfile] = {
"qwen3.7-plus": ChatModelProfile(
name="qwen3.7-plus",
client=OPENAI_COMPATIBLE_CLIENT,
supports_enable_thinking=True,
),
"qwen3.6-plus": ChatModelProfile(
name="qwen3.6-plus",
client=OPENAI_COMPATIBLE_CLIENT,
supports_enable_thinking=True,
),
"qwen3.5-plus": ChatModelProfile(
name="qwen3.5-plus",
client=OPENAI_COMPATIBLE_CLIENT,
supports_enable_thinking=True,
),
"qwen-plus": ChatModelProfile(name="qwen-plus"),
"qwen3.6-flash": ChatModelProfile(
name="qwen3.6-flash",
client=OPENAI_COMPATIBLE_CLIENT,
supports_enable_thinking=True,
),
"qwen3.5-flash": ChatModelProfile(
name="qwen3.5-flash",
client=OPENAI_COMPATIBLE_CLIENT,
supports_enable_thinking=True,
),
"qwen-flash": ChatModelProfile(name="qwen-flash"),
"deepseek-v4.1-flash": ChatModelProfile(
name="deepseek-v4.1-flash",
client=OPENAI_COMPATIBLE_CLIENT, # 原生 text-generation 端点对该模型报 url error,只能走兼容模式
supports_enable_thinking=True,
temperature=None,
),
"deepseek-v4-pro": ChatModelProfile(
name="deepseek-v4-pro",
supports_enable_thinking=True,
temperature=None,
),
"deepseek-v3.2": ChatModelProfile(
name="deepseek-v3.2",
supports_enable_thinking=True,
temperature=None,
),
}
_TRUE_VALUES = {"1", "true", "yes", "y", "on"}
_FALSE_VALUES = {"0", "false", "no", "n", "off"}
_AUTO_VALUES = {"", "auto", "default"}
def get_chat_model_profile(model_name: str) -> ChatModelProfile:
normalized = _normalize_model_name(model_name)
try:
return _CHAT_MODEL_PROFILES[normalized]
except KeyError as exc:
supported = ", ".join(SUPPORTED_CHAT_MODELS)
raise ValueError(f"Unsupported chat model: {model_name!r}. Supported models: {supported}") from exc
def build_model_init_kwargs(
model_name: str,
*,
api_key: str,
purpose: str | None = None,
temperature: float | None = None,
enable_thinking: bool | None = None,
) -> dict[str, Any]:
profile = get_chat_model_profile(model_name)
kwargs: dict[str, Any] = _base_model_kwargs(profile, api_key)
generate_kwargs: dict[str, Any] = {}
# 显式传入的 enable_thinking 优先于 env 解析:调用方(如 Map 阶段)可强制关思考。
if enable_thinking is None:
enable_thinking = resolve_enable_thinking(purpose)
if enable_thinking is not None:
if profile.supports_enable_thinking:
if profile.client == OPENAI_COMPATIBLE_CLIENT:
generate_kwargs.setdefault("extra_body", {})["enable_thinking"] = enable_thinking
else:
kwargs["enable_thinking"] = enable_thinking
elif enable_thinking:
raise ValueError(f"Model {profile.name!r} does not support enable_thinking")
# profile.temperature 为 None 表示该模型不接受 temperature 参数(如 deepseek 系列),
# 此时调用方的显式取值也不下发,否则会把这份刻意配置冲掉。
if profile.temperature is None:
if temperature is not None:
logger.warning(
"[LLM] model=%s does not accept temperature; ignoring temperature=%s",
profile.name,
temperature,
)
else:
effective = temperature if temperature is not None else profile.temperature
generate_kwargs["temperature"] = _validate_temperature(effective)
if generate_kwargs:
kwargs["generate_kwargs"] = generate_kwargs
return kwargs
def _validate_temperature(value: Any) -> float:
try:
temperature = float(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"temperature must be a number, got {value!r}") from exc
if not 0.0 <= temperature <= 2.0:
raise ValueError(f"temperature must be within [0, 2], got {temperature}")
return temperature
def resolve_enable_thinking(purpose: str | None = None) -> bool | None:
for env_name in _thinking_env_names(purpose):
if env_name not in os.environ:
continue
return _parse_thinking_env(os.environ.get(env_name, ""), env_name)
return None
def is_multimodal_model(model_name: str) -> bool:
return get_chat_model_profile(model_name).multimodal
def is_default_thinking_enabled(model_name: str) -> bool:
get_chat_model_profile(model_name)
return False
def formatter_name_for_model(model_name: str) -> str:
profile = get_chat_model_profile(model_name)
if profile.client == OPENAI_COMPATIBLE_CLIENT:
return "openai"
return "dashscope"
def extract_text_content(content: Any) -> str:
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
return "".join(extract_text_content(item) for item in content)
if isinstance(content, dict):
if content.get("type") == "thinking":
return ""
if "text" in content:
return str(content.get("text") or "")
if "content" in content:
return extract_text_content(content.get("content"))
return ""
return str(content)
def extract_thinking_content(content: Any) -> str:
if content is None or isinstance(content, str):
return ""
if isinstance(content, list):
return "".join(extract_thinking_content(item) for item in content)
if isinstance(content, dict):
parts = []
if "thinking" in content:
parts.append(str(content.get("thinking") or ""))
if "reasoning_content" in content:
parts.append(str(content.get("reasoning_content") or ""))
if "content" in content:
parts.append(extract_thinking_content(content.get("content")))
return "".join(parts)
return ""
def _normalize_model_name(model_name: str) -> str:
return str(model_name or "").strip().lower()
def _thinking_env_names(purpose: str | None) -> tuple[str, ...]:
if not purpose:
return ("LLM_ENABLE_THINKING",)
normalized = purpose.strip().upper().replace("-", "_")
return (
f"{normalized}_ENABLE_THINKING",
f"{normalized}_MODEL_ENABLE_THINKING",
"LLM_ENABLE_THINKING",
)
def _parse_thinking_env(raw_value: str, env_name: str) -> bool | None:
value = str(raw_value).strip().lower()
if value in _AUTO_VALUES:
return None
if value in _TRUE_VALUES:
return True
if value in _FALSE_VALUES:
return False
raise ValueError(f"{env_name} must be one of: auto, true, false")
def _base_model_kwargs(profile: ChatModelProfile, api_key: str) -> dict[str, Any]:
kwargs: dict[str, Any] = {
"model_name": profile.name,
"api_key": api_key,
}
if profile.client == OPENAI_COMPATIBLE_CLIENT:
kwargs["client_kwargs"] = {
"base_url": os.environ.get(
"DASHSCOPE_COMPATIBLE_BASE_URL",
DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL,
),
}
else:
kwargs["multimodality"] = profile.multimodal
return kwargs