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,462 @@
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 __future__ import annotations
21
+
22
+ # date: 2026-08-22
23
+ """SQLite 数据库工具类
24
+
25
+ 基于 yimo.kit.db 统一数据库层封装,提供开箱即用的服务方法。
26
+ 业务代码无需管理 session/transaction,直接调用即可。
27
+
28
+ 本类继承 BaseDbKit,复用全部共享实现(连接管理 / ORM / 原生 SQL / 原生表操作 /
29
+ 事务 / 表操作),并额外提供基于 sqlite-vector 扩展的 5 个向量方法,以及 2 个
30
+ **编码原语**(`encode_vector` / `decode_vector`,仅本后端具备)。
31
+
32
+ 使用方式::
33
+
34
+ # 单条操作(自动管理事务)
35
+ user = SQLiteKit.create(UserModel, {"name": "张三"})
36
+ users = SQLiteKit.list(UserModel, skip=0, limit=10)
37
+ SQLiteKit.update(UserModel, user.id, {"name": "李四"})
38
+
39
+ # 向量操作(dims 必填;默认精确检索)
40
+ SQLiteKit.create_vector_table("images", 384)
41
+ SQLiteKit.insert_vectors("images", [[0.1, 0.2, ...], ...])
42
+ rows = SQLiteKit.search_vectors("images", [0.1, 0.2, ...], top_k=5)
43
+
44
+ 向量能力要点(跨库差异见 docs/agents/modules/kit-db.md「向量能力差异」):
45
+
46
+ - ``exact=True``(默认)走 ``vector_full_scan``:距离为**真值 L2**,无需量化,且不受
47
+ 量化快照影响;``exact=False`` 走 ``vector_quantize_scan``:距离为 **int8 量化后的
48
+ L2(= L2 × 255,非物理距离)**,且每次调用都会重建量化,**不提供性能收益**。
49
+ - 距离类型**仅支持 L2**(sqlite-vector 未暴露距离度量配置入口),其余取值抛 ValueError。
50
+ - ``filter_sql`` 为「**先过滤、再取 top_k**」语义(与 PgKit 一致)。
51
+ - ``dims`` 通过建表时的 ``CHECK (length(column) = dims * 4)`` 成为数据库层约束
52
+ (仅对**新建表**生效;既有表由方法内校验兜住)。
53
+ """
54
+
55
+ from sqlalchemy import text
56
+ from sqlalchemy.engine import Connection
57
+
58
+ from yimo.kit.config.log_config import get_default_logger
59
+ from yimo.kit.db.base_db_kit import (
60
+ DEFAULT_DISTANCE_TYPE,
61
+ BaseDbKit,
62
+ normalize_extra_cols,
63
+ )
64
+ from yimo.kit.db.engine import SQLITE, get_engine
65
+ from yimo.kit.db.exceptions import DBError
66
+ from yimo.kit.db.session import session_scope
67
+
68
+ logger = get_default_logger(__name__)
69
+
70
+ # 本后端支持的距离类型:sqlite-vector 未暴露距离度量配置入口,
71
+ # 精确路径(vector_full_scan)与量化路径(vector_quantize_scan)实际都只有 L2
72
+ SUPPORTED_DISTANCE_TYPES: tuple[str, ...] = ("L2",)
73
+
74
+ # float32 = 4 字节/维:BLOB 长度与维度的换算基准
75
+ BYTES_PER_DIM = 4
76
+
77
+ # sqlite-vector 的向量表示:**小端** float32(显式指定,不依赖本机字节序)
78
+ _VECTOR_DTYPE = "<f4"
79
+
80
+
81
+ class SQLiteKit(BaseDbKit):
82
+ """SQLite 数据库工具类
83
+
84
+ 基于 yimo.kit.db 统一数据库层,封装为业务可直调的服务方法。
85
+ 所有 ORM 方法内部使用 session_scope 管理事务(自动提交/回滚),
86
+ 业务代码无需手动管理 session。
87
+
88
+ 对于多操作事务场景,请使用 transaction() 上下文管理器。
89
+ """
90
+
91
+ DB_TYPE = SQLITE
92
+
93
+ # 向量能力声明(供调用方 feature-detect,详见 docs/agents/modules/kit-db.md)
94
+ VECTOR_CAPABILITIES: dict[str, object] = {
95
+ "store": True, # create_vector_table / insert_vectors 可用
96
+ "search": True, # search_vectors 可用
97
+ "exact": True, # 支持 exact=True(精确检索)
98
+ "distances": SUPPORTED_DISTANCE_TYPES, # 支持的距离类型
99
+ "distance_kind": "true", # exact=True 时的 distance 口径
100
+ "fast_distance_kind": "quantized_l2_x255", # exact=False 时的 distance 口径
101
+ "dimension_kind": None, # 无维度元数据,vector_column_dimension 恒返回 None
102
+ }
103
+
104
+ @classmethod
105
+ def get_table_info(cls, table_name: str) -> list[dict[str, object]]:
106
+ """获取表的列信息
107
+
108
+ Args:
109
+ table_name: 表名
110
+
111
+ Returns:
112
+ 列信息字典列表(column_name, data_type, is_nullable, column_default)
113
+ """
114
+ sql = """
115
+ SELECT
116
+ name as column_name,
117
+ type as data_type,
118
+ CASE WHEN "notnull" = 0 THEN 'YES' ELSE 'NO' END as is_nullable,
119
+ dflt_value as column_default
120
+ FROM pragma_table_info(:table_name)
121
+ ORDER BY cid
122
+ """
123
+ return cls.query(sql, {"table_name": table_name})
124
+
125
+ # ==================== 向量操作 ====================
126
+
127
+ @classmethod
128
+ def _vector_param(cls, vector: list[float]) -> object:
129
+ """向量 → BLOB(小端 float32);覆写基类的文本字面量实现"""
130
+ return cls.encode_vector(vector)
131
+
132
+ @classmethod
133
+ def encode_vector(cls, vector: list[float]) -> bytes:
134
+ """把向量编码为 sqlite-vector 使用的 float32 **小端** BLOB(4 字节/维)
135
+
136
+ Args:
137
+ vector: 一维向量(float 序列,也接受一维 numpy 数组)
138
+
139
+ Returns:
140
+ ``len(vector) * 4`` 字节的 BLOB
141
+
142
+ Raises:
143
+ ValueError: 向量为空,或输入不是一维(二维数组会被静默编成多个向量)
144
+
145
+ Note:
146
+ 本方法是**后端专属原语**(文本后端对应 `to_vector_literal`,两者不可互换):
147
+ 用于调用方在**自有事务/连接**内拼写 INSERT 时编码,例如::
148
+
149
+ with SQLiteKit.raw_connection() as conn:
150
+ conn.execute(
151
+ "INSERT INTO item_vectors (id, embedding) VALUES (?, ?)",
152
+ (item_id, SQLiteKit.encode_vector(vec)),
153
+ )
154
+ conn.commit()
155
+ """
156
+ # numpy 仅向量方法需要(vec extra),延迟导入保持基础安装可用
157
+ import numpy as np
158
+
159
+ array = np.asarray(vector, dtype=_VECTOR_DTYPE)
160
+ if array.size == 0:
161
+ raise ValueError("vector 不能为空")
162
+ if array.ndim != 1:
163
+ raise ValueError(f"encode_vector 只接受一维向量,当前 ndim={array.ndim}")
164
+ return array.tobytes()
165
+
166
+ @classmethod
167
+ def decode_vector(cls, blob: bytes) -> list[float]:
168
+ """把 float32 小端 BLOB 解码为 float 列表(便于自检与断言)
169
+
170
+ Args:
171
+ blob: `encode_vector` 产出的字节串(4 的整数倍)
172
+
173
+ Returns:
174
+ float 列表
175
+ """
176
+ import numpy as np
177
+
178
+ return [float(x) for x in np.frombuffer(blob, dtype=_VECTOR_DTYPE)]
179
+
180
+ @classmethod
181
+ def vector_column_dimension(
182
+ cls, table_name: str, column: str = "embedding"
183
+ ) -> int | None:
184
+ """查询向量列的声明维度,**本后端恒返回 None**
185
+
186
+ Args:
187
+ table_name: 表名(未使用,仅为保持三库签名一致)
188
+ column: 向量列名(未使用,同上)
189
+
190
+ Returns:
191
+ 恒为 ``None``
192
+
193
+ Note:
194
+ SQLite 没有向量类型,也没有维度元数据:`create_vector_table` 把维度落实为
195
+ ``CHECK (length(column) = dims * 4)``,写入时由数据库强制,但**查不出来**。
196
+
197
+ 不解析 ``sqlite_master.sql`` 里的 CHECK 文本:列名转义、既有表无该约束、
198
+ 文本格式都可能变形,反解不可靠。
199
+
200
+ 守卫建议:维度约束已由 ``CHECK`` 承担(写入维度不符即报错),无需前置探测;
201
+ 若确需提前校验,可读一行数据的 ``length(column) / 4`` 推断(空表无法推断)。
202
+
203
+ ``VECTOR_CAPABILITIES["dimension_kind"] is None`` 表明本后端不支持该查询。
204
+ """
205
+ return None
206
+
207
+ @classmethod
208
+ def create_vector_table(
209
+ cls,
210
+ table_name: str,
211
+ dims: int,
212
+ id_col: str = "id",
213
+ column: str = "embedding",
214
+ extra_cols: dict[str, str] | list[dict[str, str]] | None = None,
215
+ ) -> None:
216
+ """创建包含向量列的表
217
+
218
+ Args:
219
+ table_name: 表名
220
+ dims: 向量维度(**必填**;本后端通过 ``CHECK`` 约束落实为数据库层约束)
221
+ id_col: 主键列名(``INTEGER PRIMARY KEY``,即 SQLite 的 64 位整数主键,
222
+ 等价于另两库的 ``BIGINT``;id 由调用方提供或由 `insert_vectors`
223
+ 兜底生成雪花 ID)。须为 rowid 别名,见 `search_vectors` 的 Note
224
+ column: 向量列名(默认 ``embedding``)
225
+ extra_cols: 额外列定义,**两种形态**(产出 DDL 逐字一致):
226
+ ``{列名: 方言类型串}``(**推荐**,与 `create_raw_table` 同形,键序即列序)
227
+ 或既有 ``[{"name": str, "type": str}]``;
228
+ 如 ``{"label": "TEXT"}``
229
+
230
+ 表结构示例::
231
+
232
+ CREATE TABLE images (
233
+ id INTEGER PRIMARY KEY,
234
+ embedding BLOB CHECK (length(embedding) = 1536), -- dims=384 × 4 字节
235
+ label TEXT
236
+ );
237
+
238
+ Raises:
239
+ ValueError: dims < 1
240
+
241
+ Note:
242
+ `dims` 在这里是**真约束**(``BLOB`` 长度 = dims × 4),写入维度不符会被数据库拒绝;
243
+ 但 ``CHECK`` 只对**新建表**生效——既有(0.2.1 及更早创建的)表没有该约束,
244
+ 由 `insert_vectors` / `search_vectors` 的显式校验兜住。
245
+ """
246
+ if dims < 1:
247
+ raise ValueError(f"dims 必须为正整数,当前为 {dims}")
248
+
249
+ extra_defs = "".join(
250
+ f", {name} {col_type}"
251
+ for name, col_type in normalize_extra_cols(extra_cols)
252
+ )
253
+
254
+ sql = f"""
255
+ CREATE TABLE IF NOT EXISTS {table_name} (
256
+ {id_col} INTEGER PRIMARY KEY,
257
+ {column} BLOB CHECK (length({column}) = {dims * BYTES_PER_DIM}){extra_defs}
258
+ )
259
+ """
260
+ with session_scope(cls.DB_TYPE, autocommit=False) as session:
261
+ session.execute(text(sql))
262
+ logger.info(f"✅ 创建向量表 {table_name}(维度={dims})")
263
+
264
+ @classmethod
265
+ def insert_vectors(
266
+ cls,
267
+ table_name: str,
268
+ vectors: list[list[float]],
269
+ ids: list[int] | None = None,
270
+ extra_data: list[dict[str, object]] | None = None,
271
+ id_col: str = "id",
272
+ column: str = "embedding",
273
+ ) -> int:
274
+ """批量插入向量数据
275
+
276
+ Args:
277
+ table_name: 表名
278
+ vectors: 向量列表,每个向量为 float 列表(也接受二维 numpy 数组)
279
+ ids: 可选的 ID 列表(长度需与 vectors 一致);None 时由 Kit 生成雪花 ID
280
+ (应用侧生成,**非数据库自增**)
281
+ extra_data: 额外列数据列表(长度需与 vectors 一致)
282
+ id_col: 主键列名(默认 ``id``,供自建 DDL 的表使用)
283
+ column: 向量列名(默认 ``embedding``,供自建 DDL 的表使用)
284
+
285
+ Returns:
286
+ 插入的行数
287
+
288
+ Raises:
289
+ ValueError: 入参自洽性校验失败——ids / extra_data 长度与 vectors 不一致、
290
+ 批内向量长度不一致、``extra_data`` 键为保留绑定名(``id`` / ``vec``)、
291
+ 键与 ``id_col`` / ``column`` 重复、键不是合法标识符、``id_col == column``
292
+
293
+ Note:
294
+ - `ids=None` 时**不使用 SQLite rowid 自增**,改由 Kit 生成雪花 ID
295
+ (64 位,18~19 位数字),与 PgKit / MySqlKit 语义一致。
296
+ - 单次事务内批量写入(``cls.transaction()``);语句由 `build_insert_vectors`
297
+ 构造(**单一事实源**)。需要把向量行写入**调用方自己的事务**时,请改用
298
+ `build_insert_vectors` + `transaction()`,或 `raw_connection()`(见文档 cookbook)。
299
+ """
300
+ with cls.transaction() as session:
301
+ for sql, params in cls.build_insert_vectors(
302
+ table_name,
303
+ vectors,
304
+ ids=ids,
305
+ extra_data=extra_data,
306
+ id_col=id_col,
307
+ column=column,
308
+ ):
309
+ session.execute(text(sql), params)
310
+ logger.info(f"✅ 插入 {len(vectors)} 条向量到 {table_name}")
311
+ return len(vectors)
312
+
313
+ @classmethod
314
+ def _vector_dims(cls, table_name: str, column: str, conn: Connection) -> int | None:
315
+ """读取表内已有的实际向量维度(无数据时返回 None)"""
316
+ row = conn.execute(
317
+ text(
318
+ f"SELECT length({column}) AS n FROM {table_name} "
319
+ f"WHERE {column} IS NOT NULL LIMIT 1"
320
+ )
321
+ ).fetchone()
322
+ if row is None or row[0] is None:
323
+ return None
324
+ return int(row[0]) // BYTES_PER_DIM
325
+
326
+ @classmethod
327
+ def search_vectors(
328
+ cls,
329
+ table_name: str,
330
+ query_vector: list[float],
331
+ top_k: int = 10,
332
+ distance_type: str = DEFAULT_DISTANCE_TYPE,
333
+ filter_sql: str | None = None,
334
+ exact: bool = True,
335
+ id_col: str = "id",
336
+ column: str = "embedding",
337
+ ) -> list[dict[str, object]]:
338
+ """搜索最近邻向量
339
+
340
+ Args:
341
+ table_name: 表名
342
+ query_vector: 查询向量(float 列表)
343
+ top_k: 返回结果数上限(**先过滤、再取 top_k**)
344
+ distance_type: 距离类型。本后端**仅支持 L2**(与另两库默认值一致),
345
+ 其余取值抛 ValueError
346
+ filter_sql: 可选的过滤条件 WHERE 子句(不含 WHERE 关键字),
347
+ 如 "label = 'cat'"
348
+ exact: 是否禁止近似加速(默认 True)。
349
+ - ``True``:`vector_full_scan`,距离为**真值 L2**,不做量化
350
+ - ``False``:`vector_quantize_scan`,距离为 **int8 量化 L2(×255)**,
351
+ 且每次调用都会重建量化 —— **不提供性能收益**,仅用于复现 0.2.1 口径
352
+ id_col: 主键列名(默认 ``id``)
353
+ column: 向量列名(默认 ``embedding``)
354
+
355
+ Returns:
356
+ 按距离升序排列的结果列表,每项为 {"id": int, "distance": float}
357
+
358
+ Raises:
359
+ ValueError: top_k < 1、query_vector 为空、或 distance_type 取值不支持
360
+ DBError: 查询向量维度与表内实际维度不一致
361
+
362
+ Note:
363
+ - 过滤语义为「**先过滤、再取 top_k**」:先按过滤条件计数,再据此取候选,
364
+ 因此返回的是满足条件的最近 ``top_k`` 条(与 PgKit 一致)。
365
+ - ⚠ 本后端的扫描函数按 **rowid** 定位行,故 ``id_col`` 必须是 rowid 别名
366
+ (``INTEGER PRIMARY KEY``,即 `create_vector_table` 的默认做法);
367
+ 自建 DDL 若用了非 rowid 别名的主键列,检索阶段无法关联。
368
+ """
369
+ if top_k < 1:
370
+ raise ValueError(f"top_k 必须为正整数,当前为 {top_k}")
371
+ # 用 len() 而非真值判断:入参可为 list 或 numpy 数组
372
+ if len(query_vector) == 0:
373
+ raise ValueError("query_vector 不能为空")
374
+ if distance_type not in SUPPORTED_DISTANCE_TYPES:
375
+ raise ValueError(
376
+ f"不支持的向量距离类型: {distance_type}"
377
+ f"(本后端可选: {' / '.join(SUPPORTED_DISTANCE_TYPES)})"
378
+ )
379
+
380
+ dims = len(query_vector)
381
+ engine = get_engine(cls.DB_TYPE)
382
+
383
+ query_bytes = cls.encode_vector(query_vector)
384
+
385
+ with engine.connect() as conn:
386
+ # 维度前置校验:把「Invalid vector blob found at rowid N」换成语义明确的错误
387
+ stored_dims = cls._vector_dims(table_name, column, conn)
388
+ if stored_dims is not None and stored_dims != dims:
389
+ raise DBError(
390
+ f"查询向量维度与表内数据不一致:{table_name}.{column} 存的是 "
391
+ f"{stored_dims} 维,查询向量为 {dims} 维"
392
+ )
393
+
394
+ # 初始化向量索引配置(每调用一次,约 0.5ms,不留进程级状态)
395
+ conn.execute(
396
+ text(
397
+ f"SELECT vector_init('{table_name}', '{column}', "
398
+ f"'type=FLOAT32,dimension={dims}')"
399
+ )
400
+ )
401
+
402
+ if exact:
403
+ scan_func = "vector_full_scan"
404
+ # full_scan 返回的标识列名为 id
405
+ scan_id_expr = "s.id"
406
+ else:
407
+ # 量化路径:距离为量化值,且每次调用都重建(无性能收益)
408
+ conn.execute(text(f"SELECT vector_quantize('{table_name}', '{column}')"))
409
+ scan_func = "vector_quantize_scan"
410
+ # quantize_scan 返回的标识列名为 rowid
411
+ scan_id_expr = "s.rowid"
412
+
413
+ where_clause = f"WHERE {filter_sql}" if filter_sql else ""
414
+
415
+ # 「先过滤、再取 top_k」:有过滤条件时按**全表行数**取候选。
416
+ # ⚠ 不能按 count(filter) 取候选:过滤后的最近行在全局排序中可能位于任意靠后的
417
+ # 位置(实测反例:5 行表中过滤命中 2 行,但二者全局排名第 3/4,取 2 个候选会漏空)。
418
+ # 无过滤条件时候选数即 top_k(不产生额外查询)。
419
+ candidate_k = top_k
420
+ if filter_sql:
421
+ count_row = conn.execute(
422
+ text(f"SELECT count(*) FROM {table_name}")
423
+ ).fetchone()
424
+ candidate_k = int(count_row[0]) if count_row else 0
425
+ if candidate_k == 0:
426
+ logger.info(f"🔍 向量搜索 {table_name} → 表内无数据,返回 0 条")
427
+ return []
428
+
429
+ sql = f"""
430
+ SELECT e.{id_col} AS id, s.distance
431
+ FROM {table_name} AS e
432
+ JOIN {scan_func}('{table_name}', '{column}', :query, {candidate_k}) AS s
433
+ ON e.{id_col} = {scan_id_expr}
434
+ {where_clause}
435
+ ORDER BY s.distance ASC
436
+ LIMIT {top_k}
437
+ """
438
+ result = conn.execute(text(sql), {"query": query_bytes})
439
+ rows = result.fetchall()
440
+ columns = result.keys()
441
+ data = [dict(zip(columns, row)) for row in rows]
442
+ logger.info(
443
+ f"🔍 向量搜索 {table_name}(exact={exact})→ 返回 {len(data)} 条"
444
+ )
445
+ return data
446
+
447
+ @classmethod
448
+ def vector_version(cls) -> str:
449
+ """获取 sqlite-vector 扩展版本
450
+
451
+ Returns:
452
+ 版本号字符串;加载/查询失败时返回 "unavailable",
453
+ 扩展未返回版本号时返回 "unknown"
454
+ """
455
+ try:
456
+ engine = get_engine(cls.DB_TYPE)
457
+ with engine.connect() as conn:
458
+ row = conn.execute(text("SELECT vector_version()")).fetchone()
459
+ return str(row[0]) if row else "unknown"
460
+ except Exception as e:
461
+ logger.warning(f"⚠️ 获取 vector_version 失败: {e}")
462
+ return "unavailable"
@@ -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-23
21
+ """事务管理模块
22
+
23
+ 提供 @transactional 装饰器:捕获 SQLAlchemyError(含 DBError 及其所有子类),
24
+ 确保重试逻辑对数据库异常有效。
25
+ """
26
+
27
+ import functools
28
+ import inspect
29
+ import time
30
+ from collections.abc import Callable
31
+ from typing import TypeVar
32
+
33
+ from sqlalchemy.exc import SQLAlchemyError
34
+
35
+ from yimo.kit.config.log_config import get_default_logger
36
+ from yimo.kit.db.exceptions import DBError
37
+ from yimo.kit.db.session import session_scope
38
+
39
+ logger = get_default_logger(__name__)
40
+
41
+ F = TypeVar("F", bound=Callable[..., object])
42
+
43
+
44
+ def transactional(
45
+ db_type: str | None = None,
46
+ *,
47
+ retry_count: int = 0,
48
+ retry_delay: float = 0.5,
49
+ ) -> Callable[[F], F]:
50
+ """事务装饰器:自动注入 session,统一捕获 SQLAlchemyError 并重试
51
+
52
+ 被装饰的函数必须接受 ``session`` 关键字参数。
53
+ 捕获 SQLAlchemyError(含 DBError、IntegrityError、OperationalError 等所有子类)。
54
+
55
+ Args:
56
+ db_type: 数据库类型,None 时使用配置默认值
57
+ retry_count: 失败后的额外重试次数(0 表示不重试)
58
+ retry_delay: 初始重试延迟(秒),每次重试翻倍(指数退避)
59
+
60
+ 用法::
61
+
62
+ @transactional()
63
+ def transfer(session: Session, from_id: int, to_id: int, amount: float):
64
+ # 多个 CRUD 操作在同一事务中
65
+ sender = user_crud.get_or_raise(session, from_id)
66
+ receiver = user_crud.get_or_raise(session, to_id)
67
+ sender.balance -= amount
68
+ receiver.balance += amount
69
+ # 退出时自动提交
70
+ """
71
+
72
+ def decorator(func: F) -> F:
73
+ sig = inspect.signature(func)
74
+
75
+ @functools.wraps(func)
76
+ def wrapper(*args: object, **kwargs: object) -> object:
77
+ # 检查函数是否接受 session 参数
78
+ if "session" not in sig.parameters:
79
+ raise TypeError(
80
+ f"被 @transactional 装饰的函数 '{func.__name__}' "
81
+ "必须接受 'session' 关键字参数"
82
+ )
83
+
84
+ last_exception: Exception | None = None
85
+
86
+ for attempt in range(retry_count + 1):
87
+ try:
88
+ with session_scope(db_type, autocommit=True) as session:
89
+ kwargs["session"] = session
90
+ return func(*args, **kwargs)
91
+ except SQLAlchemyError as e:
92
+ last_exception = e
93
+ if attempt < retry_count:
94
+ delay = retry_delay * (2**attempt)
95
+ logger.warning(
96
+ f"⚠️ 事务失败,{delay:.1f}s 后重试 "
97
+ f"({attempt + 1}/{retry_count}): {e}"
98
+ )
99
+ time.sleep(delay)
100
+ else:
101
+ break
102
+
103
+ raise DBError(
104
+ f"事务执行失败(重试 {retry_count} 次后仍失败): {last_exception}"
105
+ )
106
+
107
+ return wrapper # type: ignore
108
+
109
+ return decorator
@@ -0,0 +1,34 @@
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-10-16
21
+ """文档格式转换子包——文档解析 / 渲染 / 模板填充工具集
22
+
23
+ 成员(均按需 import,各自绑定独立 extras,缺依赖时模块顶层报错并提示安装命令):
24
+ - anydoc_kit: AnyDocKit 文档转 Markdown(firecrawl-anydoc,extra: anydoc)
25
+ - md2doc_kit: Md2DocKit Markdown 转 Word/PDF/HTML(pimd,extra: md2doc)
26
+ - docx_kit: DocxKit Word 模板动态填充(docxtpl,extra: docx)
27
+ - mineru_kit: MinerUKit MinerU 文档解析 API(requests,extra: mineru)
28
+ - marker_kit: MarkerKit PDF + 图片本地解析(marker-pdf,extra: marker)
29
+ ⚠ 0.7.0 起**暂停发布**:不进 wheel、不可安装;需要请用 yimo-kit==0.6.10
30
+ - rc_docparser_kit: RcDocParserKit 离线 docx 解析(rc-docparser,extra: docx-parse)
31
+
32
+ 本 __init__ 不导入任何成员:五个模块均携带重型可选依赖,保持
33
+ `import yimo.kit.docs` 在基础安装下零成本可用(对齐 yimo.kit.crawl 先例)。
34
+ """