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,198 @@
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
+ # refactor: 2026-11-04 传输层改 openai SDK(维度契约与批量编排不变)
22
+ """向量化服务(全异步,openai SDK 传输)。"""
23
+
24
+ import asyncio
25
+ import itertools
26
+ import math
27
+ import time
28
+ from typing import ClassVar
29
+
30
+ from yimo.kit.ai._internal.sdk_client import SdkServiceBase
31
+ from yimo.kit.ai.exceptions import AIError, AIRequestError, AIResponseError
32
+ from yimo.kit.ai.profiles import ModelProfile
33
+ from yimo.kit.config.log_config import get_default_logger
34
+
35
+ __all__ = ["EmbeddingService"]
36
+
37
+ logger = get_default_logger(__name__)
38
+
39
+ _DEFAULT_CONCURRENCY = 4
40
+
41
+
42
+ class EmbeddingService(SdkServiceBase):
43
+ """向量化服务(全异步)。
44
+
45
+ 公网 API 有限流限速前提,通过分批 + 可选并发(信号量)控制压力。
46
+ 信号量在运行中的事件循环内惰性创建,避免构造期绑定循环的隐患。
47
+
48
+ **维度契约**:``profile.dimension`` 是**目标向量维度**(不是「模型原生维度」),
49
+ 本服务保证输出恒等于它:
50
+
51
+ - 模型返回维 == ``dimension`` → 原样返回(零计算,逐字节不变);
52
+ - 模型返回维 > ``dimension`` → **截断到该维度并做 L2 归一化**(依赖模型的 MRL
53
+ 支持;非 MRL 模型截断后质量会退化);
54
+ - 模型返回维 < ``dimension`` → 抛 `AIResponseError`(降维只能变小,不能放大)。
55
+
56
+ 这样「建表维度 = 配置维度 = 输出维度」可由同一个配置值统一,
57
+ 换模型(原生维度更大)时无需重构向量列。
58
+
59
+ ⚠ 候选链内各档案的 ``dimension`` 必须一致:故障切换后输出维度跟随
60
+ 被选中档案的配置,不一致会导致同一业务表写入不同维度的向量。
61
+ """
62
+
63
+ _LABEL: ClassVar[str] = "向量化模型"
64
+
65
+ def __init__(self, profile: ModelProfile) -> None:
66
+ super().__init__(profile)
67
+ if profile.dimension is None:
68
+ raise ValueError(f"模型 {profile.model} 未配置 dimension,无法用于向量化")
69
+ # 仅用于「截断只提示一次」,不参与任何行为分支
70
+ self._truncate_logged = False
71
+
72
+ @property
73
+ def dimension(self) -> int:
74
+ dim = self._profile.dimension
75
+ if not isinstance(dim, int):
76
+ raise AIResponseError("dimension 在构造期已校验非空,不应缺失")
77
+ return dim
78
+
79
+ def _fit_dimension(self, vector: list[float]) -> list[float]:
80
+ """把模型输出对齐到配置的目标维度
81
+
82
+ Args:
83
+ vector: 模型原始输出的向量
84
+
85
+ Returns:
86
+ 目标维度的向量:等长时原样返回;超长时截断并 L2 归一化
87
+
88
+ Raises:
89
+ AIResponseError: 输出维度**不足**配置维度(无法放大),
90
+ 或截断后前 N 维全为 0(无法归一化)
91
+ """
92
+ target = self.dimension
93
+ if len(vector) == target:
94
+ return vector
95
+ if len(vector) < target:
96
+ raise AIResponseError(
97
+ f"向量维度不足:模型 {self._profile.model} 返回 {len(vector)} 维,"
98
+ f"配置 dimension={target}。降维只能变小不能放大,"
99
+ f"请改用原生维度 >= {target} 的模型,"
100
+ f"或调低 dimension 并重建向量表(表内既有向量需重新入库)。"
101
+ )
102
+
103
+ head = vector[:target]
104
+ norm = math.sqrt(sum(value * value for value in head))
105
+ if norm == 0.0:
106
+ raise AIResponseError(
107
+ f"模型 {self._profile.model} 返回向量的前 {target} 维全为 0,"
108
+ f"无法按配置 dimension={target} 归一化;请检查模型输出是否正常。"
109
+ )
110
+ if not self._truncate_logged:
111
+ logger.info(
112
+ f"向量已按配置截断:{len(vector)} → {target} 维(含 L2 归一化)。"
113
+ f"截断依赖模型的 MRL 支持,非 MRL 模型质量会退化"
114
+ )
115
+ self._truncate_logged = True
116
+ return [value / norm for value in head]
117
+
118
+ async def _embed_batch(
119
+ self, texts: list[str], *, log: bool = True
120
+ ) -> list[list[float]]:
121
+ """单批向量化 + 维度对齐。"""
122
+ self._debug_payload(
123
+ {
124
+ "model": self._profile.model,
125
+ "input": texts,
126
+ "encoding_format": "float",
127
+ }
128
+ )
129
+ with self._log_call(log=log):
130
+ vectors = await self._client.embed(texts)
131
+ if len(vectors) != len(texts):
132
+ raise AIResponseError(
133
+ f"向量化返回条数不符:输入 {len(texts)} 条,返回 {len(vectors)} 条"
134
+ )
135
+ return [self._fit_dimension(vector) for vector in vectors]
136
+
137
+ async def create(self, text: str) -> list[float]:
138
+ """对单个文本向量化,返回向量。"""
139
+ vectors = await self._embed_batch([text])
140
+ return vectors[0]
141
+
142
+ async def create_batch(
143
+ self,
144
+ texts: list[str],
145
+ *,
146
+ batch_size: int | None = None,
147
+ concurrency: int = _DEFAULT_CONCURRENCY,
148
+ ) -> list[list[float]]:
149
+ """批量向量化(分批 + 限并发)。
150
+
151
+ 日志只由本方法的「整批汇总」记录起止:内层批次传 ``log=False`` 静默,
152
+ 避免 3N+3 条重复输出;单批失败仍由基类记 ERROR。
153
+ """
154
+ if not texts:
155
+ return []
156
+
157
+ batch = batch_size or self._profile.batch_size
158
+ batches = list(itertools.batched(texts, batch, strict=False))
159
+ desc = self._log_desc(suffix=",整批汇总")
160
+ logger.info(f"********** {desc} ********** Start")
161
+ logger.info(
162
+ f"请求参数: 共 {len(texts)} 条文本,分 {len(batches)} 批"
163
+ f"(批大小 {batch},并发 {concurrency})"
164
+ )
165
+ start = time.perf_counter()
166
+ note = ""
167
+ failures: list[str] = []
168
+ try:
169
+ semaphore = asyncio.Semaphore(concurrency)
170
+ results: list[list[float] | None] = [None] * len(texts)
171
+
172
+ async def _one(batch_index: int, chunk: tuple[str, ...]) -> None:
173
+ async with semaphore:
174
+ try:
175
+ vectors = await self._embed_batch(list(chunk), log=False)
176
+ except AIError as exc:
177
+ failures.append(f"批次 {batch_index}: {exc}")
178
+ return
179
+ offset = batch_index * batch
180
+ for index, vec in enumerate(vectors):
181
+ results[offset + index] = vec
182
+
183
+ await asyncio.gather(*(_one(i, chunk) for i, chunk in enumerate(batches)))
184
+
185
+ if failures:
186
+ note = f"(失败:{len(failures)}/{len(batches)} 批)"
187
+ raise AIRequestError(
188
+ f"有 {len(failures)}/{len(batches)} 批向量化失败: "
189
+ + " | ".join(failures)
190
+ )
191
+
192
+ return [vec for vec in results if vec is not None]
193
+ finally:
194
+ log = logger.error if failures else logger.info
195
+ log(
196
+ f"********** {desc} ********** "
197
+ f"耗时 {time.perf_counter() - start:.1f}秒{note}"
198
+ )
@@ -0,0 +1,109 @@
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
+ """yimo/kit/ai 统一异常体系
22
+
23
+ 继承链:
24
+ AIError 基类
25
+ ├── AIConfigError 档案文件缺失/非法、档案不存在、密钥未配置、必填字段缺失
26
+ │ └── AIModelTypeNotConfiguredError 类型名合法但档案未配置该类型段
27
+ ├── AIRequestError 网络异常、HTTP >= 400
28
+ │ ├── AITimeoutError 请求超时(可用于重试策略)
29
+ │ └── AIAggregateError 候选链聚合异常(全部候选失败或整链预算耗尽)
30
+ └── AIResponseError 响应结构解析失败、流式数据无法解析
31
+ """
32
+
33
+
34
+ class AIError(Exception):
35
+ """AI 模型服务基类异常"""
36
+
37
+
38
+ class AIConfigError(AIError):
39
+ """模型档案配置异常(文件缺失/非法、档案不存在、密钥未配置、必填字段缺失)"""
40
+
41
+
42
+ class AIModelTypeNotConfiguredError(AIConfigError):
43
+ """类型名合法但 ``ai_models.json`` 未配置该类型段(可预期的空态)。
44
+
45
+ ``AI.available(type)`` 对这种情况返回空列表;其余 ``AIConfigError``
46
+ (类型名非法、文件缺失、注册表未加载)仍照常抛出。继承 ``AIConfigError``
47
+ 使既有 ``except AIConfigError`` 捕获点零改动。
48
+ """
49
+
50
+
51
+ class AIRequestError(AIError):
52
+ """模型服务请求异常(网络异常、HTTP >= 400)。
53
+
54
+ Attributes:
55
+ status_code: HTTP 状态码;非 HTTP 错误(超时、连接失败等)为 None。
56
+ retry_after: 服务端 ``Retry-After`` 建议等待秒数(429 时解析,
57
+ 整数秒与 HTTP-date 两种格式);未提供为 None。
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ message: str,
63
+ *,
64
+ status_code: int | None = None,
65
+ retry_after: float | None = None,
66
+ ) -> None:
67
+ super().__init__(message)
68
+ self.status_code: int | None = status_code
69
+ self.retry_after: float | None = retry_after
70
+
71
+
72
+ class AITimeoutError(AIRequestError):
73
+ """模型服务请求超时异常(可用于重试策略)"""
74
+
75
+
76
+ class AIAggregateError(AIRequestError):
77
+ """候选链聚合异常:全部候选失败(或整链预算耗尽)时抛出。
78
+
79
+ 继承 ``AIRequestError``:业务按 ``AIRequestError`` 捕获零改动。
80
+ ``status_code`` 在「全部候选状态码一致」时透传该值(如整链 429),
81
+ 否则为 None——业务可据此一行判定限流。
82
+
83
+ Attributes:
84
+ tried: 已尝试的档案名列表。
85
+ statuses: 各候选异常的 HTTP 状态码(非 HTTP 错误为 None)。
86
+ last_error: 最后一个候选的异常;预算耗尽且无候选失败时为 None。
87
+ budget_exhausted: 是否因整链预算耗尽而提前终止(未再发起新候选)。
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ message: str,
93
+ *,
94
+ status_code: int | None = None,
95
+ retry_after: float | None = None,
96
+ tried: list[str] | None = None,
97
+ statuses: list[int | None] | None = None,
98
+ last_error: AIError | None = None,
99
+ budget_exhausted: bool = False,
100
+ ) -> None:
101
+ super().__init__(message, status_code=status_code, retry_after=retry_after)
102
+ self.tried: list[str] = list(tried or [])
103
+ self.statuses: list[int | None] = list(statuses or [])
104
+ self.last_error: AIError | None = last_error
105
+ self.budget_exhausted: bool = budget_exhausted
106
+
107
+
108
+ class AIResponseError(AIError):
109
+ """模型服务响应异常(响应结构解析失败、流式数据无法解析)"""
@@ -0,0 +1,84 @@
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-22
21
+ # refactor: 2026-11-04 传输层改 openai SDK(厂商私有字段走 extra_body)
22
+ """图像生成服务(全异步,openai SDK 传输)。"""
23
+
24
+ from dataclasses import dataclass
25
+ from typing import ClassVar
26
+
27
+ from yimo.kit.ai._internal.sdk_client import SdkServiceBase
28
+
29
+ __all__ = ["ImageResult", "ImageService"]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ImageResult:
34
+ """图像生成结果。
35
+
36
+ ``url`` 与 ``b64`` 至少一个非空;两者都有时都填充(不同厂商回退行为不同)。
37
+ 需要二进制时:有 ``b64`` 直接解码,否则下载 ``url``。
38
+ """
39
+
40
+ url: str | None
41
+ b64: str | None
42
+
43
+
44
+ class ImageService(SdkServiceBase):
45
+ """图像生成服务(全异步)。
46
+
47
+ ``n > 1`` 时仅返回第一张图片,调用方如需多图请自行扩展。
48
+ 返回 :class:`ImageResult`(``url`` / ``b64`` 至少一个非空)。
49
+ """
50
+
51
+ _LABEL: ClassVar[str] = "图像生成模型"
52
+
53
+ async def create(
54
+ self,
55
+ prompt: str,
56
+ *,
57
+ size: str | None = None,
58
+ n: int = 1,
59
+ return_base64: bool = False,
60
+ ratio: str | None = None,
61
+ ) -> ImageResult:
62
+ """文生图,返回 :class:`ImageResult`。"""
63
+ extra: dict[str, object] = {}
64
+ if return_base64:
65
+ extra["return_base64"] = True
66
+ if ratio is not None:
67
+ extra["ratio"] = ratio
68
+ self._debug_payload(
69
+ {
70
+ "model": self._profile.model,
71
+ "prompt": prompt,
72
+ "n": n,
73
+ "size": size,
74
+ "extra_body": extra,
75
+ }
76
+ )
77
+ with self._log_call():
78
+ url, b64 = await self._client.image(
79
+ prompt,
80
+ size=size,
81
+ n=n,
82
+ extra_body=extra or None,
83
+ )
84
+ return ImageResult(url=url, b64=b64)
@@ -0,0 +1,105 @@
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-11-10
21
+ """yimo/kit/ai 消息类型契约(OpenAI 兼容的消息结构)。
22
+
23
+ 0.7.5 起由 ``dict[str, str]`` 改为 TypedDict 联合:运行时仍是 ``dict``,
24
+ 现有字面量调用零改动;类型层可精确表达工具调用与 tool 回灌消息。
25
+ """
26
+
27
+ from dataclasses import dataclass, field
28
+ from typing import Literal, NotRequired, TypedDict
29
+
30
+ __all__ = [
31
+ "AssistantMessage",
32
+ "ChatReply",
33
+ "FunctionCall",
34
+ "Message",
35
+ "SystemMessage",
36
+ "ToolCall",
37
+ "ToolMessage",
38
+ "UserMessage",
39
+ ]
40
+
41
+
42
+ class FunctionCall(TypedDict):
43
+ """工具调用中的函数名与参数。
44
+
45
+ ``arguments`` 为 JSON 字符串(OpenAI 协议即如此,不是 dict)。
46
+ """
47
+
48
+ name: str
49
+ arguments: str
50
+
51
+
52
+ class ToolCall(TypedDict):
53
+ """模型返回的一次工具调用。"""
54
+
55
+ id: str
56
+ type: Literal["function"]
57
+ function: FunctionCall
58
+
59
+
60
+ class SystemMessage(TypedDict):
61
+ """系统提示消息。"""
62
+
63
+ role: Literal["system"]
64
+ content: str
65
+
66
+
67
+ class UserMessage(TypedDict):
68
+ """用户消息。"""
69
+
70
+ role: Literal["user"]
71
+ content: str
72
+
73
+
74
+ class AssistantMessage(TypedDict):
75
+ """模型回复消息;携带工具调用时 ``content`` 可为空。"""
76
+
77
+ role: Literal["assistant"]
78
+ content: NotRequired[str | None]
79
+ tool_calls: NotRequired[list[ToolCall]]
80
+
81
+
82
+ class ToolMessage(TypedDict):
83
+ """工具执行结果回灌消息。"""
84
+
85
+ role: Literal["tool"]
86
+ content: str
87
+ tool_call_id: str
88
+
89
+
90
+ # 四种角色的联合;``list[Message]`` 即 OpenAI 的 messages 数组
91
+ type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class ChatReply:
96
+ """一次非流式对话的完整回复(工具循环专用)。
97
+
98
+ 与 :meth:`ChatService.create` 的三元组返回值并存:三元组保持旧契约,
99
+ 本类型额外携带 ``tool_calls``,供 Agent 循环回灌工具结果。
100
+ """
101
+
102
+ content: str | None
103
+ reasoning: str
104
+ finish_reason: str | None
105
+ tool_calls: list[ToolCall] = field(default_factory=list)
@@ -0,0 +1,121 @@
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
+ from yimo.kit.ai.chat_service import ChatService
21
+ from yimo.kit.ai.embedding_service import EmbeddingService
22
+ from yimo.kit.ai.image_service import ImageService
23
+ from yimo.kit.ai.profiles import (
24
+ MODEL_TYPES,
25
+ ModelProfile,
26
+ get_model_registry,
27
+ with_api_key,
28
+ )
29
+ from yimo.kit.ai.rerank_service import RerankService
30
+
31
+ __all__ = ["ModelBuilder"]
32
+
33
+ Service = ChatService | EmbeddingService | RerankService | ImageService
34
+
35
+
36
+ class ModelBuilder:
37
+ """根据模型类型构建对应的 AI 服务实例。"""
38
+
39
+ @staticmethod
40
+ def _resolve_profile(
41
+ model_type: str,
42
+ model: str | None = None,
43
+ *,
44
+ api_key: str | None = None,
45
+ ) -> ModelProfile:
46
+ registry = get_model_registry()
47
+ profile = registry.get(model_type, model)
48
+ if api_key is not None:
49
+ profile = with_api_key(profile, api_key)
50
+ return profile
51
+
52
+ @staticmethod
53
+ def build(
54
+ model_type: str,
55
+ model: str | None = None,
56
+ *,
57
+ api_key: str | None = None,
58
+ ) -> Service:
59
+ """构建指定的 AI 服务。
60
+
61
+ Args:
62
+ model_type: 模型类型(chat / embedding / rerank / image)
63
+ model: 档案名,None 时回退到该类型默认档案
64
+ api_key: 可选,覆盖档案中的密钥
65
+
66
+ Raises:
67
+ ValueError: 未知模型类型。
68
+ """
69
+ match model_type:
70
+ case "chat":
71
+ profile = ModelBuilder._resolve_profile(
72
+ model_type, model, api_key=api_key
73
+ )
74
+ return ChatService(profile)
75
+ case "embedding":
76
+ profile = ModelBuilder._resolve_profile(
77
+ model_type, model, api_key=api_key
78
+ )
79
+ return EmbeddingService(profile)
80
+ case "rerank":
81
+ profile = ModelBuilder._resolve_profile(
82
+ model_type, model, api_key=api_key
83
+ )
84
+ return RerankService(profile)
85
+ case "image":
86
+ profile = ModelBuilder._resolve_profile(
87
+ model_type, model, api_key=api_key
88
+ )
89
+ return ImageService(profile)
90
+ case _:
91
+ raise ValueError(
92
+ f"未知模型类型: {model_type},支持: {', '.join(MODEL_TYPES)}"
93
+ )
94
+
95
+ @classmethod
96
+ def build_chat(
97
+ cls, model: str | None = None, *, api_key: str | None = None
98
+ ) -> ChatService:
99
+ profile = cls._resolve_profile("chat", model, api_key=api_key)
100
+ return ChatService(profile)
101
+
102
+ @classmethod
103
+ def build_embedding(
104
+ cls, model: str | None = None, *, api_key: str | None = None
105
+ ) -> EmbeddingService:
106
+ profile = cls._resolve_profile("embedding", model, api_key=api_key)
107
+ return EmbeddingService(profile)
108
+
109
+ @classmethod
110
+ def build_rerank(
111
+ cls, model: str | None = None, *, api_key: str | None = None
112
+ ) -> RerankService:
113
+ profile = cls._resolve_profile("rerank", model, api_key=api_key)
114
+ return RerankService(profile)
115
+
116
+ @classmethod
117
+ def build_image(
118
+ cls, model: str | None = None, *, api_key: str | None = None
119
+ ) -> ImageService:
120
+ profile = cls._resolve_profile("image", model, api_key=api_key)
121
+ return ImageService(profile)
@@ -0,0 +1,62 @@
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-11-04
21
+ """模型档案轻探测客户端(``ProbeClient``)。
22
+
23
+ 破坏性变更:``post_json`` / ``stream_json`` 已删除——请求发送改由
24
+ :class:`yimo.kit.ai.sdk_client.SdkClient` 承担,rerank 走
25
+ :class:`yimo.kit.ai.rerank_transport.RerankTransport`。本类只保留
26
+ ``list_models()`` / ``close()``,供业务侧做「密钥是否有效」的连通性测试。
27
+
28
+ 0.7.0 由 ``ModelClient`` 改名;0.7.1 起**弃用别名已删除**,旧名不可导入
29
+ (``from yimo.kit.ai.model_client import ModelClient`` 抛 ``ImportError``)。
30
+ """
31
+
32
+ from yimo.kit.ai._internal.sdk_client import SdkClient
33
+ from yimo.kit.ai._internal.types import JSONObject
34
+ from yimo.kit.ai.profiles import ModelProfile
35
+
36
+ __all__ = ["ProbeClient"]
37
+
38
+
39
+ class ProbeClient:
40
+ """单档案连通性探测客户端(全异步)。
41
+
42
+ 它只做 ``list_models`` 探活,真正的传输在
43
+ :class:`yimo.kit.ai.sdk_client.SdkClient`。
44
+ """
45
+
46
+ def __init__(self, profile: ModelProfile) -> None:
47
+ self._profile: ModelProfile = profile
48
+ self._client: SdkClient = SdkClient(profile)
49
+
50
+ async def list_models(self) -> JSONObject:
51
+ """``GET {base_url}/models`` 轻探测(独立 10 秒超时)。
52
+
53
+ 返回值只表达成功(失败抛异常),统一返回空对象。
54
+
55
+ Raises:
56
+ AIRequestError: 非 2xx 或连接失败。
57
+ AITimeoutError: 探测超时。
58
+ """
59
+ return await self._client.list_models()
60
+
61
+ async def close(self) -> None:
62
+ await self._client.close()