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.
- yimo/__init__.py +26 -0
- yimo/kit/__init__.py +98 -0
- yimo/kit/ai/__init__.py +110 -0
- yimo/kit/ai/_internal/__init__.py +27 -0
- yimo/kit/ai/_internal/failover.py +535 -0
- yimo/kit/ai/_internal/pool.py +526 -0
- yimo/kit/ai/_internal/rerank_transport.py +137 -0
- yimo/kit/ai/_internal/retry_after.py +51 -0
- yimo/kit/ai/_internal/sdk_client.py +463 -0
- yimo/kit/ai/_internal/service_base.py +115 -0
- yimo/kit/ai/_internal/types.py +28 -0
- yimo/kit/ai/agent/__init__.py +127 -0
- yimo/kit/ai/agent/approval.py +66 -0
- yimo/kit/ai/agent/errors.py +128 -0
- yimo/kit/ai/agent/loop.py +643 -0
- yimo/kit/ai/agent/mcp.py +278 -0
- yimo/kit/ai/agent/registry.py +203 -0
- yimo/kit/ai/agent/session.py +150 -0
- yimo/kit/ai/agent/skill.py +370 -0
- yimo/kit/ai/agent/types.py +161 -0
- yimo/kit/ai/chat_service.py +724 -0
- yimo/kit/ai/decision/__init__.py +57 -0
- yimo/kit/ai/decision/decima.py +853 -0
- yimo/kit/ai/decision/laya.py +552 -0
- yimo/kit/ai/embedding_service.py +198 -0
- yimo/kit/ai/exceptions.py +109 -0
- yimo/kit/ai/image_service.py +84 -0
- yimo/kit/ai/messages.py +105 -0
- yimo/kit/ai/model_builder.py +121 -0
- yimo/kit/ai/model_client.py +62 -0
- yimo/kit/ai/profiles.py +577 -0
- yimo/kit/ai/rerank_service.py +136 -0
- yimo/kit/ai/runner.py +1127 -0
- yimo/kit/common_kit.py +221 -0
- yimo/kit/config/__init__.py +44 -0
- yimo/kit/config/kit_config.py +210 -0
- yimo/kit/config/log_config.py +171 -0
- yimo/kit/crawl/__init__.py +71 -0
- yimo/kit/crawl/article_io.py +325 -0
- yimo/kit/crawl/article_models.py +172 -0
- yimo/kit/crawl/deepseek_kit.py +673 -0
- yimo/kit/crawl/web_article_kit.py +638 -0
- yimo/kit/crawl/wx_article_kit.py +692 -0
- yimo/kit/db/__init__.py +101 -0
- yimo/kit/db/audit.py +625 -0
- yimo/kit/db/base_db_kit.py +1265 -0
- yimo/kit/db/crud.py +423 -0
- yimo/kit/db/engine.py +235 -0
- yimo/kit/db/exceptions.py +45 -0
- yimo/kit/db/models/__init__.py +33 -0
- yimo/kit/db/models/base.py +56 -0
- yimo/kit/db/mysql_kit.py +348 -0
- yimo/kit/db/pg_kit.py +442 -0
- yimo/kit/db/query.py +338 -0
- yimo/kit/db/session.py +85 -0
- yimo/kit/db/sqlite_kit.py +462 -0
- yimo/kit/db/transaction.py +109 -0
- yimo/kit/docs/__init__.py +34 -0
- yimo/kit/docs/anydoc_kit.py +490 -0
- yimo/kit/docs/docx_kit.py +895 -0
- yimo/kit/docs/md2doc_kit.py +1801 -0
- yimo/kit/docs/mineru_kit.py +1497 -0
- yimo/kit/docs/rc_docparser_kit.py +654 -0
- yimo/kit/file_kit.py +518 -0
- yimo/kit/license_kit.py +533 -0
- yimo/kit/redis_kit.py +392 -0
- yimo_kit-0.1.0.dist-info/METADATA +1673 -0
- yimo_kit-0.1.0.dist-info/RECORD +70 -0
- yimo_kit-0.1.0.dist-info/WHEEL +4 -0
- yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
yimo/kit/db/pg_kit.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
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
|
+
"""PostgreSQL 数据库工具类
|
|
24
|
+
|
|
25
|
+
基于 yimo.kit.db 统一数据库层封装,提供开箱即用的服务方法。
|
|
26
|
+
业务代码无需管理 session/transaction,直接调用即可。
|
|
27
|
+
|
|
28
|
+
本类继承 BaseDbKit,复用全部共享实现(连接管理 / ORM / 原生 SQL / 原生表操作 /
|
|
29
|
+
事务 / 表操作),并覆写 PostgreSQL 专属的 get_table_info,另提供基于 pgvector 的
|
|
30
|
+
5 个向量方法(签名与 SQLiteKit / MySqlKit 完全一致)。
|
|
31
|
+
|
|
32
|
+
使用方式::
|
|
33
|
+
|
|
34
|
+
# 单条操作(自动管理事务)
|
|
35
|
+
user = PgKit.create(UserModel, {"name": "张三", "email": "zs@example.com"})
|
|
36
|
+
users = PgKit.list(UserModel, skip=0, limit=10)
|
|
37
|
+
PgKit.update(UserModel, user.id, {"name": "李四"})
|
|
38
|
+
|
|
39
|
+
# 原生 SQL 操作
|
|
40
|
+
rows = PgKit.query("SELECT * FROM users WHERE active = :active", {"active": True})
|
|
41
|
+
|
|
42
|
+
# 多操作事务
|
|
43
|
+
with PgKit.transaction() as session:
|
|
44
|
+
crud = CRUDBase(UserModel)
|
|
45
|
+
crud.create(session, {"name": "test"})
|
|
46
|
+
# 退出 with 时统一提交
|
|
47
|
+
|
|
48
|
+
# 向量操作(dims 必填;create_vector_table 自动尝试创建 pgvector 扩展)
|
|
49
|
+
PgKit.create_vector_table("images", 384)
|
|
50
|
+
PgKit.insert_vectors("images", [[0.1, 0.2, ...], ...])
|
|
51
|
+
rows = PgKit.search_vectors("images", [0.1, 0.2, ...], top_k=5)
|
|
52
|
+
|
|
53
|
+
向量能力要点(跨库差异见 docs/agents/modules/kit-db.md「向量能力差异」):
|
|
54
|
+
|
|
55
|
+
- 距离类型:``COSINE``(``<=>``) / ``L2``(``<->``) / ``L1``(``<+>``,pgvector 0.7+) /
|
|
56
|
+
``DOT``(``<#>``,**负内积**) / ``SQUARED_L2``(``power(<->, 2)``);默认 ``L2``(三库一致)。
|
|
57
|
+
- ``exact=True``(默认)**禁止近似加速**:同一事务内 ``SET LOCAL enable_indexscan = off``,
|
|
58
|
+
即使自建了 hnsw/ivfflat 索引也走精确计算(代价:该查询不使用任何索引,含过滤列索引)。
|
|
59
|
+
需要速度时显式传 ``exact=False``(有索引则利用索引,结果可能为近似召回)。
|
|
60
|
+
- ``filter_sql`` 为「**先过滤、再取 top_k**」语义(与 SQLiteKit 一致)。
|
|
61
|
+
- 本模块**不创建向量索引**;需要 ANN 请自行 ``execute()`` 建索引并传 ``exact=False``。
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
from sqlalchemy import text
|
|
65
|
+
|
|
66
|
+
from yimo.kit.config.log_config import get_default_logger
|
|
67
|
+
from yimo.kit.db.base_db_kit import (
|
|
68
|
+
DEFAULT_DISTANCE_TYPE,
|
|
69
|
+
BaseDbKit,
|
|
70
|
+
normalize_extra_cols,
|
|
71
|
+
to_vector_literal,
|
|
72
|
+
)
|
|
73
|
+
from yimo.kit.db.engine import POSTGRESQL, get_engine
|
|
74
|
+
from yimo.kit.db.exceptions import DBError
|
|
75
|
+
|
|
76
|
+
logger = get_default_logger(__name__)
|
|
77
|
+
|
|
78
|
+
# 距离类型 → pgvector 算子(ASC 排序即"最相似在前")
|
|
79
|
+
# ⚠ DOT 用 pgvector 的 "<#>",返回**负内积**,故升序等价于按内积降序
|
|
80
|
+
VECTOR_OPERATORS: dict[str, str] = {
|
|
81
|
+
"COSINE": "<=>",
|
|
82
|
+
"L2": "<->",
|
|
83
|
+
"L1": "<+>", # pgvector 0.7+
|
|
84
|
+
"DOT": "<#>",
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
# 支持的距离类型(SQUARED_L2 无专用算子,用 power(<->, 2) 表达式实现)
|
|
88
|
+
SUPPORTED_DISTANCE_TYPES: tuple[str, ...] = ("COSINE", "L2", "L1", "DOT", "SQUARED_L2")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class PgKit(BaseDbKit):
|
|
92
|
+
"""PostgreSQL 数据库工具类
|
|
93
|
+
|
|
94
|
+
基于 yimo.kit.db 统一数据库层,封装为业务可直调的服务方法。
|
|
95
|
+
所有 ORM 方法内部使用 session_scope 管理事务(自动提交/回滚),
|
|
96
|
+
业务代码无需手动管理 session。
|
|
97
|
+
|
|
98
|
+
对于多操作事务场景,请使用 transaction() 上下文管理器。
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
DB_TYPE = POSTGRESQL
|
|
102
|
+
|
|
103
|
+
# 向量能力声明(供调用方 feature-detect,详见 docs/agents/modules/kit-db.md)
|
|
104
|
+
VECTOR_CAPABILITIES: dict[str, object] = {
|
|
105
|
+
"store": True,
|
|
106
|
+
"search": True,
|
|
107
|
+
"exact": True,
|
|
108
|
+
"distances": SUPPORTED_DISTANCE_TYPES,
|
|
109
|
+
"distance_kind": "true", # exact=True 与 False 下 distance 都是真值
|
|
110
|
+
"fast_distance_kind": "true", # 近似仅影响候选集(索引),数值仍是真值
|
|
111
|
+
"dimension_kind": "exact", # vector_column_dimension 返回「必须相等」的精确维度
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def get_table_info(cls, table_name: str) -> list[dict[str, object]]:
|
|
116
|
+
"""获取表的列信息(按列序返回)
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
table_name: 表名(**非限定名**,如 ``items``)
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
列信息字典列表,公共键 4 个:``column_name`` / ``data_type`` /
|
|
123
|
+
``is_nullable``(``"YES"``/``"NO"``)/ ``column_default``;
|
|
124
|
+
``data_type`` 为**后端原生类型名**(不做跨库归一化)
|
|
125
|
+
|
|
126
|
+
Note:
|
|
127
|
+
- 表按 **PostgreSQL 自身的解析规则**定位(``to_regclass``,即 ``search_path``
|
|
128
|
+
顺序),与 ``SELECT … FROM 表名`` 命中的那张表一致——因此不会因多 schema
|
|
129
|
+
同名表而返回混行;表不存在时返回空列表。
|
|
130
|
+
- **只接受非限定表名**:跨 schema 请用 `query()` 显式指定 ``table_schema``。
|
|
131
|
+
- 与 `list_tables()`(枚举**当前默认 schema**)语义不同,二者非互斥。
|
|
132
|
+
"""
|
|
133
|
+
sql = """
|
|
134
|
+
SELECT
|
|
135
|
+
column_name,
|
|
136
|
+
data_type,
|
|
137
|
+
is_nullable,
|
|
138
|
+
column_default
|
|
139
|
+
FROM information_schema.columns
|
|
140
|
+
WHERE table_name = :table_name
|
|
141
|
+
AND table_schema = (
|
|
142
|
+
SELECT n.nspname
|
|
143
|
+
FROM pg_class cl
|
|
144
|
+
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
|
145
|
+
WHERE cl.oid = to_regclass(:table_name)
|
|
146
|
+
)
|
|
147
|
+
ORDER BY ordinal_position
|
|
148
|
+
"""
|
|
149
|
+
return cls.query(sql, {"table_name": table_name})
|
|
150
|
+
|
|
151
|
+
# ==================== 向量操作(pgvector) ====================
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def vector_column_dimension(
|
|
155
|
+
cls, table_name: str, column: str = "embedding"
|
|
156
|
+
) -> int | None:
|
|
157
|
+
"""查询向量列的声明维度(pgvector 的 ``vector`` 类型)
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
table_name: 表名(**非限定名**,按 ``search_path`` 解析,与 `get_table_info` 同源)
|
|
161
|
+
column: 向量列名(默认 ``embedding``)
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
列声明的维度;下列情况返回 ``None``:列不存在、不是 ``vector`` 类型、
|
|
165
|
+
建为**无维度**的 ``vector``
|
|
166
|
+
|
|
167
|
+
Note:
|
|
168
|
+
- pgvector 把维度存在 ``pg_attribute.atttypmod``,值**直接等于维度**
|
|
169
|
+
(实测 pgvector 0.8.7:``vector(1024)`` → 1024,无 varchar 那样的 +4 偏移)。
|
|
170
|
+
- 必须联 ``pg_type`` 校验类型名:``varchar(20)`` / ``numeric`` 等同样有
|
|
171
|
+
``atttypmod``,不判类型会误报出维度。
|
|
172
|
+
- 本后端维度是**硬约束**(写入维度必须相等),故
|
|
173
|
+
``VECTOR_CAPABILITIES["dimension_kind"] == "exact"``。
|
|
174
|
+
- 用 ``to_regclass()`` 定位(表不存在返回 NULL 而非报错);
|
|
175
|
+
**不要**改用 ``CAST(:表名 AS regclass)``。
|
|
176
|
+
"""
|
|
177
|
+
rows = cls.query(
|
|
178
|
+
"SELECT a.atttypmod AS typmod "
|
|
179
|
+
"FROM pg_attribute a "
|
|
180
|
+
"JOIN pg_type t ON t.oid = a.atttypid "
|
|
181
|
+
"WHERE a.attrelid = to_regclass(:table_name) "
|
|
182
|
+
"AND a.attname = :column "
|
|
183
|
+
"AND a.attnum > 0 "
|
|
184
|
+
"AND NOT a.attisdropped "
|
|
185
|
+
"AND t.typname = 'vector'",
|
|
186
|
+
{"table_name": table_name, "column": column},
|
|
187
|
+
)
|
|
188
|
+
if not rows:
|
|
189
|
+
return None
|
|
190
|
+
typmod = rows[0]["typmod"]
|
|
191
|
+
if not isinstance(typmod, int) or typmod <= 0:
|
|
192
|
+
return None
|
|
193
|
+
return typmod
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def _ensure_vector_extension(cls) -> None:
|
|
197
|
+
"""确保 pgvector 扩展可用(缺失则尝试创建)
|
|
198
|
+
|
|
199
|
+
Raises:
|
|
200
|
+
DBError: 未能确保扩展可用。三种可能:服务端未安装 pgvector、
|
|
201
|
+
当前账号无 CREATE EXTENSION 权限、数据库本身不可达;
|
|
202
|
+
具体原因见异常消息末尾的「原始错误」
|
|
203
|
+
"""
|
|
204
|
+
try:
|
|
205
|
+
cls.execute("CREATE EXTENSION IF NOT EXISTS vector")
|
|
206
|
+
except Exception as e:
|
|
207
|
+
raise DBError(
|
|
208
|
+
"未能确保 pgvector 扩展可用(可能原因:服务端未安装 pgvector / "
|
|
209
|
+
"当前账号无 CREATE EXTENSION 权限 / 数据库不可达);"
|
|
210
|
+
"若确为扩展缺失或无权限,请由 DBA 在目标库执行 "
|
|
211
|
+
"CREATE EXTENSION vector 后重试。"
|
|
212
|
+
f"原始错误: {e}"
|
|
213
|
+
) from e
|
|
214
|
+
|
|
215
|
+
@classmethod
|
|
216
|
+
def create_vector_table(
|
|
217
|
+
cls,
|
|
218
|
+
table_name: str,
|
|
219
|
+
dims: int,
|
|
220
|
+
id_col: str = "id",
|
|
221
|
+
column: str = "embedding",
|
|
222
|
+
extra_cols: dict[str, str] | list[dict[str, str]] | None = None,
|
|
223
|
+
) -> None:
|
|
224
|
+
"""创建包含向量列的表(pgvector)
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
table_name: 表名
|
|
228
|
+
dims: 向量维度(**必填**;PG 侧为硬约束,写入维度必须一致)
|
|
229
|
+
id_col: 主键列名(``BIGINT PRIMARY KEY``,**不自增**,id 由调用方提供
|
|
230
|
+
或由 `insert_vectors` 兜底生成雪花 ID)
|
|
231
|
+
column: 向量列名(默认 ``embedding``)
|
|
232
|
+
extra_cols: 额外列定义,**两种形态**(产出 DDL 逐字一致):
|
|
233
|
+
``{列名: 方言类型串}``(**推荐**,与 `create_raw_table` 同形,键序即列序)
|
|
234
|
+
或既有 ``[{"name": str, "type": str}]``;
|
|
235
|
+
type 按 PostgreSQL 方言书写,如 ``{"label": "TEXT"}``
|
|
236
|
+
|
|
237
|
+
内部自动执行 ``CREATE EXTENSION IF NOT EXISTS vector``(需相应权限)。
|
|
238
|
+
|
|
239
|
+
表结构示例::
|
|
240
|
+
|
|
241
|
+
CREATE TABLE images (
|
|
242
|
+
id BIGINT PRIMARY KEY, -- 雪花 ID(18~19 位,int64)
|
|
243
|
+
embedding vector(384),
|
|
244
|
+
label TEXT
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
ValueError: dims < 1
|
|
249
|
+
DBError: 扩展不可用(见 `_ensure_vector_extension`),或**表已存在且
|
|
250
|
+
向量列维度与入参不一致**(``CREATE TABLE IF NOT EXISTS`` 会静默保留旧结构)
|
|
251
|
+
|
|
252
|
+
Note:
|
|
253
|
+
主键为纯 ``BIGINT``(非 ``BIGSERIAL``):三库统一由应用侧生成 id,
|
|
254
|
+
避免 PostgreSQL 序列不随显式 id 推进、后续自增插入主键冲突的问题。
|
|
255
|
+
"""
|
|
256
|
+
if dims < 1:
|
|
257
|
+
raise ValueError(f"dims 必须为正整数,当前为 {dims}")
|
|
258
|
+
|
|
259
|
+
cls._ensure_vector_extension()
|
|
260
|
+
|
|
261
|
+
extra_defs = "".join(
|
|
262
|
+
f", {name} {col_type}"
|
|
263
|
+
for name, col_type in normalize_extra_cols(extra_cols)
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
sql = (
|
|
267
|
+
f"CREATE TABLE IF NOT EXISTS {table_name} ("
|
|
268
|
+
f"{id_col} BIGINT PRIMARY KEY, "
|
|
269
|
+
f"{column} vector({int(dims)}){extra_defs})"
|
|
270
|
+
)
|
|
271
|
+
cls.execute(sql)
|
|
272
|
+
|
|
273
|
+
# 表已存在时 IF NOT EXISTS 会静默保留旧维度,故回读实际列类型做校验
|
|
274
|
+
rows = cls.query(
|
|
275
|
+
"SELECT format_type(a.atttypid, a.atttypmod) AS col_type "
|
|
276
|
+
"FROM pg_attribute a "
|
|
277
|
+
"WHERE a.attrelid = CAST(:table_name AS regclass) "
|
|
278
|
+
"AND a.attname = :column AND NOT a.attisdropped",
|
|
279
|
+
{"table_name": table_name, "column": column},
|
|
280
|
+
)
|
|
281
|
+
actual_type = str(rows[0]["col_type"]) if rows else ""
|
|
282
|
+
expected_type = f"vector({int(dims)})"
|
|
283
|
+
if actual_type and actual_type != expected_type:
|
|
284
|
+
raise DBError(
|
|
285
|
+
f"表 {table_name} 的 {column} 列已存在且维度不同:"
|
|
286
|
+
f"实际为 {actual_type},请求为 {expected_type}。"
|
|
287
|
+
"如需变更维度请先迁移数据并重建该列。"
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
logger.info(f"✅ 创建向量表 {table_name}(维度={dims})")
|
|
291
|
+
|
|
292
|
+
@classmethod
|
|
293
|
+
def insert_vectors(
|
|
294
|
+
cls,
|
|
295
|
+
table_name: str,
|
|
296
|
+
vectors: list[list[float]],
|
|
297
|
+
ids: list[int] | None = None,
|
|
298
|
+
extra_data: list[dict[str, object]] | None = None,
|
|
299
|
+
id_col: str = "id",
|
|
300
|
+
column: str = "embedding",
|
|
301
|
+
) -> int:
|
|
302
|
+
"""批量插入向量数据
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
table_name: 表名
|
|
306
|
+
vectors: 向量列表,每个向量为 float 列表(维度须与表定义一致)
|
|
307
|
+
ids: 可选的 ID 列表(长度需与 vectors 一致);None 时由 Kit 生成雪花 ID
|
|
308
|
+
(应用侧生成,**非数据库自增**)
|
|
309
|
+
extra_data: 额外列数据列表(长度需与 vectors 一致)
|
|
310
|
+
id_col: 主键列名(默认 ``id``,供自建 DDL 的表使用)
|
|
311
|
+
column: 向量列名(默认 ``embedding``,供自建 DDL 的表使用)
|
|
312
|
+
|
|
313
|
+
Returns:
|
|
314
|
+
插入的行数
|
|
315
|
+
|
|
316
|
+
Raises:
|
|
317
|
+
ValueError: 入参自洽性校验失败——ids / extra_data 长度与 vectors 不一致、
|
|
318
|
+
批内向量长度不一致、``extra_data`` 键为保留绑定名(``id`` / ``vec``)、
|
|
319
|
+
键与 ``id_col`` / ``column`` 重复、键不是合法标识符、``id_col == column``
|
|
320
|
+
|
|
321
|
+
Note:
|
|
322
|
+
单次事务内批量写入(``cls.transaction()``,与 SQLiteKit / MySqlKit 同语义:整体提交);
|
|
323
|
+
语句由 `build_insert_vectors` 构造(**单一事实源**)。需要把向量行写入**调用方自己的事务**时,
|
|
324
|
+
请改用 `build_insert_vectors` + `transaction()`。
|
|
325
|
+
"""
|
|
326
|
+
with cls.transaction() as session:
|
|
327
|
+
for sql, params in cls.build_insert_vectors(
|
|
328
|
+
table_name,
|
|
329
|
+
vectors,
|
|
330
|
+
ids=ids,
|
|
331
|
+
extra_data=extra_data,
|
|
332
|
+
id_col=id_col,
|
|
333
|
+
column=column,
|
|
334
|
+
):
|
|
335
|
+
session.execute(text(sql), params)
|
|
336
|
+
logger.info(f"✅ 插入 {len(vectors)} 条向量到 {table_name}")
|
|
337
|
+
return len(vectors)
|
|
338
|
+
|
|
339
|
+
@classmethod
|
|
340
|
+
def search_vectors(
|
|
341
|
+
cls,
|
|
342
|
+
table_name: str,
|
|
343
|
+
query_vector: list[float],
|
|
344
|
+
top_k: int = 10,
|
|
345
|
+
distance_type: str = DEFAULT_DISTANCE_TYPE,
|
|
346
|
+
filter_sql: str | None = None,
|
|
347
|
+
exact: bool = True,
|
|
348
|
+
id_col: str = "id",
|
|
349
|
+
column: str = "embedding",
|
|
350
|
+
) -> list[dict[str, object]]:
|
|
351
|
+
"""搜索最近邻向量(pgvector)
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
table_name: 表名
|
|
355
|
+
query_vector: 查询向量(float 列表)
|
|
356
|
+
top_k: 返回结果数上限(**先过滤、后取 top_k**)
|
|
357
|
+
distance_type: 距离类型,取值 COSINE / L2 / L1 / DOT / SQUARED_L2
|
|
358
|
+
(大小写不敏感)。⚠ DOT 为**负内积**(pgvector 约定)
|
|
359
|
+
filter_sql: 可选的过滤条件 WHERE 子句(不含 WHERE 关键字),
|
|
360
|
+
如 "label = 'cat'"
|
|
361
|
+
exact: 是否禁止近似加速(默认 True)。``True`` 时在同一事务内执行
|
|
362
|
+
``SET LOCAL enable_indexscan = off``,即使表上有 hnsw/ivfflat 索引
|
|
363
|
+
也走精确计算;``False`` 时不干预查询计划(有索引即可能为近似召回)
|
|
364
|
+
id_col: 主键列名(默认 ``id``)
|
|
365
|
+
column: 向量列名(默认 ``embedding``)
|
|
366
|
+
|
|
367
|
+
Returns:
|
|
368
|
+
按距离升序排列的结果列表,每项为 {"id": int, "distance": float}
|
|
369
|
+
|
|
370
|
+
Raises:
|
|
371
|
+
ValueError: top_k < 1、query_vector 为空、或 distance_type 取值不支持
|
|
372
|
+
|
|
373
|
+
Note:
|
|
374
|
+
- 过滤顺序为「**先套用 `filter_sql` 再取 `top_k`**」(与 SQLiteKit 一致)。
|
|
375
|
+
- ⚠ ``exact=True`` 是事务级粗粒度开关:它会禁用该查询的**所有**索引扫描,
|
|
376
|
+
包括 ``filter_sql`` 用到的高选择性列索引 → 有过滤条件且依赖过滤列索引的大表
|
|
377
|
+
查询会退化为顺序扫描。这是"精确 + 先过滤"的代价;要速度请显式传
|
|
378
|
+
``exact=False``(接受近似)。本模块**不创建向量索引**,需要 ANN 时自行建索引::
|
|
379
|
+
|
|
380
|
+
PgKit.execute("CREATE INDEX ON images "
|
|
381
|
+
"USING hnsw (embedding vector_cosine_ops)")
|
|
382
|
+
PgKit.search_vectors("images", q, top_k=5, exact=False)
|
|
383
|
+
"""
|
|
384
|
+
if top_k < 1:
|
|
385
|
+
raise ValueError(f"top_k 必须为正整数,当前为 {top_k}")
|
|
386
|
+
# 用 len() 而非真值判断:入参可为 list 或 numpy 数组
|
|
387
|
+
if len(query_vector) == 0:
|
|
388
|
+
raise ValueError("query_vector 不能为空")
|
|
389
|
+
|
|
390
|
+
key = distance_type.strip().upper()
|
|
391
|
+
if key not in SUPPORTED_DISTANCE_TYPES:
|
|
392
|
+
raise ValueError(
|
|
393
|
+
f"不支持的向量距离类型: {distance_type};可选: "
|
|
394
|
+
+ " / ".join(SUPPORTED_DISTANCE_TYPES)
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
operator = VECTOR_OPERATORS.get(key)
|
|
398
|
+
if operator is not None:
|
|
399
|
+
distance_expr = f"e.{column} {operator} :query"
|
|
400
|
+
else:
|
|
401
|
+
# SQUARED_L2:pgvector 无专用算子,用 power(<->, 2) 等价表达
|
|
402
|
+
distance_expr = f"power(e.{column} <-> :query, 2)"
|
|
403
|
+
|
|
404
|
+
where_clause = f"WHERE {filter_sql}" if filter_sql else ""
|
|
405
|
+
sql = (
|
|
406
|
+
f"SELECT e.{id_col} AS id, {distance_expr} AS distance "
|
|
407
|
+
f"FROM {table_name} AS e "
|
|
408
|
+
f"{where_clause} ORDER BY distance ASC LIMIT {int(top_k)}"
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
# ⚠ 不能复用 cls.query():SET LOCAL 只在当前事务内有效,必须与查询同连接
|
|
412
|
+
with get_engine(cls.DB_TYPE).connect() as conn:
|
|
413
|
+
if exact:
|
|
414
|
+
conn.execute(text("SET LOCAL enable_indexscan = off"))
|
|
415
|
+
result = conn.execute(text(sql), {"query": to_vector_literal(query_vector)})
|
|
416
|
+
rows = result.fetchall()
|
|
417
|
+
columns = result.keys()
|
|
418
|
+
|
|
419
|
+
data = [dict(zip(columns, row)) for row in rows]
|
|
420
|
+
logger.info(
|
|
421
|
+
f"🔍 向量搜索 {table_name}({key},exact={exact})→ 返回 {len(data)} 条"
|
|
422
|
+
)
|
|
423
|
+
return data
|
|
424
|
+
|
|
425
|
+
@classmethod
|
|
426
|
+
def vector_version(cls) -> str:
|
|
427
|
+
"""获取 pgvector 扩展版本
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
版本号字符串(如 "0.8.3");未安装或查询失败时返回 "unavailable"
|
|
431
|
+
"""
|
|
432
|
+
try:
|
|
433
|
+
rows = cls.query(
|
|
434
|
+
"SELECT extversion FROM pg_extension WHERE extname = 'vector'"
|
|
435
|
+
)
|
|
436
|
+
if rows:
|
|
437
|
+
return str(rows[0]["extversion"])
|
|
438
|
+
logger.warning("⚠️ pgvector 扩展未安装")
|
|
439
|
+
return "unavailable"
|
|
440
|
+
except Exception as e:
|
|
441
|
+
logger.warning(f"⚠️ 获取 pgvector 版本失败: {e}")
|
|
442
|
+
return "unavailable"
|