yimo-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,577 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-08-21
21
+ """模型档案(ModelProfile)与注册表(ModelRegistry)
22
+
23
+ 从 ``config/ai_models.json`` 读取四类型(chat / embedding / rerank / image)
24
+ 多厂商模型档案,用 pydantic 模型校验结构,并在 ``get()`` 时解析档案引用
25
+ 的环境变量密钥。
26
+
27
+ 密钥来源优先级:真实环境变量 > 项目根 ``.env``(``load()`` 时经
28
+ ``load_dotenv`` 注入,不覆盖已有环境变量)> 缺失报 ``AIConfigError``。
29
+ 档案数量与密钥变量名完全由 JSON 决定,无需改 ``sys_config``。
30
+ """
31
+
32
+ import enum
33
+ import os
34
+ from dataclasses import dataclass, replace
35
+ from functools import lru_cache
36
+ from pathlib import Path
37
+ from typing import Any, Final, Literal, Self
38
+
39
+ from dotenv import load_dotenv
40
+ from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator
41
+
42
+ from yimo.kit.ai.exceptions import AIConfigError, AIModelTypeNotConfiguredError
43
+ from yimo.kit.config.kit_config import get_settings
44
+ from yimo.kit.config.log_config import get_default_logger
45
+
46
+ logger = get_default_logger(__name__)
47
+
48
+ # 支持的模型类型
49
+ MODEL_TYPES: Final[tuple[str, ...]] = ("chat", "embedding", "rerank", "image")
50
+
51
+ # 文件缺失报错时附带的最小可用模板(api_key 为环境变量名,密钥配置在 .env)
52
+ _MINIMAL_MODELS_JSON: Final[str] = (
53
+ '{"chat": {"default_profile": "default", "profiles": {"default": '
54
+ '{"api_key": "SILICONFLOW_API_KEY", "base_url": "https://api.siliconflow.cn/v1", '
55
+ '"endpoint": "/chat/completions", "model": "Qwen/Qwen3-8B", "timeout": 120}}}}'
56
+ )
57
+
58
+
59
+ # 请求体保留键:思考开关 / 结构化输出声明(档案 thinking.arg / structured_output.arg)
60
+ # 不得占用,配置期与运行期双重校验
61
+ _RESERVED_PAYLOAD_KEYS: Final[frozenset[str]] = frozenset(
62
+ {"model", "messages", "stream", "input", "prompt", "max_tokens", "temperature"}
63
+ )
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class ThinkingSwitchSpec:
68
+ """厂商思考开关的注入方式(档案声明;缺失即「不支持切换」)。
69
+
70
+ kit 不认识任何厂商字段名,只按本声明组装请求体:
71
+
72
+ Attributes:
73
+ arg: 请求体顶层键名(如 ``thinking`` / ``chat_template_kwargs`` /
74
+ ``enable_thinking``);保留键(``model`` / ``messages`` 等)禁用
75
+ off: 关闭思考时该键的取值,任意 JSON 值。与请求体中同键**都是 dict**
76
+ 时浅合并(保留其它子键),否则整键替换
77
+ on: 开启思考时的取值;``None`` 表示不能显式开启(如强制思考模型)
78
+ default: 档案默认策略——``None`` 不干预 / ``False`` 默认关 /
79
+ ``True`` 默认开。仅在逐调用未传 ``thinking`` 时生效
80
+ """
81
+
82
+ arg: str
83
+ off: Any
84
+ on: Any = None
85
+ default: bool | None = None
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class StructuredOutputSpec:
90
+ """厂商结构化输出(JSON 模式)的注入方式(档案声明;缺失即用内置默认)。
91
+
92
+ kit 不认识任何厂商字段名与取值结构,只按本声明把 ``json_mode`` 的
93
+ 取值写到 ``arg`` 键上。``response_format`` 属 OpenAI 兼容协议字段,
94
+ 故缺省可作内置默认;档案写 ``"structured_output": false`` 可显式关闭。
95
+
96
+ Attributes:
97
+ arg: 请求体顶层键名;保留键(``model`` / ``messages`` 等)禁用
98
+ json_mode: 要求 JSON 对象时该键的取值(如 ``{"type": "json_object"}``)
99
+ """
100
+
101
+ arg: str = "response_format"
102
+ json_mode: Any = None
103
+
104
+
105
+ # 内置协议默认(D1=B 开箱即用):实测不支持该字段的端点应在档案写 false
106
+ _DEFAULT_STRUCTURED_OUTPUT: Final[StructuredOutputSpec] = StructuredOutputSpec(
107
+ arg="response_format", json_mode={"type": "json_object"}
108
+ )
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class ModelProfile:
113
+ """单个模型档案(运行时已解析密钥)。
114
+
115
+ Attributes:
116
+ name: 档案名(如 ``siliconflow``)
117
+ model_type: 模型类型(chat / embedding / rerank / image)
118
+ api_key_env: 密钥所在环境变量名
119
+ api_key: 已解析的密钥值
120
+ base_url: API 基础地址
121
+ endpoint: API 路径(以 ``/`` 开头)
122
+ model: 模型名称
123
+ timeout: 请求超时秒数
124
+ max_tokens: 单次请求输出上限(chat 用;None 表示由 provider 默认值决定)
125
+ retries: 5xx 重试次数(超时不重试,候选链切换才是有效重试)
126
+ dimension: **目标**向量维度(仅 embedding 有效)。`EmbeddingService`
127
+ 保证输出恒等于该值:模型原生维度更大时截断(含 L2 归一化),
128
+ 更小时报错;建表与维度守卫均应以它为唯一来源
129
+ batch_size: 单次请求最大文本数(仅 embedding 有效)
130
+ extra_body: 档案级额外请求体字段(厂商专有参数透传,如 GLM/Qwen 的
131
+ ``{"thinking": {"type": "disabled"}}``);与服务构造的同名键
132
+ 冲突时**以服务的值为准**(不可覆盖 model / messages / stream 等保留键)
133
+ thinking: 思考开关的注入声明(逐调用 ``thinking=`` 据此翻译成厂商字段);
134
+ None 表示该档案不支持按调用切换思考
135
+ structured_output: 结构化输出的注入声明(逐调用 ``json_mode=`` 据此翻译);
136
+ 未声明时取内置协议默认,``None`` 表示档案显式声明不支持
137
+ supports_tools: 是否支持 OpenAI function calling;None 表示未声明
138
+ (按 0.8.1 行为直接尝试),False 表示明确不支持(工具循环跳过该档案)
139
+ """
140
+
141
+ name: str
142
+ model_type: str
143
+ api_key_env: str
144
+ api_key: str
145
+ base_url: str
146
+ endpoint: str
147
+ model: str
148
+ timeout: int = 60
149
+ max_tokens: int | None = None
150
+ retries: int = 2
151
+ dimension: int | None = None
152
+ batch_size: int = 32
153
+ extra_body: dict[str, Any] | None = None
154
+ thinking: ThinkingSwitchSpec | None = None
155
+ structured_output: StructuredOutputSpec | None = None
156
+ supports_tools: bool | None = None
157
+
158
+
159
+ class ProfileState(enum.Enum):
160
+ """档案运行时状态(候选链与状态快照使用)。"""
161
+
162
+ AVAILABLE = "available" # 密钥已配置且可用(探测通过或尚未验证)
163
+ COOLING = "cooling" # 调用失败冷却中(到期自动恢复)
164
+ INVALID_KEY = "invalid_key" # 探测判定密钥无效
165
+ UNREACHABLE = "unreachable" # 探测无法判定(超时 / 404 / 5xx)
166
+ UNCONFIGURED = "unconfigured" # 密钥未配置
167
+ EXCLUDED = "excluded" # 因约束被剔除(如 embedding 链内 model 不一致)
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class ProfileStatus:
172
+ """档案状态快照行(``AIServicePool.available`` / ``AI.available`` 返回)。
173
+
174
+ Attributes:
175
+ name: 档案名
176
+ model: 模型名称
177
+ state: 运行时状态
178
+ current: 是否为该类型当前使用项(链头)
179
+ last_error: 最近一次失败原因(无失败为 None)
180
+ last_ok_at: 最近一次成功/探测通过时刻(Unix 秒;从未成功为 None)
181
+ thinking_switchable: 该档案是否声明了思考开关(可逐调用关/开思考)
182
+ json_mode_supported: 该档案是否支持结构化输出(仅显式 ``false`` 为 False;
183
+ 未声明按内置协议默认,视为支持)
184
+ tools_supported: 是否支持 function calling;None=未声明/未探测,
185
+ False=声明或运行时判定不支持
186
+ """
187
+
188
+ name: str
189
+ model: str
190
+ state: ProfileState
191
+ current: bool = False
192
+ last_error: str | None = None
193
+ last_ok_at: float | None = None
194
+ thinking_switchable: bool = False
195
+ json_mode_supported: bool = False
196
+ tools_supported: bool | None = None
197
+
198
+
199
+ class ThinkingSwitchSpecModel(BaseModel):
200
+ """档案 ``thinking`` 字段的原始声明(结构校验,厂商无关)。
201
+
202
+ 只校验外形(``arg`` 非空且非保留键、``off`` 必须给出),语义正确性
203
+ 由应用侧预设库保证——kit 不认识任何厂商字段名。
204
+ """
205
+
206
+ arg: str = Field(min_length=1)
207
+ off: Any = None
208
+ on: Any = None
209
+ default: bool | None = None
210
+
211
+ @field_validator("arg")
212
+ @classmethod
213
+ def _validate_arg(cls, value: str) -> str:
214
+ """``arg`` 不得占用请求体保留键(否则写坏请求骨架)。"""
215
+ if value in _RESERVED_PAYLOAD_KEYS:
216
+ raise ValueError(
217
+ f"thinking.arg 不得使用请求体保留键: {value}"
218
+ f"(禁用: {', '.join(sorted(_RESERVED_PAYLOAD_KEYS))})"
219
+ )
220
+ return value
221
+
222
+ @model_validator(mode="after")
223
+ def _validate_off(self) -> Self:
224
+ """``off`` 必须给出关闭取值(缺省与显式 null 都拒绝)。"""
225
+ if self.off is None:
226
+ raise ValueError("thinking.off 不得为空(须给出关闭思考时的取值)")
227
+ return self
228
+
229
+
230
+ def _build_thinking_spec(
231
+ config: ThinkingSwitchSpecModel | None,
232
+ ) -> ThinkingSwitchSpec | None:
233
+ """静态声明 → 运行时 spec(未声明返回 None,表示不支持按调用切换)。"""
234
+ if config is None:
235
+ return None
236
+ return ThinkingSwitchSpec(
237
+ arg=config.arg, off=config.off, on=config.on, default=config.default
238
+ )
239
+
240
+
241
+ class StructuredOutputSpecModel(BaseModel):
242
+ """档案 ``structured_output`` 字段的原始声明(结构校验,厂商无关)。
243
+
244
+ 只校验外形(``arg`` 非空且非保留键、``json_mode`` 必须给出取值);
245
+ 语义正确性由应用侧保证——kit 不认识任何厂商字段名。
246
+ """
247
+
248
+ arg: str = Field(default="response_format", min_length=1)
249
+ json_mode: Any = None
250
+
251
+ @field_validator("arg")
252
+ @classmethod
253
+ def _validate_arg(cls, value: str) -> str:
254
+ """``arg`` 不得占用请求体保留键(否则写坏请求骨架)。"""
255
+ if value in _RESERVED_PAYLOAD_KEYS:
256
+ raise ValueError(
257
+ f"structured_output.arg 不得使用请求体保留键: {value}"
258
+ f"(禁用: {', '.join(sorted(_RESERVED_PAYLOAD_KEYS))})"
259
+ )
260
+ return value
261
+
262
+ @model_validator(mode="after")
263
+ def _validate_json_mode(self) -> Self:
264
+ """``json_mode`` 必须给出取值(不支持请写 ``structured_output: false``)。"""
265
+ if self.json_mode is None:
266
+ raise ValueError(
267
+ "structured_output.json_mode 不得为空"
268
+ "(不支持结构化输出的档案请写 structured_output: false)"
269
+ )
270
+ return self
271
+
272
+
273
+ def _build_structured_output_spec(
274
+ config: StructuredOutputSpecModel | Literal[False] | None,
275
+ ) -> StructuredOutputSpec | None:
276
+ """静态声明 → 运行时 spec。
277
+
278
+ ``False`` → ``None``(运行期不支持);缺省(``None``)→ 内置协议默认;
279
+ 显式声明 → 该声明。``None`` 是**唯一**的「不支持」表示,避免在
280
+ 注入点再区分「未声明」与「显式关闭」。
281
+ """
282
+ if config is False:
283
+ return None
284
+ if config is None:
285
+ return _DEFAULT_STRUCTURED_OUTPUT
286
+ return StructuredOutputSpec(arg=config.arg, json_mode=config.json_mode)
287
+
288
+
289
+ class ProfileConfig(BaseModel):
290
+ """档案配置(JSON 文件中单个 profile 的原始字段)。
291
+
292
+ 注意:``api_key`` 存的是密钥所在环境变量名,
293
+ 与 ``ModelProfile.api_key``(已解析的密钥值)同名不同义。
294
+ """
295
+
296
+ api_key: str = Field(min_length=1)
297
+ base_url: str = Field(min_length=1)
298
+ endpoint: str = Field(min_length=1)
299
+ model: str = Field(min_length=1)
300
+ timeout: int = Field(default=60, gt=0)
301
+ max_tokens: int | None = Field(default=None, gt=0)
302
+ retries: int = Field(default=2, ge=0)
303
+ dimension: int | None = Field(default=None, gt=0)
304
+ batch_size: int = Field(default=32, gt=0)
305
+ # 厂商专有请求字段透传(如 {"thinking": {"type": "disabled"}});
306
+ # 与服务构造的同名键冲突时以服务的值为准,故保留键无法被覆盖
307
+ extra_body: dict[str, Any] | None = None
308
+ # 思考开关注入声明:逐调用 thinking= 据此翻译为厂商字段(未声明 = 不支持切换)
309
+ thinking: ThinkingSwitchSpecModel | None = None
310
+ # 结构化输出注入声明:False = 该档案显式不支持;缺省 = 用内置协议默认
311
+ structured_output: StructuredOutputSpecModel | Literal[False] | None = None
312
+ # function calling 能力声明:False = 明确不支持(工具循环跳过);
313
+ # 缺省 None = 未声明,按 0.8.1 行为直接尝试,由运行时 400 兜底
314
+ supports_tools: bool | None = None
315
+
316
+
317
+ class TypeConfig(BaseModel):
318
+ """某模型类型的档案集合"""
319
+
320
+ default_profile: str = Field(min_length=1)
321
+ # 整链预算(秒):门面同步等待上限,容纳「首选失败 + 备胎跑完」的降级;
322
+ # 未配置时由 runner 按 sum(候选 timeout) + 余量自适应
323
+ chain_timeout: int | None = Field(default=None, gt=0)
324
+ profiles: dict[str, ProfileConfig]
325
+
326
+ @model_validator(mode="after")
327
+ def _validate_default_profile(self) -> Self:
328
+ """默认档案必须在该类型的 profiles 中(加载期即报,避免运行期 KeyError)。"""
329
+ if self.default_profile not in self.profiles:
330
+ raise ValueError(
331
+ f"default_profile 未在 profiles 中定义: {self.default_profile}"
332
+ f"(已知档案: {', '.join(sorted(self.profiles)) or '无'})"
333
+ )
334
+ return self
335
+
336
+
337
+ class RegistryConfig(BaseModel):
338
+ """模型档案文件整体结构(顶层对象)"""
339
+
340
+ chat: TypeConfig | None = None
341
+ embedding: TypeConfig | None = None
342
+ rerank: TypeConfig | None = None
343
+ image: TypeConfig | None = None
344
+
345
+ def type_config(self, model_type: str) -> TypeConfig:
346
+ """取某类型的档案集合,区分「类型名非法」与「类型未配置」两种情况。
347
+
348
+ Raises:
349
+ AIConfigError: 类型名不在四类之内(调用方写错)。
350
+ AIModelTypeNotConfiguredError: 类型名合法但 JSON 缺该段(可预期空态,
351
+ ``AI.available`` 据此返回空列表)。
352
+ """
353
+ if model_type not in MODEL_TYPES:
354
+ available = ", ".join(MODEL_TYPES)
355
+ raise AIConfigError(f"模型类型不存在: {model_type},可用类型: {available}")
356
+ config = getattr(self, model_type)
357
+ if config is None:
358
+ raise AIModelTypeNotConfiguredError(
359
+ f"模型类型未配置: {model_type}"
360
+ f"(ai_models.json 缺少 {model_type} 段)"
361
+ )
362
+ return config
363
+
364
+
365
+ class ModelRegistry:
366
+ """模型档案注册表。
367
+
368
+ 用法::
369
+
370
+ registry = ModelRegistry()
371
+ registry.load("./config/ai_models.json")
372
+ profile = registry.get("chat", "siliconflow")
373
+ """
374
+
375
+ def __init__(self) -> None:
376
+ self._config: RegistryConfig | None = None
377
+
378
+ def load(self, path: str | None = None) -> None:
379
+ """加载并校验模型档案文件。
380
+
381
+ 加载前将项目根 ``.env`` 注入 ``os.environ``(``override=False``:
382
+ 真实环境变量优先,重复调用幂等),使密钥仅配置在 ``.env`` 时
383
+ ``get()`` 也能解析——档案数量与密钥变量名由 JSON 决定,
384
+ 无需改 ``sys_config``。
385
+
386
+ Args:
387
+ path: 档案文件路径,None 时取 ``Settings.AI_MODELS_CONFIG_PATH``
388
+
389
+ Raises:
390
+ AIConfigError: 文件缺失、JSON 非法、结构非法、档案必填字段缺失、
391
+ 默认档案未配置。
392
+ """
393
+ load_dotenv(Path.cwd() / ".env", override=False)
394
+
395
+ config_path = path or get_settings().AI_MODELS_CONFIG_PATH
396
+ file_path = Path(config_path)
397
+
398
+ if not file_path.is_file():
399
+ raise AIConfigError(
400
+ f"模型档案文件不存在: {config_path}。"
401
+ "请在项目根创建该文件(api_key 值为环境变量名,密钥配置在 .env),"
402
+ f"最小模板:\n{_MINIMAL_MODELS_JSON}\n"
403
+ "或调整 Settings.AI_MODELS_CONFIG_PATH 指向已有档案文件"
404
+ )
405
+
406
+ try:
407
+ self._config = RegistryConfig.model_validate_json(
408
+ file_path.read_text(encoding="utf-8")
409
+ )
410
+ except (OSError, ValidationError) as exc:
411
+ raise AIConfigError(f"模型档案文件解析失败: {config_path}: {exc}") from exc
412
+
413
+ loaded_types = [t for t in MODEL_TYPES if getattr(self._config, t) is not None]
414
+ logger.info(
415
+ f"AI 模型档案已加载: {config_path},类型: {', '.join(loaded_types) or '无'}"
416
+ )
417
+
418
+ def _resolve_profile(
419
+ self, model_type: str, profile: str | None
420
+ ) -> tuple[str, ProfileConfig]:
421
+ """解析类型 + 档案名,返回 (档案名, 静态 ProfileConfig),不解析密钥。"""
422
+ if self._config is None:
423
+ raise AIConfigError("ModelRegistry 未加载,请先调用 load()")
424
+
425
+ type_config = self._config.type_config(model_type)
426
+ profile_name = profile or type_config.default_profile
427
+ profile_config = type_config.profiles.get(profile_name)
428
+ if profile_config is None:
429
+ raise AIConfigError(
430
+ f"档案不存在: {model_type}.{profile_name},"
431
+ f"可用档案: {', '.join(sorted(type_config.profiles))}"
432
+ )
433
+ return profile_name, profile_config
434
+
435
+ def get(self, model_type: str, profile: str | None = None) -> ModelProfile:
436
+ """获取模型档案,profile 为 None 时回退到该类型默认档案。
437
+
438
+ Raises:
439
+ AIConfigError: 类型/档案不存在、密钥环境变量未配置。
440
+ """
441
+ profile_name, profile_config = self._resolve_profile(model_type, profile)
442
+
443
+ api_key = os.environ.get(profile_config.api_key) or ""
444
+ if not api_key:
445
+ raise AIConfigError(
446
+ f"未配置环境变量 {profile_config.api_key},"
447
+ f"请检查 .env 中的 {profile_config.api_key}"
448
+ )
449
+
450
+ return self._build_profile(model_type, profile_name, profile_config, api_key)
451
+
452
+ @staticmethod
453
+ def _build_profile(
454
+ model_type: str, name: str, config: ProfileConfig, api_key: str
455
+ ) -> ModelProfile:
456
+ """由静态配置 + 已解析密钥构建运行时档案(get/chain 共用)。"""
457
+ return ModelProfile(
458
+ name=name,
459
+ model_type=model_type,
460
+ api_key_env=config.api_key,
461
+ api_key=api_key,
462
+ base_url=config.base_url,
463
+ endpoint=config.endpoint,
464
+ model=config.model,
465
+ timeout=config.timeout,
466
+ max_tokens=config.max_tokens,
467
+ retries=config.retries,
468
+ dimension=config.dimension,
469
+ batch_size=config.batch_size,
470
+ extra_body=config.extra_body,
471
+ thinking=_build_thinking_spec(config.thinking),
472
+ # 结构化输出仅对 chat 有意义:其余类型一律视为不支持(避免状态快照误报)
473
+ structured_output=(
474
+ _build_structured_output_spec(config.structured_output)
475
+ if model_type == "chat"
476
+ else None
477
+ ),
478
+ # 工具能力仅对 chat 有意义;其余类型不参与 Agent
479
+ supports_tools=config.supports_tools if model_type == "chat" else None,
480
+ )
481
+
482
+ def get_profile(self, model_type: str, profile: str | None = None) -> ProfileConfig:
483
+ """读取静态档案(不含密钥),用于维度/模型名等无需密钥的配置。"""
484
+ return self._resolve_profile(model_type, profile)[1]
485
+
486
+ def chain_timeout(self, model_type: str) -> float | None:
487
+ """该类型的整链预算(秒,``TypeConfig.chain_timeout``);未配置返回 None。"""
488
+ if self._config is None:
489
+ raise AIConfigError("ModelRegistry 未加载,请先调用 load()")
490
+ value = self._config.type_config(model_type).chain_timeout
491
+ return float(value) if value is not None else None
492
+
493
+ def type_profiles(self, model_type: str) -> dict[str, ProfileConfig]:
494
+ """返回该类型全部静态档案(含密钥未配置者),供状态快照展示。
495
+
496
+ Raises:
497
+ AIConfigError: 注册表未加载或类型不存在。
498
+ """
499
+ if self._config is None:
500
+ raise AIConfigError("ModelRegistry 未加载,请先调用 load()")
501
+ return dict(self._config.type_config(model_type).profiles)
502
+
503
+ def chain(self, model_type: str) -> list[ModelProfile]:
504
+ """解析该类型候选链:``default_profile`` 打头,其余按 JSON 声明顺序。
505
+
506
+ 规则:
507
+ 1. ``default_profile`` 打头,其余按 JSON 声明顺序;
508
+ 2. 密钥未配置的档案剔除出链(debug 日志)。
509
+
510
+ Args:
511
+ model_type: 模型类型(chat / embedding / rerank / image)
512
+
513
+ Returns:
514
+ 候选档案列表(密钥已解析;可能为空——全部未配置密钥)。
515
+
516
+ Raises:
517
+ AIConfigError: 注册表未加载或类型不存在。
518
+ """
519
+ if self._config is None:
520
+ raise AIConfigError("ModelRegistry 未加载,请先调用 load()")
521
+ type_config = self._config.type_config(model_type)
522
+
523
+ order = [
524
+ type_config.default_profile,
525
+ *(
526
+ name
527
+ for name in type_config.profiles
528
+ if name != type_config.default_profile
529
+ ),
530
+ ]
531
+
532
+ profiles: list[ModelProfile] = []
533
+ for name in order:
534
+ config = type_config.profiles[name]
535
+ api_key = os.environ.get(config.api_key) or ""
536
+ if not api_key:
537
+ logger.debug(
538
+ f"{model_type}.{name} 密钥未配置({config.api_key}),剔除出链"
539
+ )
540
+ continue
541
+ profiles.append(self._build_profile(model_type, name, config, api_key))
542
+ return profiles
543
+
544
+
545
+ def with_api_key(profile: ModelProfile, api_key: str) -> ModelProfile:
546
+ """返回替换 api_key 后的新档案(ModelProfile 为不可变)。"""
547
+ return replace(profile, api_key=api_key)
548
+
549
+
550
+ def resolve_max_tokens(profile: ModelProfile, max_tokens: int | None) -> int | None:
551
+ """解析本次实际下发的输出上限:调用方 → 档案 → ``None``(provider 默认)。
552
+
553
+ 单一数据源:``ChatService``(写入 ``StreamStats`` 与日志)与
554
+ ``SdkClient._chat_params``(构造请求体)共用,避免两处回落逻辑漂移。
555
+ """
556
+ return max_tokens if max_tokens is not None else profile.max_tokens
557
+
558
+
559
+ @lru_cache(maxsize=1)
560
+ def get_model_registry() -> ModelRegistry:
561
+ """获取全局单例 ModelRegistry(首次调用自动 load 默认档案文件)。"""
562
+ registry = ModelRegistry()
563
+ registry.load()
564
+ return registry
565
+
566
+
567
+ def embedding_dimension() -> int:
568
+ """embedding 默认档案的向量维度(读静态字段,无需密钥)。"""
569
+ dimension = get_model_registry().get_profile("embedding").dimension
570
+ if dimension is None:
571
+ raise AIConfigError("ai_models.json 的 embedding 档案缺少 dimension")
572
+ return dimension
573
+
574
+
575
+ def embedding_model() -> str:
576
+ """embedding 默认档案的模型名(读静态字段,无需密钥)。"""
577
+ return get_model_registry().get_profile("embedding").model